auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DataSet<ExecRow> writeAvroFile(DataSetProcessor dsp, int[] partitionBy, String location, String compression, OperationContext context) { try { StructType dataSchema = null; StructType tableSchema = context.getOperation().getExecRowDefinition().schema(); dataSchema = ExternalTableUtils.getDataSchema(dsp, tableSchema, partitionBy, location, "a"); if (dataSchema == null) dataSchema = tableSchema; Dataset<Row> insertDF = SpliceSpark.getSession().createDataFrame( rdd.map(new SparkSpliceFunctionWrapper<>(new CountWriteFunction(context))).map(new LocatedRowToRowAvroFunction()), dataSchema); List<String> partitionByCols = new ArrayList(); for (int i = 0; i < partitionBy.length; i++) { partitionByCols.add(ValueRow.getNamedColumn(partitionBy[i])); } if (partitionBy.length > 0) { List<Column> repartitionCols = new ArrayList(); for (int i = 0; i < partitionBy.length; i++) { repartitionCols.add(new Column(ValueRow.getNamedColumn(partitionBy[i]))); } insertDF = insertDF.repartition(scala.collection.JavaConversions.asScalaBuffer(repartitionCols).toList()); } insertDF.write().option(SPARK_COMPRESSION_OPTION,compression).partitionBy(partitionByCols.toArray(new String[partitionByCols.size()])) .mode(SaveMode.Append).format("com.databricks.spark.avro").save(location); ValueRow valueRow=new ValueRow(1); valueRow.setColumn(1,new SQLLongint(context.getRecordsWritten())); return new SparkDataSet<>(SpliceSpark.getContext().parallelize(Collections.singletonList(valueRow), 1)); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public DataSet<ExecRow> writeAvroFile(DataSetProcessor dsp, int[] partitionBy, String location, String compression, OperationContext context) { try { StructType dataSchema = null; StructType tableSchema = context.getOperation().getExecRowDefinition().schema(); dataSchema = ExternalTableUtils.getDataSchema(dsp, tableSchema, partitionBy, location, "a"); if (dataSchema == null) dataSchema = tableSchema; Dataset<Row> insertDF = SpliceSpark.getSession().createDataFrame( rdd.map(new SparkSpliceFunctionWrapper<>(new CountWriteFunction(context))).map(new LocatedRowToRowAvroFunction()), dataSchema); List<String> partitionByCols = new ArrayList(); for (int i = 0; i < partitionBy.length; i++) { partitionByCols.add(dataSchema.fields()[partitionBy[i]].name()); } if (partitionBy.length > 0) { List<Column> repartitionCols = new ArrayList(); for (int i = 0; i < partitionBy.length; i++) { repartitionCols.add(new Column(dataSchema.fields()[partitionBy[i]].name())); } insertDF = insertDF.repartition(scala.collection.JavaConversions.asScalaBuffer(repartitionCols).toList()); } insertDF.write().option(SPARK_COMPRESSION_OPTION,compression).partitionBy(partitionByCols.toArray(new String[partitionByCols.size()])) .mode(SaveMode.Append).format("com.databricks.spark.avro").save(location); ValueRow valueRow=new ValueRow(1); valueRow.setColumn(1,new SQLLongint(context.getRecordsWritten())); return new SparkDataSet<>(SpliceSpark.getContext().parallelize(Collections.singletonList(valueRow), 1)); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public void queryOneNonExistedObjectObservable() { putUsersBlocking(3); final Observable<User> userObservable = storIOSQLite .get() .object(User.class) .withQuery(Query.builder() .table(UserTableMeta.TABLE) .where(UserTableMeta.COLUMN_EMAIL + "=?") .whereArgs("some arg") .build()) .prepare() .createObservable(); TestSubscriber<User> testSubscriber = new TestSubscriber<User>(); userObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(500, MILLISECONDS); testSubscriber.assertValueCount(1); testSubscriber.assertValue(null); testSubscriber.assertNoErrors(); testSubscriber.unsubscribe(); }

Target:
public void queryOneNonExistedObjectObservable() { putUsersBlocking(3); final Observable<User> userObservable = storIOSQLite .get() .object(User.class) .withQuery(Query.builder() .table(UserTableMeta.TABLE) .where(UserTableMeta.COLUMN_EMAIL + "=?") .whereArgs("some arg") .build()) .prepare() .createObservable() .take(1); TestSubscriber<User> testSubscriber = new TestSubscriber<User>(); userObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(5, SECONDS); testSubscriber.assertValue(null); testSubscriber.assertNoErrors(); testSubscriber.unsubscribe(); }
Source:
public void emitTuples() { output.emit(jsonSample); }

Target:
public void emitTuples() { output.emit(jsonSample.getBytes()); }
Source:
public void finish() { finished = true; blocked.set(null); if (source != null) { recordSourceRawInputStats(); try { source.close(); } catch (IOException e) { throw new UncheckedIOException(e); } systemMemoryContext.setBytes(source.getSystemMemoryUsage()); } }

Target:
public void finish() { finished = true; blocked.set(null); if (source != null) { try { source.close(); } catch (IOException e) { throw new UncheckedIOException(e); } systemMemoryContext.setBytes(source.getSystemMemoryUsage()); } }
Source:
void updateErrors(JSONObject nodeRoot) { synchronized (errorMap) { try { removeAllErrors(); JSONArray sPoints = nodeRoot.getJSONArray("values"); for (int i = 0; i < sPoints.length(); i++) { JSONObject subJSON = sPoints.getJSONObject(i); HashMap<String, String> valMap = new HashMap<String, String>(); Map<String, Object> oMap = subJSON.toMap(); for (String para : oMap.keySet()) { logger.debug("Set: val: {}", para, oMap.get(para).toString()); valMap.put(para, oMap.get(para).toString()); } errorMap.add(valMap); } } catch (Exception e) { logger.error("Error in parsing of the errorlist: {}", e.getMessage()); e.printStackTrace(); } } }

Target:
void updateErrors(JSONObject nodeRoot) { synchronized (errorMap) { try { removeAllErrors(); JSONArray sPoints = nodeRoot.getJSONArray("values"); for (int i = 0; i < sPoints.length(); i++) { JSONObject subJSON = sPoints.getJSONObject(i); HashMap<String, String> valMap = new HashMap<String, String>(); Map<String, Object> oMap = subJSON.toMap(); for (String para : oMap.keySet()) { logger.debug("Set: val: {}", para, oMap.get(para)); valMap.put(para, oMap.get(para).toString()); } errorMap.add(valMap); } } catch (Exception e) { logger.error("Error in parsing of the errorlist: {}", e.getMessage()); e.printStackTrace(); } } }
Source:
public static ChatColor getColor(char colorChar) { return charToColor.get(colorChar); }

Target:
public static ChatColor getColor(char colorChar) { ChatColor c = charToColor.get(colorChar); if (c == null) throw new IllegalArgumentException("no color with character " + colorChar); return c; }
Source:
public CompletableFuture<Void> hideMapVersion(MapBean map) { String id = map.getId(); MapVersion mapVersion = new MapVersion(); mapVersion.setHidden(true); mapVersion.setId(map.getId()); fafApiAccessor.updateMapVersion(id, mapVersion); return null; }

Target:
public CompletableFuture<Void> hideMapVersion(MapBean map) { String id = map.getId(); MapVersion mapVersion = new MapVersion(); mapVersion.setHidden(true); mapVersion.setId(map.getId()); fafApiAccessor.updateMapVersion(id, mapVersion); return CompletableFuture.completedFuture(null); }
Source:
public Stddev(String fieldName, Schema fieldSchema) { this.fieldName = fieldName; boolean isNullable = fieldSchema.isNullable(); Schema.Type fieldType = isNullable ? fieldSchema.getNonNullable().getType() : fieldSchema.getType(); if (!(fieldType == Schema.Type.INT || fieldType == Schema.Type.LONG || fieldType == Schema.Type.FLOAT || fieldType == Schema.Type.DOUBLE)) { throw new IllegalArgumentException(String.format( "Cannot compute avg on field %s because its type %s is not numeric", fieldName, fieldType)); } outputSchema = isNullable ? Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)) : Schema.of(Schema.Type.DOUBLE); }

Target:
public Stddev(String fieldName, Schema fieldSchema) { this.fieldName = fieldName; boolean isNullable = fieldSchema.isNullable(); Schema.Type fieldType = isNullable ? fieldSchema.getNonNullable().getType() : fieldSchema.getType(); if (!AggregationUtils.isNumericType(fieldType)) { throw new IllegalArgumentException(String.format( "Cannot compute standard deviation on field %s because its type %s is not numeric", fieldName, fieldType)); } outputSchema = isNullable ? Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)) : Schema.of(Schema.Type.DOUBLE); }
Source:
private void addVolumeToDb(final GlusterVolumeEntity createdVolume) { TransactionSupport.executeInNewTransaction( new TransactionMethod<Void>() { @Override public Void runInTransaction() { createdVolume.setClusterId(getVdsGroupId()); DbFacade.getInstance().getGlusterVolumeDao().save(createdVolume); return null; } }); }

