auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Map<String, String> parseArguments(String[] args) throws Exception { Map<String, String> argMap = new HashMap<>(); if ((args.length < 2 && getName().equals(args[0])) || ACTION_HELP.equals(args[1])) { action = ACTION_HELP; return argMap; } action = args[1]; argMap.put(action, args[2]); ExtendedCliParser parser = initParser(action); argMap = parser.parse(args, 2, args.length); if(argMap.containsKey(ACTION_HELP)) { action = ACTION_HELP; } return argMap; }

Target:
public void parseArguments(String[] args) throws Exception { if (args.length < 2 || ACTION_HELP.equals(args[1])) { action = ACTION_HELP; return; } action = args[1]; argMap.put(action, args[1]); ExtendedCliParser parser = initParser(action); argMap = parser.parse(args, 2, args.length); if(argMap.containsKey(ACTION_HELP)) { action = ACTION_HELP; } }
Source:
public Configuration getConfiguration(GraphContext context) { Configuration configuration = ConfigurationBuilder.begin() .addRule() .when(Query.find(TestXmlMetaFacetModel.class).as("xmlModels")) .perform(Iteration .over(TestXmlMetaFacetModel.class, "xmlModels") .when(new AbstractIterationFilter<TestXmlMetaFacetModel>(TestXmlMetaFacetModel.class, Iteration.singleVariableIterationName("xmlModels")) { @Override public boolean evaluate(GraphRewrite event, EvaluationContext context, TestXmlMetaFacetModel payload) { String rootTagName = payload.getRootTagName(); boolean result = !"xmlTag3".equals(rootTagName); return result; } }) .perform(new AbstractIterationOperation<TestXmlMetaFacetModel>(TestXmlMetaFacetModel.class, Iteration.singleVariableIterationName("xmlModels")) { @Override public void perform(GraphRewrite event, EvaluationContext context, TestXmlMetaFacetModel xmlFacetModel) { typeSearchResults.add(xmlFacetModel); if (xmlRootNames.contains(xmlFacetModel.getRootTagName())) { Assert.fail("Tag found multiple times"); } xmlRootNames.add(xmlFacetModel.getRootTagName()); } }) .otherwise(new AbstractIterationOperation<TestXmlMetaFacetModel>(TestXmlMetaFacetModel.class, Iteration.singleVariableIterationName("xmlModels")) { @Override public void perform(GraphRewrite event, EvaluationContext context, TestXmlMetaFacetModel payload) { typeSearchResults.add(payload); if (excludedXmlRootNames.contains(payload.getRootTagName())) { Assert.fail("Tag found multiple times"); } excludedXmlRootNames.add(payload.getRootTagName()); } }) .endIteration() ); return configuration; }

Target:
public Configuration getConfiguration(GraphContext context) { Configuration configuration = ConfigurationBuilder.begin() .addRule() .when(Query.find(TestXmlMetaFacetModel.class)) .perform(Iteration .over() .when(new AbstractIterationFilter<TestXmlMetaFacetModel>(TestXmlMetaFacetModel.class, Iteration.DEFAULT_SINGLE_VARIABLE_STRING) { @Override public boolean evaluate(GraphRewrite event, EvaluationContext context, TestXmlMetaFacetModel payload) { String rootTagName = payload.getRootTagName(); boolean result = !"xmlTag3".equals(rootTagName); return result; } }) .perform(new AbstractIterationOperation<TestXmlMetaFacetModel>(TestXmlMetaFacetModel.class, Iteration.DEFAULT_SINGLE_VARIABLE_STRING) { @Override public void perform(GraphRewrite event, EvaluationContext context, TestXmlMetaFacetModel xmlFacetModel) { typeSearchResults.add(xmlFacetModel); if (xmlRootNames.contains(xmlFacetModel.getRootTagName())) { Assert.fail("Tag found multiple times"); } xmlRootNames.add(xmlFacetModel.getRootTagName()); } }) .otherwise(new AbstractIterationOperation<TestXmlMetaFacetModel>(TestXmlMetaFacetModel.class,Iteration.DEFAULT_SINGLE_VARIABLE_STRING) { @Override public void perform(GraphRewrite event, EvaluationContext context, TestXmlMetaFacetModel payload) { typeSearchResults.add(payload); if (excludedXmlRootNames.contains(payload.getRootTagName())) { Assert.fail("Tag found multiple times"); } excludedXmlRootNames.add(payload.getRootTagName()); } }) .endIteration() ); return configuration; }
Source:
default DataType[] getFormatFieldNames() { return Arrays.stream(getSchema().getFieldNames()) .filter(name -> !getPartitionKeys().contains(name)) .map(name -> getSchema().getFieldDataType(name).get()) .toArray(DataType[]::new); }

Target:
default String[] getFormatFieldNames() { return Arrays.stream(getSchema().getFieldNames()) .filter(name -> !getPartitionKeys().contains(name)) .toArray(String[]::new); }
Source:
private static void compose(StringBuilder builder, String key, String value) { final char DELIMITER = ','; builder.append(key).append('=').append(value).append(DELIMITER); }

Target:
private static void compose(StringBuilder builder, String key, String value) { final char PROPERTY_DELIMITER = ','; final char NAME_VALUE_SEPARATOR = '='; builder.append(key).append(NAME_VALUE_SEPARATOR).append(value).append(PROPERTY_DELIMITER); }
Source:
public void populateAndApplyDefaults(ParallelTransferOptions other) { if (other == null) { other = new ParallelTransferOptions(); } this.setBlockSize(other.getBlockSize() == null ? BLOB_DEFAULT_UPLOAD_BLOCK_SIZE : other.getBlockSize()); this.setNumBuffers(other.getNumBuffers() == null ? BLOB_DEFAULT_NUMBER_OF_BUFFERS : other.getNumBuffers()); this.setProgressReceiver(other.getProgressReceiver()); }

