auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isInSketchbook() { return getFolder().getAbsolutePath().startsWith(BaseNoGui.getDefaultSketchbookFolder().getAbsolutePath()); }

Target:
public boolean isInSketchbook() { return getFolder().getAbsolutePath().startsWith(BaseNoGui.getSketchbookHardwareFolder().getAbsolutePath()); }
Source:
private void draw() { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); commonDrawer.begin(); if (solGame != null) { solGame.draw(); } uiDrawer.updateMtx(); inputManager.draw(uiDrawer, this); if (solGame != null) { solGame.drawDebugUi(uiDrawer); factionDisplay.drawFactionNames(uiDrawer); } if (fatalErrorMsg != null) { uiDrawer.draw(uiDrawer.whiteTexture, displayDimensions.getRatio(), .5f, 0, 0, 0, .25f, 0, SolColor.UI_BG); uiDrawer.drawString(fatalErrorMsg, displayDimensions.getRatio(), .5f, FontSize.MENU, true, SolColor.WHITE); uiDrawer.drawString(fatalErrorTrace, .2f * displayDimensions.getRatio(), .6f, FontSize.DEBUG, false, SolColor.WHITE); } DebugCollector.draw(uiDrawer); if (solGame == null) { uiDrawer.drawString("v" + Const.VERSION, 0.01f, .974f, FontSize.DEBUG, UiDrawer.TextAlignment.LEFT, false, SolColor.WHITE); } commonDrawer.end(); }

Target:
private void draw() { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); commonDrawer.begin(); if (solGame != null) { solGame.draw(); } uiDrawer.updateMtx(); inputManager.draw(uiDrawer, this); if (solGame != null) { solGame.drawDebugUi(uiDrawer); factionDisplay.drawFactionNames(solGame, uiDrawer, inputManager, solGame.getObjectManager()); } if (fatalErrorMsg != null) { uiDrawer.draw(uiDrawer.whiteTexture, displayDimensions.getRatio(), .5f, 0, 0, 0, .25f, 0, SolColor.UI_BG); uiDrawer.drawString(fatalErrorMsg, displayDimensions.getRatio(), .5f, FontSize.MENU, true, SolColor.WHITE); uiDrawer.drawString(fatalErrorTrace, .2f * displayDimensions.getRatio(), .6f, FontSize.DEBUG, false, SolColor.WHITE); } DebugCollector.draw(uiDrawer); if (solGame == null) { uiDrawer.drawString("v" + Const.VERSION, 0.01f, .974f, FontSize.DEBUG, UiDrawer.TextAlignment.LEFT, false, SolColor.WHITE); } commonDrawer.end(); }
Source:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); description.addProperty("deathdateEstimated"); description.addProperty("birthtime"); return description; }

Target:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); description.addProperty("birthtime"); return description; }
Source:
public CustomTierSelectorStrategy( @JacksonInject ServerSelectorStrategy serverSelectorStrategy, @JacksonInject CustomTierSelectorStrategyConfig config ) { super(serverSelectorStrategy); final Map<Integer, Integer> lookup = Maps.newHashMap(); int pos = 0; for (Integer integer : config.getPriorities()) { lookup.put(integer, pos); pos++; } this.comparator = (o1, o2) -> { int pos1 = lookup.get(o1); int pos2 = lookup.get(o2); return Ints.compare(pos1, pos2); }; }

Target:
public CustomTierSelectorStrategy( @JacksonInject ServerSelectorStrategy serverSelectorStrategy, @JacksonInject CustomTierSelectorStrategyConfig config ) { super(serverSelectorStrategy); final Map<Integer, Integer> lookup = Maps.newHashMap(); int pos = 0; for (Integer integer : config.getPriorities()) { lookup.put(integer, pos); pos++; } this.comparator = Comparator.comparingInt(lookup::get); }
Source:
public CompletableFuture<String> next() { return next(timeout); }

Target:
public CompletableFuture<String> next() { return next(null); }
Source:
private static void checkCondition(List<Event> events, SoftAssertions softly, Condition<? super Event> condition) { boolean matches = events.stream().anyMatch(condition::matches); if (!matches) softly.fail("Condition did not match any event: " + condition); }

Target:
private static void checkCondition(List<Event> events, SoftAssertions softly, Condition<? super Event> condition) { boolean matches = events.stream().anyMatch(condition::matches); if (!matches) { softly.fail("Condition did not match any event: " + condition); } }
Source:
protected Subject createSubject(final CallbackProperties properties, final X509Certificate certificate, final PublicKey publicKey) throws SAMLComponentBuilderException { String x509Name = properties.getUsername(); OpenSAML2ComponentBuilder openSamlBuilder = OpenSAML2ComponentBuilder.getInstance(); if ((NullChecker.isNullish(x509Name) || !checkDistinguishedName(x509Name)) && null != certificate && null != certificate.getSubjectDN()) { x509Name = certificate.getSubjectDN().getName(); } Subject subject = openSamlBuilder.createSubject(x509Name, publicKey); List<SubjectConfirmationDataBean> bearBeans = properties.getBearerBeans(); if (CollectionUtils.isNotEmpty(bearBeans)) { for (SubjectConfirmationDataBean bear : bearBeans) { SubjectConfirmation bearConfirmation = openSamlBuilder.createBearConfirmation(bear); subject.getSubjectConfirmations().add(bearConfirmation); } } List<SubjectConfirmationDataBean> senderVouchesBeans = properties.getSenderVouchesBeans(); if (CollectionUtils.isNotEmpty(senderVouchesBeans)) { for (SubjectConfirmationDataBean sender : senderVouchesBeans) { SubjectConfirmation bearConfirmation = openSamlBuilder.createSenderVouchesConfirmation(sender); subject.getSubjectConfirmations().add(bearConfirmation); } } return subject; }