Target:
private void addVolumeToDb(final GlusterVolumeEntity createdVolume) { createdVolume.setClusterId(getVdsGroupId()); DbFacade.getInstance().getGlusterVolumeDao().save(createdVolume); }
Source:
public final ClientResponseImpl dispatchNTProcedure(InvocationClientHandler handler, StoredProcedureInvocation task, AuthUser user, Connection ccxn, long nowNanos, boolean ntPriority) { long connectionId = handler.connectionId(); final ClientInterfaceHandleManager cihm = m_cihm.get(connectionId); if (cihm == null) { hostLog.rateLimitedLog(60, Level.WARN, null, "Dispatch Non-Transactional Procedure request rejected. " + "This is likely due to VoltDB ceasing client communication as it " + "shuts down."); return new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0], "VoltDB failed to create the transaction internally. It is possible this " + "was caused by a node failure or intentional shutdown. If the cluster recovers, " + "it should be safe to resend the work, as the work was never started.", task.clientHandle); } final int NTPROC_JUNK_ID = -2; long handle = cihm.getHandle(true, NTPROC_JUNK_ID, task.clientHandle, task.getSerializedSize(), nowNanos, task.getProcName(), NTPROC_JUNK_ID, true, true); ParameterSet paramSet = task.getParams(); m_NTProcedureService.callProcedureNT(handle, user, ccxn, handler.isAdmin(), ntPriority, task); return null; }

Target:
public final ClientResponseImpl dispatchNTProcedure(InvocationClientHandler handler, StoredProcedureInvocation task, AuthUser user, Connection ccxn, long nowNanos, boolean ntPriority) { long connectionId = handler.connectionId(); final ClientInterfaceHandleManager cihm = m_cihm.get(connectionId); if (cihm == null) { hostLog.rateLimitedLog(60, Level.WARN, null, "Dispatch Non-Transactional Procedure request rejected. " + "This is likely due to VoltDB ceasing client communication as it " + "shuts down."); return new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0], "VoltDB failed to create the transaction internally. It is possible this " + "was caused by a node failure or intentional shutdown. If the cluster recovers, " + "it should be safe to resend the work, as the work was never started.", task.clientHandle); } final int NTPROC_JUNK_ID = -2; long handle = cihm.getHandle(true, NTPROC_JUNK_ID, task.clientHandle, task.getSerializedSize(), nowNanos, task.getProcName(), NTPROC_JUNK_ID, true, true); m_NTProcedureService.callProcedureNT(handle, user, ccxn, handler.isAdmin(), ntPriority, task); return null; }
Source:
public void verifyActiveRequests() throws Exception { ModelNodeResult value = operations.readAttribute(REQUEST_CONTROLLER_SUBSYSTEM_ADDRESS, ACTIVE_REQUESTS, ReadAttributeOption.INCLUDE_DEFAULTS); value.assertSuccess(); Assert.assertEquals(page.getConfigFragment().edit().text(ACTIVE_REQUESTS), value.stringValue()); }

