auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public <P, R> R accept(RealmEventVisitor<P, R> visitor, P param) throws RealmUnavailableException { return visitor.handleUnknownEvent(this, param); }

Target:
public <P, R> R accept(RealmEventVisitor<P, R> visitor, P param) { return visitor.handleUnknownEvent(this, param); }
Source:
public void doPatchsetCreatedHook(final Change change, final PatchSet patchSet) { final PatchSetCreatedEvent event = new PatchSetCreatedEvent(); event.project = change.getProject().get(); event.branch = change.getDest().getShortName(); event.change = change.getKey().get(); event.commit = patchSet.getRevision().get(); event.patchSet = Integer.toString(patchSet.getPatchSetId()); for (ChangeListenerHolder holder : listeners.values()) { if (!isVisibleTo(change, holder.user)) continue; holder.listener.onPatchsetCreated(event); } final List<String> args = new ArrayList<String>(); args.add(patchsetCreatedHook.getAbsolutePath()); args.add("--change"); args.add(event.change); args.add("--project"); args.add(event.project); args.add("--branch"); args.add(event.branch); args.add("--commit"); args.add(event.commit); args.add("--patchset"); args.add(event.patchSet); runHook(getRepo(change), args); }

Target:
public void doPatchsetCreatedHook(final Change change, final PatchSet patchSet) { final PatchSetCreatedEvent event = new PatchSetCreatedEvent(); event.project = change.getProject().get(); event.branch = change.getDest().getShortName(); event.change = change.getKey().get(); event.commit = patchSet.getRevision().get(); event.patchSet = Integer.toString(patchSet.getPatchSetId()); for (ChangeListenerHolder holder : listeners.values()) { if (isVisibleTo(change, holder.user)) { holder.listener.onChangeEvent(event); } } final List<String> args = new ArrayList<String>(); args.add(patchsetCreatedHook.getAbsolutePath()); args.add("--change"); args.add(event.change); args.add("--project"); args.add(event.project); args.add("--branch"); args.add(event.branch); args.add("--commit"); args.add(event.commit); args.add("--patchset"); args.add(event.patchSet); runHook(getRepo(change), args); }
Source:
public IPropertyDescriptor[] getPropertyDescriptors() { Map<String, String> envVariables = getTraceProperties(); if (envVariables != null && !envVariables.isEmpty()) { ArrayList<IPropertyDescriptor> propertyDescriptorList = new ArrayList<IPropertyDescriptor>(); for (Map.Entry<String, String> varName : envVariables.entrySet()) { ReadOnlyTextPropertyDescriptor descriptor = new ReadOnlyTextPropertyDescriptor(varName.getKey(), varName.getKey()); descriptor.setCategory(sfTracePropertiesCategory); propertyDescriptorList.add(descriptor); } propertyDescriptorList.addAll(Arrays.asList(sfDescriptors)); IPropertyDescriptor array[] = new IPropertyDescriptor[propertyDescriptorList.size()]; return Arrays.copyOf(propertyDescriptorList.toArray(array), propertyDescriptorList.size()); } return Arrays.copyOf(sfDescriptors, sfDescriptors.length); }

Target:
public IPropertyDescriptor[] getPropertyDescriptors() { Map<String, String> envVariables = getTraceProperties(); if (!envVariables.isEmpty()) { IPropertyDescriptor[] propertyDescriptorArray = new IPropertyDescriptor[envVariables.size()+sfDescriptors.length]; int index =0; for (Map.Entry<String, String> varName : envVariables.entrySet()) { ReadOnlyTextPropertyDescriptor descriptor = new ReadOnlyTextPropertyDescriptor(varName.getKey(), varName.getKey()); descriptor.setCategory(sfTracePropertiesCategory); propertyDescriptorArray[index] = descriptor; index++; } for(int i=0; i<sfDescriptors.length; i++) { propertyDescriptorArray[index] = sfDescriptors[i]; index++; } return propertyDescriptorArray; } return Arrays.copyOf(sfDescriptors, sfDescriptors.length); }
Source:
public static String patternToString(List<LockPatternView.Cell> pattern) { if (pattern == null) { return ""; } final int patternSize = pattern.size(); byte[] res = new byte[patternSize]; for (int i = 0; i < patternSize; i++) { LockPatternView.Cell cell = pattern.get(i); res[i] = (byte) (cell.getRow() * 3 + cell.getColumn()); } try { return new String(res, CHARSET); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Internal error", e); } }

Target:
public static String patternToString(List<LockPatternView.Cell> pattern) { if (pattern == null) { return ""; } final int patternSize = pattern.size(); byte[] res = new byte[patternSize]; for (int i = 0; i < patternSize; i++) { LockPatternView.Cell cell = pattern.get(i); res[i] = (byte) (cell.getRow() * 3 + cell.getColumn()); } return getString(res); }
Source:
private void checkStatus(StatusCode status) throws IOException { logger.debug("result status code: {}", status); if (status == null) { throw new NoSuchElementException(message.errorNullResult()); } if (!status.isGood()) { throw new IOException(message.errorBadResultStatus() + status); } }

Target:
private void checkStatus(StatusCode status) throws IOException { logger.debug("result status code: {}", status); if (status == null) { throw new NullPointerException(message.errorNullResult()); } if (!status.isGood()) { throw new IOException(message.errorBadResultStatus() + status); } }
Source:
} catch (IOException e) { Activator.getDefault().logInfo("Cannot read the file from URL due to "+e.getMessage()); }

Target:
} catch (IOException e) { Activator.getDefault().logError("Cannot read the file from URL due to ", e); }
Source:
public boolean isValid(JsonNode value) { if (value.isTextual() && (value.textValue() != null && !value.textValue().isEmpty())) { return true; } return false; }

