auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void processEvent(CloudTrailEvent event) { List<String> instanceIds = getInstanceIds(event); for(String id : instanceIds) { Map userData = getUserData(event, id); String source = (String)userData.get(SOURCE); if (source == null) { violationSink.put(new ViolationBuilder(format("InstanceID: %s is missing 'source' property in userData.", id)) .withEventId(getCloudTrailEventId(event)) .withRegion(getCloudTrailEventRegion(event)) .withAccountId(getCloudTrailEventAccountId(event)) .build()); } else if (source.matches(SNAPSHOT_REGEX)) { violationSink.put(new ViolationBuilder(format("InstanceID: %s was started with a mutable SNAPSHOT image.", id)).withEventId(getCloudTrailEventId(event)) .withRegion(getCloudTrailEventRegion(event)) .withAccountId(getCloudTrailEventAccountId(event)) .build()); } }throw new UnsupportedOperationException("Not supported yet."); }

Target:
public void processEvent(CloudTrailEvent event) { List<String> instanceIds = getInstanceIds(event); for (String id : instanceIds) { Map userData = null; try { userData = userDataProvider.getUserData(event, id); } catch (AmazonServiceException e) { LOG.error(e.getMessage()); violationSink.put(new ViolationBuilder(format("InstanceId: %s doesn't have any userData.", id)) .withEventId(getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)) .withAccountId(getCloudTrailEventAccountId(event)).build()); return; } if (userData == null) { violationSink.put(new ViolationBuilder(format("InstanceId: %s doesn't have any userData.", id)) .withEventId(getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)) .withAccountId(getCloudTrailEventAccountId(event)).build()); } String source = (String) userData.get(SOURCE); if (source == null) { violationSink.put(new ViolationBuilder(format( "InstanceID: %s is missing 'source' property in userData.", id)) .withEventId(getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)) .withAccountId(getCloudTrailEventAccountId(event)).build()); } else if (source.matches(SNAPSHOT_REGEX)) { violationSink.put(new ViolationBuilder(format( "InstanceID: %s was started with a mutable SNAPSHOT image.", id)) .withEventId(getCloudTrailEventId(event)).withRegion(getCloudTrailEventRegion(event)) .withAccountId(getCloudTrailEventAccountId(event)).build()); } } }
Source:
private void validateProto(Topology.Rule protoRule) { if (!protoRule.hasAction()) throw new ZoomConvert.ConvertException("Rule " + protoRule.getId() + " has no action set"); switch (protoRule.getType()) { case JUMP_RULE: if (protoRule.getAction() != Topology.Rule.Action.JUMP) throw new ZoomConvert.ConvertException( "Rule: " + protoRule.getId() + " is a JUMP rule but " + "does not have its action set to JUMP"); break; case NAT_RULE: if (protoRule.getMatchReturnFlow() && !protoRule.getNatRuleData().hasDnat()) throw new ZoomConvert.ConvertException("Reverse NAT rule: " + UUIDUtil.fromProto(protoRule.getId()) + " must have its booleans dnat set"); if (protoRule.getMatchForwardFlow() && protoRule.getNatRuleData().getNatTargetsCount() == 0) throw new ZoomConvert.ConvertException("Rule: " + protoRule.getId() + " is a forward NAT rule but " + "has no targets set"); break; case TRACE_RULE: if (protoRule.getAction() != Topology.Rule.Action.CONTINUE) throw new ZoomConvert.ConvertException( "Trace rule: " + protoRule.getId() + " must have its " + " action set to CONTINUE"); break; } }

Target:
private void validateProto(Topology.Rule protoRule) { if (!protoRule.hasAction()) throw new ZoomConvert.ConvertException("Rule " + protoRule.getId() + " has no action set"); switch (protoRule.getType()) { case JUMP_RULE: if (protoRule.getAction() != Topology.Rule.Action.JUMP) throw new ZoomConvert.ConvertException( "Rule: " + protoRule.getId() + " is a JUMP rule but " + "does not have its action set to JUMP"); break; case NAT_RULE: if (protoRule.getMatchReturnFlow() && !protoRule.getNatRuleData().hasDnat()) throw new ZoomConvert.ConvertException("Reverse NAT rule: " + UUIDUtil.fromProto(protoRule.getId()) + " must have its boolean dnat set"); if (protoRule.getMatchForwardFlow() && protoRule.getNatRuleData().getNatTargetsCount() == 0) throw new ZoomConvert.ConvertException("Rule: " + protoRule.getId() + " is a forward NAT rule but " + "has no targets set"); break; case TRACE_RULE: if (protoRule.getAction() != Topology.Rule.Action.CONTINUE) throw new ZoomConvert.ConvertException( "Trace rule: " + protoRule.getId() + " must have its " + " action set to CONTINUE"); break; } }
Source:
protected void setManagedProvider(ManagedProvider<Rule, String> managedProvider) { LOGGER.info("Rule Managed Provider: is added.", managedProvider); super.setManagedProvider(managedProvider); this.managedRuleProviderReg = bundleContext.registerService(RuleProvider.class.getName(), this.managedProvider, null); }

Target:
protected void setManagedProvider(ManagedProvider<Rule, String> managedProvider) { logger.info("Rule Managed Provider: is added.", managedProvider); super.setManagedProvider(managedProvider); }
Source:
public int hashCode() { String projectName = project.getName(); String projectFilePath; if (!project.isDisposed()) { projectFilePath = project.getProjectFilePath(); } else { projectFilePath = null; } return Objects.hash(projectFilePath, projectName, moduleName); }

Target:
public int hashCode() { return module.hashCode(); }
Source:
private IncrementalIndex makeIncIndex() { return new OnheapIncrementalIndex.Builder() .setIncrementalIndexSchema( new IncrementalIndexSchema.Builder() .withQueryGranularity(Granularities.NONE) .withMetrics(schemaInfo.getAggsArray()) .withDimensionsSpec(DimensionsSpec.ofEmpty()) .build() ) .setReportParseExceptions(false) .setMaxRowCount(rowsPerSegment) .build(); }

Target:
private IncrementalIndex makeIncIndex() { return new IncrementalIndex.Builder() .setSimpleTestingIndexSchema(schemaInfo.getAggsArray()) .setReportParseExceptions(false) .setMaxRowCount(rowsPerSegment) .buildOnheap(); }
Source:
public static Map<String, String> toStringMap(String... pairs) { Map<String, String> parameters = new HashMap<>(); if (pairs == null || pairs.length == 0) { return parameters; } if (pairs.length > 0) { if (pairs.length % 2 != 0) { throw new IllegalArgumentException("pairs must be even."); } for (int i = 0; i < pairs.length; i = i + 2) { parameters.put(pairs[i], pairs[i + 1]); } } return parameters; }