Target:
public void verifyActiveRequests() throws Exception { ModelNodeResult value = operations.readAttribute(REQUEST_CONTROLLER_SUBSYSTEM_ADDRESS, ACTIVE_REQUESTS, ReadAttributeOption.NOT_INCLUDE_DEFAULTS); value.assertDefinedValue(); Assert.assertEquals(page.getConfigFragment().edit().text(ACTIVE_REQUESTS), value.stringValue()); }
Source:
public void restore(String alternateTheme) { String prefThemeId = getPreferenceThemeId(); boolean flag = true; if (prefThemeId != null) { for (ITheme t : getThemes()) { if (prefThemeId.equals(t.getId())) { setTheme(t, false); flag = false; break; } } } boolean hasDarkTheme = false; for (ITheme t : getThemes()) { if (t.getId().startsWith(E4_DARK_THEME_ID)) { hasDarkTheme = true; break; } } String os = Platform.getOS(); String themeToRestore = (Platform.OS_LINUX.equals(os) || Platform.OS_MACOSX.equals(os)) && Display.isSystemDarkTheme() && hasDarkTheme ? E4_DARK_THEME_ID : alternateTheme; if (themeToRestore != null && flag) { setTheme(themeToRestore, false); } }

Target:
public void restore(String alternateTheme) { String prefThemeId = getPreferenceThemeId(); boolean flag = true; if (prefThemeId != null) { for (ITheme t : getThemes()) { if (prefThemeId.equals(t.getId())) { setTheme(t, false); flag = false; break; } } } boolean hasDarkTheme = getThemes().stream().anyMatch(t -> t.getId().startsWith(E4_DARK_THEME_ID)); String os = Platform.getOS(); String themeToRestore = (Platform.OS_LINUX.equals(os) || Platform.OS_MACOSX.equals(os)) && Display.isSystemDarkTheme() && hasDarkTheme ? E4_DARK_THEME_ID : alternateTheme; if (themeToRestore != null && flag) { setTheme(themeToRestore, false); } }
Source:
private static TimeZone getTimeZone(String content) { Pattern pattern = Pattern.compile(REGEX_TIMEZONE_OFFSET); Matcher matcher = pattern.matcher(content); String timeZoneOffset = "+0000"; while (matcher.find()) { timeZoneOffset = matcher.group(1); } return TimeZone.getTimeZone("GMT" + timeZoneOffset); }

Target:
private static TimeZone getTimeZone(String content) { Pattern pattern = Pattern.compile(REGEX_TIMEZONE_OFFSET); Matcher matcher = pattern.matcher(content); String timeZoneOffset = "+0000"; if (matcher.find()) { timeZoneOffset = matcher.group(1); } return TimeZone.getTimeZone("GMT" + timeZoneOffset); }
Source:
public void deactivate() { logger.debug("Deactivate"); }

Target:
public void deactivate() { logger.debug("GoogleTTS service has been deactivated"); }
Source:
catch ( IOException e ) { throw new RuntimeException( "Time zone id file is missing." ); }

Target:
catch ( IOException e ) { throw new RuntimeException( "Failed to read time zone id file." ); }
Source:
public RollConvention toRollConvention( LocalDate start, LocalDate end, Frequency frequency, boolean preferEndOfMonth) { ArgChecker.notNull(start, "start"); ArgChecker.notNull(end, "end"); ArgChecker.notNull(frequency, "frequency"); if (this == NONE) { if (start.getDayOfMonth() != end.getDayOfMonth() && start.getMonth() != end.getMonth() && (start.getDayOfMonth() == start.lengthOfMonth() || end.getDayOfMonth() == end.lengthOfMonth())) { return RollConvention.ofDayOfMonth(Math.max(start.getDayOfMonth(), end.getDayOfMonth())); } } if (isCalculateBackwards()) { return impliedRollConvention(end, start, frequency, preferEndOfMonth); } else { return impliedRollConvention(start, end, frequency, preferEndOfMonth); } }

Target:
public RollConvention toRollConvention( LocalDate start, LocalDate end, Frequency frequency, boolean preferEndOfMonth) { ArgChecker.notNull(start, "start"); ArgChecker.notNull(end, "end"); ArgChecker.notNull(frequency, "frequency"); if (this == NONE) { if (start.getDayOfMonth() != end.getDayOfMonth() && start.getLong(PROLEPTIC_MONTH) != end.getLong(PROLEPTIC_MONTH) && (start.getDayOfMonth() == start.lengthOfMonth() || end.getDayOfMonth() == end.lengthOfMonth())) { return preferEndOfMonth ? RollConventions.EOM : RollConvention.ofDayOfMonth(Math.max(start.getDayOfMonth(), end.getDayOfMonth())); } } if (isCalculateBackwards()) { return impliedRollConvention(end, start, frequency, preferEndOfMonth); } else { return impliedRollConvention(start, end, frequency, preferEndOfMonth); } }
Source:
public TraversalControl visitGraphQLTypeReference(GraphQLTypeReference node, TraverserContext<GraphQLType> context) { final GraphQLType resolvedType = typeMap.get(node.getName()); Assert.assertTrue(resolvedType != null, "type %s not found in schema", node.getName()); context.getParentContext().thisNode().accept(context, new GraphQLTypeRefResolvingVisitor(resolvedType)); return super.visitGraphQLTypeReference(node, context); }

Target:
public TraversalControl visitGraphQLTypeReference(GraphQLTypeReference node, TraverserContext<GraphQLType> context) { final GraphQLType resolvedType = typeMap.get(node.getName()); assertNotNull(resolvedType, "type %s not found in schema", node.getName()); context.getParentContext().thisNode().accept(context, new TypeRefResolvingVisitor(resolvedType)); return super.visitGraphQLTypeReference(node, context); }
Source:
private void assertTag(Project.NameKey project, String branch, String tagName) throws IOException { Repository r = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(r); try { String commitSha1 = r.getRef(branch).getObjectId().getName(); String tag = r.getRef(tagName).getObjectId().getName(); assertEquals(commitSha1, tag); } finally { rw.release(); } } finally { r.close(); } }