Target:
public boolean isValid(JsonNode value) { if (value.isTextual() && StringUtils.isNotBlank(value.textValue())) { return true; } return false; }
Source:
public void downloadBlob(HttpServletRequest request, HttpServletResponse response, String key, String reason) throws IOException { TransientStore ts = Framework.getService(TransientStoreService.class).getStore(STORE_NAME); if (!ts.exists(key)) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } List<Blob> blobs = ts.getBlobs(key); if (blobs == null || blobs.isEmpty()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (blobs.size() > 1) { throw new IllegalArgumentException("multipart download not yet implemented"); } if (ts.getParameter(key, ERROR) != null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ((Throwable) ts.getParameter(key, ERROR)).getMessage()); } else if (ts.isCompleted(key)) { try { Blob blob = blobs.get(0); downloadBlob(request, response, null, null, blob, blob.getFilename(), reason); } finally { ts.remove(key); } } else { response.setStatus(HttpServletResponse.SC_ACCEPTED); } }

Target:
public void downloadBlob(HttpServletRequest request, HttpServletResponse response, String key, String reason) throws IOException { this.downloadBlob(request, response, key, reason, false); }
Source:
public <RetType> RetType submit(TaskAction<RetType> taskAction) { try { byte[] dataToSend = jsonMapper.writeValueAsBytes(taskAction); final String response = httpClient.post(getServiceUri().toURL()) .setContent("application/json", dataToSend) .go(new ToStringResponseHandler(Charsets.UTF_8)) .get(); if(response.equals("")) { return null; } else { return jsonMapper.readValue(response, taskAction.getReturnTypeReference()); } } catch (Exception e) { throw Throwables.propagate(e); } }

Target:
public <RetType> RetType submit(TaskAction<RetType> taskAction) { try { byte[] dataToSend = jsonMapper.writeValueAsBytes(taskAction); final String response = httpClient.post(getServiceUri().toURL()) .setContent("application/json", dataToSend) .go(new ToStringResponseHandler(Charsets.UTF_8)) .get(); final Map<String, Object> responseDict = jsonMapper.readValue( response, new TypeReference<Map<String, Object>>() ); return jsonMapper.convertValue(responseDict.get("result"), taskAction.getReturnTypeReference()); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
private static void waitForService(final ServiceController<?> controller) throws OperationFailedException { try { final CountDownLatch latch = new CountDownLatch(1); final LifecycleListener listener = new LifecycleListener() { @Override public void handleEvent(ServiceController<?> controller, LifecycleEvent event) { latch.countDown(); } }; controller.addListener(listener); latch.await(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); throw SecurityLogger.ROOT_LOGGER.interruptedWaitingForSecurityDomain(controller.getName().getSimpleName()); } catch (final Throwable ignored) if (controller.getState() != ServiceController.State.UP) { throw SecurityLogger.ROOT_LOGGER.requiredSecurityDomainServiceNotAvailable(controller.getName().getSimpleName()); } }

Target:
private static void waitForService(final ServiceController<?> controller) throws OperationFailedException { try { final CountDownLatch latch = new CountDownLatch(1); final LifecycleListener listener = new LifecycleListener() { @Override public void handleEvent(ServiceController<?> controller, LifecycleEvent event) { latch.countDown(); controller.removeListener(this); } }; controller.addListener(listener); latch.await(100, TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); throw SecurityLogger.ROOT_LOGGER.interruptedWaitingForSecurityDomain(controller.getName().getSimpleName()); } catch (final Throwable ignored) if (controller.getState() != ServiceController.State.UP) { throw SecurityLogger.ROOT_LOGGER.requiredSecurityDomainServiceNotAvailable(controller.getName().getSimpleName()); } }
Source:
private Indexes(InternalSerializationService serializationService, IndexCopyBehavior copyBehavior) { this.serializationService = serializationService; this.indexProvider = new DefaultIndexProvider(); this.extractors = Extractors.empty(); this.global = true; this.copyBehavior = copyBehavior; this.queryableEntriesAreCached = false; this.queryContextProvider = new GlobalQueryContextProvider(); this.stats = InternalIndexesStats.EMPTY; }

Target:
private Indexes(InternalSerializationService serializationService, IndexCopyBehavior copyBehavior) { this.serializationService = serializationService; this.indexProvider = new DefaultIndexProvider(); this.extractors = Extractors.empty(); this.global = true; this.copyBehavior = copyBehavior; this.queryableEntriesAreCached = false; this.queryContextProvider = new GlobalQueryContextProvider(); this.stats = IndexesStats.EMPTY; }
Source:
public static HttpsURLConnection createConnection(final String urlPath, final boolean multiPart) { try { final URL url = new URL(SERVER_URL + "/" + urlPath); final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(SimlarSSLSocketFactory.getInstance()); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); if (multiPart) { connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + DATA_BOUNDARY); } else { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } Lg.v("created connection for: ", urlPath); return connection; } catch (final MalformedURLException e) { Lg.ex(e, "MalformedURLException"); } catch (final ProtocolException e) { Lg.ex(e, "ProtocolException"); } catch (final IOException e) { Lg.ex(e, "IOException while creating connection"); } Lg.e("failed to create connection for: ", urlPath); return null; }

Target:
public static HttpsURLConnection createConnection(final String urlPath, final boolean multiPart) { try { final URL url = new URL(SERVER_URL + "/" + urlPath); final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(SimlarSSLSocketFactory.getInstance()); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); if (multiPart) { connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + DATA_BOUNDARY); } else { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } Lg.v("created connection for: ", urlPath); return connection; } catch (final IOException e) { Lg.ex(e); } Lg.e("failed to create connection for: ", urlPath); return null; }
Source:
@Override protected void onKernalStart0() { metricsUpdateTask = ctx.timeout().schedule(new MetricsUpdater(), METRICS_UPDATE_FREQ, METRICS_UPDATE_FREQ); }