Target:
public void populateAndApplyDefaults(ParallelTransferOptions other) { if (other == null) { other = new ParallelTransferOptions(); } this.setBlockSize(other.getBlockSize() == null ? Integer.valueOf(BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize()); this.setNumBuffers(other.getNumBuffers() == null ? Integer.valueOf(BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers()); this.setProgressReceiver(other.getProgressReceiver()); }
Source:
private CommitHistory pathCommitHistory(final RevWalk rw) throws MissingObjectException, IncorrectObjectTypeException, IOException { final Map<AnyObjectId, String> pathByCommit = new HashMap<>(); final List<RevCommit> commits = new ArrayList<>(); final RenameCaptor renameCaptor = new RenameCaptor(); final TreeRevFilter revFilter = createTreeRevFilter(rw, path, renameCaptor); String curPath = path; for (RevCommit commit : rw) { if (revFilter.include(rw, commit)) { @SuppressWarnings("resource") final TreeWalk tw = new TreeWalk(rw.getObjectReader()); tw.setRecursive(true); tw.setFilter(PathFilter.create(curPath)); tw.addTree(commit.getTree()); if (tw.next()) { commits.add(commit); pathByCommit.put(commit.getId(), curPath); if (renameCaptor.hasCaptured()) { curPath = renameCaptor.getAndReset().getOldPath(); } } } } return new CommitHistory(commits, pathByCommit, path); }

Target:
private CommitHistory pathCommitHistory(final RevWalk rw) throws MissingObjectException, IncorrectObjectTypeException, IOException { final Map<AnyObjectId, String> pathByCommit = new HashMap<>(); final List<RevCommit> commits = new ArrayList<>(); final RenameCaptor renameCaptor = new RenameCaptor(); final TreeRevFilter revFilter = createTreeRevFilter(rw, path, renameCaptor); String curPath = path; for (final RevCommit commit : rw) { if (revFilter.include(rw, commit)) { @SuppressWarnings("resource") final TreeWalk tw = new TreeWalk(rw.getObjectReader()); tw.setRecursive(true); tw.setFilter(PathFilter.create(curPath)); tw.addTree(commit.getTree()); if (tw.next()) { commits.add(commit); pathByCommit.put(commit.getId(), curPath); if (renameCaptor.hasCaptured()) { curPath = renameCaptor.getAndReset().getOldPath(); } } } } return new CommitHistory(commits, pathByCommit, path); }
Source:
protected void performDefaults() { CDTPrefUtil.cleanPreferredTCs(); h_selected.handleSelection(); }

Target:
protected void performDefaults() { CDTPrefUtil.cleanPreferredTCs(); h_selected.handleSelection(); MinGW.changeMinGWDefaultLocation(MinGW.getAllMinGWHome().get(0)); comboMinGWChains.select(0); }
Source:
public String getLink(HttpServletRequest req, String requestedUrl) { if (urlComputerClass != null && urlComputer == null) { try { urlComputer = urlComputerClass.newInstance(); } catch (ReflectiveOperationException e) { log.error("Unable to instantiate LoginProviderLinkComputer", e); } } if (urlComputer != null) { return urlComputer.computeUrl(req, requestedUrl); } else { return link; } }

Target:
public String getLink(HttpServletRequest req, String requestedUrl) { if (urlComputerClass != null && urlComputer == null) { try { urlComputer = urlComputerClass.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { log.error("Unable to instantiate LoginProviderLinkComputer", e); } } if (urlComputer != null) { return urlComputer.computeUrl(req, requestedUrl); } else { return link; } }
Source:
private void getDefaultConfigurationVersion(final LoginModel loginModel) { AsyncQuery callback = new AsyncQuery<>(new AsyncCallback<VdcQueryReturnValue>() { @Override public void onSuccess(VdcQueryReturnValue returnValue) { if (returnValue != null) { _defaultConfigurationVersion = returnValue.getReturnValue(); } else { _defaultConfigurationVersion = GENERAL; } loginModel.getLoggedInEvent().raise(loginModel, EventArgs.EMPTY); } }); callback.setHandleFailure(true); Frontend.getInstance().runQuery(VdcQueryType.GetDefaultConfigurationVersion, new VdcQueryParametersBase(), callback); }

Target:
private void getDefaultConfigurationVersion(final LoginModel loginModel) { AsyncQuery callback = new AsyncQuery<>(new AsyncCallback<VdcQueryReturnValue>() { @Override public void onSuccess(VdcQueryReturnValue returnValue) { if (returnValue != null) { _defaultConfigurationVersion = ((VdcQueryReturnValue) returnValue).getReturnValue(); } else { _defaultConfigurationVersion = GENERAL; } loginModel.getLoggedInEvent().raise(loginModel, EventArgs.EMPTY); } }); callback.setHandleFailure(true); Frontend.getInstance().runQuery(VdcQueryType.GetDefaultConfigurationVersion, new VdcQueryParametersBase(), callback); }
Source:
public static String stripFullLineComments(String statement) { StringBuilder newStatement = new StringBuilder(statement.length()); for (String line : statement.split("\n")) { if (!line.trim().startsWith("--")) { newStatement.append(line); newStatement.append('\n'); } } return newStatement.toString().trim(); }

Target:
public static String stripFullLineComments(String statement) { StringBuilder newStatement = new StringBuilder(statement.length()); String[] lines = statement.split("\n"); for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (!line.trim().startsWith("--")) { newStatement.append(line); if (i < lines.length - 1) { newStatement.append('\n'); } } } return newStatement.toString(); }
Source:
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { baseRequest.setHandled(true); ServletContext sc = baseRequest.getContext(); ServiceLocator sl = ((ServletContainer) environment.getJerseyServletContainer()).getApplicationHandler().getServiceLocator(); RegistersConfiguration rc = sl.getService(RegistersConfiguration.class); String registerId = RegisterNameExtractor.extractRegisterName(request.getHeader("Host")); RegisterData rd = rc.getRegisterData(registerId); String registerName = registerId.replace('-',' '); WebContext wc = new WebContext(request, response, sc, request.getLocale()); wc.setVariable("register", rd.getRegister()); wc.setVariable("friendlyRegisterName", StringUtils.capitalize(registerName) + " register"); engine.process("404.html", wc, response.getWriter()); }

Target:
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { if (response.getStatus() != HttpServletResponse.SC_NOT_FOUND) { return; } baseRequest.setHandled(true); ServletContext sc = baseRequest.getContext(); ServiceLocator sl = ((ServletContainer) environment.getJerseyServletContainer()).getApplicationHandler().getServiceLocator(); RegistersConfiguration rc = sl.getService(RegistersConfiguration.class); String registerId = RegisterNameExtractor.extractRegisterName(request.getHeader("Host")); RegisterData rd = rc.getRegisterData(registerId); String registerName = registerId.replace('-', ' '); WebContext wc = new WebContext(request, response, sc, request.getLocale()); wc.setVariable("register", rd.getRegister()); wc.setVariable("friendlyRegisterName", StringUtils.capitalize(registerName) + " register"); response.setHeader("Content-Type", "text/html; charset=UTF-8"); engine.process("404.html", wc, response.getWriter()); }
Source:
protected <E extends MongoEntity> void extendBatchQuery(MongoQuery<E> query) { if (!Traced.class.isAssignableFrom(query.getDescriptor().getType())) { throw new IllegalArgumentException("Entitis for which 'ChangeChecks' are created must implement 'Traced'."); } query.where(QueryBuilder.FILTERS.gt(Traced.TRACE.inner(TraceData.CHANGED_AT), LocalDateTime.now().minusDays(1))); }

Target:
protected <E extends MongoEntity> void extendBatchQuery(MongoQuery<E> query) { if (!Traced.class.isAssignableFrom(query.getDescriptor().getType())) { throw new IllegalArgumentException("Entities for which 'ChangeChecks' are created must implement 'Traced'."); } query.where(QueryBuilder.FILTERS.gt(Traced.TRACE.inner(TraceData.CHANGED_AT), LocalDateTime.now().minusDays(1))); }
Source:
private void handleContent(HttpContent httpContent) throws RestServiceException { if (request != null && !requestContentFullyReceived) { long processingStartTime = System.currentTimeMillis(); nettyMetrics.bytesReadRate.mark(httpContent.content().readableBytes()); requestContentFullyReceived = httpContent instanceof LastHttpContent; logger.trace("Received content for request - {}", request.getUri()); try { request.addContent(httpContent); } catch (IllegalStateException e) { nettyMetrics.contentAdditionError.inc(); throw new RestServiceException(e, RestServiceErrorCode.InvalidRequestState); } finally { long chunkProcessingTime = System.currentTimeMillis() - processingStartTime; nettyMetrics.requestChunkProcessingTimeInMs.update(chunkProcessingTime); request.getMetricsTracker().nioMetricsTracker.addToRequestProcessingTime(chunkProcessingTime); } if (!request.getRestMethod().equals(RestMethod.POST) || (request.isMultipart() && requestContentFullyReceived)) { requestHandler.handleRequest(request, responseChannel); } } else { resetState(); logger.warn("Received content when it was not expected on channel {}", ctx.channel()); nettyMetrics.noRequestError.inc(); responseChannel.onResponseComplete( new RestServiceException("Received content without a request", RestServiceErrorCode.InvalidRequestState)); } }

Target:
private boolean handleContent(HttpContent httpContent) throws RestServiceException { boolean success = true; if (request != null && !requestContentFullyReceived) { long processingStartTime = System.currentTimeMillis(); nettyMetrics.bytesReadRate.mark(httpContent.content().readableBytes()); requestContentFullyReceived = httpContent instanceof LastHttpContent; logger.trace("Received content for request - {}", request.getUri()); try { request.addContent(httpContent); } catch (IllegalStateException e) { success = false; nettyMetrics.contentAdditionError.inc(); responseChannel.onResponseComplete(new RestServiceException(e, RestServiceErrorCode.InvalidRequestState)); } finally { long chunkProcessingTime = System.currentTimeMillis() - processingStartTime; nettyMetrics.requestChunkProcessingTimeInMs.update(chunkProcessingTime); request.getMetricsTracker().nioMetricsTracker.addToRequestProcessingTime(chunkProcessingTime); } if (success && (!request.getRestMethod().equals(RestMethod.POST) || (request.isMultipart() && requestContentFullyReceived))) { requestHandler.handleRequest(request, responseChannel); } } else { success = false; resetState(); logger.warn("Received content when it was not expected on channel {}", ctx.channel()); nettyMetrics.noRequestError.inc(); responseChannel.onResponseComplete( new RestServiceException("Received content without a request", RestServiceErrorCode.InvalidRequestState)); } return success; }
Source:
public void visit(final MethodCallExpr n, final Void arg) { printComment(n.getComment(), arg); n.getScope().ifPresent(scope -> { scope.accept(this, arg); boolean mayAlignColumns = n.findParent(Statement.class) .map(p -> p.isReturnStmt() || p.isExpressionStmt()) .orElse(false); if (mayAlignColumns && configuration.isColumnAlignFirstMethodChain()) { if (!(scope instanceof MethodCallExpr) || !((MethodCallExpr) scope).getScope().isPresent()) { printer.reindentWithAlignToCursor(); } else { printer.println(); } } printer.print("."); }); printTypeArgs(n, arg); n.getName().accept(this, arg); printer.duplicateIndent(); printArguments(n.getArguments(), arg); printer.unindent(); }

Target:
public void visit(final MethodCallExpr n, final Void arg) { printComment(n.getComment(), arg); n.getScope().ifPresent(scope -> { scope.accept(this, arg); if (configuration.isColumnAlignFirstMethodChain()) { if (n.findParent(Statement.class).map(p -> p.isReturnStmt() || p.isThrowStmt() || p.isAssertStmt() || p.isExpressionStmt()).orElse(false)) { if (scope instanceof MethodCallExpr && ((MethodCallExpr) scope).getScope().isPresent()) { printer.println(); } else { printer.reindentWithAlignToCursor(); } } } printer.print("."); }); printTypeArgs(n, arg); n.getName().accept(this, arg); printer.duplicateIndent(); printArguments(n.getArguments(), arg); printer.unindent(); }
Source:
public void testTimestamp() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_time", "2014-10-02T15:01:23.045123456Z"); Notification notification = mpPushSpy.createNotification(intent); Instant instant = Instant.parse( "2014-10-02T15:01:23.045123456Z" ); verify(builderSpy).setShowWhen(true); verify(builderSpy).setWhen(instant.toEpochMilli()); }

Target:
public void testTimestamp() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_time", "2014-10-02T15:01:23.045123456Z"); Notification notification = mpPushSpy.createNotification(intent); Instant instant = Instant.parse("2014-10-02T15:01:23.045123456Z"); verify(builderSpy).setShowWhen(true); verify(builderSpy).setWhen(instant.toEpochMilli()); } }
Source:
public static final void commonDownloadFile(ServerConnectionInfo serverInfo, File f, String downloadUrl) throws URISyntaxException, IOException, TransmissionException { log.info("Downloading URL into {}", downloadUrl, f); URI u = null; try { log.info("Parsing URL {}", downloadUrl); URL uurl = new URL(downloadUrl); u = uurl.toURI(); } catch (MalformedURLException | URISyntaxException e) { log.error("bad download url", e); throw e; } HttpClient httpclient = WebUtils.createHttpClient(); HttpClientContext localContext = WebUtils.getHttpContext(); HttpGet req = WebUtils.createOpenRosaHttpGet(u); WebUtils.setCredentials(localContext, serverInfo, u); HttpResponse response = null; { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { WebUtils.resetHttpContext(); throw new TransmissionException("Authentication failure"); } else if (statusCode != 200) { String errMsg = "Fetch failed. Detailed reason: " + response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; log.error(errMsg); flushEntityBytes(response.getEntity()); throw new TransmissionException(errMsg); } try (InputStream is = response.getEntity().getContent(); OutputStream os = new FileOutputStream(f)) { byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); } } }

Target:
public static final void commonDownloadFile(ServerConnectionInfo serverInfo, File f, String downloadUrl) throws URISyntaxException, IOException, TransmissionException { log.info("Downloading URL into {}", downloadUrl, f); URI u = null; try { log.info("Parsing URL {}", downloadUrl); URL uurl = new URL(downloadUrl); u = uurl.toURI(); } catch (MalformedURLException | URISyntaxException e) { log.warn("bad download url", e); throw e; } HttpClient httpclient = WebUtils.createHttpClient(); HttpClientContext localContext = WebUtils.getHttpContext(); HttpGet req = WebUtils.createOpenRosaHttpGet(u); WebUtils.setCredentials(localContext, serverInfo, u); HttpResponse response = null; { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { WebUtils.resetHttpContext(); throw new TransmissionException("Authentication failure"); } else if (statusCode != 200) { String errMsg = "Fetch failed. Detailed reason: " + response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; log.error(errMsg); flushEntityBytes(response.getEntity()); throw new TransmissionException(errMsg); } try (InputStream is = response.getEntity().getContent(); OutputStream os = new FileOutputStream(f)) { byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); } } }
Source:
private Object remoteGetBeforeWrite(InvocationContext ctx, Object key, FlagAffectedCommand command) throws Throwable { if (isStateTransferInProgressForKey(key)) { if (trace) log.tracef("Doing a remote get for key %s", key); InternalCacheEntry ice = dm.retrieveFromRemoteSource(key, ctx, false, command); if (ice != null) { CacheEntry ce = ctx.lookupEntry(key); if (ce == null || ce.isNull() || ce.isLockPlaceholder() || ce.getValue() == null) { if (ce != null && ce.isChanged()) { ce.setValue(ice.getValue()); } else { lockAndWrap(ctx, key, ice, command); } } return ice.getValue(); } } else { if (trace) log.tracef("Not doing a remote get for key %s since entry is mapped to current node (%s), or is in L1. Owners are %s", key, rpcManager.getAddress(), dm.locate(key)); } return null; }

