auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Address[] getRecipients(RecipientType type) { switch (type) { case TO: { if (mTo == null) { mTo = Address.parse(MimeUtility.unfold(getFirstHeader("To"))); } return mTo; } case CC: { if (mCc == null) { mCc = Address.parse(MimeUtility.unfold(getFirstHeader("CC"))); } return mCc; } case BCC: { if (mBcc == null) { mBcc = Address.parse(MimeUtility.unfold(getFirstHeader("BCC"))); } return mBcc; } case RESENT_TO: { if (mResentTo == null) { mResentTo = Address.parse(MimeUtility.unfold(getFirstHeader("Resent-To"))); } return mTo; } case RESENT_CC: { if (mResentCc == null) { mResentCc = Address.parse(MimeUtility.unfold(getFirstHeader("Resent-CC"))); } return mCc; } case RESENT_BCC: { if (mResentBcc == null) { mResentBcc = Address.parse(MimeUtility.unfold(getFirstHeader("Resent-BCC"))); } return mBcc; } } throw new IllegalArgumentException("Unrecognized recipient type."); }

Target:
public Address[] getRecipients(RecipientType type) { switch (type) { case TO: { if (mTo == null) { mTo = Address.parse(MimeUtility.unfold(getFirstHeader("To"))); } return mTo; } case CC: { if (mCc == null) { mCc = Address.parse(MimeUtility.unfold(getFirstHeader("CC"))); } return mCc; } case BCC: { if (mBcc == null) { mBcc = Address.parse(MimeUtility.unfold(getFirstHeader("BCC"))); } return mBcc; } case RESENT_TO: { if (mResentTo == null) { mResentTo = Address.parse(MimeUtility.unfold(getFirstHeader("Resent-To"))); } return mResentTo; } case RESENT_CC: { if (mResentCc == null) { mResentCc = Address.parse(MimeUtility.unfold(getFirstHeader("Resent-CC"))); } return mResentCc; } case RESENT_BCC: { if (mResentBcc == null) { mResentBcc = Address.parse(MimeUtility.unfold(getFirstHeader("Resent-BCC"))); } return mResentBcc; } } throw new IllegalArgumentException("Unrecognized recipient type."); }
Source:
public static int hash( short[] values ) { final int max = values.length; int result = COEFFICIENTS[max]; for ( int i = 0; i < values.length && i < COEFFICIENTS.length - 1; ++i ) { result += COEFFICIENTS[max - i - 1] * values[i]; } return result; }

Target:
public static int hash( short[] values ) { final int max = Math.min( values.length, MAX_LENGTH ); int result = COEFFICIENTS[max]; for ( int i = 0; i < values.length && i < COEFFICIENTS.length - 1; ++i ) { result += COEFFICIENTS[max - i - 1] * values[i]; } return result; }
Source:
private static BulkObject getBlobFromPosition(final ImmutableMultimap<BulkObject, Range> blobs, final long position) { if (Guard.isMultiMapNullOrEmpty(blobs)) { return null; } for (final BulkObject bulkObject : blobs.keySet()) { if (bulkObject.getOffset() <= position && position <= (bulkObject.getOffset() + bulkObject.getLength() - 1)) { return bulkObject; } } return null; }

Target:
private static BulkObject getBlobFromPosition(final ImmutableMultimap<BulkObject, Range> blobs, final long position) { if (Guard.isMultiMapNullOrEmpty(blobs)) { return null; } for (final BulkObject bulkObject : blobs.keySet()) { if (bulkObject.getOffset() <= position && position < bulkObject.getOffset() + bulkObject.getLength()) { return bulkObject; } } return null; }
Source:
private void createPointCloudLayer() { PointCloudLayer pointCloudLayer = new PointCloudLayer( Environment.getExternalStorageDirectory() + getString(R.string.scene_layer_package_location)); pointCloudLayer.addLoadStatusChangedListener(loadStatusChangedEvent -> { if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.LOADED) { mScene.getOperationalLayers().add(pointCloudLayer); } else if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.FAILED_TO_LOAD) { Toast.makeText(this, R.string.point_cloud_layer_load_failure_message, Toast.LENGTH_LONG).show(); } }); pointCloudLayer.loadAsync(); }

Target:
private void createPointCloudLayer() { PointCloudLayer pointCloudLayer = new PointCloudLayer( Environment.getExternalStorageDirectory() + getString(R.string.scene_layer_package_location)); pointCloudLayer.addLoadStatusChangedListener(loadStatusChangedEvent -> { if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.LOADED) { mSceneView.getScene().getOperationalLayers().add(pointCloudLayer); } else if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.FAILED_TO_LOAD) { String error = getString(R.string.point_cloud_layer_load_failure_message); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); Log.e(TAG, error); } }); pointCloudLayer.loadAsync(); }
Source:
public void testTransformWhenFileIsNew() { final String fileName = "file.dmn"; final String xml = ""; final ServiceCallback<Diagram> callback = mock(ServiceCallback.class); final String title = "title"; doReturn(title).when(service).getDiagramTitle(fileName); doNothing().when(service).doNewDiagram(title, callback); service.transform(fileName, xml, callback); verify(service).doNewDiagram(title, callback); }

Target:
public void testTransformWhenFileIsNew() { final String fileName = "file.dmn"; final String xml = ""; final ServiceCallback<Diagram> callback = mock(ServiceCallback.class); final String title = "file"; doNothing().when(service).doNewDiagram(title, callback); service.transform(fileName, xml, callback); verify(service).doNewDiagram(title, callback); }
Source:
public void testValues() { int i; long[] values = { 0, 100, 1000, 1500, 64000, 124531, 3651782, 86400000, 86434349, 1075634299, 86480001 }; String[] expected = { "0 ms", "100 ms", "1.0 seconds", "1.500 seconds", "0:01:04", "0:02:04", "1:00:51", "1 day", "1 day", "12 days 10:47:14", "1 day 00:01:20" }; for (i = 0; i < values.length; i++) { assertEquals(expected[i], StringUtils.getReadableTime(values[i])); } }