Target:
@Override protected void onKernalStart0() throws IgniteCheckedException { metricsUpdateTask = ctx.timeout().schedule(new MetricsUpdater(), METRICS_UPDATE_FREQ, METRICS_UPDATE_FREQ); }
Source:
public void connect() { disconnect(); _zkclient = createZkClient(); _zkclient.subscribeStateChanges(getOrCreateStateChangeListener()); _leaderElectionListener = new ZkLeaderElectionListener(); _instanceName = createLiveInstanceNode(); LOG.info("Coordinator instance " + _instanceName + " is online"); _assignmentList = new ZkBackedTaskListProvider(_cluster, _instanceName); onBecomeFollower(); joinLeaderElection(); LOG.info("Instance " + _instanceName + " is ready."); }

Target:
public void connect() { disconnect(); _zkclient = createZkClient(); _stateChangeListener = new ZkStateChangeListener(); _leaderElectionListener = new ZkLeaderElectionListener(); _instanceName = createLiveInstanceNode(); LOG.info("Coordinator instance " + _instanceName + " is online"); _assignmentList = new ZkBackedTaskListProvider(_cluster, _instanceName); onBecomeFollower(); joinLeaderElection(); LOG.info("Instance " + _instanceName + " is ready."); }
Source:
public void remove(RemoteFile file) throws IOException, JadbException { InputStream s = device.executeShell("rm", "-f", Bash.quote(file.getPath())); Stream.flushRead(s); s.close(); }

Target:
public void remove(RemoteFile file) throws IOException, JadbException { try (InputStream stream = device.executeShell("rm", "-f", Bash.quote(file.getPath()))) { Stream.flushRead(stream); } }
Source:
public static EventFiringWebDriver getDriverInstanceForBrowser(String browser, String userAgent) { browserName = browser; switch (browser.toUpperCase()) { case "FF": return getFFInstanceWithUserAgent(userAgent); case "CHROME": return getChromeInstanceWithUserAgent(userAgent); default: throw new RuntimeException( "Bad browser provided. Browser " + browser + " not known" ); } }

Target:
public static EventFiringWebDriver getDriverInstanceForBrowser(String browser, String userAgent) { browserName = browser; switch (browser.toUpperCase()) { case "FF": return getFFInstanceWithUserAgent(userAgent); case "CHROME": return getChromeInstanceWithUserAgent(userAgent); default: throw new RuntimeException( "Wrong browser provided. Browser " + browser + " not known" ); } }
Source:
public List<Integer> getAlleleIndices(final Collection<Allele> alleles) { return alleles.stream() .map(this::getAlleleIndex) .collect(Collectors.toCollection(LinkedList::new)); }

Target:
public List<Integer> getAlleleIndices(final Collection<Allele> alleles) { return alleles.stream() .map(this::getAlleleIndex) .collect(Collectors.toCollection(() -> new ArrayList<>(alleles.size()))); }
Source:
public int available() throws IOException { int available = in.available() + (int) (((FSDataInputStream) in).getPos() - mPos); return available > 0 ? available : 0; }

Target:
public int available() throws IOException { if (mPos != ((FSDataInputStream) in).getPos()) { return 0; } return in.available(); }
Source:
public PipeRunResult doPipe(Message message, IPipeLineSession session) throws PipeRunException { try { try (MessageOutputStream target=MessageOutputStream.getTargetStream(this, session, getNextPipe())) { try (OutputStream out = target.asStream()) { pgpAction.run(message.asInputStream(), out); } return target.getPipeRunResult(); } } catch (Exception e) { throw new PipeRunException(this, "Exception was thrown during PGPPipe execution.", e); } }

Target:
public PipeRunResult doPipe(Message message, IPipeLineSession session) throws PipeRunException { try (MessageOutputStream target=MessageOutputStream.getTargetStream(this, session, getNextPipe())) { try (OutputStream out = target.asStream()) { pgpAction.run(message.asInputStream(), out); } return target.getPipeRunResult(); } catch (Exception e) { throw new PipeRunException(this, "Exception was thrown during PGPPipe execution.", e); } }
Source:
public Binder build(Annotation annotation) { return new Binder<BindSomething, Something>() { @Override public void bind(SQLStatement q, BindSomething bindSomethingAnnotation, Something arg) { q.bind(bindSomethingAnnotation.value() + ".id", arg.getId()); q.bind(bindSomethingAnnotation.value() + ".name", arg.getName()); } }; }

Target:
public Binder build(Annotation annotation) { return new Binder<BindSomething, Something>() { @Override public void bind(SQLStatement q, BindSomething bs, Something arg) { q.bind(bs.value() + ".id", arg.getId()); q.bind(bs.value() + ".name", arg.getName()); } }; }
Source:
protected EntityDynamicType(Class<? extends Entity> clazz, AbstractEntity entity) { this.entityClass = clazz; this.entity = entity; String id = entity==null ? clazz.getName() : entity.getId(); effectors.putAll(findEffectors(clazz, entity)); if (LOG.isTraceEnabled()) LOG.trace("Entity effectors: {}", id, Joiner.on(", ").join(effectors.keySet())); sensors.putAll(findSensors(clazz, entity)); if (LOG.isTraceEnabled()) LOG.trace("Entity sensors: {}", id, Joiner.on(", ").join(sensors.keySet())); configKeys.putAll(findConfigKeys(clazz, entity)); if (LOG.isTraceEnabled()) LOG.trace("Entity config keys: {}", id, Joiner.on(", ").join(configKeys.keySet())); refreshSnapshot(); }

Target:
private EntityDynamicType(Class<? extends Entity> clazz, AbstractEntity entity) { this.entityClass = clazz; this.entity = entity; String id = entity==null ? clazz.getName() : entity.getId(); effectors.putAll(findEffectors(clazz, entity)); if (LOG.isTraceEnabled()) LOG.trace("Entity effectors: {}", id, Joiner.on(", ").join(effectors.keySet())); sensors.putAll(findSensors(clazz, entity)); if (LOG.isTraceEnabled()) LOG.trace("Entity sensors: {}", id, Joiner.on(", ").join(sensors.keySet())); configKeys.putAll(findConfigKeys(clazz, entity)); if (LOG.isTraceEnabled()) LOG.trace("Entity config keys: {}", id, Joiner.on(", ").join(configKeys.keySet())); refreshSnapshot(); }
Source:
protected boolean doLunsUseConnection(StorageServerConnections connection) { luns = getLunDao().getAllForStorageServerConnection(connection.getid()); return !luns.isEmpty(); }