Target:
public static Map<String, String> toStringMap(String... pairs) { Map<String, String> parameters = new HashMap<>(); if(ArrayUtils.isEmpty(pairs)){ return parameters; } if (pairs.length > 0) { if (pairs.length % 2 != 0) { throw new IllegalArgumentException("pairs must be even."); } for (int i = 0; i < pairs.length; i = i + 2) { parameters.put(pairs[i], pairs[i + 1]); } } return parameters; }
Source:
public AmazonInfo autoBuild(String namespace) { return this.autoBuild(namespace, false); }

Target:
public AmazonInfo autoBuild(String namespace) { initProperties(namespace); for (MetaDataKey key : MetaDataKey.values()) { int numOfRetries = awsMetaDataRetries.get(); while (numOfRetries-- > 0) { try { String mac = null; if (key == MetaDataKey.vpcId) { mac = result.metadata.get(MetaDataKey.mac.getName()); } URL url = key.getURL(null, mac); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setConnectTimeout(awsMetaDataConnectTimeout.get()); uc.setReadTimeout(awsMetaDataReadTimeout.get()); if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(uc.getErrorStream())); try { while (br.readLine() != null) { } } finally { br.close(); } } else { String value = key.read(uc.getInputStream()); if (value != null) { result.metadata.put(key.getName(), value); } } break; } catch (Throwable e) { if (shouldLogAWSMetadataError.get()) { logger.warn("Cannot get the value for the metadata key :" + key + " Reason :", e); } if (numOfRetries >= 0) { try { Thread.sleep(SLEEP_TIME_MS); } catch (InterruptedException e1) { } continue; } } } if (key == MetaDataKey.instanceId && awsMetaDataFailFastOnFirstLoad.get() && !result.metadata.containsKey(MetaDataKey.instanceId.getName())) { logger.warn("Skipping the rest of AmazonInfo init as we were not able to load instanceId after " + "the configured number of retries: {}, per fail fast configuration: {}", awsMetaDataRetries.get(), awsMetaDataFailFastOnFirstLoad.get()); break; } } return result; }
Source:
public static double beta(double a, double b) { return ((Gamma.gamma(a) * Gamma.gamma(b)) / Gamma.gamma(a + b)); }

Target:
private static double beta(double a, double b) { return ((Gamma.gamma(a) * Gamma.gamma(b)) / Gamma.gamma(a + b)); }
Source:
LRESULT WM_CHAR (long wParam, long lParam) { if (ignoreCharacter) return null; LRESULT result = super.WM_CHAR (wParam, lParam); if (result != null) return result; switch ((int) wParam) { case SWT.DEL: if (OS.GetKeyState (OS.VK_CONTROL) < 0) { if ((style & SWT.READ_ONLY) != 0) return LRESULT.ZERO; Point selection = getSelection (); int x = selection.x; int y = selection.y; if (x == y) { String actText = getText ().substring (0, getCaretPosition()); java.util.regex.Matcher m = CTRL_BS_PATTERN.matcher (actText); if (m.find ()) { x = m.start (); y = m.end (); OS.SendMessage (handle, OS.EM_SETSEL, x, y); } } if (x < y) { OS.SendMessage (handle, OS.EM_REPLACESEL, 1, 0); } return LRESULT.ZERO; } } if ((style & SWT.SINGLE) != 0) { switch ((int) wParam) { case SWT.CR: sendSelectionEvent (SWT.DefaultSelection); case SWT.TAB: case SWT.ESC: return LRESULT.ZERO; } } return result; }

Target:
LRESULT WM_CHAR (long wParam, long lParam) { if (ignoreCharacter) return null; LRESULT result = super.WM_CHAR (wParam, lParam); if (result != null) return result; switch ((int) wParam) { case SWT.DEL: if (OS.GetKeyState (OS.VK_CONTROL) < 0) { if ((style & SWT.READ_ONLY) != 0) return LRESULT.ZERO; Point selection = getSelection (); int x = selection.x; int y = selection.y; if (x == y) { String actText = getText (0, getCaretPosition ()); java.util.regex.Matcher m = CTRL_BS_PATTERN.matcher (actText); if (m.find ()) { x = m.start (); y = m.end (); OS.SendMessage (handle, OS.EM_SETSEL, x, y); } } if (x < y) { OS.SendMessage (handle, OS.EM_REPLACESEL, 1, 0); } return LRESULT.ZERO; } } if ((style & SWT.SINGLE) != 0) { switch ((int) wParam) { case SWT.CR: sendSelectionEvent (SWT.DefaultSelection); case SWT.TAB: case SWT.ESC: return LRESULT.ZERO; } } return result; }
Source:
public Path createTarFromProject(Path projectDir, Path tmcLangs, Path tmcrun, Path targetLocation) throws IOException, ArchiveException { Files.copy(tmcrun, projectDir.resolve(tmcrun.getFileName().toString())); Files.copy(tmcLangs, projectDir.resolve(tmcLangs.getFileName().toString())); createTarBall(projectDir.toFile(), targetLocation); return projectDir.getParent(); }

Target:
public void createTarFromProject(Path projectDir, Path tmcLangs, Path tmcrun, Path targetLocation) throws IOException, ArchiveException { Files.copy(tmcrun, projectDir.resolve(tmcrun.getFileName())); Files.copy(tmcLangs, projectDir.resolve(tmcLangs.getFileName())); createTarBall(projectDir, targetLocation); }
Source:
public static <T> T attempt(final Callable<T> command, int times) throws RiakRetryFailedException { try { return command.call(); } catch (Exception e) { if(e instanceof MatchFoundException) { throw (RuntimeException)e; } if (times == 0) { throw new RiakRetryFailedException(e); } else { return attempt(command, --times); } } }