Target:
public void testValues() { int i; long[] values = { 0, 100, 1000, 1500, 64000, 124531, 3651782, 86400000, 86434349, 1075634299, 86480001, 86400001 }; String[] expected = { "0 ms", "100 ms", "1.0 seconds", "1.500 seconds", "0:01:04", "0:02:04", "1:00:51", "1 day", "1 day", "12 days 10:47:14", "1 day 00:01:20", "1 day" }; for (i = 0; i < values.length; i++) { assertEquals(expected[i], StringUtils.getReadableTime(values[i])); } }
Source:
void killTopologyHandler(String topologyName) throws TopologyRuntimeManagementException { Scheduler.KillTopologyRequest killTopologyRequest = Scheduler.KillTopologyRequest.newBuilder() .setTopologyName(topologyName).build(); if (!schedulerClient.killTopology(killTopologyRequest)) { throw new TopologyRuntimeManagementException( String.format("Failed to kill topology '%s' with scheduler, " + "please re-try the kill command later", topologyName)); } cleanState(topologyName, Runtime.schedulerStateManagerAdaptor(runtime)); if (foundData) { LOG.fine(String.format("Scheduler killed topology %s successfully.", topologyName)); } else { LOG.warning(String.format("Topology %s data is not found, but scheduler has tried to" + " clean up data for it anyway.", topologyName)); } }

Target:
void killTopologyHandler(String topologyName) throws TopologyRuntimeManagementException { Scheduler.KillTopologyRequest killTopologyRequest = Scheduler.KillTopologyRequest.newBuilder() .setTopologyName(topologyName).build(); if (!schedulerClient.killTopology(killTopologyRequest)) { throw new TopologyRuntimeManagementException( String.format("Failed to kill topology '%s' with scheduler, " + "please re-try the kill command later", topologyName)); } cleanState(topologyName, Runtime.schedulerStateManagerAdaptor(runtime)); if (potentialStaleExecutionData) { LOG.warning(String.format("Topology %s does not exist. Cleaned up potential stale state.", topologyName)); } else { LOG.fine(String.format("Scheduler killed topology %s successfully.", topologyName)); } }
Source:
public void updateAllRevisionDatasetsEntries(String globalId, String schema, String version, Revision revision) throws RepresentationNotExistsException { Representation rep = recordDAO.getRepresentation(globalId, schema, version); if (rep == null) throw new RepresentationNotExistsException(schema); Collection<CompoundDataSetId> dataSets = dataSetDAO.getDataSetAssignments(globalId, schema, version); for (CompoundDataSetId dsID : dataSets) { String datasetName = dsID.getDataSetId(); String datasetProvider = dsID.getDataSetProviderId(); String revisionId = RevisionUtils.getRevisionKey(revision); dataSetDAO.insertProviderDatasetRepresentationInfo(datasetName, datasetProvider, globalId, version, schema, revisionId, revision.getUpdateTimeStamp(), revision.isAcceptance(), revision.isPublished(), revision.isDeleted()); dataSetDAO.insertLatestProviderDatasetRepresentationInfo(datasetName, datasetProvider, globalId, schema, revision.getRevisionName(), revision.getRevisionProviderId(), revision.getUpdateTimeStamp(), version, revision.isAcceptance(), revision.isPublished(), revision.isDeleted()); dataSetDAO.addDataSetsRevision(datasetProvider, datasetName, revisionId, schema, globalId); } }

Target:
public void updateAllRevisionDatasetsEntries(String globalId, String schema, String version, Revision revision) throws RepresentationNotExistsException { Representation rep = recordDAO.getRepresentation(globalId, schema, version); if (rep == null) throw new RepresentationNotExistsException(schema); Collection<CompoundDataSetId> dataSets = dataSetDAO.getDataSetAssignments(globalId, schema, version); for (CompoundDataSetId dsID : dataSets) { String datasetName = dsID.getDataSetId(); String datasetProvider = dsID.getDataSetProviderId(); String revisionId = RevisionUtils.getRevisionKey(revision); dataSetDAO.insertProviderDatasetRepresentationInfo(datasetName, datasetProvider, globalId, version, schema, revisionId, revision.getUpdateTimeStamp(), revision.isAcceptance(), revision.isPublished(), revision.isDeleted()); dataSetDAO.insertLatestProviderDatasetRepresentationInfo(datasetName, datasetProvider, globalId, schema, revision.getRevisionName(), revision.getRevisionProviderId(), revision.getUpdateTimeStamp(), version, revision.isAcceptance(), revision.isPublished(), revision.isDeleted()); dataSetDAO.addDataSetsRevision(datasetProvider, datasetName, revisionId, schema, globalId); dataSetDAO.addLatestRevisionForDatasetAssignment(dataSetDAO.getDataSet(datasetProvider, datasetName), rep, revision); } }
Source:
public DSpaceCSVLine resolveEntityRefs(DSpaceCSVLine line) throws MetadataImportException { DSpaceCSVLine newLine = new DSpaceCSVLine(line.getID()); for (String key : line.keys()) { if (key.split("\\.")[0].equalsIgnoreCase("relation")) { if (line.get(key).size() > 0) { for (String val : line.get(key)) { String uuid = resolveEntityRef(c, val).toString(); newLine.add(key, uuid); } } } else { if (line.get(key).size() > 1) { for (String value : line.get(key)) { newLine.add(key, value); } } else { newLine.add(key, line.get(key).get(0)); } } } return newLine; }

Target:
public DSpaceCSVLine resolveEntityRefs(DSpaceCSVLine line) throws MetadataImportException { DSpaceCSVLine newLine = new DSpaceCSVLine(line.getID()); for (String key : line.keys()) { if (key.split("\\.")[0].equalsIgnoreCase("relation")) { if (line.get(key).size() > 0) { for (String val : line.get(key)) { String uuid = resolveEntityRef(c, val).toString(); newLine.add(key, uuid); } } } else { if (line.get(key).size() > 1) { for (String value : line.get(key)) { newLine.add(key, value); } } else { if (line.get(key).size() > 0) { newLine.add(key, line.get(key).get(0)); } } } } return newLine; }
Source:
protected DockerResponse request(String method, String path, String query, List<Pair<String, ?>> headers, Entity entity) throws IOException { final String requestUri = path + (Strings.isNullOrEmpty(query) ? "" : "?" + query); final URL url = baseUri.resolve(requestUri).toURL(); final String protocol = url.getProtocol(); connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); if ("https".equals(protocol)) { ((HttpsURLConnection)connection).setSSLSocketFactory(certificates.getSslContext().getSocketFactory()); } connection.setRequestMethod(method); connection.setRequestProperty("Connection", "close"); for (Pair<String, ?> header : headers) { connection.setRequestProperty(header.first, String.valueOf(header.second)); } connection.setRequestProperty("Host", url.toString()); if (entity != null) { connection.setDoOutput(true); try (OutputStream output = connection.getOutputStream()) { entity.writeTo(output); } } return new TcpDockerResponse(connection); }