Target:
private void assertTag(Project.NameKey project, String branch, String tagName) throws IOException { Repository r = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(r); try { ObjectId headCommit = r.getRef(branch).getObjectId(); ObjectId taggedCommit = r.getRef(tagName).getObjectId(); assertEquals(headCommit, taggedCommit); } finally { rw.release(); } } finally { r.close(); } }
Source:
SpawnResult execLocallyAndUpload( Spawn spawn, SpawnExecutionContext context, SortedMap<PathFragment, ActionInput> inputMap, AbstractRemoteActionCache remoteCache, ActionKey actionKey, Action action, Command command, boolean uploadLocalResults) throws ExecException, IOException, InterruptedException { Map<Path, Long> ctimesBefore = getInputCtimes(inputMap); SpawnResult result = execLocally(spawn, context); Map<Path, Long> ctimesAfter = getInputCtimes(inputMap); for (Map.Entry<Path, Long> e : ctimesBefore.entrySet()) { if (!ctimesAfter.get(e.getKey()).equals(e.getValue())) { return result; } } uploadLocalResults = uploadLocalResults && Status.SUCCESS.equals(result.status()) && result.exitCode() == 0; if (!uploadLocalResults) { return result; } Collection<Path> outputFiles = resolveActionInputs(execRoot, spawn.getOutputFiles()); try (SilentCloseable c = Profiler.instance().profile("Remote.upload")) { remoteCache.upload( actionKey, action, command, execRoot, outputFiles, context.getFileOutErr()); } catch (IOException e) { if (verboseFailures) { report(Event.debug("Upload to remote cache failed: " + e.getMessage())); } else { reportOnce(Event.warn("Some artifacts failed be uploaded to the remote cache.")); } } return result; }

Target:
SpawnResult execLocallyAndUpload( Spawn spawn, SpawnExecutionContext context, SortedMap<PathFragment, ActionInput> inputMap, AbstractRemoteActionCache remoteCache, ActionKey actionKey, Action action, Command command, boolean uploadLocalResults) throws ExecException, IOException, InterruptedException { Map<Path, Long> ctimesBefore = getInputCtimes(inputMap); SpawnResult result = execLocally(spawn, context); Map<Path, Long> ctimesAfter = getInputCtimes(inputMap); uploadLocalResults = uploadLocalResults && Status.SUCCESS.equals(result.status()) && result.exitCode() == 0; if (!uploadLocalResults) { return result; } for (Map.Entry<Path, Long> e : ctimesBefore.entrySet()) { if (!ctimesAfter.get(e.getKey()).equals(e.getValue())) { return result; } } Collection<Path> outputFiles = resolveActionInputs(execRoot, spawn.getOutputFiles()); try (SilentCloseable c = Profiler.instance().profile("Remote.upload")) { remoteCache.upload( actionKey, action, command, execRoot, outputFiles, context.getFileOutErr()); } catch (IOException e) { if (verboseFailures) { report(Event.debug("Upload to remote cache failed: " + e.getMessage())); } else { reportOnce(Event.warn("Some artifacts failed be uploaded to the remote cache.")); } } return result; }
Source:
public void setWhiteListedAgencies(String s) { if (s != null && !s.equals("")) whiteListedAgencies = new HashSet<String>(Arrays.asList(s.split(","))); }

Target:
public void setWhiteListedAgencies(String s) { if (!s.isEmpty()) { whiteListedAgencies = new HashSet<>(); Collections.addAll(whiteListedAgencies, s.split(",")); } }
Source:
public void visitCode() { super.visitCode(); Type[] args = Type.getArgumentTypes(desc); int idx = isStatic ? 0 : 1; for (int i = 0; i < args.length; i++) { if(args[i].getDescriptor().equals(Configuration.TAINT_TAG_DESC)) { callCheckTaintTag(idx, idx + args[i].getSize(), args[i+1]); } else if(args[i].getSort() == Type.OBJECT) { callCheckTaintObject(idx); } idx += args[i].getSize(); } callEnteringSink(); if(numberOfRemainingTryCatchBlocks == 0) { addTryCatchBlockHeader(); } }

Target:
public void visitCode() { super.visitCode(); Type[] args = Type.getArgumentTypes(desc); int idx = isStatic ? 0 : 1; for (int i = 0; i < args.length; i++) { if(args[i].getDescriptor().equals(Configuration.TAINT_TAG_DESC)) { callCheckTaintTag(idx, idx + args[i].getSize(), args[i+1]); } else if(args[i].getSort() == Type.OBJECT) { callCheckTaintObject(idx); } else if(args[i].getSort() == Type.ARRAY && args[i].getElementType().getSort() == Type.OBJECT) { callCheckTaintObject(idx); } idx += args[i].getSize(); } callEnteringSink(); if(numberOfRemainingTryCatchBlocks == 0) { addTryCatchBlockHeader(); } }
Source:
@Test public void getAlertTextTest() { driver.findElement(MobileBy .IosUIAutomation(".elements().withName(\"show alert\")")).click(); WebDriverWait wating = new WebDriverWait(driver, 10000); wating.until(alertIsPresent()); assertNotNull(driver.switchTo().alert().getText()); }