Target:
private Object remoteGetBeforeWrite(InvocationContext ctx, Object key, FlagAffectedCommand command) throws Throwable { if (dm.isAffectedByRehash(key) && !dataContainer.containsKey(key)) { if (trace) log.tracef("Doing a remote get for key %s", key); InternalCacheEntry ice = dm.retrieveFromRemoteSource(key, ctx, false, command); if (ice != null) { if (!ctx.replaceValue(key, ice.getValue())) { entryFactory.wrapEntryForPut(ctx, key, ice, false, command); } return ice.getValue(); } } else { if (trace) log.tracef("Not doing a remote get for key %s since entry is not affected by rehash or is already in data container. We are %s, owners are %s", key, rpcManager.getAddress(), dm.locate(key)); } return null; }
Source:
protected void setUp() throws Exception { String[] commands = {"cmd", "/c", "start", "iexplore.exe","-nohome", "\"<LINK_0>\""}; Runtime.getRuntime().exec(commands); Thread.sleep(30000); }

Target:
public void setUp() throws Exception { Runtime.getRuntime().exec("cmd /c start iexplore.exe -nohome \"about:blank\""); Thread.sleep(3000); }
Source:
public static MigrationOptions map(HasMigrationOptions entity, MigrationOptions template) { if (template == null) { template = new MigrationOptions(); } template.setAutoConverge(mapToInheritableBoolean(entity.getAutoConverge())); template.setCompressed(mapToInheritableBoolean(entity.getMigrateCompressed())); if (entity.getMigrationPolicyId() != null) { MigrationPolicy policy = new MigrationPolicy(); policy.setId(entity.getMigrationPolicyId().toString()); template.setPolicy(policy); } return template; }