Target:
public static <T> T attempt(final Callable<T> command, int times) throws RiakRetryFailedException { try { return command.call(); } catch (MatchFoundException e) { throw e; } catch (ConversionException e) { throw e; } catch (Exception e) { if (times == 0) { throw new RiakRetryFailedException(e); } else { return attempt(command, --times); } } }
Source:
public CommandResponse run(ZooKeeperServer zkServer, Map<String, String> kwargs) { CommandResponse response = initializeResponse(); if (zkServer instanceof QuorumZooKeeperServer) { QuorumPeer peer = ((QuorumZooKeeperServer) zkServer).self; QuorumPeer.ZabState zabState = peer.getZabState(); QuorumVerifier qv = peer.getQuorumVerifier(); QuorumPeer.QuorumServer voter = qv.getVotingMembers().get(peer.getId()); boolean voting = ( voter != null && voter.addr.equals(peer.getQuorumAddress()) && voter.electionAddr.equals(peer.getElectionAddress()) ); response.put("myid", zkServer.getConf().getServerId()); response.put("is_leader", zkServer instanceof LeaderZooKeeperServer); response.put("endpoint", peer.getElectionAddress().toString().split(":")[0]+ ":" + peer.getClientPort()); response.put("voting", voting); long lastProcessedZxid = zkServer.getZKDatabase().getDataTreeLastProcessedZxid(); response.put("last_zxid", "0x" + ZxidUtils.zxidToString(lastProcessedZxid)); response.put("zab_epoch", ZxidUtils.getEpochFromZxid(lastProcessedZxid)); response.put("zab_counter",ZxidUtils.getCounterFromZxid(lastProcessedZxid)); response.put("zabstate", zabState.name().toLowerCase()); } else { response.put("voting", false); response.put("zabstate", ""); } return response ; }

Target:
public CommandResponse run(ZooKeeperServer zkServer, Map<String, String> kwargs) { CommandResponse response = initializeResponse(); if (zkServer instanceof QuorumZooKeeperServer) { QuorumPeer peer = ((QuorumZooKeeperServer) zkServer).self; QuorumPeer.ZabState zabState = peer.getZabState(); QuorumVerifier qv = peer.getQuorumVerifier(); QuorumPeer.QuorumServer voter = qv.getVotingMembers().get(peer.getId()); boolean voting = ( voter != null && voter.addr.equals(peer.getQuorumAddress()) && voter.electionAddr.equals(peer.getElectionAddress()) ); response.put("myid", zkServer.getConf().getServerId()); response.put("is_leader", zkServer instanceof LeaderZooKeeperServer); response.put("quorum_address", peer.getQuorumAddress()); response.put("election_address", peer.getElectionAddress()); response.put("client_address", peer.getClientAddress()); response.put("voting", voting); long lastProcessedZxid = zkServer.getZKDatabase().getDataTreeLastProcessedZxid(); response.put("last_zxid", "0x" + ZxidUtils.zxidToString(lastProcessedZxid)); response.put("zab_epoch", ZxidUtils.getEpochFromZxid(lastProcessedZxid)); response.put("zab_counter", ZxidUtils.getCounterFromZxid(lastProcessedZxid)); response.put("zabstate", zabState.name().toLowerCase()); } else { response.put("voting", false); response.put("zabstate", ""); } return response; }
Source:
public static Vector3d getPosition3d(final DataView view, @Nullable final DataQuery query) { final DataView internal = query == null ? view : view.getView(query).orElseThrow(dataNotFound()); final double x = internal.getDouble(Queries.POSITION_X).orElseThrow(dataNotFound()); final double y = internal.getDouble(Queries.POSITION_Y).orElseThrow(dataNotFound()); final double z = internal.getDouble(Queries.POSITION_Z).orElseThrow(dataNotFound()); return new Vector3d(x, y, z); }

Target:
public static Vector3d getPosition3d(final DataView view, @Nullable final DataQuery query) { final DataView internal = query == null ? view : view.getView(query).orElseThrow(DataUtil.dataNotFound()); final double x = internal.getDouble(Queries.POSITION_X).orElseThrow(DataUtil.dataNotFound()); final double y = internal.getDouble(Queries.POSITION_Y).orElseThrow(DataUtil.dataNotFound()); final double z = internal.getDouble(Queries.POSITION_Z).orElseThrow(DataUtil.dataNotFound()); return new Vector3d(x, y, z); }
Source:
public void allWithMoreThatOneTask() throws Exception{ final Repo repo = new MkRepo(); final Region region = DyTasksTest.region(repo.name(),10L,20L); DyTasks tasks = new DyTasks(region, repo); Iterator<Task> iteTask = tasks.all().iterator(); MatcherAssert.assertThat(iteTask.hasNext(),Matchers.equalTo(true)); iteTask.next(); MatcherAssert.assertThat(iteTask.hasNext(),Matchers.equalTo(true)); iteTask.next(); MatcherAssert.assertThat(iteTask.hasNext(),Matchers.equalTo(false)); }

Target:
public void allWithMoreThatOneTask() throws Exception { final Repo repo = new MkRepo(); final DyTasks tasks = new DyTasks( DyTasksTest.region(repo.name(), 10L, 20L), repo ); MatcherAssert.assertThat( tasks.all(), Matchers.<Task>iterableWithSize(2) ); }
Source:
public void setupEnvironment() { CorrelationIdTracker.clean(); DbUser user = mock(DbUser.class); when(engineSessionDao.remove(anyLong())).thenReturn(1); mcr.mockConfigValue(ConfigValues.UserSessionTimeOutInterval, 30); sessionDataContainer.setUser(session, user); }

Target:
public void setupEnvironment() { CorrelationIdTracker.clean(); DbUser user = mock(DbUser.class); when(engineSessionDao.remove(anyLong())).thenReturn(1); sessionDataContainer.setUser(session, user); }
Source:
public ImmutableSpongeTagsData() { this(Collections.<String>emptySet()); }

Target:
public ImmutableSpongeTagsData() { this(Collections.emptySet()); }
Source:
private boolean isAttributeClean(String key, String value) { String tValue = value.trim(); if (ATTRIBUTES_WHITELIST.contains(key) || extraAttributes.contains(key)) { return true; } else if (VULNERABLE_ATTRIBUTES.contains(key)) { boolean isURL = Pattern.matches("^[a-zA-Z0-9+.-]*://.*$", tValue); if (isURL || tValue.startsWith("/") || tValue.startsWith("mailto") || tValue.startsWith("#")) { return true; } } else if (Pattern.matches("^[a-zA-Z]+:[a-zA-Z]+$", key)) { return true; } return false; }