Target:
@Test public void getAlertTextTest() { driver.findElement(MobileBy .IosUIAutomation(".elements().withName(\"show alert\")")).click(); WebDriverWait wating = new WebDriverWait(driver, 10000); wating.until(alertIsPresent()); assertFalse(StringUtils.isBlank(driver.switchTo().alert().getText())); }
Source:
public void applyUpdates(final TraceInfo traceInfo) { synchronized (this) { updateCounter = new CountDownLatch(waiterIds.size()); for (final String waiterId : waiterIds) { final Migration updatedInfo = checkAndUpdateState(waiterId, Migration.WAITING_UPDATE, Migration.UPDATING_RECEIVER); final String receiverId = updatedInfo.getReceiverId(); sender.get().sendUpdateMsg(receiverId, waiterId, traceInfo); } waiterIds.clear(); } try { updateCounter.await(updateTimeoutMillis, TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { throw new RuntimeException(e); } }

Target:
public void applyUpdates(final TraceInfo traceInfo) { synchronized (this) { updateCounter = new CountDownLatch(waitingOperationIds.size()); for (final String waitingOperationId : waitingOperationIds) { final Migration migration = ongoingMigrations.get(waitingOperationId); if (migration == null) { LOG.log(Level.WARNING, "Migration with ID {0} was not registered, or it has already been finished.", waitingOperationId); continue; } migration.checkAndUpdate(Migration.WAITING_UPDATE, Migration.UPDATING_RECEIVER); final String receiverId = migration.getReceiverId(); sender.get().sendUpdateMsg(receiverId, waitingOperationId, traceInfo); } waitingOperationIds.clear(); } try { updateCounter.await(updateTimeoutMillis, TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { throw new RuntimeException(e); } }
Source:
protected String[] getLocations() { return new String[] { this.extensionsLocation + "/*.xml" }; }

Target:
protected String[] getLocations() { String[] locations = StringUtils.commaDelimitedListToStringArray(this.extensionsLocations); for (int i = 0; i < locations.length; i++) { locations[i] = locations[i] + " *.xml"; } return locations; }
Source:
private static void normalizeRuleMetadata(Rule rule) { if (!(rule instanceof Context)) return; Context ctx = (Context) rule; Object cat = ctx.get(RuleMetadata.CATEGORY); if (cat == null) { ctx.put(RuleMetadata.CATEGORY, new HashSet()); return; } if (cat instanceof String) cat = ((String)cat).split("\\s*,\\s*+"); if (cat instanceof String[]) cat = Arrays.asList((String[]) cat); if (cat instanceof Collection && !(cat instanceof Set)) { HashSet catSet = new HashSet(); for (Object catItem : (Collection) cat) if (!(catItem instanceof String)) throw new WindupException("Rule categories may only contain strings, but contains: " + catItem.getClass().getSimpleName()); else if ("".equals(catItem)) continue; else catSet.add(((String)catItem).trim()); ctx.put(RuleMetadata.CATEGORY, catSet); } }

Target:
private static void normalizeRuleMetadata(Rule rule) { if (!(rule instanceof Context)) return; Context ctx = (Context) rule; Object tags = ctx.get(RuleMetadata.TAGS); if (tags == null) { ctx.put(RuleMetadata.TAGS, new HashSet()); return; } if (tags instanceof String) tags = ((String)tags).split(WindupRuleProviderBuilder.TAGS_SPLIT_PATTERN); if (tags instanceof String[]) tags = Arrays.asList((String[]) tags); if (tags instanceof Collection && !(tags instanceof Set)) { HashSet tagsSet = new HashSet(); for (Object tagItem : (Collection) tags) if (!(tagItem instanceof String)) throw new WindupException("Rule tags may only contain strings, but contains: " + tagItem.getClass().getSimpleName()); else if ("".equals(tagItem)) continue; else tagsSet.add(((String)tagItem).trim()); ctx.put(RuleMetadata.TAGS, tagsSet); } }
Source:
public Details newInstance(StaplerRequest req, JSONObject formData) throws FormException { if (req == null) { throw new FormException("Stapler request is missing in the call", "staplerRequest"); } String pwd = Util.fixEmpty(req.getParameter("user.password")); String pwd2= Util.fixEmpty(req.getParameter("user.password2")); if(!Util.fixNull(pwd).equals(Util.fixNull(pwd2))) throw new FormException("Please confirm the password by typing it twice","user.password2"); User user = Util.getNearestAncestorOfTypeOrThrow(req, User.class); UserProperty p = user.getProperty(Details.class); String data = Protector.unprotect(pwd); if(data!=null) { String prefix = Stapler.getCurrentRequest().getSession().getId() + ':'; if(data.startsWith(prefix)) SecurityListener.fireUserPropertyUpdated(p, user.getId()); return Details.fromHashedPassword(data.substring(prefix.length())); } SecurityListener.fireUserPropertyUpdated(p, user.getId()); UserSeedProperty userSeedProperty = user.getProperty(UserSeedProperty.class); if (userSeedProperty != null) { userSeedProperty.renewSeed(); } return Details.fromPlainPassword(Util.fixNull(pwd)); }

Target:
public Details newInstance(StaplerRequest req, JSONObject formData) throws FormException { if (req == null) { throw new FormException("Stapler request is missing in the call", "staplerRequest"); } String pwd = Util.fixEmpty(req.getParameter("user.password")); String pwd2= Util.fixEmpty(req.getParameter("user.password2")); if(!Util.fixNull(pwd).equals(Util.fixNull(pwd2))) throw new FormException("Please confirm the password by typing it twice","user.password2"); User user = Util.getNearestAncestorOfTypeOrThrow(req, User.class); UserProperty p = user.getProperty(Details.class); String currentUserHashedPassword = ((Details) p).getPassword(); String data = Protector.unprotect(pwd); if(data!=null) { String prefix = Stapler.getCurrentRequest().getSession().getId() + ':'; if(data.startsWith(prefix)) PasswordPropertyListener.fireOnChanged(user.getId(), Util.fixNull(currentUserHashedPassword), Util.fixNull(pwd)); return Details.fromHashedPassword(data.substring(prefix.length())); } if (p != null) { PasswordPropertyListener.fireOnChanged(user.getId(), Util.fixNull(currentUserHashedPassword), Util.fixNull(pwd)); } UserSeedProperty userSeedProperty = user.getProperty(UserSeedProperty.class); if (userSeedProperty != null) { userSeedProperty.renewSeed(); } return Details.fromPlainPassword(Util.fixNull(pwd)); }
Source:
public String getPreview() { StringBuilder bld= new StringBuilder(); bld.append("\n"); if (isEnabled(CleanUpConstants.NUMBER_SUFFIX)) { bld.append("long number1 = 10L;\n"); bld.append("float number2 = 10F;\n"); bld.append("double number3 = 10D;\n"); } else { bld.append("long number1 = 10l;\n"); bld.append("float number2 = 10f;\n"); bld.append("double number3 = 10d;\n"); } return bld.toString(); }

Target:
public String getPreview() { StringBuilder bld= new StringBuilder(); bld.append("\n"); if (isEnabled(CleanUpConstants.NUMBER_SUFFIX)) { bld.append("long number1 = 10L;\n"); } else { bld.append("long number1 = 10l;\n"); } return bld.toString(); }
Source:
public void handle_mistakes_in_query_silently() { final Stand stand = prepareStandWithAggregateRepo(InMemoryStandStorage.newBuilder().build()); final Customer sampleCustomer = getSampleCustomer(); stand.update(sampleCustomer.getId(), AnyPacker.pack(sampleCustomer)); final String[] paths = {"blablabla", Project.getDescriptor().getFields().get(2).getFullName()}; final Query customerQuery = Queries.readAll(Customer.class, paths); final MemoizeQueryResponseObserver observer = new MemoizeQueryResponseObserver() { @Override public void onNext(QueryResponse value) { super.onNext(value); final List<Any> messages = value.getMessagesList(); assertFalse(messages.isEmpty()); final Customer customer = AnyPacker.unpack(messages.get(0)); assertNotEquals(customer, null); assertFalse(customer.hasId()); assertFalse(customer.hasName()); assertTrue(customer.getNicknamesList() .isEmpty()); } }; stand.execute(customerQuery, observer); verifyObserver(observer); }

Target:
public void handle_mistakes_in_query_silently() { final Stand stand = prepareStandWithAggregateRepo(InMemoryStandStorage.newBuilder().build()); final Customer sampleCustomer = getSampleCustomer(); stand.update(sampleCustomer.getId(), AnyPacker.pack(sampleCustomer)); final String[] paths = {"invalid_type_url_example", Project.getDescriptor().getFields().get(2).getFullName()}; final Query customerQuery = Queries.readAll(Customer.class, paths); final MemoizeQueryResponseObserver observer = new MemoizeQueryResponseObserver() { @Override public void onNext(QueryResponse value) { super.onNext(value); final List<Any> messages = value.getMessagesList(); assertFalse(messages.isEmpty()); final Customer customer = AnyPacker.unpack(messages.get(0)); assertNotEquals(customer, null); assertFalse(customer.hasId()); assertFalse(customer.hasName()); assertTrue(customer.getNicknamesList() .isEmpty()); } }; stand.execute(customerQuery, observer); verifyObserver(observer); }
Source:
public TaskProgressImpl(String progressFilePath, PrintStream output, PrintStream error) { if (progressFilePath != null) { progressFile = new File(progressFilePath); } else { } this.output = output; this.error = error; }

Target:
public TaskProgressImpl(String progressFilePath, PrintStream output, PrintStream error) { if (progressFilePath != null) { progressFile = new File(progressFilePath); } this.output = output; this.error = error; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_lab_recycler_view_on_map); recyclerView = (RecyclerView) findViewById(R.id.rv_on_top_of_map); Toast.makeText(this, R.string.toast_instruction, Toast.LENGTH_SHORT).show(); mapView = (MapView) findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { RecyclerViewOnMapActivity.this.mapboxMap = mapboxMap; setUpLists(); locationAdapter = new LocationRecyclerViewAdapter(locationList, mapboxMap); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, true)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(locationAdapter); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_lab_recycler_view_on_map); recyclerView = (RecyclerView) findViewById(R.id.rv_on_top_of_map); Toast.makeText(this, R.string.toast_instruction, Toast.LENGTH_SHORT).show(); mapView = (MapView) findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { RecyclerViewOnMapActivity.this.mapboxMap = mapboxMap; setUpLists(); locationAdapter = new LocationRecyclerViewAdapter(locationList, mapboxMap); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, true)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(locationAdapter); SnapHelper snapHelper = new LinearSnapHelper(); snapHelper.attachToRecyclerView(recyclerView); } }); }
Source:
private void reset() { if (chunk != null) { chunkedInput = new HttpChunkedInput(new RepeatedBytesInput()); request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, path); HttpUtil.setContentLength(request, totalSize); request.headers().add(RestUtils.Headers.BLOB_SIZE, totalSize); request.headers().add(RestUtils.Headers.SERVICE_ID, serviceId); request.headers().add(RestUtils.Headers.AMBRY_CONTENT_TYPE, "application/octet-stream"); request.headers().add(RestUtils.Headers.TARGET_ACCOUNT_NAME, targetAccountName); request.headers().add(RestUtils.Headers.TARGET_CONTAINER_NAME, targetContainerName); for (Pair<String, String> headerNameValue : customHeaders) { request.headers().add(headerNameValue.getFirst(), headerNameValue.getSecond()); } } else { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); } chunksReceived = 0; sizeReceived = 0; lastChunkReceiveTime = 0; requestStartTime = System.currentTimeMillis(); response = null; }