Target:
protected Subject createSubject(final CallbackProperties properties, final X509Certificate certificate, final PublicKey publicKey) throws SAMLComponentBuilderException { String x509Name = properties.getUsername(); OpenSAML2ComponentBuilder openSamlBuilder = OpenSAML2ComponentBuilder.getInstance(); if ((NullChecker.isNullish(x509Name) || !checkDistinguishedName(x509Name)) && null != certificate && null != certificate.getSubjectDN()) { x509Name = certificate.getSubjectDN().getName(); } Subject subject = openSamlBuilder.createSubject(x509Name, publicKey); List<SAMLSubjectConfirmation> subjectConfirmations = properties.getSubjectConfirmations(); if (CollectionUtils.isNotEmpty(subjectConfirmations)) { for (SAMLSubjectConfirmation confirmation : subjectConfirmations) { SubjectConfirmation subjectConfirmation = openSamlBuilder.createSubjectConfirmation(confirmation); if (subjectConfirmation != null) { subject.getSubjectConfirmations().add(openSamlBuilder.createSubjectConfirmation(confirmation)); } } } return subject; }
Source:
public Map<String, Object> baseline(final Blackhole blackhole) { Map<String, Object> parsed = flatParser.parseToMap(flatInputs.get(flatCounter)); for (Map.Entry<String, Object> entry : parsed.entrySet()) { String s = entry.getKey(); blackhole.consume(parsed.get(s)); } flatCounter = (flatCounter + 1) % numEvents; return parsed; }

Target:
public Map<String, Object> baseline(final Blackhole blackhole) { Map<String, Object> parsed = flatParser.parseToMap(flatInputs.get(flatCounter)); for (Object s : parsed.values()) { blackhole.consume(s); } flatCounter = (flatCounter + 1) % numEvents; return parsed; }
Source:
private RelRoot optimize(Planner planner, RelRoot relRoot) { RelTraitSet relTraitSet = RelTraitSet.createEmpty(); try { RelRoot optimizedRelRoot = RelRoot.of(planner.transform(0, relTraitSet, relRoot.project()), SqlKind.SELECT); LOG.info("query plan with optimization:\n" + RelOptUtil.toString(optimizedRelRoot.rel, SqlExplainLevel.EXPPLAN_ATTRIBUTES)); return optimizedRelRoot; } catch (Exception e) { String errorMsg = "Error while optimizing query plan:\n" + RelOptUtil.toString(relRoot.rel, SqlExplainLevel.EXPPLAN_ATTRIBUTES); LOG.error(errorMsg, e); planner.close(); throw new SamzaException(errorMsg, e); } }

Target:
private RelRoot optimize(Planner planner, RelRoot relRoot) { RelTraitSet relTraitSet = RelTraitSet.createEmpty(); try { RelRoot optimizedRelRoot = RelRoot.of(planner.transform(0, relTraitSet, relRoot.project()), SqlKind.SELECT); LOG.info("query plan with optimization:\n" + RelOptUtil.toString(optimizedRelRoot.rel, SqlExplainLevel.EXPPLAN_ATTRIBUTES)); return optimizedRelRoot; } catch (Exception e) { String errorMsg = "Error while optimizing query plan:\n" + RelOptUtil.toString(relRoot.rel, SqlExplainLevel.EXPPLAN_ATTRIBUTES); LOG.error(errorMsg, e); throw new SamzaException(errorMsg, e); } }
Source:
public String getValidationReason() { return why; }

Target:
public String getValidationReason() { return message; }
Source:
private ValueMatcher makeMatcher(final ValueMatcher[] baseMatchers){ if (baseMatchers.length == 0) { return BooleanValueMatcher.of(false); } if (baseMatchers.length == 1) { return baseMatchers[0]; } return new ValueMatcher() { @Override public boolean matches() { for (ValueMatcher matcher : baseMatchers) { if (matcher.matches()) { return true; } } return false; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("firstBaseMatcher", baseMatchers[0]); inspector.visit("secondBaseMatcher", baseMatchers[1]); } }; }

Target:
private ValueMatcher makeMatcher(final ValueMatcher[] baseMatchers){ Preconditions.checkState(baseMatchers.length > 0); if (baseMatchers.length == 1) { return baseMatchers[0]; } return new ValueMatcher() { @Override public boolean matches() { for (ValueMatcher matcher : baseMatchers) { if (matcher.matches()) { return true; } } return false; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("firstBaseMatcher", baseMatchers[0]); inspector.visit("secondBaseMatcher", baseMatchers[1]); } }; }
Source:
public CollectionOfClassesObjectFormatter(Collection<Class<?>> classes) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Class<?> clazz : classes ) { if ( !isFirst ) { sb.append( ", " ); } else { isFirst = false; } sb.append( clazz.getName() ); } this.stringRepresentation = sb.toString(); }

Target:
public CollectionOfClassesObjectFormatter(Collection<Class<?>> classes) { this.stringRepresentation = classes.stream() .map( c -> c.getName() ) .collect( Collectors.joining( ", " ) ); }
Source:
public static String convertEdgeToGraph(String outputNode, Node value, GRAPH_TYPE graphType) { String outputEdge = ""; for (EDGETYPE et : EDGETYPE.values()) { for (VKmer e : value.getEdgeList(et)) { String destNode = ""; switch (graphType) { case UNDIRECTED_GRAPH_WITHOUT_LABELS: if (map.containsKey(e.toString())) destNode += map.get(e.toString()); else { count++; map.put(e.toString(), count); destNode += count; } outputEdge += outputNode + " -> " + destNode + "[dir=none]\n"; break; case DIRECTED_GRAPH_WITH_SIMPLELABEL_AND_EDGETYPE: if (map.containsKey(e.toString())) destNode += map.get(e.toString()); else { count++; map.put(e.toString(), count); destNode += count; } outputEdge += outputNode + " -> " + destNode + "[color = \"" + getColor(et) + "\" label =\"" + et + "\"]\n"; break; case DIRECTED_GRAPH_WITH_KMERS_AND_EDGETYPE: outputEdge += outputNode + " -> " + e.toString() + "[color = \"" + getColor(et) + "\" label =\"" + et + "\"]\n"; break; case DIRECTED_GRAPH_WITH_ALLDETAILS: outputEdge += outputNode + " -> " + e.toString() + "[color = \"" + getColor(et) + "\" label =\"" + et + "\"]\n"; break; default: throw new IllegalStateException("Invalid input Graph Type!!!"); } } } if (outputEdge == "") outputEdge += outputNode; return outputEdge; }