Target:
public static MigrationOptions map(HasMigrationOptions entity, MigrationOptions template) { if (template == null) { template = new MigrationOptions(); } template.setAutoConverge(mapToInheritableBoolean(entity.getAutoConverge())); template.setCompressed(mapToInheritableBoolean(entity.getMigrateCompressed())); if (entity.getMigrationPolicyId() != null) { MigrationPolicy policy = template.getPolicy(); if (policy == null) { policy = new MigrationPolicy(); template.setPolicy(policy); } policy.setId(entity.getMigrationPolicyId().toString()); template.setPolicy(policy); } return template; }
Source:
public static Bitmap centerInside(@NonNull BitmapPool pool, @NonNull Bitmap inBitmap, int width, int height) { if (inBitmap.getWidth() == width && inBitmap.getHeight() == height) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "requested target size matches input, returning input"); } return inBitmap; } if (inBitmap.getWidth() > width || inBitmap.getHeight() > height) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "requested target size too big for input, fit centering instead"); } return fitCenter(pool, inBitmap, width, height); } final int horizontalPadding = (width - inBitmap.getWidth()) / 2; final int verticalPadding = (height - inBitmap.getHeight()) / 2; Bitmap.Config config = getSafeConfig(inBitmap); Bitmap toReuse = pool.get(width, height, config); TransformationUtils.setAlpha(inBitmap, toReuse); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "request: " + width + "x" + height); Log.v(TAG, "toCenter: " + inBitmap.getWidth() + "x" + inBitmap.getHeight()); Log.v(TAG, "toReuse: " + toReuse.getWidth() + "x" + toReuse.getHeight()); Log.v(TAG, "padding: " + horizontalPadding + "x" + verticalPadding); } Canvas canvas = new Canvas(toReuse); canvas.drawBitmap(inBitmap, horizontalPadding, verticalPadding, DEFAULT_PAINT); clear(canvas); return toReuse; }