Target:
private boolean isAttributeClean(String key, String value) { String tValue; if (value == null) { tValue = ""; } else { tValue = value.trim(); } if (ATTRIBUTES_WHITELIST.contains(key) || extraAttributes.contains(key)) { return true; } else if (VULNERABLE_ATTRIBUTES.contains(key)) { boolean isURL = Pattern.matches("^[a-zA-Z0-9+.-]*://.*$", tValue); if (isURL || tValue.startsWith("/") || tValue.startsWith("mailto") || tValue.startsWith("#")) { return true; } } else if (Pattern.matches("^[a-zA-Z]+:[a-zA-Z]+$", key)) { return true; } return false; }
Source:
private void addResteasyProvidersParameter(JBossWebMetaData jbossWebMetaData) { if (jbossWebMetaData == null) { return; } List<ParamValueMetaData> contextParams = jbossWebMetaData.getContextParams(); if (null == contextParams) { contextParams = new ArrayList<>(); } ParamValueMetaData restEasyDynamicFeature = getResteasyProvidersParam(jbossWebMetaData); if (restEasyDynamicFeature.getParamValue() != null && !restEasyDynamicFeature.getParamValue().trim().isEmpty()) { restEasyDynamicFeature.setParamValue(restEasyDynamicFeature.getParamValue() + ",org.wildfly.microprofile.opentracing.smallrye.TracerDynamicFeature"); } else { restEasyDynamicFeature.setParamValue("org.wildfly.microprofile.opentracing.smallrye.TracerDynamicFeature"); } contextParams.add(restEasyDynamicFeature); jbossWebMetaData.setContextParams(contextParams); }

Target:
private void addResteasyProvidersParameter(JBossWebMetaData jbossWebMetaData) { if (jbossWebMetaData == null) { return; } ParamValueMetaData restEasyDynamicFeature = getResteasyProvidersParam(jbossWebMetaData); if (restEasyDynamicFeature.getParamValue() != null && !restEasyDynamicFeature.getParamValue().trim().isEmpty()) { restEasyDynamicFeature.setParamValue(restEasyDynamicFeature.getParamValue() + ",org.wildfly.microprofile.opentracing.smallrye.TracerDynamicFeature"); } else { restEasyDynamicFeature.setParamValue("org.wildfly.microprofile.opentracing.smallrye.TracerDynamicFeature"); } }
Source:
public void serialize(OutputArchive archive, String tag) throws IOException { archive.startRecord(this, tag); for (OpResult result : results) { int err = result.getType() == ZooDefs.OpCode.error ? ((OpResult.ErrorResult)result).getErr() : 0; new MultiHeader(result.getType(), false, err).serialize(archive, tag); switch (result.getType()) { case ZooDefs.OpCode.create: new CreateResponse(((OpResult.CreateResult) result).getPath()).serialize(archive, tag); break; case ZooDefs.OpCode.create2: OpResult.CreateResult createResult = (OpResult.CreateResult) result; new Create2Response(createResult.getPath(), createResult.getStat()).serialize(archive, tag); break; case ZooDefs.OpCode.delete: case ZooDefs.OpCode.check: break; case ZooDefs.OpCode.setData: new SetDataResponse(((OpResult.SetDataResult) result).getStat()).serialize(archive, tag); break; case ZooDefs.OpCode.getChildren: new GetChildrenResponse(((OpResult.GetChildrenResult) result).getChildren()).serialize(archive, tag); break; case ZooDefs.OpCode.getData: new GetDataResponse(((OpResult.GetDataResult) result).getData(), new Stat()).serialize(archive, tag); break; case ZooDefs.OpCode.error: new ErrorResponse(((OpResult.ErrorResult) result).getErr()).serialize(archive, tag); break; default: throw new IOException("Invalid type " + result.getType() + " in MultiResponse"); } } new MultiHeader(-1, true, -1).serialize(archive, tag); archive.endRecord(this, tag); }

Target:
public void serialize(OutputArchive archive, String tag) throws IOException { archive.startRecord(this, tag); for (OpResult result : results) { int err = result.getType() == ZooDefs.OpCode.error ? ((OpResult.ErrorResult)result).getErr() : 0; new MultiHeader(result.getType(), false, err).serialize(archive, tag); switch (result.getType()) { case ZooDefs.OpCode.create: new CreateResponse(((OpResult.CreateResult) result).getPath()).serialize(archive, tag); break; case ZooDefs.OpCode.create2: OpResult.CreateResult createResult = (OpResult.CreateResult) result; new Create2Response(createResult.getPath(), createResult.getStat()).serialize(archive, tag); break; case ZooDefs.OpCode.delete: case ZooDefs.OpCode.check: break; case ZooDefs.OpCode.setData: new SetDataResponse(((OpResult.SetDataResult) result).getStat()).serialize(archive, tag); break; case ZooDefs.OpCode.getChildren: new GetChildrenResponse(((OpResult.GetChildrenResult) result).getChildren()).serialize(archive, tag); break; case ZooDefs.OpCode.getData: new GetDataResponse(((OpResult.GetDataResult) result).getData(),((OpResult.GetDataResult) result).getStat()).serialize(archive, tag); break; case ZooDefs.OpCode.error: new ErrorResponse(((OpResult.ErrorResult) result).getErr()).serialize(archive, tag); break; default: throw new IOException("Invalid type " + result.getType() + " in MultiResponse"); } } new MultiHeader(-1, true, -1).serialize(archive, tag); archive.endRecord(this, tag); }
Source:
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { ObjectUtil.checkNotNull(unit, "unit"); if (delay < 0) { delay = 0; } validateScheduled0(delay, unit); return schedule(new ScheduledFutureTask<Void>( this, ObjectUtil.checkNotNull(command, "command"), deadlineNanos(unit.toNanos(delay)))); }

Target:
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { ObjectUtil.checkNotNull(command, "command"); ObjectUtil.checkNotNull(unit, "unit"); if (delay < 0) { delay = 0; } validateScheduled0(delay, unit); return schedule(new ScheduledFutureTask<Void>( this, command, deadlineNanos(unit.toNanos(delay)))); }
Source:
public void removeEntry(String entry) { if (entry.equals(LOCAL_ADDRESS)) { return; } try { Optional<Ban.Ip> ban = getService().getBanFor(InetAddress.getByName(entry)); ban.ifPresent(ip -> getService().removeBan(ip)); } catch (UnknownHostException e) { throw new IllegalArgumentException("Error parsing Ban IP address!", e); } }

Target:
public void removeEntry(String entry) { if (entry.equals(LOCAL_ADDRESS)) { return; } try { getService().pardon(InetAddress.getByName(entry)); } catch (UnknownHostException e) { throw new IllegalArgumentException("Error parsing Ban IP address!", e); } }
Source:
public void write ( byte[] b, int off, int len ) throws IOException { if ( ( off | len | ( b.length - ( len + off )) | ( off + len )) < 0 ) throw new IndexOutOfBoundsException(); super.write( b, off, len ); size += len; boolean isSubArray = 0 != off || len < b.length ; byte[] sub = ( isSubArray ? Arrays.copyOfRange( b, off, len ) : b ); for ( final AbstractChecksumGenerator checksum : checksums ) { checksum.update( sub ); } }