Target:
public static String convertEdgeToGraph(String outputNode, Node value, GRAPH_TYPE graphType) { String outputEdge = ""; for (EDGETYPE et : EDGETYPE.values) { for (VKmer e : value.getEdges(et)) { String destNode = ""; switch (graphType) { case UNDIRECTED_GRAPH_WITHOUT_LABELS: if (map.containsKey(e.toString())) destNode += map.get(e.toString()); else { count++; map.put(e.toString(), count); destNode += count; } outputEdge += outputNode + " -> " + destNode + "[dir=none]\n"; break; case DIRECTED_GRAPH_WITH_SIMPLELABEL_AND_EDGETYPE: if (map.containsKey(e.toString())) destNode += map.get(e.toString()); else { count++; map.put(e.toString(), count); destNode += count; } outputEdge += outputNode + " -> " + destNode + "[color = \"" + getColor(et) + "\" label =\"" + et + "\"]\n"; break; case DIRECTED_GRAPH_WITH_KMERS_AND_EDGETYPE: outputEdge += outputNode + " -> " + e.toString() + "[color = \"" + getColor(et) + "\" label =\"" + et + "\"]\n"; break; case DIRECTED_GRAPH_WITH_ALLDETAILS: outputEdge += outputNode + " -> " + e.toString() + "[color = \"" + getColor(et) + "\" label =\"" + et + "\"]\n"; break; default: throw new IllegalStateException("Invalid input Graph Type!!!"); } } } if (outputEdge == "") outputEdge += outputNode; return outputEdge; }
Source:
private void dialogUpdated() { if (Strings.isNullOrEmpty(destination.getText()) || Strings.isNullOrEmpty(commitMessage.getText())) { disableOKButton(); } else { enableOKButton(); } }

Target:
private void dialogUpdated() { boolean isSubmittable = !Strings.isNullOrEmpty(destination.getText()) && !Strings.isNullOrEmpty(commitMessage.getText()); setOKButtonEnabled(isSubmittable); }
Source:
public void testSTArea() throws Exception { assertQuery("select ST_Area(ST_GeometryFromText('Polygon ((2 2, 2 6, 6 6, 6 2))'))", "select 16.0"); assertQueryFails("select ST_Area(ST_GeometryFromText('Point (1 4)'))", "ST_Area only applies to Polygon. Input type is: Point"); }

Target:
public void testSTArea() throws Exception { assertFunction("ST_Area(ST_GeometryFromText('POLYGON ((2 2, 2 6, 6 6, 6 2))'))", DOUBLE, 16.0); assertFunction("ST_Area(ST_GeometryFromText('POLYGON EMPTY'))", DOUBLE, 0.0); assertInvalidFunction("ST_Area(ST_GeometryFromText('POINT (1 4)'))", "ST_Area only applies to POLYGON or MULTI_POLYGON. Input type is: POINT"); }
Source:
private Map<String,String> readDescriptions(File file) throws IOException { BufferedReader readerHeader = new BufferedReader(new FileReader(file)); BufferedReader readerbody = new BufferedReader(new FileReader(file)); String header = ""; String description = ""; String line; Map<String,String> descriptions = new HashMap<String,String>(); while ((line = readerHeader.readLine()) != null) { if (line.startsWith("#")) { header += line + "\n"; } if (line.isEmpty()) { descriptions.put("hasHeader", "true"); descriptions.put("header", header); break; } else if ((!(line.startsWith("#")) && (!(line.isEmpty())))) { descriptions.put("header", "false"); } } readerHeader.close(); while ((line = readerbody.readLine()) != null) { if (line.startsWith("#")) { description += line + "\n"; } if (line.isEmpty()) { description = ""; } else if ((!(line.startsWith("#")) && (!(line.isEmpty())))) { String[] nameValue = line.split("="); String name = nameValue[0]; descriptions.put(name, description); description = ""; } } readerbody.close(); return descriptions; }

Target:
private Map<String,String> readDescriptions(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String header = ""; String description = ""; String line; Map<String,String> descriptions = new HashMap<String,String>(); while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { description += line + "\n"; } if (line.isEmpty()) { description = ""; } else if ((!(line.startsWith("#")) && (!(line.isEmpty())))) { String[] nameValue = line.split("="); String name = nameValue[0]; descriptions.put(name, description); description = ""; } } reader.close(); return descriptions; }
Source:
public ClassFactory(final SSymbol name, final MixinDefinition mixinDef, final EconomicSet<SlotDefinition> instanceSlots, final EconomicMap<SSymbol, Dispatchable> dispatchables, final boolean declaredAsValue, final boolean isTransferObject, final boolean isArray, final SClass[] superclassAndMixins, final boolean hasOnlyImmutableFields, final ClassFactory classClassFactory, final NodeFactory<? extends AbstractSerializationNode> serializerFactory) { assert instanceSlots == null || instanceSlots.size() > 0; this.className = name; this.mixinDef = mixinDef; this.instanceSlots = instanceSlots; this.dispatchables = dispatchables; this.isDeclaredAsValue = declaredAsValue; this.isTransferObject = isTransferObject; this.isArray = isArray; this.hasOnlyImmutableFields = hasOnlyImmutableFields; this.superclassAndMixins = superclassAndMixins; if (VmSettings.SNAPSHOTS_ENABLED) { CompilerDirectives.transferToInterpreter(); this.serializationRoot = new SerializerRootNode(null, serializerFactory.createNode(this)); } else { this.serializationRoot = null; } VM.callerNeedsToBeOptimized( "instanceLayout should only be accessed on slow path. (and ClassFactory should only be instantiated on slowpath, too)"); this.instanceLayout = (instanceSlots == null) ? null : new ObjectLayout(instanceSlots, this, isTransferObject); this.classClassFactory = classClassFactory; }