Target:
protected boolean doLunsUseConnection(StorageServerConnections connection) { luns = getLunDao().getAllForStorageServerConnection(connection.getid()); return domains != null && !luns.isEmpty(); }
Source:
public FutureResult<ProcessExecutionDetail> executeProcess(ProcessExecution execution) { notNull(execution, "execution"); final ProcessExecutionTask executionTask; try { executionTask = restTemplate.postForObject(execution.getExecutionsUri(), execution, ProcessExecutionTask.class); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Cannot start execution", e); } if (executionTask == null) { throw new GoodDataException("Cannot find started execution."); } return new FutureResult<>(this, new PollHandler<Void, ProcessExecutionDetail>(executionTask.getPollLink(), Void.class, ProcessExecutionDetail.class) { @Override protected boolean isFinished(ClientHttpResponse response) throws IOException { return HttpStatus.NO_CONTENT.equals(response.getStatusCode()); } @Override protected void handlePollResult(Void pollResult) { ProcessExecutionDetail executionDetail; try { executionDetail = restTemplate.getForObject(executionTask.getDetailLink(), ProcessExecutionDetail.class); } catch (GoodDataException | RestClientException e) { throw new ProcessExecutionException("Execution finished, but cannot get its result.", e, executionTask.getDetailLink()); } if (!executionDetail.isSuccess()) { throw new ProcessExecutionException("Execution was not successful", executionDetail); } else { setResult(executionDetail); } } }); }

Target:
public FutureResult<ProcessExecutionDetail> executeProcess(ProcessExecution execution) { notNull(execution, "execution"); ProcessExecutionTask executionTask; try { executionTask = restTemplate.postForObject(execution.getExecutionsUri(), execution, ProcessExecutionTask.class); } catch (GoodDataException | RestClientException e) { throw new ProcessExecutionException("Cannot execute process", e); } if (executionTask == null) { throw new ProcessExecutionException("Cannot find started execution."); } final String detailLink = executionTask.getDetailLink(); return new FutureResult<>(this, new PollHandler<Void, ProcessExecutionDetail>(executionTask.getPollLink(), Void.class, ProcessExecutionDetail.class) { @Override protected boolean isFinished(ClientHttpResponse response) throws IOException { return HttpStatus.NO_CONTENT.equals(response.getStatusCode()); } @Override protected void handlePollResult(Void pollResult) { ProcessExecutionDetail executionDetail; try { executionDetail = restTemplate.getForObject(detailLink, ProcessExecutionDetail.class); } catch (GoodDataException | RestClientException e) { throw new ProcessExecutionException("Execution finished, but cannot get its result.", e, detailLink); } if (!executionDetail.isSuccess()) { throw new ProcessExecutionException("Execution was not successful", executionDetail); } else { setResult(executionDetail); } } }); }
Source:
@Override protected Map<String, ?> run(@Nullable VisorMetricTaskArg arg) throws IgniteException { String name = arg.name(); GridMetricManager mMgr = ignite.context().metric(); for (ReadOnlyMetricRegistry mReg : mMgr) { String mRegName = mReg.name(); if (mRegName.equals(name)) { Map<String, Object> res = new HashMap<>(); mReg.forEach(metric -> res.put(metric.name(), valueOf(metric))); return res; } String mRegPrefix = mRegName + SEPARATOR; if (!name.startsWith(mRegPrefix)) continue; if (mRegPrefix.length() == name.length()) return null; String metricName = name.substring(mRegPrefix.length()); Metric metric = mReg.findMetric(metricName); if (metric != null) return Collections.singletonMap(name, valueOf(metric)); Object val = searchHistogram(metricName, mReg); if (val != null) return Collections.singletonMap(name, val); } return null; }

Target:
@Override protected Map<String, ?> run(@Nullable VisorMetricTaskArg arg) throws IgniteException { String name = arg.name(); GridMetricManager mmgr = ignite.context().metric(); for (ReadOnlyMetricRegistry mreg : mmgr) { String mregName = mreg.name(); if (mregName.equals(name)) { Map<String, Object> res = new HashMap<>(); mreg.forEach(metric -> res.put(metric.name(), valueOf(metric))); return res; } String mregPrefix = mregName + SEPARATOR; if (!name.startsWith(mregPrefix)) continue; if (mregPrefix.length() == name.length()) return null; String metricName = name.substring(mregPrefix.length()); Metric metric = mreg.findMetric(metricName); if (metric != null) return Collections.singletonMap(name, valueOf(metric)); Object val = searchHistogram(metricName, mreg); if (val != null) return Collections.singletonMap(name, val); } return null; }
Source:
public void testCreateDecoratedTwoRequestsToGetDifferentlyDecoratedSamePoolUseSameLock() { DecoratedMacPoolFactory factory = new DecoratedMacPoolFactory(lockedObjectFactorySpy); MacPool decoratedPoolA = factory.createDecoratedPool(poolId, macPool, singletonList(macPoolDecoratorA)); MacPool decoratedPoolB = factory.createDecoratedPool(poolId, macPool, singletonList(macPoolDecoratorB)); assertThat(decoratedPoolA, is(macPoolDecoratorA)); assertThat(decoratedPoolB, is(macPoolDecoratorB)); ArgumentCaptor<ReentrantReadWriteLock> captor1 = ArgumentCaptor.forClass(ReentrantReadWriteLock.class); verify(lockedObjectFactorySpy, times(2)).createLockingInstance(eq(macPool), eq(MacPool.class), any()); }

Target:
public void testCreateDecoratedTwoRequestsToGetDifferentlyDecoratedSamePoolUseSameLock() { multipleDecoratorsUsesSameLock(macPoolDecoratorA, macPoolDecoratorB); }
Source:
public void setArtifactIdentifyData(IAtsAction fromAction, IAtsTeamWorkflow toTeam, IAtsChangeSet changes) throws OseeCoreException { ArtifactReadable fromActionArt = (ArtifactReadable) fromAction.getStoreObject(); setArtifactIdentifyData(toTeam, fromAction.getName(), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.Description, ""), ChangeTypeUtil.getChangeType(fromAction), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.PriorityType, ""), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.ValidationRequired, false), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.NeedBy, (Date) null), changes); }