Target:
private void reset() { if (chunk != null) { chunkedInput = new HttpChunkedInput(new RepeatedBytesInput()); request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, path); HttpUtil.setContentLength(request, totalSize); request.headers().add(RestUtils.Headers.BLOB_SIZE, totalSize); request.headers().add(RestUtils.Headers.SERVICE_ID, serviceId); request.headers().add(RestUtils.Headers.AMBRY_CONTENT_TYPE, "application/octet-stream"); request.headers().add(RestUtils.Headers.TARGET_ACCOUNT_NAME, targetAccountName); request.headers().add(RestUtils.Headers.TARGET_CONTAINER_NAME, targetContainerName); } else { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); } for (Pair<String, String> headerNameValue : customHeaders) { request.headers().add(headerNameValue.getFirst(), headerNameValue.getSecond()); } chunksReceived = 0; sizeReceived = 0; lastChunkReceiveTime = 0; requestStartTime = System.currentTimeMillis(); response = null; }
Source:
public void loadImageFromTar() throws Exception { final Path imageTarFile = Paths.get("src/test/resources/testLoadImageFromTar/image.tar"); try (InputStream uploadStream = Files.newInputStream(imageTarFile)) { dockerClient.loadImageCmd(uploadStream).exec(); } final Image image = findImageWithId(expectedImageId, dockerClient.listImagesCmd().exec()); assertNotNull(image, "Can't find expected image after loading from a tar archive"); assertEquals(image.getRepoTags(), new String[]{"docker-java/load:1.0"}, "Image after loading from a tar archive has wrong tags!"); }