Target:
public static Bitmap centerInside(@NonNull BitmapPool pool, @NonNull Bitmap inBitmap, int width, int height) { if (inBitmap.getWidth() <= width && inBitmap.getHeight() <= height) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "requested target size larger or equal to input, returning input"); } return inBitmap; } else { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "requested target size too big for input, fit centering instead"); } return fitCenter(pool, inBitmap, width, height); } }
Source:
public void do_not_display_submitter_param_in_log_when_submitterLogin_is_not_set_in_case_of_success() throws Exception { when(queue.peek(anyString())).thenReturn(Optional.of(createCeTask(null))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(LoggerLevel.INFO); assertThat(logs).hasSize(2); for (int i = 0; i < 2; i++) { assertThat(logs.get(i)).doesNotContain("lgsubmitter="); } }

Target:
public void do_not_display_submitter_param_in_log_when_submitterLogin_is_not_set_in_case_of_success() throws Exception { when(queue.peek(anyString())).thenReturn(Optional.of(createCeTask(null))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(LoggerLevel.INFO); assertThat(logs).hasSize(2); for (int i = 0; i < 2; i++) { assertThat(logs.get(i)).doesNotContain(" | submitter="); } }
Source:
public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsNotStructure() { final DataType dataType = mock(DataType.class); when(dataTypeSelectComponent.getValue()).thenReturn("String"); when(dataType.getSubDataTypes()).thenReturn(emptyList()); doReturn(dataType).when(listItem).getDataType(); listItem.insertNewFieldIfDataTypeIsStructure(); verify(listItem, never()).insertNestedField(); }

Target:
public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsNotStructure() { final DataType dataType = mock(DataType.class); final String hash = "hash"; when(dataTypeSelectComponent.getValue()).thenReturn("String"); when(dataType.getSubDataTypes()).thenReturn(emptyList()); doReturn(dataType).when(listItem).getDataType(); listItem.insertNewFieldIfDataTypeIsStructure(hash); verify(dataTypeList, never()).insertNestedField(anyString()); }
Source:
public DynamicSchemaResolver(List<String> additionalFields) { ConfigurationStore.getInstance().addConfigurationListener(this); this.schemaFields = new SchemaFields(); metadataMaximumBytes = getMetadataSizeLimit(); caseInsensitiveSort = "true".equals(System.getProperty("solr.sort.case-insensitive")); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED); fieldsCache.add( Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED + SchemaFields.HAS_CASE); fieldsCache.add(Metacard.TAGS + SchemaFields.TEXT_SUFFIX); anyTextFieldsCache.add(Metacard.METADATA + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Validation.VALIDATION_ERRORS + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Validation.VALIDATION_WARNINGS + SchemaFields.TEXT_SUFFIX); fieldsCache.add(SchemaFields.METACARD_TYPE_FIELD_NAME); fieldsCache.add(SchemaFields.METACARD_TYPE_OBJECT_FIELD_NAME); addAdditionalFields(this, additionalFields); filterAnyTextFieldCache(); }

Target:
public DynamicSchemaResolver(List<String> additionalFields) { schemaFields = new SchemaFields(); metadataMaximumBytes = getMetadataSizeLimit(); anyTextFields = getAnyTextFields(); caseInsensitiveSort = "true".equals(System.getProperty("solr.query.sort.caseInsensitive")); try { textSortCharacterLimit = Integer.parseInt(System.getProperty("solr.index.sort.characterLimit", "127").trim()); } catch (NumberFormatException nfe) { LOGGER.warn("Invalid sorting character limit, defaulting to 127", nfe); textSortCharacterLimit = 127; } fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED); fieldsCache.add( Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED + SchemaFields.HAS_CASE); fieldsCache.add(SchemaFields.METACARD_TYPE_FIELD_NAME); fieldsCache.add(SchemaFields.METACARD_TYPE_OBJECT_FIELD_NAME); addAdditionalFields(this, additionalFields); }
Source:
void methodOne() { Anon foo = new Anon() { public void foo() { this.doSideEffect(); } public void doSideEffect() }; new Anon() { public void foo() { new Anon() { private int anonMember; private String name; public void foo() { int anonMember = 0; this.anonMember++; this.name = "something"; } }; } }; }

