/* * Copyright 2013 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.git; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.transport.ReceiveCommand; import com.gitblit.Constants; import com.gitblit.models.TicketModel; import com.gitblit.models.TicketModel.Change; import com.gitblit.models.TicketModel.Field; import com.gitblit.models.TicketModel.Patchset; import com.gitblit.models.TicketModel.PatchsetType; import com.gitblit.models.TicketModel.Status; import com.gitblit.utils.ArrayUtils; import com.gitblit.utils.StringUtils; /** * * A subclass of ReceiveCommand which constructs a ticket change based on a * patchset and data derived from the push ref. * * @author James Moger * */ public class PatchsetCommand extends ReceiveCommand { public static final String TOPIC = "t="; public static final String RESPONSIBLE = "r="; public static final String WATCH = "cc="; public static final String MILESTONE = "m="; protected final Change change; protected boolean isNew; protected long ticketId; public static String getBasePatchsetBranch(long ticketNumber) { StringBuilder sb = new StringBuilder(); sb.append(Constants.R_TICKETS_PATCHSETS); long m = ticketNumber % 100L; if (m < 10) { sb.append('0'); } sb.append(m); sb.append('/'); sb.append(ticketNumber); sb.append('/'); return sb.toString(); } public static String getTicketBranch(long ticketNumber) { return Constants.R_TICKET + ticketNumber; } public static String getReviewBranch(long ticketNumber) { return "ticket-" + ticketNumber; } public static String getPatchsetBranch(long ticketId, long patchset) { return getBasePatchsetBranch(ticketId) + patchset; } public static long getTicketNumber(String ref) { if (ref.startsWith(Constants.R_TICKETS_PATCHSETS)) { // patchset revision // strip changes ref String p = ref.substring(Constants.R_TICKETS_PATCHSETS.length()); // strip shard id p = p.substring(p.indexOf('/') + 1); // strip revision p = p.substring(0, p.indexOf('/')); // parse ticket number return Long.parseLong(p); } else if (ref.startsWith(Constants.R_TICKET)) { String p = ref.substring(Constants.R_TICKET.length()); // parse ticket number return Long.parseLong(p); } return 0L; } public PatchsetCommand(String username, Patchset patchset) { super(patchset.isFF() ? ObjectId.fromString(patchset.parent) : ObjectId.zeroId(), ObjectId.fromString(patchset.tip), null); this.change = new Change(username); this.change.patchset = patchset; } public PatchsetType getPatchsetType() { return change.patchset.type; } public boolean isNewTicket() { return isNew; } public long getTicketId() { return ticketId; } public Change getChange() { return change; } /** * Creates a "new ticket" change for the proposal. * * @param commit * @param mergeTo * @param ticketId * @parem pushRef */ public void newTicket(RevCommit commit, String mergeTo, long ticketId, String pushRef) { this.ticketId = ticketId; isNew = true; change.setField(Field.title, getTitle(commit)); change.setField(Field.body, getBody(commit)); change.setField(Field.status, Status.New); change.setField(Field.mergeTo, mergeTo); change.setField(Field.type, TicketModel.Type.Proposal); Set watchSet = new TreeSet(); watchSet.add(change.author); // identify parameters passed in the push ref if (!StringUtils.isEmpty(pushRef)) { List watchers = getOptions(pushRef, WATCH); if (!ArrayUtils.isEmpty(watchers)) { for (String cc : watchers) { watchSet.add(cc.toLowerCase()); } } String milestone = getSingleOption(pushRef, MILESTONE); if (!StringUtils.isEmpty(milestone)) { // user provided milestone change.setField(Field.milestone, milestone); } String responsible = getSingleOption(pushRef, RESPONSIBLE); if (!StringUtils.isEmpty(responsible)) { // user provided responsible change.setField(Field.responsible, responsible); watchSet.add(responsible); } String topic = getSingleOption(pushRef, TOPIC); if (!StringUtils.isEmpty(topic)) { // user provided topic change.setField(Field.topic, topic); } } // set the watchers change.watch(watchSet.toArray(new String[watchSet.size()])); } /** * * @param commit * @param mergeTo * @param ticket * @param pushRef */ public void updateTicket(RevCommit commit, String mergeTo, TicketModel ticket, String pushRef) { this.ticketId = ticket.number; if (ticket.isClosed()) { // re-opening a closed ticket change.setField(Field.status, Status.Open); } // ticket may or may not already have an integration branch if (StringUtils.isEmpty(ticket.mergeTo) || !ticket.mergeTo.equals(mergeTo)) { change.setField(Field.mergeTo, mergeTo); } if (ticket.isProposal() && change.patchset.commits == 1 && change.patchset.type.isRewrite()) { // Gerrit-style title and description updates from the commit // message String title = getTitle(commit); String body = getBody(commit); if (!ticket.title.equals(title)) { // title changed change.setField(Field.title, title); } if (!ticket.body.equals(body)) { // description changed change.setField(Field.body, body); } } Set watchSet = new TreeSet(); watchSet.add(change.author); // update the patchset command metadata if (!StringUtils.isEmpty(pushRef)) { List watchers = getOptions(pushRef, WATCH); if (!ArrayUtils.isEmpty(watchers)) { for (String cc : watchers) { watchSet.add(cc.toLowerCase()); } } String milestone = getSingleOption(pushRef, MILESTONE); if (!StringUtils.isEmpty(milestone) && !milestone.equals(ticket.milestone)) { // user specified a (different) milestone change.setField(Field.milestone, milestone); } String responsible = getSingleOption(pushRef, RESPONSIBLE); if (!StringUtils.isEmpty(responsible) && !responsible.equals(ticket.responsible)) { // user specified a (different) responsible change.setField(Field.responsible, responsible); watchSet.add(responsible); } String topic = getSingleOption(pushRef, TOPIC); if (!StringUtils.isEmpty(topic) && !topic.equals(ticket.topic)) { // user specified a (different) topic change.setField(Field.topic, topic); } } // update the watchers watchSet.removeAll(ticket.getWatchers()); if (!watchSet.isEmpty()) { change.watch(watchSet.toArray(new String[watchSet.size()])); } } @Override public String getRefName() { return getPatchsetBranch(); } public String getPatchsetBranch() { return getBasePatchsetBranch(ticketId) + change.patchset.number; } public String getTicketBranch() { return getTicketBranch(ticketId); } private String getTitle(RevCommit commit) { String title = commit.getShortMessage(); return title; } /** * Returns the body of the commit message * * @return */ private String getBody(RevCommit commit) { String body = commit.getFullMessage().substring(commit.getShortMessage().length()).trim(); return body; } /** Extracts a ticket field from the ref name */ private static List getOptions(String refName, String token) { if (refName.indexOf('%') > -1) { List list = new ArrayList(); String [] strings = refName.substring(refName.indexOf('%') + 1).split(","); for (String str : strings) { if (str.toLowerCase().startsWith(token)) { String val = str.substring(token.length()); list.add(val); } } return list; } return null; } /** Extracts a ticket field from the ref name */ private static String getSingleOption(String refName, String token) { List list = getOptions(refName, token); if (list != null && list.size() > 0) { return list.get(0); } return null; } /** Extracts a ticket field from the ref name */ public static String getSingleOption(ReceiveCommand cmd, String token) { return getSingleOption(cmd.getRefName(), token); } /** Extracts a ticket field from the ref name */ public static List getOptions(ReceiveCommand cmd, String token) { return getOptions(cmd.getRefName(), token); } }d='n160' href='#n160'>160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
/*
 * Copyright 2011 gitblit.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitblit.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import com.gitblit.Constants.AccessPermission;
import com.gitblit.GitBlitException.ForbiddenException;
import com.gitblit.GitBlitException.NotAllowedException;
import com.gitblit.GitBlitException.UnauthorizedException;
import com.gitblit.GitBlitException.UnknownRequestException;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.UserModel;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/**
 * Utility methods for json calls to a Gitblit server.
 *
 * @author James Moger
 *
 */
public class JsonUtils {

	public static final Type REPOSITORIES_TYPE = new TypeToken<Map<String, RepositoryModel>>() {
	}.getType();

	public static final Type USERS_TYPE = new TypeToken<Collection<UserModel>>() {
	}.getType();

	/**
	 * Creates JSON from the specified object.
	 *
	 * @param o
	 * @return json
	 */
	public static String toJsonString(Object o) {
		String json = gson().toJson(o);
		return json;
	}

	/**
	 * Convert a json string to an object of the specified type.
	 * 
	 * @param json
	 * @param clazz
	 * @return the deserialized object
	 * @throws JsonParseException
	 * @throws JsonSyntaxException
	 */
	public static <X> X fromJsonString(String json, Class<X> clazz) throws JsonParseException,
			JsonSyntaxException {
		return gson().fromJson(json, clazz);
	}

	/**
	 * Convert a json string to an object of the specified type.
	 * 
	 * @param json
	 * @param type
	 * @return the deserialized object
	 * @throws JsonParseException
	 * @throws JsonSyntaxException
	 */
	public static <X> X fromJsonString(String json, Type type) throws JsonParseException,
			JsonSyntaxException {
		return gson().fromJson(json, type);
	}

	/**
	 * Reads a gson object from the specified url.
	 *
	 * @param url
	 * @param type
	 * @return the deserialized object
	 * @throws {@link IOException}
	 */
	public static <X> X retrieveJson(String url, Type type) throws IOException,
			UnauthorizedException {
		return retrieveJson(url, type, null, null);
	}

	/**
	 * Reads a gson object from the specified url.
	 *
	 * @param url
	 * @param type
	 * @return the deserialized object
	 * @throws {@link IOException}
	 */
	public static <X> X retrieveJson(String url, Class<? extends X> clazz) throws IOException,
			UnauthorizedException {
		return retrieveJson(url, clazz, null, null);
	}

	/**
	 * Reads a gson object from the specified url.
	 *
	 * @param url
	 * @param type
	 * @param username
	 * @param password
	 * @return the deserialized object
	 * @throws {@link IOException}
	 */
	public static <X> X retrieveJson(String url, Type type, String username, char[] password)
			throws IOException {
		String json = retrieveJsonString(url, username, password);
		if (StringUtils.isEmpty(json)) {
			return null;
		}
		return gson().fromJson(json, type);
	}

	/**
	 * Reads a gson object from the specified url.
	 *
	 * @param url
	 * @param clazz
	 * @param username
	 * @param password
	 * @return the deserialized object
	 * @throws {@link IOException}
	 */
	public static <X> X retrieveJson(String url, Class<X> clazz, String username, char[] password)
			throws IOException {
		String json = retrieveJsonString(url, username, password);
		if (StringUtils.isEmpty(json)) {
			return null;
		}
		return gson().fromJson(json, clazz);
	}

	/**
	 * Retrieves a JSON message.
	 *
	 * @param url
	 * @return the JSON message as a string
	 * @throws {@link IOException}
	 */
	public static String retrieveJsonString(String url, String username, char[] password)
			throws IOException {
		try {
			URLConnection conn = ConnectionUtils.openReadConnection(url, username, password);
			InputStream is = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,
					ConnectionUtils.CHARSET));
			StringBuilder json = new StringBuilder();
			char[] buffer = new char[4096];
			int len = 0;
			while ((len = reader.read(buffer)) > -1) {
				json.append(buffer, 0, len);
			}
			is.close();
			return json.toString();
		} catch (IOException e) {
			if (e.getMessage().indexOf("401") > -1) {
				// unauthorized
				throw new UnauthorizedException(url);
			} else if (e.getMessage().indexOf("403") > -1) {
				// requested url is forbidden by the requesting user
				throw new ForbiddenException(url);
			} else if (e.getMessage().indexOf("405") > -1) {
				// requested url is not allowed by the server
				throw new NotAllowedException(url);
			} else if (e.getMessage().indexOf("501") > -1) {
				// requested url is not recognized by the server
				throw new UnknownRequestException(url);
			}
			throw e;
		}
	}

	/**
	 * Sends a JSON message.
	 *
	 * @param url
	 *            the url to write to
	 * @param json
	 *            the json message to send
	 * @return the http request result code
	 * @throws {@link IOException}
	 */
	public static int sendJsonString(String url, String json) throws IOException {
		return sendJsonString(url, json, null, null);
	}

	/**
	 * Sends a JSON message.
	 *
	 * @param url
	 *            the url to write to
	 * @param json
	 *            the json message to send
	 * @param username
	 * @param password
	 * @return the http request result code
	 * @throws {@link IOException}
	 */
	public static int sendJsonString(String url, String json, String username, char[] password)
			throws IOException {
		try {
			byte[] jsonBytes = json.getBytes(ConnectionUtils.CHARSET);
			URLConnection conn = ConnectionUtils.openConnection(url, username, password);
			conn.setRequestProperty("Content-Type", "text/plain;charset=" + ConnectionUtils.CHARSET);
			conn.setRequestProperty("Content-Length", "" + jsonBytes.length);

			// write json body
			OutputStream os = conn.getOutputStream();
			os.write(jsonBytes);
			os.close();

			int status = ((HttpURLConnection) conn).getResponseCode();
			return status;
		} catch (IOException e) {
			if (e.getMessage().indexOf("401") > -1) {
				// unauthorized
				throw new UnauthorizedException(url);
			} else if (e.getMessage().indexOf("403") > -1) {
				// requested url is forbidden by the requesting user
				throw new ForbiddenException(url);
			} else if (e.getMessage().indexOf("405") > -1) {
				// requested url is not allowed by the server
				throw new NotAllowedException(url);
			} else if (e.getMessage().indexOf("501") > -1) {
				// requested url is not recognized by the server
				throw new UnknownRequestException(url);
			}
			throw e;
		}
	}

	// build custom gson instance with GMT date serializer/deserializer
	// http://code.google.com/p/google-gson/issues/detail?id=281
	public static Gson gson(ExclusionStrategy... strategies) {
		GsonBuilder builder = new GsonBuilder();
		builder.registerTypeAdapter(Date.class, new GmtDateTypeAdapter());
		builder.registerTypeAdapter(AccessPermission.class, new AccessPermissionTypeAdapter());
		if (!ArrayUtils.isEmpty(strategies)) {
			builder.setExclusionStrategies(strategies);
		}
		return builder.create();
	}

	public static class GmtDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
		private final DateFormat dateFormat;

		public GmtDateTypeAdapter() {
			dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
			dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		}

		@Override
		public synchronized JsonElement serialize(Date date, Type type,
				JsonSerializationContext jsonSerializationContext) {
			synchronized (dateFormat) {
				String dateFormatAsString = dateFormat.format(date);
				return new JsonPrimitive(dateFormatAsString);
			}
		}

		@Override
		public synchronized Date deserialize(JsonElement jsonElement, Type type,
				JsonDeserializationContext jsonDeserializationContext) {
			try {
				synchronized (dateFormat) {
					Date date = dateFormat.parse(jsonElement.getAsString());
					return new Date((date.getTime() / 1000) * 1000);
				}
			} catch (ParseException e) {
				throw new JsonSyntaxException(jsonElement.getAsString(), e);
			}
		}
	}

	private static class AccessPermissionTypeAdapter implements JsonSerializer<AccessPermission>, JsonDeserializer<AccessPermission> {

		private AccessPermissionTypeAdapter() {
		}

		@Override
		public synchronized JsonElement serialize(AccessPermission permission, Type type,
				JsonSerializationContext jsonSerializationContext) {
			return new JsonPrimitive(permission.code);
		}

		@Override
		public synchronized AccessPermission deserialize(JsonElement jsonElement, Type type,
				JsonDeserializationContext jsonDeserializationContext) {
			return AccessPermission.fromCode(jsonElement.getAsString());
		}
	}

	public static class ExcludeField implements ExclusionStrategy {

		private Class<?> c;
		private String fieldName;

		public ExcludeField(String fqfn) throws SecurityException, NoSuchFieldException,
				ClassNotFoundException {
			this.c = Class.forName(fqfn.substring(0, fqfn.lastIndexOf(".")));
			this.fieldName = fqfn.substring(fqfn.lastIndexOf(".") + 1);
		}

		@Override
		public boolean shouldSkipClass(Class<?> arg0) {
			return false;
		}

		@Override
		public boolean shouldSkipField(FieldAttributes f) {
			return (f.getDeclaringClass() == c && f.getName().equals(fieldName));
		}
	}
}