Target:
protected DockerResponse request(String method, String path, String query, List<Pair<String, ?>> headers, Entity entity) throws IOException { final String requestUri = path + (Strings.isNullOrEmpty(query) ? "" : "?" + query); final URL url = baseUri.resolve(requestUri).toURL(); final String protocol = url.getProtocol(); connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); if ("https".equals(protocol)) { ((HttpsURLConnection)connection).setSSLSocketFactory(certificates.getSslContext().getSocketFactory()); } connection.setRequestMethod(method); connection.setRequestProperty("Connection", "close"); for (Pair<String, ?> header : headers) { connection.setRequestProperty(header.first, String.valueOf(header.second)); } String host = url.getHost(); if (url.getPort() != -1) { host += ":" + Integer.toString(url.getPort()); } connection.setRequestProperty("Host", host); if (entity != null) { connection.setDoOutput(true); try (OutputStream output = connection.getOutputStream()) { entity.writeTo(output); } } return new TcpDockerResponse(connection); }
Source:
public TMSKeyBuilder(final String prefix, TileLayerDispatcher layers) { this.prefix = Strings.isNullOrEmpty(prefix) ? "" : prefix + "/"; this.layers = layers; }

Target:
public TMSKeyBuilder(final String prefix, TileLayerDispatcher layers) { this.prefix = prefix; this.layers = layers; }
Source:
public static <T> Set<T> of(T e1, T e2, T e3, T e4, T e5) { final Set<T> set = new HashSet<>(5); set.add(e1); set.add(e2); set.add(e3); set.add(e4); set.add(e5); return set; }

Target:
public static <T> Set<T> of(T e1, T e2, T e3, T e4, T e5) { final Set<T> set = new HashSet<>(5); set.add(e1); set.add(e2); set.add(e3); set.add(e4); set.add(e5); return unmodifiableSet(set); }
Source:
public void close() { cancelTimer.cancel(); protoConnection.close(); openStackTrace = null; }

Target:
public void close() { protoConnection.close(); openStackTrace = null; timerLoan.release(); }
Source:
public void setSecurityProvider(SecurityProvider securityProvider) { if (securityProvider != null) { this.securityProvider = securityProvider; } else { this.securityProvider = (keyId) -> Security.getProvider("SunRsaSign"); } }

Target:
public final void setSecurityProvider(SecurityProvider securityProvider) { this.securityProvider = Objects.requireNonNull(securityProvider, "security provider cannot be null"); }
Source:
public void run() { final Tile tile = tileQueue.remove(); int remainingAttempts = 3; while (!tile.isLoaded() && remainingAttempts > 0) { remainingAttempts--; try { URI uri = getURI(tile); BufferedImage img = cache.get(uri); if (img == null) { img = getImage(uri); } if (img != null) { addImageToTile(tile, img); } } catch (OutOfMemoryError memErr) { cache.needMoreMemory(); } catch (Exception ex) { if (remainingAttempts == 0) { logger.log(Level.SEVERE, String.format("Failed to load a tile at URL: %s, stopping", tile.getURL()), ex); } else { logger.log(Level.WARNING, "Failed to load a tile at URL: " + tile.getURL() + ", retrying", ex); } } } tile.setLoading(false); }

Target:
public void run() { final Tile tile = tileQueue.remove(); int remainingAttempts = 3; while (!tile.isLoaded() && remainingAttempts > 0) { remainingAttempts--; try { URI uri = getURI(tile); BufferedImage img = cache.get(uri); if (img == null) { img = getImage(uri); } if (img != null) { addImageToTile(tile, img); } } catch (OutOfMemoryError memErr) { cache.needMoreMemory(); } catch (IOException | GeoLocationDataException | InterruptedException | InvocationTargetException | URISyntaxException ex) { if (remainingAttempts == 0) { logger.log(Level.SEVERE, String.format("Failed to load a tile at URL: %s, stopping", tile.getURL()), ex); } else { logger.log(Level.WARNING, "Failed to load a tile at URL: " + tile.getURL() + ", retrying", ex); } } } tile.setLoading(false); }
Source:
private static boolean canMatchPacket(final ITmfEvent event) { ITmfEventField content = event.getContent(); if ((content.getField(TcpEventStrings.SEQ) != null) && (content.getField(TcpEventStrings.ACKSEQ) != null) && (content.getField(TcpEventStrings.FLAGS) != null)) { return true; } return false; }

Target:
private static boolean canMatchPacket(final ITmfEvent event) { ITmfEventField content = event.getContent(); if ((content.getFieldValue(Long.class, TcpEventStrings.SEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.ACKSEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.FLAGS) == null)) { return false; } return true; }
Source:
private <V> ListenableFuture<V> runAsyncInternal(String callableName, RetryStats stats, Callable<ListenableFuture<V>> callable, RetryStatus retryStatus) { retryStatus.nextAttempt(); ListenableFuture<V> resultFuture; try { resultFuture = callable.call(); Futures.addCallback(resultFuture, new FutureCallback() { @Override public void onSuccess(@Nullable Object result) { stats.addSuccess(); stats.addAttemptsBeforeSuccess(retryStatus.getAttempts()); stats.addSuccessLatency(retryStatus.getDuration()); } @Override public void onFailure(Throwable t) { } }); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw propagate(retryStatus, stats, ie); } catch (Exception e) { resultFuture = immediateFailedFuture(e); } return Futures.catchingAsync(resultFuture, Exception.class, e -> { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); throw propagate(retryStatus, stats, e); } else if (retryStatus.shouldStopRetry(e)) { throw propagate(retryStatus, stats, e); } log.warn(e, "Failed on executing %s with attempt %d, will perform async retry.", callableName, retryStatus.getAttempts()); return Futures.dereference(retryExecutorService.schedule(() -> runAsyncInternal(callableName, stats, callable, retryStatus), retryStatus.getRetryDelayInMs(), MILLISECONDS)); }); }