Target:
public void write ( byte[] b, int off, int len ) throws IOException { super.write( b, off, len ); size += len; for ( final AbstractChecksumGenerator checksum : checksums ) { checksum.update( b, off, len ); } }
Source:
private Gson buildGsonWithAdapters() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .registerTypeAdapter(Patient.class, new Patient.PatientSerializer()) .registerTypeAdapter(Program.class, new Program.ProgramSerializer()) .create(); }

Target:
private Gson buildGsonWithAdapters() { return new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .registerTypeAdapter(Patient.class, new Patient.PatientSerializer()) .registerTypeAdapter(Program.class, new Program.ProgramSerializer()) .registerTypeAdapter(Location.class, new Location.LocationSerializer()) .create(); }
Source:
public void testSimpleExternalizable() throws Exception { SimpleExternalizable exp = new SimpleExternalizable("field"); SimpleExternalizable obj = marshalUnmarshal(exp); assertEquals(obj.field, exp.field); }

Target:
public void testSimpleExternalizable() throws Exception { SimpleExternalizable exp = new SimpleExternalizable("field"); SimpleExternalizable obj = marshalUnmarshal(exp); assertEquals(exp.field, obj.field); }
Source:
private String addRequiresCheckoutOptionColumn() { if (DbConnectionFactory.isMySql()) { return MYSQL_ADD_REQUIRES_CHECKOUT_OPTION_COLUMN; } else if (DbConnectionFactory.isPostgres()) { return POSTGRES_ADD_REQUIRES_CHECKOUT_OPTION_COLUMN; } else if (DbConnectionFactory.isMsSql()) { return MSSQL_ADD_REQUIRES_CHECKOUT_OPTION_COLUMN; } else if (DbConnectionFactory.isOracle()) { return ORACLE_ADD_REQUIRES_CHECKOUT_OPTION_COLUMN; } else { return null; } }

Target:
private String addRequiresCheckoutOptionColumn() { String sql = null; if (DbConnectionFactory.isMySql()) { sql = MYSQL_ADD_REQUIRES_CHECKOUT_OPTION_COLUMN; } else if (DbConnectionFactory.isPostgres()) { sql = POSTGRES_ADD_REQUIRES_CHECKOUT_OPTION_COLUMN; } else if (DbConnectionFactory.isMsSql()) { sql = MSSQL_ADD_REQUIRES_CHECKOUT_OPTION_COLUMN; } else if (DbConnectionFactory.isOracle()) { sql = ORACLE_ADD_REQUIRES_CHECKOUT_OPTION_COLUMN; } return sql; }
Source:
static boolean sendJsonInsteadOfRedirect() { HttpServletRequest request = ServletActionContext.getRequest(); return isJsonEnabled(request) && !isValidateOnly(request); }

Target:
protected boolean sendJsonInsteadOfRedirect() { HttpServletRequest request = ServletActionContext.getRequest(); return isJsonEnabled(request) && !isValidateOnly(request); }
Source:
public long getGreaterThan1mPauses() { return getSnapshot().getCountBetweenValues(TimeUnit.MILLISECONDS.toNanos(10000), Long.MAX_VALUE); }

Target:
public long getGreaterThan1mPauses() { return snapshot.get().getCountBetweenValues(TimeUnit.MINUTES.toNanos(1), Long.MAX_VALUE); }
Source:
public void setup() throws IOException { fs = fsRule.get(); storeDir = new File( "store" ); fs.deleteRecursively( storeDir ); fs.mkdir( storeDir ); indexDir = new File( new File( new File( new File( new File( storeDir, "schema" ), "index" ), "spatial-1.0" ), "1" ), "1-4326" ); IndexDirectoryStructure dirStructure = IndexDirectoryStructure.directoriesByProvider( storeDir ).forProvider( SPATIAL_PROVIDER_DESCRIPTOR ); index = new SpatialKnownIndex( dirStructure, CoordinateReferenceSystem.WGS84, 1L, pageCacheRule.getPageCache( fs ), fs, SchemaIndexProvider.Monitor.EMPTY, RecoveryCleanupWorkCollector.IMMEDIATE ); descriptor = IndexDescriptorFactory.forLabel( 42, 1337 ); samplingConfig = mock( IndexSamplingConfig.class ); CoordinateReferenceSystem crs = CoordinateReferenceSystem.WGS84; }

Target:
public void setup() throws IOException { fs = fsRule.get(); storeDir = new File( "store" ); fs.deleteRecursively( storeDir ); fs.mkdir( storeDir ); CoordinateReferenceSystem crs = CoordinateReferenceSystem.WGS84; String crsDir = String.format("%s-%s", crs.getTable().getTableId(), crs.getCode() ); indexDir = new File( new File( new File( new File( new File( storeDir, "schema" ), "index" ), "spatial-1.0" ), "1" ), crsDir ); IndexDirectoryStructure dirStructure = IndexDirectoryStructure.directoriesByProvider( storeDir ).forProvider( SPATIAL_PROVIDER_DESCRIPTOR ); index = new SpatialKnownIndex( dirStructure, crs, 1L, pageCacheRule.getPageCache( fs ), fs, SchemaIndexProvider.Monitor.EMPTY, RecoveryCleanupWorkCollector.IMMEDIATE ); descriptor = IndexDescriptorFactory.forLabel( 42, 1337 ); samplingConfig = mock( IndexSamplingConfig.class ); }
Source:
private boolean shouldAbortOnClientInactivityTimeout(ImageTransfer entity, long ts, Integer idleTimeFromTicket) { int inactivityTimeout = getTransferImageClientInactivityTimeoutInSeconds(); boolean timeoutExceeded = idleTimeFromTicket != null ? idleTimeFromTicket > inactivityTimeout : ts > (entity.getLastUpdated().getTime() / 1000) + inactivityTimeout; return inactivityTimeout > 0 && timeoutExceeded && entity.getPhase().canBePaused() && !entity.getActive(); }

Target:
private boolean shouldAbortOnClientInactivityTimeout(ImageTransfer entity, long ts, Integer idleTimeFromTicket) { int inactivityTimeout = getTransferImageClientInactivityTimeoutInSeconds(); boolean timeoutExceeded = idleTimeFromTicket != null ? idleTimeFromTicket > inactivityTimeout : ts > (entity.getLastUpdated().getTime() / 1000) + inactivityTimeout; return inactivityTimeout > 0 && timeoutExceeded && !entity.getActive(); }
Source:
protected void listen() { if (!connectedFlag.get() || releaseNeeded.get()) { return; } releaseNeeded.set(true); try { send(pushListener, new OnFinishedHandler() { @Override public void onFinished() { releaseNeeded.set(false); listen(); } }); } catch (Exception e) { LOG.info("Error in sending long poll", e); } }