Target:
public ClassFactory(final SSymbol name, final MixinDefinition mixinDef, final EconomicSet<SlotDefinition> instanceSlots, final EconomicMap<SSymbol, Dispatchable> dispatchables, final boolean declaredAsValue, final boolean isTransferObject, final boolean isArray, final SClass[] superclassAndMixins, final boolean hasOnlyImmutableFields, final ClassFactory classClassFactory, final NodeFactory<? extends AbstractSerializationNode> serializerFactory) { assert instanceSlots == null || instanceSlots.size() > 0; this.className = name; this.mixinDef = mixinDef; this.instanceSlots = instanceSlots; this.dispatchables = dispatchables; this.isDeclaredAsValue = declaredAsValue; this.isTransferObject = isTransferObject; this.isArray = isArray; this.hasOnlyImmutableFields = hasOnlyImmutableFields; this.superclassAndMixins = superclassAndMixins; if (VmSettings.SNAPSHOTS_ENABLED) { this.serializationRoot = new SerializerRootNode(null, serializerFactory.createNode(this)); } else { this.serializationRoot = null; } VM.callerNeedsToBeOptimized( "instanceLayout should only be accessed on slow path. (and ClassFactory should only be instantiated on slowpath, too)"); this.instanceLayout = (instanceSlots == null) ? null : new ObjectLayout(instanceSlots, this, isTransferObject); this.classClassFactory = classClassFactory; }
Source:
public static void classLevelSetup() throws Exception { Configuration conf = new Configuration(); conf.set("dfs.client.use.datanode.hostname", "true"); conf.set("hadoop.proxyuser." + Utils.getUGI().getShortUserName() + ".hosts", "*"); MiniDFSCluster miniDFSCluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).format(true).build(); HashMap<String, String> overridesForHiveConf = new HashMap<String, String>() {{ put("fs.defaultFS", miniDFSCluster.getFileSystem().getUri().toString()); put(HiveConf.ConfVars.HIVE_IN_TEST_REPL.varname, "true"); }}; HashMap<String, String> overridesForHiveConfDump = new HashMap<String, String>() {{ put("fs.defaultFS", miniDFSCluster.getFileSystem().getUri().toString()); put(HiveConf.ConfVars.HIVE_IN_TEST_REPL.varname, "true"); put(HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES.varname, "true"); }}; primary = new WarehouseInstance(LOG, miniDFSCluster, overridesForHiveConf); replica = new WarehouseInstance(LOG, miniDFSCluster, overridesForHiveConf); externalDump = new WarehouseInstance(LOG, miniDFSCluster, overridesForHiveConfDump); }

Target:
public static void classLevelSetup() throws Exception { Configuration conf = new Configuration(); conf.set("dfs.client.use.datanode.hostname", "true"); conf.set("hadoop.proxyuser." + Utils.getUGI().getShortUserName() + ".hosts", "*"); MiniDFSCluster miniDFSCluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).format(true).build(); HashMap<String, String> overridesForHiveConf = new HashMap<String, String>() {{ put("fs.defaultFS", miniDFSCluster.getFileSystem().getUri().toString()); put(HiveConf.ConfVars.HIVE_IN_TEST_REPL.varname, "true"); }}; primary = new WarehouseInstance(LOG, miniDFSCluster, overridesForHiveConf); replica = new WarehouseInstance(LOG, miniDFSCluster, overridesForHiveConf); }
Source:
public void run(MasterConfig masterConfig, Collection<Report> reports) { if (perfRepoAuth == null) { log.error("perfRepoAuth parameter has to be set"); return; } if (perfRepoTest == null) { log.error("perfRepoTest parameter has to be set"); return; } for (Report report : reports) { reportTests(report); } }

Target:
public void run(MasterConfig masterConfig, Collection<Report> reports) { this.masterConfig = masterConfig; if (perfRepoAuth == null) { log.error("perfRepoAuth parameter has to be set"); return; } if (perfRepoTest == null) { log.error("perfRepoTest parameter has to be set"); return; } for (Report report : reports) { reportTests(report); } }
Source:
protected JsonObject doBuild() { JsonArray array = new JsonArray( values.size() ); values.stream().forEach( value -> array.add( value ) ); JsonObject inner = getInnerObject(); VALUES.set( inner, array ); JsonObject outerObject = getOuterObject(); IDS.set( outerObject, getInnerObject() ); return outerObject; }

Target:
protected JsonObject doBuild() { JsonArray array = convert( values ); JsonObject inner = getInnerObject(); VALUES.set( inner, array ); JsonObject outerObject = getOuterObject(); IDS.set( outerObject, getInnerObject() ); return outerObject; }
Source:
public static final ServiceProvider setCurrent(ServiceProvider provider) { Objects.requireNonNull(provider); ServiceProvider old = current.getAndSet(provider); if (old.equals(provider)) { System.getLogger("javax.measure.spi").log(System.Logger.Level.DEBUG, "Measurement ServiceProvider {1,choice,0#set to|1#replaced by} {0}.", new Object[] {provider.getClass().getName(), (old == null) ? 0 : 1}); } return old; }

Target:
public static final ServiceProvider setCurrent(ServiceProvider provider) { Objects.requireNonNull(provider); ServiceProvider old = current.getAndSet(provider); if (old != provider) { System.getLogger("javax.measure.spi").log(System.Logger.Level.DEBUG, "Measurement ServiceProvider {1,choice,0#set to|1#replaced by} {0}.", new Object[] {provider.getClass().getName(), (old == null) ? 0 : 1}); } return old; }
Source:
private CSVListener readCsvFrom(CSVListener listener, String urlSource, String fileSource){ try { if (urlSource != null) { URL url = new URL(urlSource); try (InputStream is = url.openStream()) { new CSVLibrary().parse(is, listener); } } if (fileSource != null) { InputStream is = new BufferedInputStream(new FileInputStream(fileSource)); new CSVLibrary().parse(is, listener); } } catch (Exception e) { e.printStackTrace(); } return listener; }

Target:
private CSVListener readCsvFrom(CSVListener listener, String urlSource, String fileSource){ try { if (urlSource != null) { URL url = new URL(urlSource); try (InputStream is = url.openStream()) { new CSVLibrary().parse(is, listener); } } if (fileSource != null) { InputStream is = new BufferedInputStream(new FileInputStream(fileSource)); new CSVLibrary().parse(is, listener); } } catch (Exception e) { _log.error(e.getMessage()); } return listener; }
Source:
public void testListRoles() throws Exception { List<RoleInfo> possibleRoles = api().listRoles(); assertNotNull(possibleRoles, "possibleRoles was not set"); assertTrue(possibleRoles.size() > 0, "Expected at least 1 Role but list was empty"); boolean roleFound = false; for (RoleInfo possibleRole : possibleRoles) { if (possibleRole.name().equals(roleName)) { roleFound = true; } } assertTrue(roleFound, "Expected but could not find Role amongst " + possibleRoles.size() + " found"); }

Target:
public void testListRoles() throws Exception { List<RoleInfo> possibleRoles = api().listRoles(); assertNotNull(possibleRoles, "possibleRoles was not set"); assertTrue(possibleRoles.size() > 0, "Expected at least 1 Role but list was empty"); RoleInfo possibleRole = Iterables.find(possibleRoles, new Predicate<RoleInfo>() { @Override public boolean apply(RoleInfo arg0) { return arg0.name().equals(roleName); } }, null); assertNotNull(possibleRole, "Expected but could not find Role amongst " + possibleRoles.size() + " found"); }
Source:
private int resolveIterationsCount(MessageContext synCtx) { String countStr = ""; if (getDynamicIterationsValue() != null) { countStr = getDynamicIterationsValue().evaluateValue(synCtx); } else if (getIterations() != null) { countStr = getIterations(); } return Integer.parseInt(countStr); }