Target:
public void loadImageFromTar() throws Exception { try (InputStream uploadStream = Files.newInputStream(TestResources.getApiImagesLoadTestTarball())) { dockerClient.loadImageCmd(uploadStream).exec(); } final Image image = findImageWithId(expectedImageId, dockerClient.listImagesCmd().exec()); assertThat("Can't find expected image after loading from a tar archive!", image, notNullValue()); assertThat("Image after loading from a tar archive has wrong tags!", asList(image.getRepoTags()), equalTo(singletonList("docker-java/load:1.0"))); }
Source:
public void add(final String[] log) { table.getControl().getDisplay().syncExec(new Runnable() { public void run() { table.addRow(log); try { PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().showView(ID); } catch(PartInitException pie) { } catch(NullPointerException npe) } }); }

Target:
public void add(final String[] log) { table.getControl().getDisplay().syncExec(new Runnable() { public void run() { table.addRow(log); try { PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().showView(ID); } catch(PartInitException pie) { } } }); }
Source:
public void testRound() throws Exception { ResultSet rs; for(double val : roundVals){ rs = methodWatcher.executeQuery("values ROUND("+val+")"); Assert.assertTrue(rs.next()); Assert.assertEquals(Math.round(val),rs.getDouble(1),0.0); } }

Target:
public void testRound() throws Exception { ResultSet rs; for(double val : roundVals){ rs = methodWatcher.executeQuery("values ROUND("+val+")"); Assert.assertTrue(rs.next()); Assert.assertEquals(Math.round(val),rs.getLong(1)); } }
Source:
public Response getRegistryByUUID(String registryId, MessageContext messageContext) { RegistryDTO registryDTO = null; EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistryInfo = registryProvider.getEndpointRegistryByUUID(registryId); if (endpointRegistryInfo != null) { registryDTO = EndpointRegistryMappingUtils.fromEndpointRegistrytoDTO(endpointRegistryInfo); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving details of endpoint registry by id: " + registryId, e, log); } return Response.ok().entity(registryDTO).build(); }

Target:
public Response getRegistryByUUID(String registryId, MessageContext messageContext) { RegistryDTO registryDTO = null; EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistryInfo = registryProvider.getEndpointRegistryByUUID(registryId); if (endpointRegistryInfo != null) { registryDTO = EndpointRegistryMappingUtils.fromEndpointRegistrytoDTO(endpointRegistryInfo); } else { RestApiUtil.handleResourceNotFoundError("Endpoint Registry with the id: " + registryId + " is not found", log); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving details of endpoint registry by id: " + registryId, e, log); } return Response.ok().entity(registryDTO).build(); }
Source:
public String[] getTypes() { return new String[] { "container", "virtualMachine" }; }

Target:
public String[] getTypes() { return InstanceConstants.CONTAINER_LIKE.toArray(new String[InstanceConstants.CONTAINER_LIKE.size()]); }
Source:
public MessageBuilder<T> copyHeadersIfAbsent(Map<String, ?> headersToCopy) { if (headersToCopy != null) { for (Map.Entry<String, ?> entry : headersToCopy.entrySet()) { if (!this.headerAccessor.isReadOnly(entry.getKey())) { this.headerAccessor.setHeaderIfAbsent(entry.getKey(), entry.getValue()); } else if (logger.isWarnEnabled()) { logger.warn("The header [" + entry + "] is ignored for population because it is is readOnly."); } } } return this; }

Target:
public MessageBuilder<T> copyHeadersIfAbsent(Map<String, ?> headersToCopy) { if (headersToCopy != null) { for (Map.Entry<String, ?> entry : headersToCopy.entrySet()) { if (!this.headerAccessor.isReadOnly(entry.getKey())) { this.headerAccessor.setHeaderIfAbsent(entry.getKey(), entry.getValue()); } else if (logger.isInfoEnabled()) { logger.info("The header [" + entry + "] is ignored for population because it is is readOnly."); } } } return this; }
Source:
public String getActionWithDetails(@PathParam("id") String id) throws Exception { ArtifactReadable action = AtsServerService.get().getActionById(id); return atsServer.getWorkItemPage().getHtml(action, "Action - " + id, resourceRegistry, true); }

Target:
public String getActionWithDetails(@PathParam("id") String id) throws Exception { ArtifactReadable action = AtsServerService.get().getActionById(id); if (action == null) { return AHTML.simplePage(String.format("Action with id [%s] can not be found", id)); } return atsServer.getWorkItemPage().getHtml(action, "Action - " + id, resourceRegistry, true); }
Source:
public SpillableFinalOnlyGroupedAccumulator(List<Type> types, FinalOnlyGroupedAccumulator delegate) { this.delegate = delegate; this.spillingTypes = types; }

Target:
public SpillableFinalOnlyGroupedAccumulator(List<Type> types, FinalOnlyGroupedAccumulator delegate) { this.delegate = requireNonNull(delegate, "delegate FinalOnlyGroupedAccumulator is null"); this.spillingTypes = requireNonNull(types, "types is null"); }
Source:
public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); Function function; int lastDot = expr.lastIndexOf('.'); if (lastDot < 0) { function = NOOP; } else { function = FUNCTIONS.get(expr.substring(lastDot + 1)); if (function == null) { function = NOOP; } else { expr = expr.substring(0, lastDot); } } final Parameter p = new Parameter(expr, function); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }

Target:
public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); int lastDot = expr.lastIndexOf('.'); while (lastDot > 0) { Function function; function = FUNCTIONS.get(expr.substring(lastDot + 1)); if (function == null) { function = NOOP; } functions.add(function); expr = expr.substring(0, lastDot); lastDot = expr.lastIndexOf('.'); } functions.add(NOOP); final Parameter p = new Parameter(expr, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }
Source:
public Mono<Void> complete(MessageLockToken lockToken) { if (lockToken instanceof ServiceBusReceivedMessage) { return complete(lockToken, ((ServiceBusReceivedMessage) lockToken).getSessionId()); } else { String sessionId = null; return complete(lockToken, sessionId); } }

Target:
public Mono<Void> complete(MessageLockToken lockToken) { if (lockToken instanceof ServiceBusReceivedMessage) { return complete(lockToken, ((ServiceBusReceivedMessage) lockToken).getSessionId()); } else { return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null, null, null, null); } }
Source:
public String portion$getId() { return "minecraft:" + getName(); }