Target:
private <V> ListenableFuture<V> runAsyncInternal(String callableName, RetryStats stats, Callable<ListenableFuture<V>> callable, RetryStatus retryStatus) { retryStatus.nextAttempt(); ListenableFuture<V> resultFuture; try { resultFuture = callable.call(); Futures.addCallback(resultFuture, new FutureCallback<V>() { @Override public void onSuccess(@Nullable V result) { stats.addSuccess(); stats.addAttemptsBeforeSuccess(retryStatus.getAttempts()); stats.addSuccessLatency(retryStatus.getDuration()); } @Override public void onFailure(Throwable t) }); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); recordFailure(retryStatus, stats); throw propagate(ie); } catch (Exception e) { resultFuture = immediateFailedFuture(e); } return Futures.catchingAsync(resultFuture, Exception.class, e -> { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); recordFailure(retryStatus, stats); throw propagate(e); } else if (retryStatus.shouldStopRetry(e)) { recordFailure(retryStatus, stats); throw propagate(e); } log.warn(e, "Failed on executing %s with attempt %d, will perform async retry.", callableName, retryStatus.getAttempts()); return Futures.dereference(retryExecutorService.schedule(() -> runAsyncInternal(callableName, stats, callable, retryStatus), retryStatus.getRetryDelayInMs(), MILLISECONDS)); }); }
Source:
public void testFLTRepeatability() { TmfTimestampTransformLinearFast fast = new TmfTimestampTransformLinearFast(Math.PI, 0); long deltaMax = getPrivateFieldLong(fast, "fDeltaMax"); long timestamp = ts - (ts % deltaMax); fast.transform(timestamp); long tsMiss = timestamp + deltaMax; long tsNoMiss = timestamp + deltaMax - 1; long tsTNoMiss = fast.transform(tsNoMiss); assertEquals(1, fast.getCacheMisses()); fast.transform(tsMiss); assertEquals(2, fast.getCacheMisses()); long tsTAfterMiss = fast.transform(tsNoMiss); assertEquals(tsTNoMiss, tsTAfterMiss); }

Target:
public void testFLTRepeatability() { TmfTimestampTransformLinearFast fast = new TmfTimestampTransformLinearFast(Math.PI, 0); long deltaMax = fast.getDeltaMax(); long timestamp = ts - (ts % deltaMax); fast.transform(timestamp); long tsMiss = timestamp + deltaMax; long tsNoMiss = timestamp + deltaMax - 1; long tsTNoMiss = fast.transform(tsNoMiss); assertEquals(1, fast.getCacheMisses()); fast.transform(tsMiss); assertEquals(2, fast.getCacheMisses()); long tsTAfterMiss = fast.transform(tsNoMiss); assertEquals(tsTNoMiss, tsTAfterMiss); }
Source:
public synchronized void setDDFName(DDF ddf, String name) throws DDFException { synchronized (ddf) { if (!Strings.isNullOrEmpty(name)) { if (!Strings.isNullOrEmpty(ddf.getName())) { this.mUris.remove(ddf.getUri()); } ddf.setName(name); mDDFCache.invalidate(ddf.getUUID()); mDDFwithNameCache.put(ddf.getUUID(), ddf); this.mUris.put(ddf.getUri(), ddf.getUUID()); } else { throw new DDFException(String.format("DDF's name cannot be null or empty")); } } }

Target:
public void setDDFName(DDF ddf, String name) throws DDFException { Lock lock = uuidLocks.get(ddf.getUUID()); try { if(lock.tryLock(120, TimeUnit.SECONDS)) { try { if (!Strings.isNullOrEmpty(name)) { if (!Strings.isNullOrEmpty(ddf.getName())) { this.mUris.remove(ddf.getUri()); } ddf.setName(name); mDDFCache.invalidate(ddf.getUUID()); mDDFwithNameCache.put(ddf.getUUID(), ddf); this.mUris.put(ddf.getUri(), ddf.getUUID()); } else { throw new DDFException(String.format("DDF's name cannot be null or empty")); } } finally { lock.unlock(); } } else { throw new DDFException("Timeout setting DDF name"); } } catch (Exception e) { throw new DDFException(e); } }
Source:
protected void addValue(int val) throws IOException { if (!endBuffer.hasRemaining()) { endBuffer.rewind(); flattener.write(StupidResourceHolder.create(endBuffer)); endBuffer.rewind(); } endBuffer.put(val); numInserted++; }

Target:
protected void addValue(int val) throws IOException { if (!endBuffer.hasRemaining()) { endBuffer.rewind(); flattener.write(StupidResourceHolder.create(endBuffer)); endBuffer = IntBuffer.allocate(chunkFactor); } endBuffer.put(val); numInserted++; }
Source:
@Test public void testIteratorRemoveDisallowsConcurrentModification() throws IOException { QueueFile queueFile = new QueueFile(file); for (int i = 0; i < 15; i++) { queueFile.add(values[i]); } Iterator<byte[]> iterator = queueFile.iterator(); iterator.next(); queueFile.remove(); try { iterator.remove(); fail("remove should not permit concurrent modifications."); } catch (ConcurrentModificationException ignored) { } }

Target:
@Test public void testIteratorRemoveDisallowsConcurrentModification() throws IOException { QueueFile queueFile = new QueueFile(file); for (int i = 0; i < 15; i++) { queueFile.add(values[i]); } Iterator<byte[]> iterator = queueFile.iterator(); iterator.next(); queueFile.remove(); try { iterator.remove(); fail(); } catch (ConcurrentModificationException ignored) { } }
Source:
public static String setUserSessionBaseUrl(final HttpSession session) { String resultBaseUrl; final String hashedBaseUrl = (String) session.getAttribute("BASE_URL"); if (hashedBaseUrl == null) { resultBaseUrl = JiraTimetrackerAnalytics.getBaseUrl(); session.setAttribute("BASE_URL", resultBaseUrl); } else { resultBaseUrl = hashedBaseUrl; } return resultBaseUrl; }

Target:
public static String setUserSessionBaseUrl(final HttpSession session) { String resultBaseUrl; String hashedBaseUrl = (String) session.getAttribute(BASE_URL); if (hashedBaseUrl == null) { resultBaseUrl = JiraTimetrackerAnalytics.getBaseUrl(); session.setAttribute(BASE_URL, resultBaseUrl); } else { resultBaseUrl = hashedBaseUrl; } return resultBaseUrl; }
Source:
protected static void closeStmt(Statement stmt) { try { if (stmt != null && !stmt.isClosed()) { stmt.close(); } } catch (SQLException e) { LOG.warn("Failed to close statement " + e.getMessage()); } }