Target:
protected void listen() { if (!connectedFlag.get() || releaseNeeded.get()) { return; } releaseNeeded.set(true); try { send(pushListener, new OnFinishedHandler() { @Override public void onFinished() { releaseNeeded.set(false); listen(); } }); } catch (Exception e) { LOG.error("Error in sending long poll", e); } }
Source:
public Response describeDataSet( @PathParam("datasetId") Integer datasetId){ try { return Response.ok(datasetService.getDatasetDTO(datasetId), MediaType.APPLICATION_JSON).build(); } catch (Exception e){ return createExceptionResponse(e); } }

Target:
public Response describeDataSet( @PathParam("datasetId") Integer datasetId){ try { DataSetDTO datasetDTO = datasetService.getDatasetDTO(datasetId); return Response.ok(datasetDTO, MediaType.APPLICATION_JSON).build(); } catch (Exception e){ return createExceptionResponse(e); } }
Source:
private Optional<Type> getCommonSuperTypeForRow(RowType firstType, RowType secondType) { List<Field> firstFields = firstType.getFields(); List<Field> secondFields = secondType.getFields(); if (firstFields.size() != secondFields.size()) { return Optional.empty(); } List<Type> types = new ArrayList<>(); List<Optional<String>> names = new ArrayList<>(); for (int i = 0; i < firstFields.size(); i++) { Optional<Type> commonParameterType = getCommonSuperType(firstFields.get(i).getType(), secondFields.get(i).getType()); if (!commonParameterType.isPresent()) { return Optional.empty(); } types.add(commonParameterType.get()); Optional<String> firstParameterName = firstFields.get(i).getName(); Optional<String> secondParameterName = secondFields.get(i).getName(); Optional<String> name = Optional.empty(); if (firstParameterName.equals(secondParameterName)) { name = firstParameterName; } names.add(name); } boolean hasMissing = !names.stream().allMatch(Optional::isPresent); ImmutableList.Builder<RowType.Field> fields = ImmutableList.builder(); for (int i = 0; i < types.size(); i++) { Type type = types.get(i); Optional<String> name = hasMissing ? Optional.empty() : names.get(i); fields.add(new RowType.Field(name, type)); } return Optional.of(RowType.from(fields.build())); }

Target:
private Optional<Type> getCommonSuperTypeForRow(RowType firstType, RowType secondType) { List<Field> firstFields = firstType.getFields(); List<Field> secondFields = secondType.getFields(); if (firstFields.size() != secondFields.size()) { return Optional.empty(); } ImmutableList.Builder<RowType.Field> fields = ImmutableList.builder(); for (int i = 0; i < firstFields.size(); i++) { Optional<Type> commonParameterType = getCommonSuperType(firstFields.get(i).getType(), secondFields.get(i).getType()); if (!commonParameterType.isPresent()) { return Optional.empty(); } Optional<String> firstParameterName = firstFields.get(i).getName(); Optional<String> secondParameterName = secondFields.get(i).getName(); Optional<String> name = Optional.empty(); if (firstParameterName.equals(secondParameterName)) { name = firstParameterName; } fields.add(new RowType.Field(name, commonParameterType.get())); } return Optional.of(RowType.from(fields.build())); }
Source:
public void setBuffer(Buffer buffer) { GSTSAMPLE_API.gst_sample_set_buffer(this, buffer); }

Target:
public void setBuffer(Buffer buffer) { Gst.checkVersion(1, 16); GSTSAMPLE_API.gst_sample_set_buffer(this, buffer); }
Source:
public static CompletableFuture<Void> runLaterChecked(CheckedRunnable workToEnqueue) { return runLater(() -> { try { workToEnqueue.run(); } catch (Exception e) { throw new CompletionException(e); } }); }

Target:
public static CompletableFuture<Void> runLaterChecked(CheckedRunnable workToEnqueue) { return runLater(() -> { try { workToEnqueue.run(); } catch (Throwable t) { throw new CompletionException(t); } }); }
Source:
public int addJSON(JSONObject j, Table table) { if (!this.belowMemThreshold()) { Log.e(LOGTAG, "There is not enough space left on the device to store Mixpanel data, so data was discarded"); return DBOutOfMemoryError; } final String tableName = table.getName(); Cursor c = null; int count = DBUpdateError; try { final SQLiteDatabase db = mDb.getWritableDatabase(); final ContentValues cv = new ContentValues(); cv.put(KEY_DATA, j.toString()); cv.put(KEY_CREATED_AT, System.currentTimeMillis()); db.insert(tableName, null, cv); c = db.rawQuery("SELECT COUNT(*) FROM " + tableName, null); c.moveToFirst(); count = c.getInt(0); } catch (final SQLiteException e) { Log.e(LOGTAG, "Could not add Mixpanel data to table " + tableName + ". Re-initializing database.", e); if (c != null) { c.close(); c = null; } mDb.deleteDatabase(); } finally { if (c != null) { c.close(); } mDb.close(); } return count; }

Target:
public int addJSON(JSONObject j, Table table) { if (!this.belowMemThreshold()) { Log.e(LOGTAG, "There is not enough space left on the device to store Mixpanel data, so data was discarded"); return DB_OUT_OF_MEMORY_ERROR; } final String tableName = table.getName(); Cursor c = null; int count = DB_UPDATE_ERROR; try { final SQLiteDatabase db = mDb.getWritableDatabase(); final ContentValues cv = new ContentValues(); cv.put(KEY_DATA, j.toString()); cv.put(KEY_CREATED_AT, System.currentTimeMillis()); db.insert(tableName, null, cv); c = db.rawQuery("SELECT COUNT(*) FROM " + tableName, null); c.moveToFirst(); count = c.getInt(0); } catch (final SQLiteException e) { Log.e(LOGTAG, "Could not add Mixpanel data to table " + tableName + ". Re-initializing database.", e); if (c != null) { c.close(); c = null; } mDb.deleteDatabase(); } finally { if (c != null) { c.close(); } mDb.close(); } return count; }
Source:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (Strings.isNullOrEmpty(req.getPathInfo())) { try (final PrintWriter output = resp.getWriter()) { resp.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); final ArrayList<Task> tasks = new ArrayList<>(getTasks()); Collections.sort(tasks, Comparator.comparing(Task::getName)); for (final Task task : tasks) { output.println(task.getName()); } } } else if (tasks.containsKey(req.getPathInfo())) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (Strings.isNullOrEmpty(req.getPathInfo())) { try (final PrintWriter output = resp.getWriter()) { resp.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); getTasks().stream() .map(Task::getName) .sorted() .forEach(output::println); } } else if (tasks.containsKey(req.getPathInfo())) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Source:
public RelOptRule(RelOptRuleOperand operand, RelBuilderFactory relBuilderFactory, String description) { this.operand = Objects.requireNonNull(operand); this.relBuilderFactory = Objects.requireNonNull(relBuilderFactory); if (description == null) { description = guessDescription(getClass().getName()); } if (!description.matches("[A-Za-z][-A-Za-z0-9_.(),\\[\\]:]*")) { throw new RuntimeException("Rule description '" + description + "' is not valid"); } this.description = description; this.operands = flattenOperands(operand); assignSolveOrder(); }