Target:
void methodOne() { Anon foo = new Anon() { public void foo() { this.doSideEffect(); } public void doSideEffect() }; this.bar = 0; new Anon() { public void foo() { new Anon() { private int anonMember; private String name; public void foo() { int anonMember = 0; this.anonMember++; this.name = "something"; } }; } }; }
Source:
static void modifyRegistration(OperationContext context, ModelNode op) { final MutableDiscoveryProvider mutableDiscoveryProvider = context.getCapabilityRuntimeAPI(DiscoveryExtension.DISCOVERY_PROVIDER_CAPABILITY, context.getCurrentAddressValue(), MutableDiscoveryProvider.class); if (op.hasDefined(DiscoveryExtension.PROVIDERS)) { final List<ModelNode> list = op.require(DiscoveryExtension.PROVIDERS).asList(); if (list.isEmpty()) { mutableDiscoveryProvider.setDiscoveryProvider(DiscoveryProvider.EMPTY); } else { final DiscoveryProvider[] providers = new DiscoveryProvider[list.size()]; int i = 0; for (ModelNode modelNode : list) { final String name = modelNode.asString(); providers[i ++] = context.getCapabilityRuntimeAPI(DiscoveryExtension.DISCOVERY_PROVIDER_CAPABILITY, name, DiscoveryProvider.class); } final DiscoveryProvider discoveryProvider = new AggregateDiscoveryProvider(providers); mutableDiscoveryProvider.setDiscoveryProvider(discoveryProvider); } } else { mutableDiscoveryProvider.setDiscoveryProvider(DiscoveryProvider.EMPTY); } }

Target:
static void modifyRegistration(OperationContext context, ModelNode op) throws OperationFailedException { final MutableDiscoveryProvider mutableDiscoveryProvider = context.getCapabilityRuntimeAPI(DiscoveryExtension.DISCOVERY_PROVIDER_CAPABILITY, context.getCurrentAddressValue(), MutableDiscoveryProvider.class); final ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel(); if (model.hasDefined(DiscoveryExtension.PROVIDERS)) { final List<String> list = AggregateProviderDefinition.PROVIDER_NAMES.unwrap(context, model); if (list.isEmpty()) { mutableDiscoveryProvider.setDiscoveryProvider(DiscoveryProvider.EMPTY); } else { final DiscoveryProvider[] providers = new DiscoveryProvider[list.size()]; int i = 0; for (String name : list) { providers[i ++] = context.getCapabilityRuntimeAPI(DiscoveryExtension.DISCOVERY_PROVIDER_CAPABILITY, name, DiscoveryProvider.class); } final DiscoveryProvider discoveryProvider = new AggregateDiscoveryProvider(providers); mutableDiscoveryProvider.setDiscoveryProvider(discoveryProvider); } } else { mutableDiscoveryProvider.setDiscoveryProvider(DiscoveryProvider.EMPTY); } }
Source:
private static <AutoClosableWrapper extends AutoCloseable & Wrapper> void close(AutoClosableWrapper dbObject) { if (dbObject != null) { try { dbObject.close(); dbObject = null; } catch (SQLRecoverableException ex) { handleSQLRecoverableException(dbObject, ex, true); } catch (SQLException e) { log.error("Database error. Could not close statement. Continuing with others. - " + e.getMessage(), e); } catch (Exception e) { log.error("Generic error occurred during close operation" + e.getMessage(), e); } } }

Target:
private static <AutoClosableWrapper extends AutoCloseable & Wrapper> void close(AutoClosableWrapper dbObject) { if (dbObject != null) { try { dbObject.close(); } catch (SQLRecoverableException ex) { handleSQLRecoverableException(dbObject, ex); } catch (SQLException e) { log.error("Database error. Could not close statement. Continuing with others. - " + e.getMessage(), e); } catch (Exception e) { log.error("An unknown error occurred during close operation" + e.getMessage(), e); } finally { dbObject = null; } } }
Source:
public @Nullable Integer getThreadOnCpuAtTime(int cpu, long time) { ITmfStateSystem stateSystem = getStateSystem(); if (stateSystem == null) { return null; } Integer tid = null; if (time < stateSystem.getStartTime() || time > stateSystem.getCurrentEndTime()) { return tid; } try { int cpuQuark = stateSystem.optQuarkAbsolute(Integer.toString(cpu)); if (cpuQuark == ITmfStateSystem.INVALID_ATTRIBUTE) { return null; } ITmfStateValue value = stateSystem.querySingleState(time, cpuQuark).getStateValue(); if (value.getType().equals(Type.INTEGER)) { tid = value.unboxInt(); } } catch (StateSystemDisposedException e) { Activator.getDefault().logError(NonNullUtils.nullToEmptyString(e.getMessage()), e); } return tid; }

Target:
public @Nullable Integer getThreadOnCpuAtTime(int cpu, long time) { ITmfStateSystem stateSystem = getStateSystem(); if (stateSystem == null) { return null; } if (time < stateSystem.getStartTime()) { return null; } Integer tid = null; try { int cpuQuark = stateSystem.optQuarkAbsolute(Integer.toString(cpu)); if (cpuQuark == ITmfStateSystem.INVALID_ATTRIBUTE) { return null; } ITmfStateValue value = stateSystem.querySingleState(time, cpuQuark).getStateValue(); if (value.getType().equals(Type.INTEGER)) { tid = value.unboxInt(); } } catch (StateSystemDisposedException | TimeRangeException e) { Activator.getDefault().logError(NonNullUtils.nullToEmptyString(e.getMessage()), e); } return tid; }
Source:
protected ArrayList<Object> doProjection(Tuple tuple1, Tuple tuple2) { if(streamLineProjection) return doStreamlineProjection(tuple1, tuple2); ArrayList<Object> result = new ArrayList<>(outputFields.length); for ( int i = 0; i < outputFields.length; i++ ) { FieldSelector outField = outputFields[i]; Object field = findField(outField, tuple1) ; if (field==null) field = findField(outField, tuple2); result.add(field); } return result; }