Target:
private static void closeStmt(Statement stmt) { try { if (stmt != null && !stmt.isClosed()) { stmt.close(); } } catch (SQLException e) { LOG.warn("Failed to close statement " + e.getMessage()); } }
Source:
private void unindicatePanelLoading(RepoOpenedEvent e) { togglePanelLoading(e.isPrimaryRepo, e.repoId, false); }

Target:
private void unindicatePanelLoading(RepoOpenedEvent e) { if (isIndicatorApplicable(e.isPrimaryRepo)) { removePanelLoadingIndication(); } }
Source:
public void add(VObject aVobj) { if (aVobj instanceof VSpan) { add((VSpan) aVobj); } else if (aVobj instanceof VArc) { add((VArc) aVobj); } }

Target:
public void add(VObject aVobj) { if (aVobj instanceof VSpan) { add((VSpan) aVobj); } else if (aVobj instanceof VArc) { add((VArc) aVobj); } else { throw new IllegalArgumentException("VObject is neither VSpan nor VArc."); } }
Source:
private UUID mapType(int type, int val) throws SQLException { if (type == Constants.COMMUNITY) { Community comm = communityService.findByLegacyId(context, val); return comm == null ? null : comm.getID(); } if (type == Constants.COLLECTION) { org.dspace.content.Collection coll = collectionService.findByLegacyId(context, val); return coll == null ? null : coll.getID(); } if (type == Constants.ITEM) { Item item = itemService.findByLegacyId(context, val); return item == null ? null : item.getID(); } if (type == Constants.BITSTREAM) { Bitstream bit = bitstreamService.findByLegacyId(context, val); return bit == null ? null : bit.getID(); } return null; }

Target:
private UUID mapType(int type, int val) throws SQLException { if (type == Constants.COMMUNITY) { Community comm = communityService.findByLegacyId(context, val); return comm == null ? null : comm.getID(); } if (type == Constants.COLLECTION) { org.dspace.content.Collection coll = collectionService.findByLegacyId(context, val); return coll == null ? null : coll.getID(); } if (type == Constants.ITEM) { Item item = itemService.findByLegacyId(context, val); checkLastItem(item); return item == null ? null : item.getID(); } if (type == Constants.BITSTREAM) { Bitstream bit = bitstreamService.findByLegacyId(context, val); UUID uuid = bit == null ? null : bit.getID(); checkLastBitstream(bit); return uuid; } return null; }
Source:
public static byte[] createHeightScriptData(final int height, final int numberOfBytes) { final int maxNumberOfBytes = 4; checkArgument(numberOfBytes <= maxNumberOfBytes); final byte[] int32Buffer = ByteBuffer.allocate(maxNumberOfBytes).order(ByteOrder.LITTLE_ENDIAN).putInt(height).array(); if (numberOfBytes != maxNumberOfBytes) { return Arrays.copyOf(int32Buffer, numberOfBytes); } else { return int32Buffer; } }

Target:
public static byte[] createHeightScriptData(final int height, final int numberOfBytes) { final int maxNumberOfBytes = 4; checkArgument(numberOfBytes <= maxNumberOfBytes); final byte[] int32Buffer = ByteBuffer.allocate(maxNumberOfBytes).order(ByteOrder.LITTLE_ENDIAN).putInt(height).array(); if (numberOfBytes < maxNumberOfBytes) { return Arrays.copyOf(int32Buffer, numberOfBytes); } else { return int32Buffer; } }
Source:
public GlusterVolumeGlobalOptionsInfoReturn(Map<String, Object> innerMap) { super(innerMap); if (getStatus().code != GlusterConstants.CODE_SUCCESS) { return; } Map<String, Object> globalOptions = (Map<String, Object>) innerMap.get(OPTION_MAP); if (globalOptions != null && !globalOptions.isEmpty()) { for (String s : globalOptions.keySet()) { if (!"".equals(s) && !StringUtils.isEmpty(s)) { globalOptionList.add(s); } } } }

Target:
public GlusterVolumeGlobalOptionsInfoReturn(Map<String, Object> innerMap) { super(innerMap); if (getStatus().code != GlusterConstants.CODE_SUCCESS) { return; } Map<String, Object> globalOptions = (Map<String, Object>) innerMap.get(OPTION_MAP); if (globalOptions != null && !globalOptions.isEmpty()) { for (String s : globalOptions.keySet()) { if (!StringUtils.isEmpty(s)) { globalOptionList.add(s); } } } }
Source:
public void testForEachDict() throws Throwable { String schemeInputString = "(begin " + "(def x 0)" + "(foreach y " + " (let " + " ( " + " ($key " + " (call-yail-primitive yail-list-get-item " + " (*list-for-runtime* (lexical-value y) 1) '(list number) \"select list item\" " + " ) " + " ) " + " ($value " + " (call-yail-primitive yail-list-get-item " + " (*list-for-runtime* (lexical-value y) 2) '(list number) \"select list item\" " + " ) " + " ) " + " ) " + " (set-var! x " + " (call-yail-primitive + " + " (*list-for-runtime* (get-var x) (lexical-value $key) (lexical-value $value) )" + " '(number number number ) \"+\"" + " ) " + " ) " + " ) " + " (call-yail-primitive make-yail-dictionary " + " (*list-for-runtime* " + " (call-yail-primitive make-ke-dictionary-pair " + " (*list-for-runtime* 1 2 ) '(key any) \"make a pair\" " + " ) " + " (call-yail-primitive make-ke-dictionary-pair " + " (*list-for-runtime* 3 4 ) '(key any) \"make a pair\" " + " ) " + " )" + " ) '(pair pair ) \"make a dictionary\"" + " ) " + ") "; String schemeResultString = "10"; assertEquals(schemeResultString, scheme.eval(schemeInputString).toString()); }