Target:
private int resolveIterationsCount(MessageContext synCtx) { String countStr = ""; if (getDynamicIterationsValue() != null) { countStr = getDynamicIterationsValue().evaluateValue(synCtx); } else { countStr = getIterations(); } try { return Integer.parseInt(countStr.trim()); } catch (NumberFormatException e) { handleException("Error while parsing iterations number in clone mediator", synCtx); } return 0; }
Source:
private static void regenerateDataBundleJson(File folder) throws IOException { File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.getName().endsWith(".json") && !NON_DATA_BUNDLE_JSON.contains(file.getName())) { String jsonString = FileHelper.readFile(file.getCanonicalPath()); Gson gson = Utils.getTeammatesGson(); DataBundle db = gson.fromJson(jsonString, DataBundle.class); for (Map.Entry<String, FeedbackResponseAttributes> responseMap : db.feedbackResponses.entrySet()) { fixResponse(responseMap.getValue()); } for (Map.Entry<String, FeedbackQuestionAttributes> questionMap : db.feedbackQuestions.entrySet()) { fixQuestion(questionMap.getValue()); } String regeneratedJsonString = gson.toJson(db).replace("+0000", "UTC"); saveFile(file.getCanonicalPath(), regeneratedJsonString); } } }

Target:
private static void regenerateDataBundleJson(File folder) throws IOException { File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (!file.getName().endsWith(".json") || NON_DATA_BUNDLE_JSON.contains(file.getName())) { continue; } String jsonString = FileHelper.readFile(file.getCanonicalPath()); Gson gson = Utils.getTeammatesGson(); DataBundle db = gson.fromJson(jsonString, DataBundle.class); for (Map.Entry<String, FeedbackResponseAttributes> responseMap : db.feedbackResponses.entrySet()) { fixResponse(responseMap.getValue()); } for (Map.Entry<String, FeedbackQuestionAttributes> questionMap : db.feedbackQuestions.entrySet()) { fixQuestion(questionMap.getValue()); } String regeneratedJsonString = gson.toJson(db).replace("+0000", "UTC"); saveFile(file.getCanonicalPath(), regeneratedJsonString); } }
Source:
private void validateLocalUTCQueryRange(final DateTime startQueryTimestampLocalUTC, final DateTime endQueryTimestampLocalUTC, final Long accountId, final long allowedRangeInSeconds) { if (startQueryTimestampLocalUTC == null || endQueryTimestampLocalUTC == null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } if(startQueryTimestampLocalUTC.getZone().equals(DateTimeZone.UTC) == false || endQueryTimestampLocalUTC.getZone().equals(DateTimeZone.UTC) == false) { LOGGER.error("validateLocalUTCQueryRange: Query start/end timestamp is not set to local UTC. start: {}, end: {}", startQueryTimestampLocalUTC, endQueryTimestampLocalUTC); throw new WebApplicationException(Response.Status.BAD_REQUEST); } if(Math.abs(startQueryTimestampLocalUTC.getMillis() - endQueryTimestampLocalUTC.getMillis()) > 2 * allowedRangeInSeconds * 1000) { LOGGER.warn("Invalid request, query to range is too big for account_id = {}", startQueryTimestampLocalUTC, endQueryTimestampLocalUTC, accountId); throw new WebApplicationException(Response.Status.FORBIDDEN); } }

Target:
private void validateLocalUTCQueryRange(final DateTime startQueryTimestampLocalUTC, final DateTime endQueryTimestampLocalUTC, final Long accountId, final long allowedRangeInSeconds) { if (startQueryTimestampLocalUTC == null || endQueryTimestampLocalUTC == null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } if(startQueryTimestampLocalUTC.getZone().equals(DateTimeZone.UTC) == false || endQueryTimestampLocalUTC.getZone().equals(DateTimeZone.UTC) == false) { LOGGER.error("validateLocalUTCQueryRange: Query start/end timestamp is not set to local UTC. start: {}, end: {}", startQueryTimestampLocalUTC, endQueryTimestampLocalUTC); throw new WebApplicationException(Response.Status.BAD_REQUEST); } if(Math.abs(startQueryTimestampLocalUTC.getMillis() - endQueryTimestampLocalUTC.getMillis()) > 2 * allowedRangeInSeconds * 1000) { LOGGER.warn("Invalid request, query to range is too big for account_id = {}", startQueryTimestampLocalUTC, endQueryTimestampLocalUTC, accountId); throw new WebApplicationException(Response.Status.BAD_REQUEST); } }
Source:
public BinaryContent transform(SourceResponse sourceResponse, Map<String, Serializable> map) throws CatalogTransformerException { if (sourceResponse == null) { throw new CatalogTransformerException("Null result set cannot be transformed to HTML"); } List<Metacard> metacards = sourceResponse.getResults().stream().map(Result::getMetacard).collect(Collectors.toList()); List<HtmlMetacardModel> metacardModels = new ArrayList<>(); for (Metacard metacard : metacards) { metacardModels.add(new HtmlMetacardModel(metacard, htmlMetacardUtility.getCategoryList())); } String html = htmlMetacardUtility.buildHtml(metacardModels); if (html == null) { throw new CatalogTransformerException("Result set cannot be transformed to HTML"); } else { return new BinaryContentImpl(new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8))); } }