Target:
public void setArtifactIdentifyData(IAtsAction fromAction, IAtsTeamWorkflow toTeam, IAtsChangeSet changes) throws OseeCoreException { Conditions.checkNotNull(fromAction, "fromAction"); Conditions.checkNotNull(toTeam, "toTeam"); Conditions.checkNotNull(changes, "changes"); ArtifactReadable fromActionArt = (ArtifactReadable) fromAction.getStoreObject(); setArtifactIdentifyData(toTeam, fromAction.getName(), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.Description, ""), ChangeTypeUtil.getChangeType(fromAction), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.PriorityType, ""), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.ValidationRequired, false), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.NeedBy, (Date) null), changes); }
Source:
protected void doWriteMaxKey() { writeStartDocument(); writeInt32("$maxkey", 1); writeEndDocument(); }

Target:
protected void doWriteMaxKey() { writeStartDocument(); writeInt32("$maxKey", 1); writeEndDocument(); }
Source:
private final static void declareImage(String key, String path, boolean shared) { declareImage(key, ImageDescriptor.createFromSupplier(()-> ImageDescriptor.createFromURL( FileLocator.find(Platform.getBundle(PlatformUI.PLUGIN_ID), new Path(path), null)) .getImageData()), shared); }

Target:
private final static void declareImage(String key, String path, boolean shared) { declareImage(key, ImageDescriptor.createFromSupplier(()-> { URL url = FileLocator.find(Platform.getBundle(PlatformUI.PLUGIN_ID), new Path(path), null); return ImageDescriptor.createFromURL(url).getImageData(); }), shared); }
Source:
protected void updateAxisAfterConfigurationChange() { List<Object> allAxisToDisplay = new ArrayList<Object>(); for (final IWrapper current : ((IMasterAxisProvider) getTableManager().getTable().getCurrentColumnAxisProvider()).getSources()) { allAxisToDisplay.addAll(getListenFeatureValueFor((EObject) current.getElement())); } List<Object> toAdd = new ArrayList<Object>(allAxisToDisplay); toAdd.removeAll(this.managedObject); List<Object> toRemove = new ArrayList<Object>(this.managedObject); toRemove.removeAll(allAxisToDisplay); updateManagedList(toAdd, toRemove); }

Target:
protected void updateAxisAfterConfigurationChange() { if (null == getTableManager() || null == getTableManager().getTable() || null == getTableManager().getTable().getCurrentColumnAxisProvider()) { return; } List<Object> allAxisToDisplay = new ArrayList<Object>(); for (final IWrapper current : ((IMasterAxisProvider) getTableManager().getTable().getCurrentColumnAxisProvider()).getSources()) { if (current.getElement() instanceof EObject) { allAxisToDisplay.addAll(getListenFeatureValueFor((EObject) current.getElement())); } } List<Object> toAdd = new ArrayList<Object>(allAxisToDisplay); toAdd.removeAll(this.managedObject); List<Object> toRemove = new ArrayList<Object>(this.managedObject); toRemove.removeAll(allAxisToDisplay); updateManagedList(toAdd, toRemove); }
Source:
private void generateConfigIni(TargetEnvironment environment, File target) throws MojoExecutionException, MojoFailureException { getLog().debug("Generating config.ini"); Properties props = new Properties(); String id = productConfiguration.getProduct(); if (id != null) { String splash = id.split("\\.")[0]; setPropertyIfNotNull(props, "osgi.splashPath", "platform:/base/plugins/" + splash); } setPropertyIfNotNull(props, "eclipse.product", id); setPropertyIfNotNull(props, "osgi.bundles.defaultStartLevel", "4"); generateOSGiBundles(props, environment); File configsFolder = new File(target, "configuration"); configsFolder.mkdirs(); File configIni = new File(configsFolder, "config.ini"); FileOutputStream fos = null; try { fos = new FileOutputStream(configIni); props.store(fos, "Product Runtime Configuration File"); } catch (IOException e) { throw new MojoExecutionException("Error creating .eclipseproduct file.", e); } finally { try { if (fos != null) { fos.close(); } } catch (IOException ex) { throw new MojoExecutionException("Error closing stream for .eclipseproduct file.", ex); } } }

Target:
private void generateConfigIni(TargetEnvironment environment, File target) throws MojoExecutionException, MojoFailureException { getLog().debug("Generating config.ini"); Properties props = new Properties(); String id = productConfiguration.getProduct(); if (id != null) { String splash = id.split("\\.")[0]; setPropertyIfNotNull(props, "osgi.splashPath", "platform:/base/plugins/" + splash); } setPropertyIfNotNull(props, "eclipse.product", id); setPropertyIfNotNull(props, "osgi.bundles.defaultStartLevel", "4"); generateOSGiBundles(props, environment); File configsFolder = new File(target, "configuration"); configsFolder.mkdirs(); File configIni = new File(configsFolder, "config.ini"); FileOutputStream fos = null; try { fos = new FileOutputStream(configIni); props.store(fos, "Product Runtime Configuration File"); } catch (IOException e) { throw new MojoExecutionException("Error creating .eclipseproduct file.", e); } finally { IOUtil.close(fos); } }
Source:
public TObject sumKeyRecord(String key, long record, AccessToken creds, TransactionToken transaction, String environment) throws SecurityException, TransactionException, TException { checkAccess(creds, transaction); AtomicSupport store = getStore(transaction, environment); BigDecimal result = new BigDecimal(0); AtomicOperation atomic = null; while (atomic == null || !atomic.commit()) { atomic = store.startAtomicOperation(); try { Set<TObject> values = atomic.select(key, record); for (TObject value : values) { Object obj = Convert.thriftToJava(value); if(!(obj instanceof Number)) { throw new UnsupportedOperationException(); } else { Number number = (Number) obj; if(number instanceof Byte || number instanceof Short) { throw new UnsupportedOperationException(); } else { result = result.add(Numbers.toBigDecimal(number)); } } } } catch (AtomicStateException e) { atomic = null; result = null; } } return Convert.javaToThrift(result); }