Target:
public void testForEachDict() throws Throwable { String schemeInputString = "(begin " + "(def x 0) " + "(foreach y " + " (let " + " ( " + " ($key " + " (call-yail-primitive yail-list-get-item " + " (*list-for-runtime* (lexical-value y) 1) '(list number) \"select list item\" " + " ) " + " ) " + " ($value " + " (call-yail-primitive yail-list-get-item " + " (*list-for-runtime* (lexical-value y) 2) '(list number) \"select list item\" " + " ) " + " ) " + " ) " + " (set-var! x " + " (call-yail-primitive + " + " (*list-for-runtime* (get-var x) (lexical-value $key) (lexical-value $value) )" + " '(number number number ) \"+\"" + " ) " + " ) " + " ) " + " (call-yail-primitive make-yail-dictionary " + " (*list-for-runtime* " + " (call-yail-primitive make-dictionary-pair " + " (*list-for-runtime* 1 2 ) '(key any) \"make a pair\" " + " ) " + " (call-yail-primitive make-dictionary-pair " + " (*list-for-runtime* 3 4 ) '(key any) \"make a pair\" " + " ) " + " ) '(pair pair ) \"make a dictionary\"" + " ) " + " ) " + " (get-var x) " + ") "; String schemeResultString = "10"; assertEquals(schemeResultString, scheme.eval(schemeInputString).toString()); }
Source:
InMemorySpanStore(InMemoryStorage.Builder builder) { this.strictTraceId = builder.strictTraceId; this.metrics = builder.metrics == null ? StorageMetrics.NOOP_METRICS : builder.metrics; this.maxSpans = builder.maxSpans; }

Target:
InMemorySpanStore(InMemoryStorage.Builder builder) { this.strictTraceId = builder.strictTraceId; this.maxSpanCount = builder.maxSpanCount; }
Source:
private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) { IndexedTypeSet selectionAsSet = IndexedTypeSets.fromClasses( selection ); Set<Class<?>> entities = extendedIntegrator.getIndexedTypesPolymorphic( selectionAsSet ).toPojosSet(); if ( entities.size() == 0 ) { IndexedTypeSet configuredTargetEntities = extendedIntegrator.getConfiguredTypesPolymorphic( selectionAsSet ); if ( configuredTargetEntities.isEmpty() ) { throw log.targetedEntityTypesNotConfigured( StringHelper.join( selection, "," ) ); } else { throw log.targetedEntityTypesNotIndexed( StringHelper.join( selection, "," ) ); } } Set<Class<?>> cleaned = new HashSet<Class<?>>(); Set<Class<?>> toRemove = new HashSet<Class<?>>(); for ( Class<?> type : entities ) { boolean typeIsOk = true; for ( Class<?> existing : cleaned ) { if ( existing.isAssignableFrom( type ) ) { typeIsOk = false; break; } if ( type.isAssignableFrom( existing ) ) { toRemove.add( existing ); } } if ( typeIsOk ) { cleaned.add( type ); } } cleaned.removeAll( toRemove ); log.debugf( "Targets for indexing job: %s", cleaned ); return IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) ); }

Target:
private static IndexedTypeSet toRootEntities(ExtendedSearchIntegrator extendedIntegrator, Class<?>... selection) { Set<Class<?>> entities = new HashSet<>(); Set<Class<?>> nonIndexedEntities = new HashSet<>(); for ( Class<?> entityType : selection ) { IndexedTypeSet entityTypeAsSet = IndexedTypeSets.fromClass( entityType ); IndexedTypeSet targetedClasses = extendedIntegrator.getIndexedTypesPolymorphic( entityTypeAsSet ); if ( targetedClasses.isEmpty() ) { nonIndexedEntities.add( entityType ); } else { entities.addAll( targetedClasses.toPojosSet() ); } } if ( !nonIndexedEntities.isEmpty() ) { IndexedTypeSet nonIndexedEntitiesAsSet = IndexedTypeSets.fromClasses( nonIndexedEntities ); IndexedTypeSet configuredTargetEntities = extendedIntegrator.getConfiguredTypesPolymorphic( nonIndexedEntitiesAsSet ); if ( configuredTargetEntities.isEmpty() ) { throw log.someTargetedEntityTypesNotConfigured( StringHelper.join( nonIndexedEntities, "," ) ); } else { throw log.someTargetedEntityTypesNotIndexed( StringHelper.join( nonIndexedEntities, "," ) ); } } Set<Class<?>> cleaned = new HashSet<Class<?>>(); Set<Class<?>> toRemove = new HashSet<Class<?>>(); for ( Class<?> type : entities ) { boolean typeIsOk = true; for ( Class<?> existing : cleaned ) { if ( existing.isAssignableFrom( type ) ) { typeIsOk = false; break; } if ( type.isAssignableFrom( existing ) ) { toRemove.add( existing ); } } if ( typeIsOk ) { cleaned.add( type ); } } cleaned.removeAll( toRemove ); log.debugf( "Targets for indexing job: %s", cleaned ); return IndexedTypeSets.fromClasses( cleaned.toArray( new Class[cleaned.size()] ) ); }
Source:
AmbryBlobStorageService(FrontendConfig frontendConfig, FrontendMetrics frontendMetrics, RestResponseHandler responseHandler, Router router, ClusterMap clusterMap, IdConverterFactory idConverterFactory, SecurityServiceFactory securityServiceFactory, AccountService accountService) { this.frontendConfig = frontendConfig; this.frontendMetrics = frontendMetrics; this.responseHandler = responseHandler; this.router = router; this.clusterMap = clusterMap; this.idConverterFactory = idConverterFactory; this.securityServiceFactory = securityServiceFactory; this.accountService = accountService; getReplicasHandler = new GetReplicasHandler(frontendMetrics, clusterMap); logger.trace("Instantiated AmbryBlobStorageService"); }

Target:
AmbryBlobStorageService(FrontendConfig frontendConfig, FrontendMetrics frontendMetrics, RestResponseHandler responseHandler, Router router, ClusterMap clusterMap, IdConverterFactory idConverterFactory, SecurityServiceFactory securityServiceFactory, AccountService accountService) { this.accountService = Objects.requireNonNull(accountService, "accountService cannot be null."); this.frontendConfig = frontendConfig; this.frontendMetrics = frontendMetrics; this.responseHandler = responseHandler; this.router = router; this.clusterMap = clusterMap; this.idConverterFactory = idConverterFactory; this.securityServiceFactory = securityServiceFactory; getReplicasHandler = new GetReplicasHandler(frontendMetrics, clusterMap); logger.trace("Instantiated AmbryBlobStorageService"); }
Source:
private Response mockResponse(int code) { Response mockResponse = mock(Response.class); when(mockResponse.isSuccessful()).thenReturn(code < 400); when(mockResponse.code()).thenReturn(code); when(mockResponse.body()).thenReturn(ResponseBody.create(MediaType.get("application/json"), "")); return mockResponse; }