Target:
public BinaryContent transform(SourceResponse sourceResponse, Map<String, Serializable> map) throws CatalogTransformerException { if (sourceResponse == null) { throw new CatalogTransformerException("Null result set cannot be transformed to HTML"); } List<HtmlExportCategory> categoryList = HtmlMetacardUtility.sortCategoryList(htmlMetacardUtility.getCategoryList()); final List<HtmlMetacardModel> metacardModels = sourceResponse .getResults() .stream() .map(Result::getMetacard) .map(metacard -> new HtmlMetacardModel(metacard, categoryList)) .collect(toList()); final String html = htmlMetacardUtility.buildHtml(metacardModels); if (StringUtils.isEmpty(html)) { throw new CatalogTransformerException("Result set cannot be transformed to HTML"); } return new BinaryContentImpl( new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)), htmlMetacardUtility.getMimeType()); }
Source:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CollaboratorsAdapter.ViewHolder holder = (CollaboratorsAdapter.ViewHolder) view.getTag(); if (holder != null && holder.collaboration != null) { BoxCollaborator collaborator = holder.collaboration.getAccessibleBy(); String userId = mController.getCurrentUserId(); boolean isCollaboratorCurrentUser = collaborator != null && collaborator.getId().equals(userId); if (rolesArr == null || (rolesArr.size() == 0 && !isCollaboratorCurrentUser)) { SdkUtils.toastSafely(getContext(), R.string.box_sharesdk_cannot_get_collaborators, Toast.LENGTH_SHORT); return; } BoxCollaboration.Role role = holder.collaboration.getRole(); String name = collaborator == null ? getString(R.string.box_sharesdk_another_person) : collaborator.getName(); boolean allowOwner = getItem().getOwnedBy().getId().equals(mController.getCurrentUserId()); if (allowOwner){ allowOwner = getItem() instanceof BoxFolder; } CollaborationRolesDialog rolesDialog = CollaborationRolesDialog.newInstance(rolesArr, role, name, true, allowOwner, holder.collaboration); rolesDialog.setOnRoleSelectedListener(this); rolesDialog.show(getFragmentManager(), TAG); } }

Target:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CollaboratorsAdapter.ViewHolder holder = (CollaboratorsAdapter.ViewHolder) view.getTag(); if (holder != null && holder.collaboration != null) { ArrayList<BoxCollaboration.Role> rolesArr = getRoles(); BoxCollaborator collaborator = holder.collaboration.getAccessibleBy(); String userId = mController.getCurrentUserId(); boolean isCollaboratorCurrentUser = collaborator != null && collaborator.getId().equals(userId); if (rolesArr == null) { SdkUtils.toastSafely(getContext(), R.string.box_sharesdk_generic_error, Toast.LENGTH_SHORT); return; } else if (rolesArr.size() == 0 && !isCollaboratorCurrentUser) { SdkUtils.toastSafely(getContext(), R.string.box_sharesdk_insufficient_permissions, Toast.LENGTH_SHORT); return; } BoxCollaboration.Role role = holder.collaboration.getRole(); String name = collaborator == null ? getString(R.string.box_sharesdk_another_person) : collaborator.getName(); boolean allowOwner = getItem().getOwnedBy().getId().equals(mController.getCurrentUserId()); if (allowOwner){ allowOwner = getItem() instanceof BoxFolder; } CollaborationRolesDialog rolesDialog = CollaborationRolesDialog.newInstance(rolesArr, role, name, true, allowOwner, holder.collaboration); rolesDialog.setOnRoleSelectedListener(this); rolesDialog.show(getFragmentManager(), TAG); } }
Source:
public String[] getImplementors(String className) throws MappingException { if (implementorsCache.get(className) != null) { return implementorsCache.get(className); } final Class clazz; String[] implementors; try { clazz = getSessionFactory().getServiceRegistry().getService( ClassLoaderService.class ).classForName( className ); } catch (ClassLoadingException e) { implementors = new String[] { className }; implementorsCache.put(className, implementors); return implementors; } ArrayList<String> results = new ArrayList<>(); for ( EntityPersister checkPersister : entityPersisters().values() ) { if ( ! Queryable.class.isInstance( checkPersister ) ) { continue; } final Queryable checkQueryable = Queryable.class.cast( checkPersister ); final String checkQueryableEntityName = checkQueryable.getEntityName(); final boolean isMappedClass = className.equals( checkQueryableEntityName ); if ( checkQueryable.isExplicitPolymorphism() ) { if ( isMappedClass ) { implementors = new String[] {className}; implementorsCache.put(className, implementors); return implementors; } } else { if ( isMappedClass ) { results.add( checkQueryableEntityName ); } else { final Class mappedClass = checkQueryable.getMappedClass(); if ( mappedClass != null && clazz.isAssignableFrom( mappedClass ) ) { final boolean assignableSuperclass; if ( checkQueryable.isInherited() ) { Class mappedSuperclass = entityPersister( checkQueryable.getMappedSuperclass() ).getMappedClass(); assignableSuperclass = clazz.isAssignableFrom( mappedSuperclass ); } else { assignableSuperclass = false; } if ( !assignableSuperclass ) { results.add( checkQueryableEntityName ); } } } } } implementors = results.toArray( new String[results.size()] ); implementorsCache.put(className, implementors); return implementors; }

Target:
public String[] getImplementors(String className) throws MappingException { String[] implementors = implementorsCache.get( className ); if ( implementors != null ) { return Arrays.copyOf( implementors, implementors.length ); } try { final Class<?> clazz = getSessionFactory().getServiceRegistry().getService( ClassLoaderService.class ).classForName( className ); implementors = doGetImplementors( clazz ); if ( implementors.length > 0 ) { implementorsCache.putIfAbsent( className, implementors ); return Arrays.copyOf( implementors, implementors.length ); } else { return EMPTY_IMPLEMENTORS; } } catch (ClassLoadingException e) { return new String[]{ className }; } }
Source:
private String generateDataString(long ledger, long entry) { return new String("ledger-" + ledger + "-" + entry); }

Target:
private static String generateDataString(long ledger, long entry) { return ("ledger-" + ledger + "-" + entry); }
Source:
public boolean isInIdClass() { return isInIdClass != null ? isInIdClass : ( parent != null && parent.isInIdClass() ); }

Target:
public boolean isInIdClass() { if ( isInIdClass != null ) { return isInIdClass; } if ( parent != null ) { return parent.isInIdClass(); } return false; }
Source:
public void sendRequest(final Exchange exchange) { Request request = exchange.getCurrentRequest(); if (request.isObserve() && 0 == exchange.getFailedTransmissionCount()) { exchangeStore.assignMessageId(request); registerObserve(request); } try { if (exchangeStore.registerOutboundRequest(exchange)) { exchange.setRemoveHandler(exchangeRemoveHandler); LOGGER.debug("tracking open request [MID: {}, Token: {}]", request.getMID(), request.getToken()); } else { LOGGER.warn("message IDs exhausted, could not register outbound request for tracking"); request.setSendError(new IllegalStateException("automatic message IDs exhausted")); } } catch (IllegalArgumentException ex) { request.setSendError(ex); } }