Target:
public TObject sumKeyRecord(String key, long record, AccessToken creds, TransactionToken transaction, String environment) throws TException { checkAccess(creds, transaction); AtomicSupport store = getStore(transaction, environment); AtomicOperation atomic = null; Number sum = 0; while (atomic == null || !atomic.commit()) { atomic = store.startAtomicOperation(); try { sum = sumKeyRecordAtomic(key, record, Time.NONE, sum, atomic); } catch (AtomicStateException e) { atomic = null; sum = 0; } } return Convert.javaToThrift(sum); }
Source:
private void delete(File file) { if (file.isDirectory()) { for (File listFile : file.listFiles()) { delete(listFile); } } file.delete(); }

Target:
private void delete(File file) { if (file.isDirectory()) { for (File f : file.listFiles()) { delete(f); } } file.delete(); }
Source:
protected void onResume() { super.onResume(); if (!mOnTransfer && mSipServiceConnection.get() != null && mSipServiceConnection.get().getCurrentCall() != null) { if (mSipServiceConnection.get().getCurrentCall().isOnHold()) { mLogger.d("SipService has call on hold"); if (!mOnHold) { mLogger.i("But the activity DOES not have the call on hold. Match the sip service."); mOnHold = true; updateCallButton(R.id.button_onhold, true); onCallStatusUpdate(CALL_PUT_ON_HOLD_ACTION); } else if (!mOnHoldButton.isActivated()) { mLogger.i("Call is on hold but the button is not active. Update the button"); updateCallButton(R.id.button_onhold, true); } } } refreshAudioSourceButton(); if(!mNetworkUtil.isOnline()) { mNetworkConnectivity.startNetworkAvailabilityActivity(); mLogger.d("No connectivity available, the Network Availability Activity is being shown"); } }

Target:
protected void onResume() { super.onResume(); updateUi(); if(!mNetworkUtil.isOnline()) { NetworkAvailabilityActivity.start(); } }
Source:
private void buildCache() { LOG.debug("Inside buildCache"); if (!MessageMonitoringUtil.isMessageMonitoringEnabled()) { LOG.debug("Message Monitoring is not enabled."); return; } LOG.debug("Message Monitoring is enabled."); List<MonitoredMessage> pendingMessages = getAllPendingMessagesFromDatabase(); LOG.debug("Total cache rows from database:" + pendingMessages.size()); clearCache(); for (MonitoredMessage trackMessage : pendingMessages) { if (!trackMessage.getStatus().equals(STATUS_ARCHIVED)) { messageMonitoringCache.put(trackMessage.getMessageid(), trackMessage); LOG.debug("Total child rows for the messageId:" + trackMessage.getMonitoredmessagenotifications().size()); } } LOG.debug("Exiting buildCache."); }

Target:
private void buildCache() { LOG.debug("Inside buildCache"); if (!MessageMonitoringUtil.isMessageMonitoringEnabled()) { LOG.debug("Message Monitoring is not enabled."); return; } LOG.debug("Message Monitoring is enabled."); List<MonitoredMessage> pendingMessages = getAllPendingMessagesFromDatabase(); LOG.debug("Total cache rows from database:" + pendingMessages.size()); clearCache(); for (MonitoredMessage trackMessage : pendingMessages) { if (!trackMessage.getStatus().equals(STATUS_ARCHIVED)) { messageMonitoringCache.put(trackMessage.getMessageid(), trackMessage); LOG.debug("Total child rows for the messageId:" + trackMessage.getMonitoredmessagenotifications().size()); } else { deleteElapsedArchivedMessage(trackMessage); } } LOG.debug("Exiting buildCache."); }
Source:
public CommunicationBridge(final WebView webView, final String baseURL) { this.webView = webView; this.marshaller = new BridgeMarshaller(); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setAllowFileAccessFromFileURLs(true); webView.getSettings().setAllowUniversalAccessFromFileURLs(true); webView.setWebChromeClient(new CommunicatingChrome()); webView.addJavascriptInterface(marshaller, "marshaller"); webView.loadUrl(baseURL); eventListeners = new HashMap<>(); this.addListener("DOMLoaded", new JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { isDOMReady = true; for (String jsString : pendingJSMessages) { CommunicationBridge.this.webView.loadUrl(jsString); } } }); }

Target:
public CommunicationBridge(final WebView webView, final String baseURL) { this.webView = webView; this.marshaller = new BridgeMarshaller(); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setAllowUniversalAccessFromFileURLs(true); webView.setWebChromeClient(new CommunicatingChrome()); webView.addJavascriptInterface(marshaller, "marshaller"); webView.loadUrl(baseURL); eventListeners = new HashMap<>(); this.addListener("DOMLoaded", new JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { isDOMReady = true; for (String jsString : pendingJSMessages) { CommunicationBridge.this.webView.loadUrl(jsString); } } }); }
Source:
public void updateAttributes() { OperatingSystem operatingSystem = getCurrentOperatingSystem(); if (operatingSystem != null) { OSProcess process = operatingSystem.getProcess(this.processID); if (process != null) { copyValuesToThisProcess(process); } else { LOG.error("No process found: {}", this.processID); } } else { LOG.error("Unsupported platform. No update performed."); } }