Target:
private Response mockResponse(int code) { return new Response.Builder() .request(new Request.Builder().url("http://mock").build()) .protocol(Protocol.HTTP_1_1) .code(code) .body(ResponseBody.create(MediaType.get("application/json"), "")) .message("mock") .build(); }
Source:
public LcmEntityFilter withDataProduct(final String dataProduct) { params.put("dataProduct", singletonList(notEmpty(dataProduct, "dataProduct"))); return this; }

Target:
public LcmEntityFilter withDataProduct(final String dataProduct) { if (isNotBlank(dataProduct)) { this.dataProduct = dataProduct; } return this; }
Source:
public Event<Object> event() { checkState(); if (event == null) { synchronized (this) { if (event == null) { event = beanManager().event(); } } } return event; }

Target:
public Event<Object> event() { checkIsRunning(); if (event == null) { synchronized (this) { if (event == null) { event = beanManager().event(); } } } return event; }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; if (InternalTask.class.isAssignableFrom(obj.getClass())) { return ((InternalTask) obj).getId().equals(getId()); } else { return false; } }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (InternalTask.class.isAssignableFrom(obj.getClass())) { return ((InternalTask) obj).getId().equals(getId()); } else { return false; } }
Source:
public Organisation getOrganisationByName(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "Organisation name.", required = true) @PathParam("name") String name) { if (!user.isPresent()) { Organisation organisation = organisationDAO.findApprovedByName(name); if (organisation == null) { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } return organisation; } else { boolean doesOrgExist = doesOrganisationByNameExistToUser(name, user.get().getId()) || user.get().getIsAdmin() || user.get().isCurator(); if (!doesOrgExist) { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } Organisation organisation = organisationDAO.findByName(name); return organisation; } }

Target:
public Organisation getOrganisationByName(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "Organisation name.", required = true) @PathParam("name") String name) { if (!user.isPresent()) { Organisation organisation = organisationDAO.findApprovedByName(name); if (organisation == null) { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } return organisation; } else { Organisation organisation = organisationDAO.findByName(name); if (organisation == null) { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } OrganisationUser role = getUserOrgRole(organisation, user.get().getId()); if (user.get().getIsAdmin() || user.get().isCurator() || role != null) { return organisation; } else { String msg = "Organisation not found"; LOG.info(msg); throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND); } } }
Source:
public void onReceive(Context context, Intent intent) { if (conMgr == null) { return; } final NetworkInfo activeInfo = conMgr.getActiveNetworkInfo(); if (activeInfo != null && activeInfo.isConnected()) { setHasNetwork(true); return; } final NetworkInfo wifiInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiInfo != null && wifiInfo.isConnected()) { setHasNetwork(true); return; } final NetworkInfo mobileInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mobileInfo == null || mobileInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) { setHasNetwork(false); return; } }

Target:
public void onReceive(Context context, Intent intent) { if (conMgr == null) { return; } final NetworkInfo activeInfo = conMgr.getActiveNetworkInfo(); if (activeInfo != null && activeInfo.isConnected()) { setHasNetwork(true); return; } final NetworkInfo wifiInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiInfo != null && wifiInfo.isConnected()) { setHasNetwork(true); return; } final NetworkInfo mobileInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mobileInfo != null && mobileInfo.isConnected()) { setHasNetwork(true); return; } setHasNetwork(false); return; }
Source:
public void incrementCounter(String name, String hostname, JSONArray tags) { ConcurrentMetricCounters.lock.lock(); try { ConcurrentMetricCounters countersInstance = ConcurrentMetricCounters.getInstance(); ConcurrentMap<CounterMetric, Integer> counters = countersInstance.get(); CounterMetric counterMetric = new CounterMetric(tags, name, hostname); Integer previousValue = counters.putIfAbsent(counterMetric, 1); if (previousValue != null){ boolean ok = counters.replace(counterMetric, previousValue, previousValue + 1); while(!ok) { logger.warning("Couldn't increment counter " + name + " with value " + (previousValue + 1) + " previousValue = " + previousValue); previousValue = counters.get(counterMetric); ok = counters.replace(counterMetric, previousValue, previousValue + 1); } } previousValue = previousValue == null ? 0 : previousValue; logger.fine("Counter " + name + " updated from previousValue " + previousValue + " to " + (previousValue + 1)); } finally { ConcurrentMetricCounters.lock.unlock(); } }

Target:
public void incrementCounter(String name, String hostname, JSONArray tags) { ConcurrentMetricCounters.getInstance().increment(name, hostname, tags); }
Source:
public void submitFrame() { if (vrCompositor == null) { return; } if (vrCompositor.Submit == null) { return; } for (int nEye = 0; nEye < 2; nEye++) { vrCompositor.Submit.apply( nEye, texType[nEye], null, JOpenVRLibrary.EVRSubmitFlags.EVRSubmitFlags_Submit_Default); } if (vrCompositor.PostPresentHandoff != null) { vrCompositor.PostPresentHandoff.apply(); } }

Target:
public void submitFrame() { for (int nEye = 0; nEye < 2; nEye++) { vrCompositor.Submit.apply( nEye, texType[nEye], null, JOpenVRLibrary.EVRSubmitFlags.EVRSubmitFlags_Submit_Default); } if (vrCompositor.PostPresentHandoff != null) { vrCompositor.PostPresentHandoff.apply(); } }
Source:
LogEventHandler(int eventCount, boolean isSlowLogTableEnabled, Configuration conf) { this.configuration = conf; EvictingQueue<SlowLogPayload> evictingQueue = EvictingQueue.create(eventCount); queueForRingBuffer = Queues.synchronizedQueue(evictingQueue); this.isSlowLogTableEnabled = isSlowLogTableEnabled; if (isSlowLogTableEnabled) { EvictingQueue<SlowLogPayload> evictingQueueForTable = EvictingQueue.create( SYS_TABLE_QUEUE_SIZE); queueForSysTable = Queues.synchronizedQueue(evictingQueueForTable); } else { queueForSysTable = null; } }