Target:
public void sendRequest(final Exchange exchange) { Request request = exchange.getCurrentRequest(); if (request.isObserve() && 0 == exchange.getFailedTransmissionCount()) { if (exchangeStore.assignMessageId(request) != Message.NONE) { registerObserve(request); } else { LOGGER.warn("message IDs exhausted, could not register outbound observe request for tracking"); request.setSendError(new IllegalStateException("automatic message IDs exhausted")); return; } } try { if (exchangeStore.registerOutboundRequest(exchange)) { exchange.setRemoveHandler(exchangeRemoveHandler); LOGGER.debug("tracking open request [MID: {}, Token: {}]", request.getMID(), request.getToken()); } else { LOGGER.warn("message IDs exhausted, could not register outbound request for tracking"); request.setSendError(new IllegalStateException("automatic message IDs exhausted")); } } catch (IllegalArgumentException ex) { request.setSendError(ex); } }
Source:
public DatabaseLifecycleManager(){ this.lifecycleExecutor = Executors.newSingleThreadExecutor(); }

Target:
public DatabaseLifecycleManager(){ this.lifecycleExecutor = Executors.newSingleThreadExecutor( (runnable) -> new Thread(runnable, "SpliceDatabaseLifecycleManager") ); }
Source:
public <V> Setting<V> get(SimpleUri id, Class<V> valueType) { Setting setting = settings.get(id); Class settingValueClass = setting.getValueClass(); if (!settingValueClass.equals(valueType)) { throw new ClassCastException( "Expected a Setting of type " + valueType.getName() + ", found a Setting of type " + settingValueClass.getName() ); } return (Setting<V>) setting; }

Target:
public <V> Setting<V> get(SimpleUri id, Class<V> valueType) { Setting setting = settings.get(id); if (setting == null) { return null; } Class settingValueClass = setting.getValueClass(); if (!settingValueClass.equals(valueType)) { throw new ClassCastException( "Expected a Setting of type " + valueType.getName() + ", found a Setting of type " + settingValueClass.getName() ); } return (Setting<V>) setting; }
Source:
public void stop() { entityFactory.abandonLeadership(entityIdentifier); try { clusterConnection.close(); } catch (IOException ex) { throw new RuntimeException(ex); } }

Target:
public void stop() { entityFactory.abandonLeadership(entityIdentifier); entityFactory = null; try { clusterConnection.close(); } catch (IOException ex) { throw new RuntimeException(ex); } }
Source:
ListOfMetrics(SweepMetric... metrics) { this.metricsList = Arrays.stream(metrics).collect(Collectors.toList()); }

Target:
ListOfMetrics(SweepMetric... metrics) { this.metricsList = Arrays.asList(metrics); }
Source:
private Answer executeRequest(ShutDownVspCommand cmd) { try { isNuageVspElementLoaded(); _nuageVspElementClient.shutdownNetwork(cmd.getNetwork(), cmd.getDhcpOptions()); return new Answer(cmd, true, "Shutdown VPC " + cmd.getNetwork().getUuid()+ " on Nuage VSD " + _hostName); } catch (ConfigurationException e) { s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e); return new Answer(cmd, e); } }

Target:
private Answer executeRequest(ShutDownVspCommand cmd) { try { isNuageVspElementLoaded(); _nuageVspElementClient.shutdownNetwork(cmd.getNetwork(), cmd.getDhcpOptions()); return new Answer(cmd, true, "Shutdown VPC " + cmd.getNetwork().getUuid()+ " on Nuage VSD " + _hostName); } catch (ConfigurationException e) { s_logger.error("Failure during " + cmd.toDetailString() + " on Nuage VSD " + _hostName, e); return new Answer(cmd, e); } }
Source:
protected ITmfTreeViewerEntry updateElements(long start, long end, boolean selection) { if (selection) { fSelection = start; } if (getTrace() == null) { return null; } ITmfTreeViewerEntry root = getInput(); if (root == null) { root = createRoot(); } else if (fFilterStatus) { clearStateSystemEntries(root); } boolean changed = updateStateSystemEntries(root, fSelection); return selection || changed ? root : null; }

Target:
protected ITmfTreeViewerEntry updateElements(long start, long end, boolean selection) { if (selection) { fSelection = start; } else { fSelection = TmfTraceManager.getInstance().getSelectionBeginTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); } if (getTrace() == null) { return null; } ITmfTreeViewerEntry root = getInput(); if (root == null) { root = createRoot(); } else if (fFilterStatus) { clearStateSystemEntries(root); } boolean changed = updateStateSystemEntries(root, fSelection); return selection || changed ? root : null; }
Source:
public void testMovingDirectoryWithErrorsAndDelays() throws Exception { int delay = 100; initNestedDirectory(7, 6, 9, 0); observer.checkAndNotify(); init(); addDelay(delay); File siblingDir = new File(monitoredDirectory, "child002"); observer.checkAndNotify(); timesToFail.set(10); Thread mover = new Thread( () -> { try { Thread.sleep(20); } catch (InterruptedException ignored) { } assertThat(grandchildDir.renameTo(siblingDir), is(true)); }); mover.start(); for (int i = 0; i < 4; i++) { runThreads(observer::checkAndNotify, 2); Thread.sleep(delay / 4); } Thread.sleep(delayBuf); observer.checkAndNotify(); Thread.sleep(delay + delayBuf); Collection<Invocation> temp = Mockito.mockingDetails(fileListener).getInvocations(); ArgumentCaptor<File> propertyKeyCaptor = ArgumentCaptor.forClass(File.class); Mockito.verify(fileListener, atLeast(0)).onFileCreate(propertyKeyCaptor.capture(), any()); Mockito.verify(fileListener, atLeast(0)).onFileDelete(propertyKeyCaptor.capture(), any()); assertThat(propertyKeyCaptor.getAllValues().size(), is(grandchildFiles.length * 2 + failures)); verify(fileListener, times(0)).onFileChange(any(File.class), any(Synchronization.class)); }