Target:
public RelOptRule(RelOptRuleOperand operand, RelBuilderFactory relBuilderFactory, String description) { this.operand = Objects.requireNonNull(operand); this.relBuilderFactory = Objects.requireNonNull(relBuilderFactory); if (description == null) { description = guessDescription(getClass().getName()); } if (!description.matches("[A-Za-z][-A-Za-z0-9_.(),\\[\\]\\s:]*")) { throw new RuntimeException("Rule description '" + description + "' is not valid"); } this.description = description; this.operands = flattenOperands(operand); assignSolveOrder(); }
Source:
public <X> WeldInstance<X> select(Type subtype, Annotation... qualifiers) { if (!this.getType().getTypeName().equals(Object.class.getName())) { throw BeanLogger.LOG.selectByTypeOnlyWorksOnObject(); } return (WeldInstance<X>)selectInstance(subtype, qualifiers); }

Target:
public <X> WeldInstance<X> select(Type subtype, Annotation... qualifiers) { if (!this.getType().equals(Object.class)) { throw BeanLogger.LOG.selectByTypeOnlyWorksOnObject(); } return (WeldInstance<X>)selectInstance(subtype, qualifiers); }
Source:
public void setUp() { mappingLocator = new MappingLocator(); mappingLocator.populate(); HashMap<Integer, String> osNames = new HashMap<>(1); osNames.put(0, "Unassigned"); }

Target:
public void setUp() { mappingLocator = new MappingLocator(); mappingLocator.populate(); }
Source:
public SlackTextMessage execute(String... args) { String projectName = args[0]; String buildNumber = args[1]; SecurityContext ctx = ACL.impersonate(ACL.SYSTEM); List<String> log = new ArrayList<String>(); Jenkins j = Jenkins.getInstance(); if (j == null) { throw new IllegalStateException(); } try { Project project = j.getItemByFullName(projectName, Project.class); if (project == null) return new SlackTextMessage("Could not find project ("+projectName+")\n"); AbstractBuild build = project.getBuildByNumber(Integer.parseInt(buildNumber)); if (build == null) return new SlackTextMessage("Could not find build #"+buildNumber+" for ("+projectName+")\n"); log = build.getLog(25); } catch (IOException ex) { return new SlackTextMessage("Error occured returning log: "+ex.getMessage()); } finally { SecurityContextHolder.setContext(ctx); } String response = "*"+projectName+"* *#"+buildNumber+"*\n"; response += "```"; StringBuffer buf = new StringBuffer(); for (String line : log) { buf.append(line).append("\n"); } response += buf.toString() + "```"; return new SlackTextMessage(response); }

Target:
public SlackTextMessage execute(String... args) { String projectName = args[0]; String buildNumber = args[1]; SecurityContext ctx = ACL.impersonate(ACL.SYSTEM); List<String> log; try { Project project = Jenkins.getActiveInstance().getItemByFullName(projectName, Project.class); if (project == null) return new SlackTextMessage("Could not find project ("+projectName+")\n"); AbstractBuild build = project.getBuildByNumber(Integer.parseInt(buildNumber)); if (build == null) return new SlackTextMessage("Could not find build #"+buildNumber+" for ("+projectName+")\n"); log = build.getLog(25); } catch (IOException ex) { return new SlackTextMessage("Error occured returning log: "+ex.getMessage()); } finally { SecurityContextHolder.setContext(ctx); } StringBuilder builder = new StringBuilder("*" + projectName + "* *#" + buildNumber + "*\n```"); for (String line : log) { builder.append(line).append("\n"); } builder.append("```"); return new SlackTextMessage(builder.toString()); }
Source:
private void processQueuedFlows(long activeExecutorsRefreshWindow, int maxContinuousFlowProcessed) throws InterruptedException, ExecutorManagerException { long lastProcessingTime = System.currentTimeMillis(); Pair<ExecutionReference, ExecutableFlow> runningCandidate; int currentContinuousFlowProcessed = 0; while (isActive() && (runningCandidate = waitAndFetchQueueHead()) != null) { ExecutionReference reference = runningCandidate.getFirst(); ExecutableFlow exflow = runningCandidate.getSecond(); long currentTime = System.currentTimeMillis(); if (currentTime - lastProcessingTime > activeExecutorsRefreshWindow || currentContinuousFlowProcessed >= maxContinuousFlowProcessed) { refreshExecutors(); lastProcessingTime = currentTime; currentContinuousFlowProcessed = 0; } processFlow(reference, exflow, new HashSet<Executor>(activeExecutors)); currentContinuousFlowProcessed++; } }

Target:
private void processQueuedFlows(long activeExecutorsRefreshWindow, int maxContinuousFlowProcessed) throws InterruptedException, ExecutorManagerException { long lastExecutorRefreshTime = System.currentTimeMillis(); Pair<ExecutionReference, ExecutableFlow> runningCandidate; int currentContinuousFlowProcessed = 0; while (isActive() && (runningCandidate = queuedFlows.fetchHead()) != null) { ExecutionReference reference = runningCandidate.getFirst(); ExecutableFlow exflow = runningCandidate.getSecond(); long currentTime = System.currentTimeMillis(); if (currentTime - lastExecutorRefreshTime > activeExecutorsRefreshWindow || currentContinuousFlowProcessed >= maxContinuousFlowProcessed) { refreshExecutors(); lastExecutorRefreshTime = currentTime; currentContinuousFlowProcessed = 0; } processFlow(reference, exflow, new HashSet<Executor>(activeExecutors)); currentContinuousFlowProcessed++; } }
Source:
private void setNumColumns(int numColumns, boolean fromSeekBar) { if (fromSeekBar) { mNumColumns = numColumns + 1; } else { mNumColumns = numColumns; mNumColumnsSeekBar.setProgress(numColumns); } TextView textValue = (TextView) getView().findViewById(R.id.text_num_columns_label); textValue.setText(String.format(getString(R.string.media_gallery_column_count), mNumColumns)); }