Target:
public boolean updateAttributes() { OSProcess process = operatingSystem.getProcess(this.processID); if (process == null) { LOG.debug("No process found: {}", this.processID); return false; } copyValuesToThisProcess(process); return true; }
Source:
void checkOperationChains(List<OperationChain> opChains) throws Exception { Map<PartitionId, Integer> partitionCount = new HashMap<>(); double blobsPut = 0; for (OperationChain opChain : opChains) { if (!opChain.latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS)) { Assert.fail("Timeout waiting for operation chain " + opChain.chainId + " to finish."); } synchronized (opChain.testFutures) { for (TestFuture testFuture : opChain.testFutures) { testFuture.check(); } } Assert.assertEquals("opChain stops in the middle.", 0, opChain.operations.size()); if (opChain.blobId != null) { blobsPut++; PartitionId partitionId = new BlobId(opChain.blobId, clusterMap).getPartition(); int count = partitionCount.getOrDefault(partitionId, 0); partitionCount.put(partitionId, count + 1); } } double numPartitions = clusterMap.getWritablePartitionIds(null).size(); if (opChains.size() > numPartitions) { double blobBalanceThreshold = BALANCE_FACTOR * Math.ceil(blobsPut / numPartitions); for (Map.Entry<PartitionId, Integer> entry : partitionCount.entrySet()) { Assert.assertTrue("Number of blobs is " + entry.getValue() + " on partition: " + entry.getKey() + ", which is greater than the threshold of " + blobBalanceThreshold, entry.getValue() <= blobBalanceThreshold); } } }

Target:
void checkOperationChains(List<OperationChain> opChains) throws Exception { Map<PartitionId, Integer> partitionCount = new HashMap<>(); double blobsPut = 0; for (OperationChain opChain : opChains) { if (!opChain.latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS)) { Assert.fail("Timeout waiting for operation chain " + opChain.chainId + " to finish."); } synchronized (opChain.testFutures) { for (TestFuture testFuture : opChain.testFutures) { testFuture.check(); } } Assert.assertEquals("opChain stopped in the middle.", 0, opChain.operations.size()); if (opChain.blobId != null) { blobsPut++; PartitionId partitionId = new BlobId(opChain.blobId, clusterMap).getPartition(); int count = partitionCount.getOrDefault(partitionId, 0); partitionCount.put(partitionId, count + 1); } } double numPartitions = clusterMap.getWritablePartitionIds(null).size(); if (opChains.size() > numPartitions) { double blobBalanceThreshold = BALANCE_FACTOR * Math.ceil(blobsPut / numPartitions); for (Map.Entry<PartitionId, Integer> entry : partitionCount.entrySet()) { Assert.assertTrue("Number of blobs is " + entry.getValue() + " on partition: " + entry.getKey() + ", which is greater than the threshold of " + blobBalanceThreshold, entry.getValue() <= blobBalanceThreshold); } } }
Source:
public List<RichGroup> getRichGroupsWithAttributesAssignedToResource(PerunSession sess, Resource resource, List<String> attrNames) throws InternalErrorException, GroupResourceMismatchException { List<Group> assignedGroups = getPerunBl().getResourcesManagerBl().getAssignedGroups(sess, resource); return this.convertGroupsToRichGroupsWithAttributes(sess, resource, assignedGroups, attrNames); }

Target:
public List<RichGroup> getRichGroupsWithAttributesAssignedToResource(PerunSession sess, Resource resource, List<String> attrNames) throws InternalErrorException { List<Group> assignedGroups = getPerunBl().getResourcesManagerBl().getAssignedGroups(sess, resource); try { return this.convertGroupsToRichGroupsWithAttributes(sess, resource, assignedGroups, attrNames); } catch (GroupResourceMismatchException ex) { throw new ConsistencyErrorException(ex); } }
Source:
protected StorageDomainStatic generateNewEntity() { StorageDomainStatic newStaticDomain = new StorageDomainStatic(); newStaticDomain.setStorageName("NewStorageDomain"); newStaticDomain.setStorage("fDMzhE-wx3s-zo3q-Qcxd-T0li-yoYU-QvVePl"); newStaticDomain.setStorageFormat(StorageFormatType.V1); newStaticDomain.setWipeAfterDelete(true); newStaticDomain.setDiscardAfterDelete(false); newStaticDomain.setWarningLowSpaceIndicator(3); newStaticDomain.setCriticalSpaceActionBlocker(9); newStaticDomain.setWarningLowConfirmedSpaceIndicator(6); newStaticDomain.setFirstMetadataDevice(FixturesTool.LUN_ID2); newStaticDomain.setVgMetadataDevice(FixturesTool.LUN_ID2); newStaticDomain.setBackup(false); newStaticDomain.setDescription(""); newStaticDomain.setComment(""); return newStaticDomain; }