Target:
protected List<Object> doProjection(Tuple tuple1, Tuple tuple2) { ArrayList<Object> result = new ArrayList<>(outputFields.length); for ( int i = 0; i < outputFields.length; i++ ) { FieldSelector outField = outputFields[i]; Object field = outField.findField(tuple1) ; if (field==null) field = outField.findField(tuple2); result.add(field); } return result; }
Source:
public void remove() { if (!config.hasRequiredAdminProps()) { throw new IllegalArgumentException("Admin configuration is missing required properties"); } Preconditions.checkArgument( !ZookeeperUtil.parseRoot(config.getInstanceZookeepers()).equals("/"), "The Zookeeper connection string (set by 'fluo.connection.zookeepers') " + " must have a chroot suffix."); if (OracleServerUtils.oracleExists(getAppCurator())) { throw new FluoException("You must stop the oracle server to remove an application"); } Connector conn = AccumuloUtil.getConnector(config); boolean tableExists = conn.tableOperations().exists(config.getAccumuloTable()); if (tableExists) { logger.info("The Accumulo table '{}' will be dropped", config.getAccumuloTable()); try { conn.tableOperations().delete(config.getAccumuloTable()); } catch (Exception e) { throw new RuntimeException(e); } } try { if (rootCurator.checkExists().forPath(appRootDir) != null) { logger.info("Clearing Fluo '{}' application in Zookeeper at {}", config.getApplicationName(), config.getAppZookeepers()); rootCurator.delete().deletingChildrenIfNeeded().forPath(appRootDir); } } catch (KeeperException.NoNodeException nne) { } catch (Exception e) { logger.error("An error occurred deleting Zookeeper root of [" + config.getAppZookeepers() + "], error=[" + e.getMessage() + "]"); throw new RuntimeException(e); } }

Target:
public void remove() { if (!config.hasRequiredAdminProps()) { throw new IllegalArgumentException("Admin configuration is missing required properties"); } Preconditions.checkArgument( !ZookeeperUtil.parseRoot(config.getInstanceZookeepers()).equals("/"), "The Zookeeper connection string (set by 'fluo.connection.zookeepers') " + " must have a chroot suffix."); if (OracleServerUtils.oracleExists(getAppCurator())) { throw new FluoException("Must stop the oracle server to remove an application"); } Connector conn = AccumuloUtil.getConnector(config); boolean tableExists = conn.tableOperations().exists(config.getAccumuloTable()); if (tableExists) { logger.info("The Accumulo table '{}' will be dropped", config.getAccumuloTable()); try { conn.tableOperations().delete(config.getAccumuloTable()); } catch (Exception e) { throw new RuntimeException(e); } } try { if (rootCurator.checkExists().forPath(appRootDir) != null) { logger.info("Clearing Fluo '{}' application in Zookeeper at {}", config.getApplicationName(), config.getAppZookeepers()); rootCurator.delete().deletingChildrenIfNeeded().forPath(appRootDir); } } catch (KeeperException.NoNodeException nne) { } catch (Exception e) { logger.error("An error occurred deleting Zookeeper root of [" + config.getAppZookeepers() + "], error=[" + e.getMessage() + "]"); throw new RuntimeException(e); } }
Source:
public void testExecute_curlLoggerWithContentEncoding() throws Exception { LogRecordingHandler recorder = new LogRecordingHandler(); HttpTransport.LOGGER.setLevel(Level.CONFIG); HttpTransport.LOGGER.addHandler(recorder); String contentValue = "hello"; byte[] bytes = StringUtils.getBytesUtf8(contentValue); InputStreamContent content = new InputStreamContent( new HttpMediaType("text/plain").setCharsetParameter(Charsets.UTF_8).build(), new ByteArrayInputStream(bytes)); new MockHttpTransport() .createRequestFactory() .buildPostRequest(new GenericUrl("<LINK_0>'b'c"), content) .setEncoding(new GZipEncoding()) .execute(); boolean found = false; for (String message : recorder.messages()) { if (message.startsWith("curl")) { found = true; assert(message.contains("curl -v --compressed -X POST -H 'Accept-Encoding: gzip'")); assert(message.contains("-H 'User-Agent: " + HttpRequest.USER_AGENT_SUFFIX + "'")); assert(message.contains("-H 'Content-Type: text/plain; charset=UTF-8' -H 'Content-Encoding: gzip'")); assert(message.contains("-d '@-' -- '<LINK_0>'\"'\"'b'\"'\"'c' << $$$")); } } assertTrue(found); }

Target:
public void testExecute_curlLoggerWithContentEncoding() throws Exception { LogRecordingHandler recorder = new LogRecordingHandler(); HttpTransport.LOGGER.setLevel(Level.CONFIG); HttpTransport.LOGGER.addHandler(recorder); String contentValue = "hello"; byte[] bytes = StringUtils.getBytesUtf8(contentValue); InputStreamContent content = new InputStreamContent( new HttpMediaType("text/plain").setCharsetParameter(Charsets.UTF_8).build(), new ByteArrayInputStream(bytes)); new MockHttpTransport() .createRequestFactory() .buildPostRequest(new GenericUrl("<LINK_0>'b'c"), content) .setEncoding(new GZipEncoding()) .execute(); boolean found = false; for (String message : recorder.messages()) { if (message.startsWith("curl")) { found = true; assertTrue(message.contains("curl -v --compressed -X POST -H 'Accept-Encoding: gzip'")); assertTrue(message.contains("-H 'User-Agent: " + HttpRequest.USER_AGENT_SUFFIX + "'")); assertTrue(message.contains("-H 'Content-Type: text/plain; charset=UTF-8' -H 'Content-Encoding: gzip'")); assertTrue(message.contains("-d '@-' -- '<LINK_0>'\"'\"'b'\"'\"'c' << $$$")); } } assertTrue(found); }
Source:
private void handleUnmanagedCommands() { List<AsyncTask> asyncTasks = asyncTaskDao.getAll(); Set<Guid> asyncTaskManagerManagedCommands = asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getRootCommandId()).collect(Collectors.toSet()); asyncTaskManagerManagedCommands.addAll(asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getCommandId()).collect(Collectors.toSet())); ENDED_WITH_FAILURE. getCommands(false).stream() .filter(x -> !x.isCallbackEnabled()) .filter(x -> x.getCommandStatus() == CommandStatus.ACTIVE) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> commandsCache.updateCommandStatus(x.getId(), CommandStatus.ENDED_WITH_FAILURE)); getCommands(false).stream() .filter(x -> x.isCallbackEnabled()) .filter(x -> x.getCommandStatus().isDuringExecution()) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> retrieveCommand(x.getId()).reacquireLocks()); }