Target:
private void setNumColumns(int numColumns, boolean fromSeekBar) { if (fromSeekBar) { mNumColumns = numColumns + 1; } else { mNumColumns = numColumns; mNumColumnsSeekBar.setProgress(numColumns); } TextView textValue = (TextView) getView().findViewById(R.id.text_num_columns_label); if (mNumColumns == 1) { textValue.setText(getString(R.string.media_gallery_column_count_single)); } else { textValue.setText(String.format(getString(R.string.media_gallery_column_count_multi), mNumColumns)); } }
Source:
protected Queue initializeQueue(AmqpAdmin admin, String channelName) { if (this.exchange == null) { String exchangeName = "si.fanout." + channelName; this.exchange = new FanoutExchange(exchangeName); } admin.declareExchange(this.exchange); this.queue = new AnonymousQueue(); admin.declareQueue(this.queue); this.binding = BindingBuilder.bind(this.queue).to(this.exchange); admin.declareBinding(this.binding); this.admin = admin; if (!this.initialized && this.getAmqpTemplate() instanceof RabbitTemplate) { ((RabbitTemplate) this.getAmqpTemplate()).getConnectionFactory().addConnectionListener(this); } this.initialized = true; return this.queue; }

Target:
protected Queue initializeQueue(AmqpAdmin admin, String channelName) { if (this.exchange == null) { String exchangeName = "si.fanout." + channelName; this.exchange = new FanoutExchange(exchangeName); } admin.declareExchange(this.exchange); admin.declareQueue(this.queue); this.binding = BindingBuilder.bind(this.queue).to(this.exchange); admin.declareBinding(this.binding); if (!this.initialized && this.getAmqpTemplate() instanceof RabbitTemplate) { ConnectionFactory connectionFactory = this.getConnectionFactory(); if (connectionFactory != null) { connectionFactory.addConnectionListener(this); } } this.initialized = true; return this.queue; }
Source:
private void onRoutingTableInitReqMsg(final AvroElasticMemoryMessage msg) { Trace.setProcessId("driver"); try (final TraceScope onRoutingTableInitReqMsgScope = Trace.startSpan(ON_ROUTING_INIT_REQ_MSG, HTraceUtils.fromAvro(msg.getTraceInfo()))) { final List<Integer> blockLocations = blockManager.getBlockLocations(); msgSender.get().sendRoutingTableInitMsg(msg.getSrcId().toString(), blockLocations, TraceInfo.fromSpan(onRoutingTableInitReqMsgScope.getSpan())); } }

Target:
private void onRoutingTableInitReqMsg(final AvroElasticMemoryMessage msg) { try (final TraceScope onRoutingTableInitReqMsgScope = Trace.startSpan("on_routing_table_init_req_msg", HTraceUtils.fromAvro(msg.getTraceInfo()))) { final List<Integer> blockLocations = blockManager.getBlockLocations(); msgSender.get().sendRoutingTableInitMsg(msg.getSrcId().toString(), blockLocations, TraceInfo.fromSpan(onRoutingTableInitReqMsgScope.getSpan())); } }
Source:
public Response toResponse(RuntimeException exception) { String errorMessage = exception.getMessage(); if (!isNullOrEmpty(errorMessage)) { DtoFactory dtoFactory = DtoFactory.getInstance(); ServiceError serviceError = dtoFactory.createDto(ServiceError.class).withMessage(errorMessage); return Response.serverError() .entity(dtoFactory.toJson(serviceError)) .type(MediaType.APPLICATION_JSON) .build(); } return Response.serverError().build(); }

Target:
public Response toResponse(RuntimeException exception) { final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); final String utcTime = dateFormat.format(new Date()); final String errorMessage = format("Internal Server Error occurred, error time: %s", utcTime); LOG.error(errorMessage, exception); ServiceError serviceError = DtoFactory.newDto(ServiceError.class).withMessage(errorMessage); return Response.serverError() .entity(DtoFactory.getInstance().toJson(serviceError)) .type(MediaType.APPLICATION_JSON) .build(); }
Source:
public String createLogForAllAlarms() { String log = userID + "\nAdresse: " + userAddress + "\nListes des alarmes: \n"; if (alarms.isEmpty()) { log += "There is no alarm for this user."; } else { log += formatAlarms(); } return log; }

Target:
public String createLogForAllAlarms() { String log = userID + "\nAddresse: " + userAddress + "\nAlarms' list: \n"; if (alarms.isEmpty()) { log += "There is no alarms for this user."; } else { log += formatAlarms(); } return log; }
Source:
private TenancyProvider getTenancyProvider() throws DeploymentEnvironmentException { String platform = System.getenv(ENV_DEPLOYMENT_PLATFORM); if (platform == null || platform.equals("")) { throw new DeploymentEnvironmentException("Unable to identify the deployment platform"); } if (platform.equalsIgnoreCase(DEPLOYMENT_KUBERNETES)) { return new KubernetesTenancyProvider(); } else { throw new DeploymentEnvironmentException("Unsupported deployment platform: " + platform); } }

Target:
private TenancyProvider getTenancyProvider() throws DeploymentEnvironmentException { String platform = System.getenv(ENV_DEPLOYMENT_PLATFORM); if (platform == null || platform.isEmpty()) { throw new DeploymentEnvironmentException("Unable to identify the deployment platform"); } if (DEPLOYMENT_KUBERNETES.equalsIgnoreCase(platform)) { return new KubernetesTenancyProvider(); } else { throw new DeploymentEnvironmentException("Unsupported deployment platform: " + platform); } }
Source:
protected void endActionOnVmConfiguration() { if (getVm() != null) { if (getVm().getstatus() == VMStatus.ImageLocked) { VmHandler.unlockVm(getVm(), getCompensationContext()); } UpdateVmInSpm(getVm().getstorage_pool_id(), Arrays.asList(getVm())); } else { setCommandShouldBeLogged(false); log.warn("VmCommand::EndVmCommand: Vm is null - not performing EndAction on Vm"); } setSucceeded(true); }

Target:
protected void endActionOnVmConfiguration() { if (getVm().getstatus() == VMStatus.ImageLocked) { VmHandler.unlockVm(getVm(), getCompensationContext()); } UpdateVmInSpm(getVm().getstorage_pool_id(), Arrays.asList(getVm())); setSucceeded(true); }
Source:
public String getShortName() { return "additionallinks"; }

Target:
public String getShortName() { return "linkgroups"; }