Target:
public String portion$getId() { return "minecraft:" + shadow$getName(); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register_email_layout); mSaveSmartLock = mActivityHelper.getSaveSmartLockInstance(); mPasswordFieldValidator = new PasswordFieldValidator( (TextInputLayout) findViewById(R.id.password_layout), getResources().getInteger(R.integer.min_password_length)); mNameValidator = new RequiredFieldValidator((TextInputLayout) findViewById(R.id.name_layout)); mEmailFieldValidator = new EmailFieldValidator((TextInputLayout) findViewById(R.id.email_layout)); mEmailEditText = (EditText) findViewById(R.id.email); mNameEditText = (EditText) findViewById(R.id.name); mPasswordEditText = (EditText) findViewById(R.id.password); mEmailEditText.setOnFocusChangeListener(this); mNameEditText.setOnFocusChangeListener(this); mPasswordEditText.setOnFocusChangeListener(this); findViewById(R.id.button_create).setOnClickListener(this); setUpTermsOfService(); if (savedInstanceState != null) { mPrevEmail = savedInstanceState.getString(PREV_EMAIL); return; } String email = getIntent().getStringExtra(ExtraConstants.EXTRA_EMAIL); if (!TextUtils.isEmpty(email)) { mEmailEditText.setText(email); mNameEditText.requestFocus(); return; } showEmailAutoCompleteHint(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register_email_layout); mSaveSmartLock = mActivityHelper.getSaveSmartLockInstance(); mPasswordFieldValidator = new PasswordFieldValidator( (TextInputLayout) findViewById(R.id.password_layout), getResources().getInteger(R.integer.min_password_length)); mNameValidator = new RequiredFieldValidator((TextInputLayout) findViewById(R.id.name_layout)); mEmailFieldValidator = new EmailFieldValidator((TextInputLayout) findViewById(R.id.email_layout)); mEmailEditText = (EditText) findViewById(R.id.email); mNameEditText = (EditText) findViewById(R.id.name); mPasswordEditText = (EditText) findViewById(R.id.password); mEmailEditText.setOnFocusChangeListener(this); mNameEditText.setOnFocusChangeListener(this); mPasswordEditText.setOnFocusChangeListener(this); findViewById(R.id.button_create).setOnClickListener(this); setUpTermsOfService(); if (savedInstanceState != null) { mPrevEmail = savedInstanceState.getString(PREV_EMAIL); return; } String email = getIntent().getStringExtra(ExtraConstants.EXTRA_EMAIL); if (!TextUtils.isEmpty(email)) { mEmailEditText.setText(email); mNameEditText.requestFocus(); return; } if (mActivityHelper.getFlowParams().smartLockEnabled) { showEmailAutoCompleteHint(); } }
Source:
public void location_lock_dir_error_03() throws IOException { Assume.assumeTrue(negativePidsTreatedAsAlive); Location dir = Location.create(tempDir.getRoot().getAbsolutePath()); LocationLock lock = dir.getLock(); Assert.assertTrue(lock.canLock()); Assert.assertFalse(lock.isLocked()); Assert.assertFalse(lock.isOwned()); Assert.assertTrue(lock.canObtain()); try (BufferedWriter writer = new BufferedWriter(new FileWriter(dir.getPath("tdb.lock")))) { writer.write(Integer.toString(-1234)); writer.write('\n'); } try { lock.canObtain(); Assert.fail("Expected the lock file to be considered invalid"); } catch (FileException e) { String errMsg = e.getMessage(); Assert.assertNotNull(errMsg); System.out.println(errMsg); Assert.assertTrue(errMsg.contains("appear to be for a TDB2 database")); } }

Target:
public void location_lock_dir_error_03() throws IOException { Assume.assumeTrue(negativePidsTreatedAsAlive); Location dir = Location.create(tempDir.getRoot().getAbsolutePath()); LocationLock lock = dir.getLock(); Assert.assertTrue(lock.canLock()); Assert.assertFalse(lock.isLocked()); Assert.assertFalse(lock.isOwned()); Assert.assertTrue(lock.canObtain()); try (BufferedWriter writer = new BufferedWriter(new FileWriter(dir.getPath("tdb.lock")))) { writer.write(Integer.toString(-1234)); writer.write('\n'); } try { lock.canObtain(); Assert.fail("Expected the lock file to be considered invalid"); } catch (FileException e) { String errMsg = e.getMessage(); Assert.assertNotNull(errMsg); Assert.assertTrue(errMsg.contains("appear to be for a TDB2 database")); } }