Target:
public void testMovingDirectoryWithErrorsAndDelays() throws Exception { initNestedDirectory(7, 6, 9, 0); observer.checkAndNotify(); init(); int toFail = 10; initSemaphore(toFail + grandchildFiles.length * 2); File siblingDir = new File(monitoredDirectory, "child002"); observer.checkAndNotify(); timesToFail.set(toFail); assertThat(grandchildDir.renameTo(siblingDir), is(true)); artificialDelay.release(totalSize + toFail); observer.checkAndNotify(); observer.checkAndNotify(); delayLatch.await(timeout, TimeUnit.MILLISECONDS); ArgumentCaptor<File> propertyKeyCaptor = ArgumentCaptor.forClass(File.class); Mockito.verify(fileListener, atLeast(0)).onFileCreate(propertyKeyCaptor.capture(), any()); Mockito.verify(fileListener, atLeast(0)).onFileDelete(propertyKeyCaptor.capture(), any()); assertThat(propertyKeyCaptor.getAllValues().size(), is(grandchildFiles.length * 2 + failures)); assertThat(failures, is(toFail)); verify(fileListener, never()).onFileChange(any(File.class), any(Synchronization.class)); assertThat(artificialDelay.getQueueLength(), is(0)); }
Source:
public static CompletionStage<Report.Result> execute(final Report report, final Injector injector, final Instant scheduled) { verifyDependencies(report, injector); final ImmutableMultimap<ReportFormat, Recipient> formatToRecipients = report.getRecipientsByFormat() .entrySet() .stream() .collect(ImmutableSetMultimap.flatteningToImmutableSetMultimap( Map.Entry::getKey, e -> e.getValue().stream())); final ImmutableMultimap<Recipient, ReportFormat> recipientToFormats = formatToRecipients.inverse(); return renderAll(injector, formatToRecipients.keySet(), report.getSource(), scheduled) .thenCompose( formatToRendered -> sendAll(injector, recipientToFormats, formatToRendered) ).thenApply( nothing -> null ); }

Target:
public static CompletionStage<Report.Result> execute(final Report report, final Injector injector, final Instant scheduled) { final ImmutableMultimap<ReportFormat, Recipient> formatToRecipients = report.getRecipientsByFormat() .entrySet() .stream() .collect(ImmutableSetMultimap.flatteningToImmutableSetMultimap( Map.Entry::getKey, e -> e.getValue().stream())); final ImmutableMultimap<Recipient, ReportFormat> recipientToFormats = formatToRecipients.inverse(); return CompletableFuture.completedFuture(null).thenApply(nothing -> { verifyDependencies(report, injector); return null; }).thenCompose(nothing -> renderAll(injector, formatToRecipients.keySet(), report.getSource(), scheduled) ).thenCompose(formatToRendered -> sendAll(injector, recipientToFormats, formatToRendered) ).thenApply(nothing -> new DefaultReportResult() ); }
Source:
public void testLoadAllNotes() { Note note; try { assertEquals(0, notebook.getAllNotes().size()); note = notebook.createNote(anonymous); Paragraph p1 = note.addParagraph(); Map config = p1.getConfig(); config.put("enabled", true); p1.setConfig(config); p1.setText("hello world"); note.persist(anonymous); } catch (IOException fe) { logger.warn("Failed to create note and paragraph. Safe to return, other tests might be failing as well", fe); return; } try { notebook.loadAllNotes(anonymous); assertEquals(1, notebook.getAllNotes().size()); } catch (IOException e) { fail("Subject is non-emtpy anonymous, shouldn't fail"); } }

Target:
public void testLoadAllNotes() { Note note; try { assertEquals(0, notebook.getAllNotes().size()); note = notebook.createNote(anonymous); Paragraph p1 = note.addParagraph(); Map config = p1.getConfig(); config.put("enabled", true); p1.setConfig(config); p1.setText("hello world"); note.persist(anonymous); } catch (IOException fe) { logger.warn("Failed to create note and paragraph. Possible problem with persisting note, safe to ignore", fe); } try { notebook.loadAllNotes(anonymous); assertEquals(1, notebook.getAllNotes().size()); } catch (IOException e) { fail("Subject is non-emtpy anonymous, shouldn't fail"); } }
Source:
protected void updateMetricsOnFinish(TEnvironment env, long runtime, boolean success) { ProcedureMetrics metrics = getProcedureMetrics(env); if (metrics == null) { return; } if (success) { Histogram timeHisto = metrics.getTimeHisto(); if (timeHisto != null) { timeHisto.update(runtime); } Histogram timeHistoOnMasterUI = metrics.getTimeHistoOnMasterUI(); if (timeHistoOnMasterUI != null) { timeHistoOnMasterUI.update(runtime); } } else { Counter failedCounter = metrics.getFailedCounter(); if (failedCounter != null) { failedCounter.increment(); } } }

Target:
protected void updateMetricsOnFinish(TEnvironment env, long runtime, boolean success) { ProcedureMetrics metrics = getProcedureMetrics(env); if (metrics == null) { return; } if (success) { Histogram timeHisto = metrics.getTimeHisto(); if (timeHisto != null) { timeHisto.update(runtime); } if (metrics instanceof ProcedureMetricsForMasterUI) { ProcedureMetricsForMasterUI procedureMetricsForMasterUI = (ProcedureMetricsForMasterUI)metrics; if (procedureMetricsForMasterUI.getHistogramForMasterUI() != null) { procedureMetricsForMasterUI.getHistogramForMasterUI().update(runtime); } } } else { Counter failedCounter = metrics.getFailedCounter(); if (failedCounter != null) { failedCounter.increment(); } } }
Source:
private void removeCheckpointFromDb() { Guid vmCheckpointId = getParameters().getVmBackup().getToCheckpointId(); log.info("Remove VmCheckpoint entity '{}'", vmCheckpointId); vmCheckpointDao.removeAllDisksFromCheckpoint(vmCheckpointId); vmCheckpointDao.remove(vmCheckpointId); }

Target:
private void removeCheckpointFromDb() { Guid vmCheckpointId = getParameters().getVmBackup().getToCheckpointId(); log.info("Remove VmCheckpoint entity '{}'", vmCheckpointId); TransactionSupport.executeInNewTransaction(() -> { vmCheckpointDao.removeAllDisksFromCheckpoint(vmCheckpointId); vmCheckpointDao.remove(vmCheckpointId); return null; }); }
Source:
public void testGoodCase() throws Exception { initialize(); BlobId convertedBlobId = RouterUtils.getBlobIdFromString(blobIdStr, clusterMap); assertTrue("The converted BlobId should be the same as the original.", convertedBlobId.equals(originalBlobId)); }

Target:
public void testGoodCase() throws Exception { initialize(); BlobId convertedBlobId = RouterUtils.getBlobIdFromString(blobIdStr, clusterMap); assertEquals("The converted BlobId should be the same as the original.", originalBlobId, convertedBlobId); }