Target:
LogEventHandler(int eventCount, boolean isSlowLogTableEnabled, Configuration conf) { this.configuration = conf; EvictingQueue<SlowLogPayload> evictingQueue = EvictingQueue.create(eventCount); queueForRingBuffer = Queues.synchronizedQueue(evictingQueue); this.isSlowLogTableEnabled = isSlowLogTableEnabled; if (isSlowLogTableEnabled) { int sysTableQueueSize = conf.getInt(SYS_TABLE_QUEUE_SIZE, DEFAULT_SYS_TABLE_QUEUE_SIZE); EvictingQueue<SlowLogPayload> evictingQueueForTable = EvictingQueue.create(sysTableQueueSize); queueForSysTable = Queues.synchronizedQueue(evictingQueueForTable); } else { queueForSysTable = null; } }
Source:
public void getSegmentPoint(final int i) { final int mulLength = 3, offset = 2; if (splinePoints[i].getY() < splinePoints[i + 1].getY()) { final Vector3f vecNew = new Vector3f().add(splinePoints[i + 1]); vecNew.setY(splinePoints[i].getY()); meshStructurePoints[splinePoints.length * mulLength + offset * i] = splinePoints[i]; meshStructurePoints[splinePoints.length * mulLength + offset * i + 1] = vecNew; } else { final Vector3f vecNew = new Vector3f().add(splinePoints[i]); vecNew.setY(splinePoints[i + 1].getY()); meshStructurePoints[splinePoints.length * mulLength + offset * i] = vecNew; meshStructurePoints[splinePoints.length * mulLength + offset * i + 1] = splinePoints[i + 1]; } }

Target:
public void getSegmentPoint(final int i) { final int mulLength = 3, offset = 2; if (splinePoints[i].getY() < splinePoints[i + 1].getY()) { final Vector3f vecNew = new Vector3f().add(splinePoints[i + 1]); vecNew.setY(splinePoints[i].getY()); meshStructurePoints[(splinePoints.length * mulLength) + (offset * i)] = splinePoints[i]; meshStructurePoints[(splinePoints.length * mulLength) + (offset * i) + 1] = vecNew; } else { final Vector3f vecNew = new Vector3f().add(splinePoints[i]); vecNew.setY(splinePoints[i + 1].getY()); meshStructurePoints[(splinePoints.length * mulLength) + (offset * i)] = vecNew; meshStructurePoints[(splinePoints.length * mulLength) + (offset * i) + 1] = splinePoints[i + 1]; } }
Source:
public Post scrollToBottom(WebDriver driver) { ((JavascriptExecutor) driver) .executeScript("window.scrollTo(0, document.body.scrollHeight)"); return this; }

Target:
public Post scrollToBottom(WebDriver driver) { jsActions.scrollToBottom(driver); return this; }
Source:
private void setCacheHeaders(boolean isPrivate, RestResponseChannel restResponseChannel) throws RestServiceException { if (isPrivate) { restResponseChannel.setHeader(RestUtils.Headers.EXPIRES, new Date(0)); restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL, "private, no-cache, no-store, proxy-revalidate"); restResponseChannel.setHeader(RestUtils.Headers.PRAGMA, "no-cache"); } else { restResponseChannel.setHeader(RestUtils.Headers.EXPIRES, new Date(System.currentTimeMillis() + adminConfig.adminCacheValiditySeconds * Time.MsPerSec)); restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL, "max-age=" + adminConfig.adminCacheValiditySeconds); } }

Target:
private void setCacheHeaders(boolean isPrivate, RestResponseChannel restResponseChannel) throws RestServiceException { if (isPrivate) { restResponseChannel.setHeader(RestUtils.Headers.EXPIRES, restResponseChannel.getHeader(RestUtils.Headers.DATE)); restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL, "private, no-cache, no-store, proxy-revalidate"); restResponseChannel.setHeader(RestUtils.Headers.PRAGMA, "no-cache"); } else { restResponseChannel.setHeader(RestUtils.Headers.EXPIRES, new Date(System.currentTimeMillis() + adminConfig.adminCacheValiditySeconds * Time.MsPerSec)); restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL, "max-age=" + adminConfig.adminCacheValiditySeconds); } }
Source:
public void lockTask(TaskExecution taskExecution) { if(this.lockRegistry == null ) { this.lockRegistry = getDefaultLockRegistry(taskExecution.getExecutionId()); } this.lockRegistryLeaderInitiator = new LockRegistryLeaderInitiator( this.lockRegistry, new DefaultCandidate(String.valueOf(taskExecution.getExecutionId()), taskNameResolver.getTaskName())); this.lockRegistryLeaderInitiator.setApplicationEventPublisher(this.applicationEventPublisher); this.lockRegistryLeaderInitiator.setPublishFailedEvents(true); this.lockRegistryLeaderInitiator.start(); while (!this.lockReady) { try { Thread.sleep(500); } catch (InterruptedException ex) { logger.warn("Thread Sleep Failed", ex); } if (this.lockFailed) { String errorMessage = String.format( "Task with name \"%s\" is already running.", this.taskNameResolver.getTaskName()); try { this.lockRegistryLeaderInitiator.destroy(); } catch (Exception exception) { throw new TaskExecutionException("Failed to destroy lock.", exception); } throw new TaskExecutionException(errorMessage); } } }

Target:
public void lockTask(TaskExecution taskExecution) { if(this.lockRegistry == null ) { this.lockRegistry = getDefaultLockRegistry(taskExecution.getExecutionId()); } this.lockRegistryLeaderInitiator = new LockRegistryLeaderInitiator( this.lockRegistry, new DefaultCandidate(String.valueOf(taskExecution.getExecutionId()), taskNameResolver.getTaskName())); this.lockRegistryLeaderInitiator.setApplicationEventPublisher(this.applicationEventPublisher); this.lockRegistryLeaderInitiator.setPublishFailedEvents(true); this.lockRegistryLeaderInitiator.start(); while (!this.lockReady) { try { Thread.sleep(this.taskProperties.getSingleInstanceLockCheckInterval()); } catch (InterruptedException ex) { logger.warn("Thread Sleep Failed", ex); } if (this.lockFailed) { String errorMessage = String.format( "Task with name \"%s\" is already running.", this.taskNameResolver.getTaskName()); try { this.lockRegistryLeaderInitiator.destroy(); } catch (Exception exception) { throw new TaskExecutionException("Failed to destroy lock.", exception); } throw new TaskExecutionException(errorMessage); } } }