Target:
protected StorageDomainStatic generateNewEntity() { StorageDomainStatic newStaticDomain = new StorageDomainStatic(); newStaticDomain.setStorageName("NewStorageDomain"); newStaticDomain.setStorage("fDMzhE-wx3s-zo3q-Qcxd-T0li-yoYU-QvVePl"); newStaticDomain.setStorageFormat(StorageFormatType.V1); newStaticDomain.setWipeAfterDelete(true); newStaticDomain.setDiscardAfterDelete(false); newStaticDomain.setWarningLowSpaceIndicator(3); newStaticDomain.setCriticalSpaceActionBlocker(9); newStaticDomain.setWarningLowConfirmedSpaceIndicator(6); newStaticDomain.setFirstMetadataDevice(FixturesTool.LUN_ID2); newStaticDomain.setVgMetadataDevice(FixturesTool.LUN_ID2); newStaticDomain.setBackup(false); return newStaticDomain; }
Source:
private PregelDriver(final ETMaster etMaster, final CentCommConfProvider centCommConfProvider, final PregelMaster pregelMaster, @Parameter(SerializedTaskConf.class) final String serializedTaskConf, @Parameter(SerializedMasterConf.class) final String serializedMasterConf) throws IOException, InjectionException { this.etMaster = etMaster; this.masterConfInjector = Tang.Factory.getTang().newInjector(ConfigurationUtils.fromString(serializedMasterConf)); this.taskConf = ConfigurationUtils.fromString(serializedTaskConf); final StreamingCodec vertexValueCodec = masterConfInjector.getNamedInstance(VertexValueCodec.class); final StreamingCodec edgeCodec = masterConfInjector.getNamedInstance(EdgeCodec.class); this.executorConf = ExecutorConfiguration.newBuilder() .setResourceConf(ResourceConfiguration.newBuilder() .setNumCores(1) .setMemSizeInMB(128) .build()) .setRemoteAccessConf(RemoteAccessConfiguration.newBuilder() .setHandlerQueueSize(2048) .setNumHandlerThreads(1) .setSenderQueueSize(2048) .setNumSenderThreads(1) .build()) .setUserContextConf(centCommConfProvider.getContextConfiguration()) .setUserServiceConf(Configurations.merge(centCommConfProvider.getServiceConfWithoutNameResolver(), Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(VertexValueCodec.class, vertexValueCodec.getClass()) .bindNamedParameter(EdgeCodec.class, edgeCodec.getClass()) .build())) .build(); }

Target:
private PregelDriver(final ETMaster etMaster, final CentCommConfProvider centCommConfProvider, final PregelMaster pregelMaster, @Parameter(SerializedTaskConf.class) final String serializedTaskConf, @Parameter(SerializedMasterConf.class) final String serializedMasterConf) throws IOException { this.etMaster = etMaster; this.masterConfInjector = Tang.Factory.getTang().newInjector(ConfigurationUtils.fromString(serializedMasterConf)); this.taskConf = ConfigurationUtils.fromString(serializedTaskConf); this.executorConf = ExecutorConfiguration.newBuilder() .setResourceConf(ResourceConfiguration.newBuilder() .setNumCores(1) .setMemSizeInMB(128) .build()) .setRemoteAccessConf(RemoteAccessConfiguration.newBuilder() .setHandlerQueueSize(2048) .setNumHandlerThreads(1) .setSenderQueueSize(2048) .setNumSenderThreads(1) .build()) .setUserContextConf(centCommConfProvider.getContextConfiguration()) .setUserServiceConf(centCommConfProvider.getServiceConfWithoutNameResolver()) .build(); }
Source:
public Query getParsedQueryExecutor(OgmSession session, String queryString, Map<String, Object> namedParameters) { FullTextSession fullTextSession = Search.getFullTextSession( session ); LuceneQueryParsingResult parsingResult = new QueryParser().parseQuery( queryString, createProcessingChain( session, unwrap( namedParameters ), fullTextSession ) ); log.createdQuery( queryString, parsingResult.getQuery() ); FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery( parsingResult.getQuery(), parsingResult.getTargetEntity() ); if ( isTheTargetEntity( parsingResult.getProjections() ) ) { fullTextQuery.setProjection( EMPTY_PROJECTION ); } else { fullTextQuery.setProjection( parsingResult.getProjections().toArray( new String[parsingResult.getProjections().size()] ) ); } fullTextQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID ); return fullTextQuery; }

Target:
public Query getParsedQueryExecutor(OgmSession session, String queryString, Map<String, Object> namedParameters) { FullTextSession fullTextSession = Search.getFullTextSession( session ); LuceneQueryParsingResult parsingResult = new QueryParser().parseQuery( queryString, createProcessingChain( session, unwrap( namedParameters ), fullTextSession ) ); log.createdQuery( queryString, parsingResult.getQuery() ); FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery( parsingResult.getQuery(), parsingResult.getTargetEntity() ); if ( requiresProjections( parsingResult.getProjections() ) ) { fullTextQuery.setProjection( parsingResult.getProjections().toArray( new String[parsingResult.getProjections().size()] ) ); } fullTextQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID ); return fullTextQuery; }
Source:
private void closeFlushScheduler() { if (flushScheduler != null) { flushScheduler.shutdown(); try { if (!flushScheduler.awaitTermination(1, TimeUnit.SECONDS)) { flushScheduler.shutdownNow(); if (!flushScheduler.awaitTermination(1, TimeUnit.SECONDS)) { LOG.error("Flush scheduler did not terminate after trials of shutdown."); } } } catch (InterruptedException ie) { flushScheduler.shutdownNow(); Thread.currentThread().interrupt(); } } }

Target:
private void closeFlushScheduler() { if (flushScheduler != null) { flushScheduler.shutdown(); try { if (!flushScheduler.awaitTermination(2, TimeUnit.SECONDS)) { flushScheduler.shutdownNow(); } } catch (InterruptedException ie) { flushScheduler.shutdownNow(); Thread.currentThread().interrupt(); } } }
Source:
public TimeoutCustomizationInterceptor(ClientBuilder.TimeoutOption connectTimeout, ClientBuilder.TimeoutOption readTimeout) { this.connectTimeout = connectTimeout.asIntMillis(); this.readTimeout = readTimeout.asIntMillis(); }

Target:
public TimeoutCustomizationInterceptor(ClientBuilder.TimeoutOption connectTimeout, ClientBuilder.TimeoutOption readTimeout) { if(connectTimeout != null && connectTimeout.asIntMillis() >= 0) { this.connectTimeout = connectTimeout.asIntMillis(); } else { throw new CouchDbException("Connection timeout cannot be null."); } if(readTimeout != null && readTimeout.asIntMillis() >= 0) { this.readTimeout = readTimeout.asIntMillis(); } else { throw new CouchDbException("Read timeout cannot be null."); } }