Target:
private void handleUnmanagedCommands() { List<AsyncTask> asyncTasks = asyncTaskDao.getAll(); Set<Guid> asyncTaskManagerManagedCommands = asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getRootCommandId()).collect(Collectors.toSet()); asyncTaskManagerManagedCommands.addAll(asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getCommandId()).collect(Collectors.toSet())); ENDED_WITH_FAILURE. getCommands(false).stream() .filter(x -> !x.isCallbackEnabled()) .filter(x -> x.getCommandStatus() == CommandStatus.ACTIVE) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> commandsCache.updateCommandStatus(x.getId(), CommandStatus.ENDED_WITH_FAILURE)); getCommands(false).stream() .filter(x -> x.isCallbackEnabled()) .filter(x -> !x.isCallbackNotified()) .filter(x -> x.getCommandStatus().isDuringExecution()) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> retrieveCommand(x.getId()).reacquireLocks()); }
Source:
private ConfigNodeInclude parseInclude(ArrayList<AbstractConfigNode> children) { Token t = nextTokenIgnoringWhitespace(children); if (Tokens.isUnquotedText(t)) { String kind = Tokens.getUnquotedText(t); if (kind.equals("url(")) { } else if (kind.equals("file(")) { } else if (kind.equals("classpath(")) { } else { throw parseError("expecting include parameter to be quoted filename, file(), classpath(), or url(). No spaces are allowed before the open paren. Not expecting: " + t); } children.add(new ConfigNodeSingleToken(t)); t = nextTokenIgnoringWhitespace(children); String name; if (!Tokens.isValueWithType(t, ConfigValueType.STRING)) { throw parseError("expecting a quoted string inside file(), classpath(), or url(), rather than: " + t); } children.add(new ConfigNodeSimpleValue(t)); t = nextTokenIgnoringWhitespace(children); if (Tokens.isUnquotedText(t) && Tokens.getUnquotedText(t).equals(")")) { } else { throw parseError("expecting a close parentheses ')' here, not: " + t); } } else if (Tokens.isValueWithType(t, ConfigValueType.STRING)) { children.add(new ConfigNodeSimpleValue(t)); } else { throw parseError("include keyword is not followed by a quoted string, but by: " + t); } return new ConfigNodeInclude(children); }

Target:
private ConfigNodeInclude parseInclude(ArrayList<AbstractConfigNode> children) { Token t = nextTokenCollectingWhitespace(children); if (Tokens.isUnquotedText(t)) { String kindText = Tokens.getUnquotedText(t); ConfigIncludeKind kind; if (kindText.equals("url(")) { kind = ConfigIncludeKind.URL; } else if (kindText.equals("file(")) { kind = ConfigIncludeKind.FILE; } else if (kindText.equals("classpath(")) { kind = ConfigIncludeKind.CLASSPATH; } else { throw parseError("expecting include parameter to be quoted filename, file(), classpath(), or url(). No spaces are allowed before the open paren. Not expecting: " + t); } children.add(new ConfigNodeSingleToken(t)); t = nextTokenCollectingWhitespace(children); String name; if (!Tokens.isValueWithType(t, ConfigValueType.STRING)) { throw parseError("expecting a quoted string inside file(), classpath(), or url(), rather than: " + t); } children.add(new ConfigNodeSimpleValue(t)); t = nextTokenCollectingWhitespace(children); if (Tokens.isUnquotedText(t) && Tokens.getUnquotedText(t).equals(")")) { } else { throw parseError("expecting a close parentheses ')' here, not: " + t); } return new ConfigNodeInclude(children, kind); } else if (Tokens.isValueWithType(t, ConfigValueType.STRING)) { children.add(new ConfigNodeSimpleValue(t)); return new ConfigNodeInclude(children, ConfigIncludeKind.HEURISTIC); } else { throw parseError("include keyword is not followed by a quoted string, but by: " + t); } }
Source:
private void deployJob(CuratorFramework client, final Job job) throws InterruptedException { if (job != null) { ModuleDeploymentPropertiesProvider provider = new JobModuleDeploymentPropertiesProvider(job); List<ModuleDescriptor> descriptors = new ArrayList<ModuleDescriptor>(); descriptors.add(job.getJobModuleDescriptor()); try { Collection<ModuleDeploymentStatus> deploymentStatus = moduleDeploymentWriter.writeDeployment(descriptors.iterator(), provider); DeploymentUnitStatus status = stateCalculator.calculate(job, provider, deploymentStatus); logger.warn("Deployment state for job: {}", status); client.setData().forPath( Paths.build(Paths.JOB_DEPLOYMENTS, job.getName(), Paths.STATUS), ZooKeeperUtils.mapToBytes(status.toMap())); } catch (NoContainerException e) { logger.warn("No containers available for deployment of job {}", job.getName()); } catch (InterruptedException e) { throw e; } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } } }

Target:
private void deployJob(CuratorFramework client, final Job job) throws InterruptedException { if (job != null) { String statusPath = Paths.build(Paths.JOB_DEPLOYMENTS, job.getName(), Paths.STATUS); DeploymentUnitStatus deployingStatus = null; try { deployingStatus = new DeploymentUnitStatus(ZooKeeperUtils.bytesToMap( client.getData().forPath(statusPath))); } catch (Exception e) { } Assert.state(deployingStatus != null && deployingStatus.getState() == DeploymentUnitStatus.State.deploying, String.format("Expected 'deploying' status for job '%s'; current status: %s", job.getName(), deployingStatus)); ModuleDeploymentPropertiesProvider provider = new JobModuleDeploymentPropertiesProvider(job); List<ModuleDescriptor> descriptors = new ArrayList<ModuleDescriptor>(); descriptors.add(job.getJobModuleDescriptor()); try { Collection<ModuleDeploymentStatus> deploymentStatus = moduleDeploymentWriter.writeDeployment(descriptors.iterator(), provider); DeploymentUnitStatus status = stateCalculator.calculate(job, provider, deploymentStatus); logger.info("Deployment status for job '{}': {}", job.getName(), status); client.setData().forPath(statusPath, ZooKeeperUtils.mapToBytes(status.toMap())); } catch (NoContainerException e) { logger.warn("No containers available for deployment of job {}", job.getName()); } catch (InterruptedException e) { throw e; } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } } }