auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public BigDecimal convertTemp(BigDecimal value) { if (this == DEFAULT_UNIT_SYSTEM) { return value; } return value.multiply(new BigDecimal(9)).divide(new BigDecimal(5)).add(new BigDecimal(32)); }

Target:
public BigDecimal convertTemp(BigDecimal value) { if (this == DEFAULT_UNIT_SYSTEM) { return value; } return value.multiply(ONE_POINT_EIGHT).add(THIRTY_TWO); }
Source:
public boolean match(OsmPrimitive osm) { for (TaggingPreset p : ps) { if (p.test(osm)) return true; } return false; }

Target:
public boolean match(OsmPrimitive osm) { for (TaggingPreset p : this.presets) { if (p.test(osm)) { return true; } } return false; }
Source:
private static boolean isValidGroupId(String idStr) { return idStr.matches("^G[0-9a-fA-F]{40}$") && !idStr.matches("^G00*$"); }

Target:
private static boolean isValidGroupId(String idStr) { return idStr.matches("^G[0-9a-fA-F]{40}$"); }
Source:
public ProcessStatus check() { if (resource.isLocked()) return ProcessStatus.NOTHING_TO_DO; Transact currentTransact = inputDock.pullTransact(); if (currentTransact == null) return ProcessStatus.NOTHING_TO_DO; System.out.println(Simulator.getTime() + ": seize body " + currentTransact.getNumber()); if (!outputDock.pushTransact(currentTransact)) { System.out.println(Simulator.getTime() + ": seize failed to give " + currentTransact.getNumber()); inputDock.rollBack(currentTransact); return ProcessStatus.FAILURE; } currentTransact = null; resource.lock(); return ProcessStatus.SUCCESS; }

Target:
public BlockStatus check() { if (resource.isLocked()) return BlockStatus.NOTHING_TO_DO; if (outputDock.hasTransact()) return BlockStatus.CHECK_AGAIN; Transact transact = inputDock.pullTransact(); if (transact == null) return BlockStatus.NOTHING_TO_DO; System.out.println(Simulator.getTime() + ": seize body " + transact.getNumber()); outputDock.pushTransact(transact); resource.lock(); return BlockStatus.SUCCESS; }
Source:
public boolean contains(Patient patient) { return getMembers() != null && getMembers().stream() .anyMatch(m -> m.getPatientId().getPatientId().equals(patient.getPatientId())); }

Target:
public boolean contains(Patient patient) { return contains(patient.getPatientId()); }
Source:
private ListenableFuture<PrestoThriftSplitBatch> sendSplitRequest(PrestoThriftService client, @Nullable PrestoThriftId nextToken) { long start = System.nanoTime(); ListenableFuture<PrestoThriftSplitBatch> future = client.getLookupSplits( schemaTableName, lookupColumnNames, outputColumnNames, keys, outputConstraint, MAX_SPLIT_COUNT, new PrestoThriftNullableToken(nextToken)); future.addListener(() -> readTimeNanos.addAndGet(System.nanoTime() - start), directExecutor()); return future; }

Target:
private ListenableFuture<PrestoThriftSplitBatch> sendSplitRequest(PrestoThriftService client, @Nullable PrestoThriftId nextToken) { long start = System.nanoTime(); ListenableFuture<PrestoThriftSplitBatch> future = client.getIndexSplits( schemaTableName, lookupColumnNames, outputColumnNames, keys, outputConstraint, MAX_SPLIT_COUNT, new PrestoThriftNullableToken(nextToken)); future.addListener(() -> readTimeNanos.addAndGet(System.nanoTime() - start), directExecutor()); return future; }
Source:
public void testLargeMessageFileLeak() throws Exception { Assume.assumeTrue(File.separatorChar == '/'); OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); long fdBaseline = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount(); final int SIZE = 2 * 1024; SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); SimpleString adName = new SimpleString("ad1"); AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(1).setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(adName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); clientSession.createQueue(adName, qName, null, false); for (int i = 0; i < 10; i++) { ClientProducer producer = clientSession.createProducer(adName); ClientMessage clientFile = clientSession.createMessage(true); clientFile.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(SIZE)); producer.send(clientFile); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(qName); ClientMessage m = clientConsumer.receive(500); m.acknowledge(); Assert.assertNotNull(m); clientSession.rollback(); m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); } assertEquals("File descriptors are leaking", 0, ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount() - fdBaseline); }

Target:
public void testLargeMessageFileLeak() throws Exception { OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); Assume.assumeTrue(os instanceof UnixOperatingSystemMXBean); long fdBaseline = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount(); final int SIZE = 2 * 1024; SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); SimpleString adName = new SimpleString("ad1"); AddressSettings addressSettings = new AddressSettings().setMaxDeliveryAttempts(1).setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(adName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); clientSession.createQueue(adName, qName, null, false); for (int i = 0; i < 10; i++) { ClientProducer producer = clientSession.createProducer(adName); ClientMessage clientFile = clientSession.createMessage(true); clientFile.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(SIZE)); producer.send(clientFile); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(qName); ClientMessage m = clientConsumer.receive(500); m.acknowledge(); Assert.assertNotNull(m); clientSession.rollback(); m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); } assertEquals("File descriptors are leaking", 0, ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount() - fdBaseline); }
Source:
private void updateAlerts() { setHasAnyAlert(false); setHasUpgradeAlert(false); setHasManualFenceAlert(false); setHasNoPowerManagementAlert(false); setHasReinstallAlertNonResponsive(false); setHasReinstallAlertInstallFailed(false); setHasReinstallAlertMaintenance(false); setHasNICsAlert(false); getEditHostCommand().setIsExecutionAllowed(canExecuteCommand(VdcActionType.UpdateVds)); setHasNICsAlert((getEntity().getNetConfigDirty() == null ? false : getEntity().getNetConfigDirty())); if (getEntity().getStatus() == VDSStatus.NonResponsive && !getEntity().isPmEnabled() && ((getEntity().getVmActive() == null ? 0 : getEntity().getVmActive()) > 0 || getEntity().getSpmStatus() == VdsSpmStatus.SPM)) { setHasManualFenceAlert(true); } else if (!getEntity().isPmEnabled()) { setHasNoPowerManagementAlert(true); } if (getEntity().getStatus() == VDSStatus.NonResponsive) { setHasReinstallAlertNonResponsive(true); } else if (getEntity().getStatus() == VDSStatus.InstallFailed) { setHasReinstallAlertInstallFailed(true); } else if (getEntity().getStatus() == VDSStatus.Maintenance) { setHasReinstallAlertMaintenance(true); } getUpgradeHostCommand().setIsExecutionAllowed(getEntity().isUpdateAvailable() && canExecuteCommand(VdcActionType.UpgradeHost)); setNonOperationalReasonEntity((getEntity().getNonOperationalReason() == NonOperationalReason.NONE ? null : (NonOperationalReason) getEntity().getNonOperationalReason())); setHasAnyAlert(); }

Target:
private void updateAlerts() { setHasAnyAlert(false); setHasUpgradeAlert(false); setHasManualFenceAlert(false); setHasNoPowerManagementAlert(false); setHasReinstallAlertNonResponsive(false); setHasReinstallAlertInstallFailed(false); setHasReinstallAlertMaintenance(false); setHasNICsAlert(false); setHasNICsAlert((getEntity().getNetConfigDirty() == null ? false : getEntity().getNetConfigDirty())); if (getEntity().getStatus() == VDSStatus.NonResponsive && !getEntity().isPmEnabled() && ((getEntity().getVmActive() == null ? 0 : getEntity().getVmActive()) > 0 || getEntity().getSpmStatus() == VdsSpmStatus.SPM)) { setHasManualFenceAlert(true); } else if (!getEntity().isPmEnabled()) { setHasNoPowerManagementAlert(true); } if (getEntity().getStatus() == VDSStatus.NonResponsive) { setHasReinstallAlertNonResponsive(true); } else if (getEntity().getStatus() == VDSStatus.InstallFailed) { setHasReinstallAlertInstallFailed(true); } else if (getEntity().getStatus() == VDSStatus.Maintenance) { setHasReinstallAlertMaintenance(true); } setNonOperationalReasonEntity((getEntity().getNonOperationalReason() == NonOperationalReason.NONE ? null : (NonOperationalReason) getEntity().getNonOperationalReason())); updateActionAvailability(); setHasAnyAlert(); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } GlusterVolumeEntity volume = getGlusterVolumeDao().getById(getGlusterVolumeId()); if (volume != null && volume.getStatus() == GlusterStatus.DOWN) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); } if (!GlusterUtil.getInstance().isVolumeThinlyProvisioned(volume)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_NOT_THINLY_PROVISIONED); } Date currentDate = new Date(); if (!(schedule.getRecurrence() == null || schedule.getRecurrence() == GlusterVolumeSnapshotScheduleRecurrence.UNKNOWN)) { if (schedule.getStartDate() != null && schedule.getStartDate().compareTo(currentDate) < 0) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_START_DATE_BEFORE_CURRENT_DATE); } if (schedule.getEndByDate() != null) { if (schedule.getEndByDate().compareTo(currentDate) < 0) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_END_BY_DATE_BEFORE_CURRENT_DATE); } if (schedule.getStartDate() != null && schedule.getEndByDate().compareTo(schedule.getStartDate()) <= 0) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_END_BY_DATE_BEFORE_START_DATE); } } } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } GlusterVolumeEntity volume = getGlusterVolume(); if (volume != null && volume.getStatus() == GlusterStatus.DOWN) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); } if (!GlusterUtil.getInstance().isVolumeThinlyProvisioned(volume)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_NOT_THINLY_PROVISIONED); } Date currentDate = new Date(); Date convertedStartDate = convertDate(schedule.getStartDate(), schedule.getTimeZone()); Date convertedEndByDate = convertDate(schedule.getEndByDate(), schedule.getTimeZone()); if (!(schedule.getRecurrence() == null || schedule.getRecurrence() == GlusterVolumeSnapshotScheduleRecurrence.UNKNOWN)) { if (schedule.getStartDate() != null && convertedStartDate.compareTo(currentDate) < 0) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_START_DATE_BEFORE_CURRENT_DATE); } if (schedule.getEndByDate() != null) { if (convertedEndByDate.compareTo(currentDate) < 0) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_END_BY_DATE_BEFORE_CURRENT_DATE); } if (schedule.getStartDate() != null && convertedEndByDate.compareTo(convertedStartDate) <= 0) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_END_BY_DATE_BEFORE_START_DATE); } } } return true; }
Source:
public void checkError() { if(startAnchor.isPresent() && endAnchor.isPresent()) { try { endAnchor.get().getBlock().asExpr().analyze(new Env(), new GenSet()); this.setStyle("-fx-stroke: black;"); } catch (HaskellTypeError e) { this.setStyle("-fx-stroke: red;"); } catch (HaskellException e) { } } }

Target:
private void checkError() { if(startAnchor.isPresent() && endAnchor.isPresent()) { try { endAnchor.get().getBlock().asExpr().analyze(new Env(), new GenSet()); this.getStyleClass().remove("error"); } catch (HaskellTypeError e) { this.getStyleClass().add("error"); } catch (HaskellException e) { e.printStackTrace(); } } }
Source:
void replaceScriptOne(StringBuilder scriptOne) { translate(scriptOne, scriptOneToScriptTwo); }

Target:
public void replaceScriptOne(StringBuilder scriptOne) { translate(scriptOne, scriptOneToScriptTwo); }
Source:
public Conversation build() { return new Conversation(this.location, this.protocol, this.lowerIp, this.upperIp, this.lowerHostname, this.upperHostname, this.application); }

Target:
public Conversation build() { return new Conversation(this); }
Source:
public MicrosoftOAuth2AP(String aClientId, String aClientSecret){ this.id = "microsoft"; this.title = "Microsoft"; this.clientId = aClientId; this.clientSecret = aClientSecret; this.scope = Arrays.asList("openid User.Read"); this.baseUserEndpoint = "<LINK_0>"; }

Target:
public MicrosoftOAuth2AP(String aClientId, String aClientSecret){ this.id = "microsoft"; this.title = "Microsoft"; this.clientId = aClientId; this.clientSecret = aClientSecret; this.scope = Arrays.asList("User.Read"); this.baseUserEndpoint = "<LINK_0>"; }
Source:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof RollershutterItem)) { throw new BindingConfigParseException( "item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', this Item is not allowed - please check your *.items configuration"); } }

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof RollershutterItem)) { throw new BindingConfigParseException( "item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', this Item is not allowed - please check your *.items configuration" + ", only SwitchItem and RollershutterItem are allowed / supported for now"); } }
Source:
public void testFoo() throws Exception { assumeTrue(postgresIsInstalled); DAO dao = dbi.open(DAO.class); Long brian_id = dao.insert("Brian"); long keith_id = dao.insert("Keith"); assertThat(dao.findNameById(brian_id), equalTo("Brian")); assertThat(dao.findNameById(keith_id), equalTo("Keith")); dao.close(); }

Target:
public void testFoo() throws Exception { DAO dao = dbi.open(DAO.class); Long brian_id = dao.insert("Brian"); long keith_id = dao.insert("Keith"); assertThat(dao.findNameById(brian_id), equalTo("Brian")); assertThat(dao.findNameById(keith_id), equalTo("Keith")); dao.close(); }
Source:
private boolean reportShortcutBinding(String message) { if (reportShortcutBinding_) events_.fireEvent(new ReportShortcutBindingEvent(message)); return reportShortcutBinding_; }

Target:
private boolean reportShortcutBinding(String message) { if (reportShortcutBinding_) { events_.fireEvent(new ReportShortcutBindingEvent(message)); reportedPending_ = false; } return reportShortcutBinding_; }
Source:
public void testEnumConstantDeclaration1() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); StringBuilder buf= new StringBuilder(); buf.append("package test;\n"); buf.append("\n"); buf.append("public enum TestEnum {\n"); buf.append(" A(11);\n"); buf.append("\n"); buf.append(" TestEnum(int value) {}\n"); buf.append("\n"); buf.append(" private static int getDefaultValue() {\n"); buf.append(" return -1;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit compilationUnit= pack1.createCompilationUnit("TestEnum.java", buf.toString(), false, null); CompilationUnit astRoot= createAST(compilationUnit); assertNoProblems(astRoot); { String str= "11"; int offset= buf.toString().indexOf(str); int flags= ScopeAnalyzer.METHODS; for (IBinding re : new ScopeAnalyzer(astRoot).getDeclarationsInScope(offset, flags)) { if ("getDefaultValue".equals(re.getName())) { return; } } assertFalse("getDefaultValue not found", true); } }

Target:
public void testEnumConstantDeclaration1() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); StringBuilder buf= new StringBuilder(); buf.append("package test;\n"); buf.append("\n"); buf.append("public enum TestEnum {\n"); buf.append(" A(11);\n"); buf.append("\n"); buf.append(" TestEnum(int value) {}\n"); buf.append("\n"); buf.append(" private static int getDefaultValue() {\n"); buf.append(" return -1;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit compilationUnit= pack1.createCompilationUnit("TestEnum.java", buf.toString(), false, null); CompilationUnit astRoot= createAST(compilationUnit); assertNoProblems(astRoot); { String str= "11"; int offset= buf.toString().indexOf(str); int flags= ScopeAnalyzer.METHODS; for (IBinding binding : new ScopeAnalyzer(astRoot).getDeclarationsInScope(offset, flags)) { if ("getDefaultValue".equals(binding.getName())) { return; } } assertFalse("getDefaultValue not found", true); } }
Source:
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception { Http2ClientStream stream = (Http2ClientStream) streams.get(streamId); stream.setStreamDependency(streamDependency); stream.setWeight(weight); onHeadersRead(ctx, streamId, headers, padding, endOfStream); }

Target:
public synchronized void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception { Http2ClientStream stream = (Http2ClientStream) streams.get(streamId); if (stream != null) { context.executeFromIO(v -> { stream.handleHeaders(headers, new StreamPriority(streamDependency, weight, exclusive), endOfStream); }); } }
Source:
public static <T> Query<T> verifyMaxQueryTimeout(Query<T> query, long maxQueryTimeout) { Object obj = query.getContextValue(TIMEOUT_KEY); if (obj == null) { return query; } else { long curr = ((Number) obj).longValue(); if (curr > maxQueryTimeout) { throw new IAE( "configured [%s = %s] is more than enforced limit of maxQueryTimeout [%s].", TIMEOUT_KEY, curr, maxQueryTimeout ); } else { return query; } } }

Target:
public static <T> Query<T> verifyMaxQueryTimeout(Query<T> query, long maxQueryTimeout) { long timeout = getTimeout(query); if (timeout > maxQueryTimeout) { throw new IAE( "configured [%s = %s] is more than enforced limit of maxQueryTimeout [%s].", TIMEOUT_KEY, timeout, maxQueryTimeout ); } else { return query; } }
Source:
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException { String restOfPath = req.getRestOfPath(); if (restOfPath.isEmpty()) { String url = Jenkins.get().getRootUrl() + browserUrl; rsp.sendRedirect(302, url); return; } AccessControlled requestRoot = Jenkins.get(); String requestUrlSuffix = this.browserUrl; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Performing a request as authentication: " + authenticationName + " to object: " + requestRoot + " and restOfUrl: " + requestUrlSuffix + " and restOfPath: " + restOfPath); } Authentication auth = Jenkins.ANONYMOUS; if (authenticationName != null) { User user = User.getById(authenticationName, false); if (user != null) { auth = user.impersonate(); } } try (ACLContext ignored = ACL.as(auth)) { Stapler.getCurrent().invoke(req, rsp, requestRoot, requestUrlSuffix + restOfPath); } catch (AccessDeniedException ade) { LOGGER.log(Level.INFO, "Failed permission check for resource URL access", ade); rsp.sendError(403, "Failed permission check: " + ade.getMessage()); } catch (Exception e) { LOGGER.log(Level.INFO, "Something else failed for resource URL access", e); rsp.sendError(404, "Failed: " + e.getMessage()); } }

Target:
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException { String restOfPath = req.getRestOfPath(); String requestUrlSuffix = this.browserUrl; LOGGER.fine(() -> "Performing a request as authentication: " + authenticationName + " and restOfUrl: " + requestUrlSuffix + " and restOfPath: " + restOfPath); Authentication auth = Jenkins.ANONYMOUS; if (authenticationName != null) { User user = User.getById(authenticationName, false); if (user != null) { try { auth = user.impersonate(); LOGGER.fine(() -> "Successfully impersonated " + authenticationName); } catch (UsernameNotFoundException ex) { LOGGER.log(Level.FINE, "Failed to impersonate " + authenticationName, ex); rsp.sendError(403, "No such user: " + authenticationName); return; } } } try (ACLContext ignored = ACL.as(auth)) { try { Stapler.getCurrent().invoke(req, rsp, Jenkins.get(), requestUrlSuffix + restOfPath); } catch (Exception ex) { Throwable cause = ex.getCause(); while (cause != null) { if (cause instanceof AccessDeniedException) { throw (AccessDeniedException) cause; } cause = cause.getCause(); } throw ex; } } catch (AccessDeniedException ade) { LOGGER.log(Level.FINE, "Failed permission check for resource URL access", ade); rsp.sendError(403, "Failed permission check: " + ade.getMessage()); } catch (Exception e) { LOGGER.log(Level.FINE, "Something else failed for resource URL access", e); rsp.sendError(404); } }
Source:
private void respondToQuery(HttpServletRequest req, HttpServletResponse resp) throws IOException { RDFService rdfService = ModelAccess.on(getServletContext()) .getRDFService(); String queryString = req.getParameter("query"); boolean download = Boolean.parseBoolean(req.getParameter("download")); Query query = SparqlQueryUtils.create(queryString); try { String format = interpretRequestedFormats(req, query); SparqlQueryApiExecutor core = SparqlQueryApiExecutor.instance( rdfService, queryString, format); resp.setContentType(core.getMediaType()); if (download) { String extension = getFilenameExtension(req, query, format); resp.setHeader("Content-Transfer-Encoding", "binary"); resp.setHeader("Content-disposition", "attachment; filename=sparqlquery." + extension); } core.executeAndFormat(resp.getOutputStream()); } catch (InvalidQueryTypeException e) { do400BadRequest("Query type is not SELECT, ASK, CONSTRUCT, " + "or DESCRIBE: '" + queryString + "'", resp); } catch (QueryParseException e) { do400BadRequest("Failed to parse query: '" + queryString + "''", e, resp); } catch (NotAcceptableException | AcceptHeaderParsingException e) { do500InternalServerError("Problem with the page fields: the " + "selected fields do not include an " + "acceptable content type.", e, resp); } catch (RDFServiceException e) { do500InternalServerError("Problem executing the query.", e, resp); } }

Target:
private void respondToQuery(HttpServletRequest req, HttpServletResponse resp) throws IOException { RDFService rdfService = ModelAccess.on(getServletContext()) .getRDFService(); String queryString = req.getParameter("query"); boolean download = Boolean.parseBoolean(req.getParameter("download")); Query query = SparqlQueryUtils.create(queryString); try { String format = interpretRequestedFormats(req, query); SparqlQueryApiExecutor core = SparqlQueryApiExecutor.instance( rdfService, queryString, format); resp.setContentType(core.getMediaType()); if (download) { String extension = getFilenameExtension(req, query, format); resp.setHeader("Content-Transfer-Encoding", "binary"); resp.setHeader("Content-disposition", "attachment; filename=query-results." + extension); } core.executeAndFormat(resp.getOutputStream()); } catch (InvalidQueryTypeException e) { do400BadRequest("Query type is not SELECT, ASK, CONSTRUCT, " + "or DESCRIBE: '" + queryString + "'", resp); } catch (QueryParseException e) { do400BadRequest("Failed to parse query: '" + queryString + "''", e, resp); } catch (NotAcceptableException | AcceptHeaderParsingException e) { do500InternalServerError("Problem with the page fields: the " + "selected fields do not include an " + "acceptable content type.", e, resp); } catch (RDFServiceException e) { do500InternalServerError("Problem executing the query.", e, resp); } }
Source:
public void load(long position, BufferReference bufferReference, int length) { if (position < 0 || position + length > totalLength) { throw new IllegalArgumentException(); } int sliceIndex = 0; while (position >= slices.get(sliceIndex).length()) { position -= slices.get(sliceIndex).length(); sliceIndex++; } int slicePosition = toIntExact(position); Slice outputSlice = bufferReference.getSlice(); int destinationIndex = 0; while (length > 0) { Slice currentSlice = slices.get(sliceIndex); int loadSize = Math.min(currentSlice.length() - slicePosition, length); currentSlice.getBytes(slicePosition, outputSlice, destinationIndex, loadSize); length -= loadSize; destinationIndex += loadSize; if (length == 0) { break; } sliceIndex++; slicePosition = 0; } }

Target:
public void load(long position, BufferReference bufferReference, int length) { if (position < 0 || position + length > totalLength) { throw new IllegalArgumentException(); } int currentSliceIndex = 0; long globalOffset = 0; while (globalOffset + slices.get(currentSliceIndex).length() <= position) { globalOffset += slices.get(currentSliceIndex).length(); currentSliceIndex++; } int currentSliceOffset = toIntExact(position - globalOffset); Slice outputSlice = bufferReference.getSlice(); int outputSliceOffset = 0; while (length > 0) { Slice currentSlice = slices.get(currentSliceIndex); int loadSize = Math.min(currentSlice.length() - currentSliceOffset, length); currentSlice.getBytes(currentSliceOffset, outputSlice, outputSliceOffset, loadSize); length -= loadSize; outputSliceOffset += loadSize; currentSliceIndex++; currentSliceOffset = 0; } }
Source:
public Reply<?> fetchEncodings() { List<Encoding> encodings = catalog.findAll(); List<String> list = adapt(encodings); return Reply.with(list).as(Json.class).ok(); }

Target:
public Reply<?> fetchEncodings() { List<Encoding> encodings = catalog.findAll(); List<String> dto = adapt(encodings); return Reply.with(dto).as(Json.class).ok(); }
Source:
public ResourceResponse<Document> upsertMetadata(CloudBlobMetadata blobMetadata) throws DocumentClientException { RequestOptions options = getRequestOptions(blobMetadata.getPartitionId()); return retryOperationWithThrottling( () -> documentClient.upsertDocument(cosmosCollectionLink, blobMetadata, null, true), azureMetrics.documentCreateTime); }

Target:
public ResourceResponse<Document> upsertMetadata(CloudBlobMetadata blobMetadata) throws DocumentClientException { RequestOptions options = getRequestOptions(blobMetadata.getPartitionId()); return retryOperationWithThrottling( () -> documentClient.upsertDocument(cosmosCollectionLink, blobMetadata, options, true), azureMetrics.documentCreateTime); }
Source:
private boolean isEditable(Object element, MergeViewerSide side) { final boolean isEditibleInConfiguration = isEditableInConfiguration(side); if (isEditibleInConfiguration && isCompareInputAdapterHoldingADiff(element)) { final CompareInputAdapter inputAdapter = (CompareInputAdapter)element; final IModelUpdateStrategy modelUpdateStrategy = inputAdapter.getModelUpdateStrategy(); final Diff diff = (Diff)inputAdapter.getComparisonObject(); return modelUpdateStrategy.canUpdate(diff, side); } return isEditibleInConfiguration; }

Target:
private boolean isEditable(Object element, MergeViewerSide side) { final boolean isEditableInConfiguration = isEditableInConfiguration(side); if (isEditableInConfiguration && isCompareInputAdapterHoldingADiff(element)) { final CompareInputAdapter inputAdapter = (CompareInputAdapter)element; final IModelUpdateStrategy modelUpdateStrategy = inputAdapter.getModelUpdateStrategy(); final Diff diff = (Diff)inputAdapter.getComparisonObject(); return modelUpdateStrategy.canUpdate(diff, side); } return isEditableInConfiguration; }
Source:
public static Map<String, Long> subtract(Map<String, Long> xs, Map<String, Long> ys) { assert xs.keySet().equals(ys.keySet()); final Map<String, Long> zs = new HashMap<String, Long>(); for (Map.Entry<String, Long> entry : xs.entrySet()) { zs.put(entry.getKey(), xs.get(entry.getKey()) - ys.get(entry.getKey())); } return zs; }

Target:
public static Map<String, Long> subtract(Map<String, Long> xs, Map<String, Long> ys) { assert xs.keySet().equals(ys.keySet()); final Map<String, Long> zs = new HashMap<String, Long>(); for (Map.Entry<String, Long> entry : xs.entrySet()) { zs.put(entry.getKey(), entry.getValue() - ys.get(entry.getKey())); } return zs; }
Source:
public void testResumeTxInAnotherThread() throws Exception { executeTestForAllCaches(new CI2Exc<Ignite, IgniteCache<Integer, Integer>>() { @Override public void applyx(Ignite ignite, final IgniteCache<Integer, Integer> cache) throws Exception { for (TransactionIsolation isolation : TransactionIsolation.values()) { final Transaction tx = ignite.transactions().txStart(transactionConcurrency(), isolation); final AtomicInteger cntr = new AtomicInteger(0); for (int j = -1; j > -10; j--) cache.put(j, j); cache.put(cntr.get(), cntr.getAndIncrement()); tx.suspend(); assertEquals(SUSPENDED, tx.state()); assertNull("Thread already have tx", ignite.transactions().tx()); assertNull(cache.get(-1)); assertNull(cache.get(cntr.get())); for (int i = 0; i < 10; i++) { GridTestUtils.runAsync(new Runnable() { @Override public void run() { assertEquals(SUSPENDED, tx.state()); tx.resume(); assertEquals(ACTIVE, tx.state()); for (int j = -1; j > -10; j--) cache.put(j, j); cache.put(cntr.get(), cntr.getAndIncrement()); tx.suspend(); } }).get(FUT_TIMEOUT); } tx.resume(); for (int j = -1; j > -10; j--) cache.remove(j); tx.commit(); assertEquals(COMMITTED, tx.state()); for (int i = 0; i < cntr.get(); i++) assertEquals(i, (int)cache.get(i)); assertFalse(cache.containsKey(-1)); cache.removeAll(); } } }); }

Target:
public void testResumeTxInAnotherThread() throws Exception { executeTestForAllCaches(new CI2Exc<Ignite, IgniteCache<Integer, Integer>>() { @Override public void applyx(Ignite ignite, final IgniteCache<Integer, Integer> cache) throws Exception { for (TransactionIsolation isolation : TransactionIsolation.values()) { final Transaction tx = ignite.transactions().txStart(transactionConcurrency(), isolation); final AtomicInteger cntr = new AtomicInteger(0); for (int j = -1; j > -10; j--) cache.put(j, j); cache.put(cntr.get(), cntr.getAndIncrement()); tx.suspend(); assertEquals(SUSPENDED, tx.state()); assertNull("Thread already have tx", ignite.transactions().tx()); assertNull(cache.get(-1)); assertNull(cache.get(cntr.get())); for (int i = 0; i < 10; i++) { GridTestUtils.runAsync(() -> { assertEquals(SUSPENDED, tx.state()); tx.resume(); assertEquals(ACTIVE, tx.state()); for (int j = -1; j > -10; j--) cache.put(j, j); cache.put(cntr.get(), cntr.getAndIncrement()); tx.suspend(); }).get(FUT_TIMEOUT); } tx.resume(); for (int j = -1; j > -10; j--) cache.remove(j); tx.commit(); assertEquals(COMMITTED, tx.state()); for (int i = 0; i < cntr.get(); i++) assertEquals(i, (int)cache.get(i)); assertFalse(cache.containsKey(-1)); cache.removeAll(); } } }); }
Source:
private boolean isKeyExpired() { return System.nanoTime() - lastGenerationNanos > keyLifetime; }

Target:
private boolean isKeyExpired() { return (System.nanoTime() - nextKeyGenerationNanos) >= 0; }
Source:
void tzidsOrderMustNotChange() throws URISyntaxException, IOException { Path path = Paths.get( TimeZones.class.getResource( "/TZIDS" ).toURI() ); String timeZonesInfo = Files.readString( path ).replace( System.lineSeparator(), "\n" ); byte[] timeZonesHash = DigestUtils.sha256( timeZonesInfo ); assertThat( timeZonesHash, equalTo( new byte[]{-9, 121, 49, -61, 86, 11, 77, -117, 77, 105, -15, -16, 4, 109, 62, 107, -118, 99, 9, -121, -58, 76, -41, 29, 43, 86, -68, 118, -86, 34, 99, 63} ) ); }

Target:
void tzidsOrderMustNotChange() throws URISyntaxException, IOException { Path path = Paths.get( TimeZones.class.getResource( "/TZIDS" ).toURI() ); String timeZonesInfo = Files.readString( path ).replace( "\r\n", "\n" ); byte[] timeZonesHash = DigestUtils.sha256( timeZonesInfo ); assertThat( timeZonesHash ).isEqualTo( new byte[]{-9, 121, 49, -61, 86, 11, 77, -117, 77, 105, -15, -16, 4, 109, 62, 107, -118, 99, 9, -121, -58, 76, -41, 29, 43, 86, -68, 118, -86, 34, 99, 63} ); }
Source:
private void cleanupExpiredInflightRequests() { Iterator<Map.Entry<Integer, InflightRequestInfo>> itr = inflightRequestInfos.entrySet().iterator(); while (itr.hasNext()) { InflightRequestInfo inflightRequestInfo = itr.next().getValue(); if (time.milliseconds() - inflightRequestInfo.submissionTime > routerConfig.routerRequestTimeoutMs) { itr.remove(); resolveRouterError(RouterErrorCode.OperationTimedOut); operationTracker.onResponse(inflightRequestInfo.replica, false); } } }

Target:
private void cleanupExpiredInflightRequests() { Iterator<Map.Entry<Integer, InflightRequestInfo>> itr = inflightRequestInfos.entrySet().iterator(); while (itr.hasNext()) { InflightRequestInfo inflightRequestInfo = itr.next().getValue(); if (time.milliseconds() - inflightRequestInfo.submissionTime > routerConfig.routerRequestTimeoutMs) { itr.remove(); updateOperationState(inflightRequestInfo.replica, RouterErrorCode.OperationTimedOut); } } }
Source:
public void actionPerformed(AnActionEvent event) { Optional<VirtualFile> maybeBuildRoot = PantsUtil.findBuildRoot(event.getProject()); Optional<VirtualFile> maybeFile = PantsUtil.getFileForEvent(event); if (!maybeBuildRoot.isPresent() || !maybeFile.isPresent()) { return; } VirtualFile buildRoot = maybeBuildRoot.get(); VirtualFile file = maybeFile.get(); Path filePath = Paths.get(file.getPath()); Path buildRootPath = Paths.get(buildRoot.getPath()); String relativePath = buildRootPath.relativize(filePath).toString(); Toolkit.getDefaultToolkit().getSystemClipboard().setContents( new StringSelection(relativePath), null ); }

Target:
public void actionPerformed(AnActionEvent event) { Optional<VirtualFile> maybeBuildRoot = PantsUtil.findBuildRoot(event.getProject()); Optional<VirtualFile> maybeFile = PantsUtil.getFileForEvent(event); if (!(maybeBuildRoot.isPresent() && maybeFile.isPresent())) { return; } VirtualFile buildRoot = maybeBuildRoot.get(); VirtualFile file = maybeFile.get(); Path filePath = Paths.get(file.getPath()); Path buildRootPath = Paths.get(buildRoot.getPath()); String relativePath = buildRootPath.relativize(filePath).toString(); Toolkit.getDefaultToolkit().getSystemClipboard().setContents( new StringSelection(relativePath), null ); }
Source:
static synchronized SnappyApi loadSnappyApi() { if (snappyApi != null) { return snappyApi; } ByteOrder order = ByteOrder.nativeOrder(); try { if(Boolean.parseBoolean(System.getProperty(KEY_SNAPPY_PUREJAVA, "false"))) { if (order.equals(ByteOrder.LITTLE_ENDIAN)) setSnappyApi(new PureJavaSnappy()); else setSnappyApi(new PureJavaSnappyBE()); } else { loadNativeLibrary(); setSnappyApi(new SnappyNative()); } } catch(Exception e) { if (order.equals(ByteOrder.LITTLE_ENDIAN)) setSnappyApi(new PureJavaSnappy()); else setSnappyApi(new PureJavaSnappyBE()); } return snappyApi; }

Target:
static synchronized SnappyApi loadSnappyApi() { if (snappyApi != null) { return snappyApi; } try { if(Boolean.parseBoolean(System.getProperty(KEY_SNAPPY_PUREJAVA, "false"))) { setSnappyApi(new PureJavaSnappy()); } else { loadNativeLibrary(); setSnappyApi(new SnappyNative()); } } catch(Exception e) { setSnappyApi(new PureJavaSnappy()); } return snappyApi; }
Source:
public List<BithumbTransactionHistoryResponse.BithumbTransactionHistory> getBithumbTrades( CurrencyPair currencyPair) throws IOException { final BithumbResponse<List<BithumbTransactionHistoryResponse.BithumbTransactionHistory>> transactionHistory = bithumb.transactionHistory(BithumbUtils.getBaseCurrency(currencyPair)); return transactionHistory.getData(); }

Target:
public List<BithumbTransactionHistory> getBithumbTrades(CurrencyPair currencyPair) throws IOException { final BithumbResponse<List<BithumbTransactionHistory>> transactionHistory = bithumb.transactionHistory(BithumbUtils.getBaseCurrency(currencyPair)); return transactionHistory.getData(); }
Source:
public CosmosDataAccessor(DocumentClient documentClient, AzureCloudConfig azureCloudConfig, AzureMetrics azureMetrics) { this.documentClient = documentClient; this.cosmosCollectionLink = azureCloudConfig.cosmosCollectionLink; this.azureMetrics = azureMetrics; this.maxRetries = azureCloudConfig.cosmosMaxRetries; }

Target:
public CosmosDataAccessor(DocumentClient documentClient, AzureCloudConfig azureCloudConfig, AzureMetrics azureMetrics) { this(documentClient, azureCloudConfig.cosmosCollectionLink, azureCloudConfig.cosmosMaxRetries, azureMetrics); }
Source:
public Snapshot archiveSnapshot(Long snapshotId) { SnapshotInfo snapshotOnPrimary = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary); if (snapshotOnPrimary == null || !snapshotOnPrimary.getStatus().equals(ObjectInDataStoreStateMachine.State.Ready)) { throw new CloudRuntimeException("Can only archive snapshots present on primary storage. " + "Cannot find snapshot " + snapshotId + " on primary storage"); } SnapshotInfo snapshotOnSecondary = snapshotSrv.backupSnapshot(snapshotOnPrimary); snapshotSrv.deleteSnapshot(snapshotOnPrimary); SnapshotVO snapshotVO = _snapshotDao.findById(snapshotOnSecondary.getId()); snapshotVO.setLocationType(Snapshot.LocationType.SECONDARY); _snapshotDao.persist(snapshotVO); return snapshotOnSecondary; }

Target:
public Snapshot archiveSnapshot(Long snapshotId) { SnapshotInfo snapshotOnPrimary = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary); if (snapshotOnPrimary == null || !snapshotOnPrimary.getStatus().equals(ObjectInDataStoreStateMachine.State.Ready)) { throw new CloudRuntimeException("Can only archive snapshots present on primary storage. " + "Cannot find snapshot " + snapshotId + " on primary storage"); } SnapshotInfo snapshotOnSecondary = snapshotSrv.backupSnapshot(snapshotOnPrimary); SnapshotVO snapshotVO = _snapshotDao.findById(snapshotOnSecondary.getId()); snapshotVO.setLocationType(Snapshot.LocationType.SECONDARY); _snapshotDao.persist(snapshotVO); try { snapshotSrv.deleteSnapshot(snapshotOnPrimary); } catch (Exception e) { throw new CloudRuntimeException("Snapshot archived to Secondary Storage but there was an error deleting " + " the snapshot on Primary Storage. Please manually delete the primary snapshot " + snapshotId, e); } return snapshotOnSecondary; }
Source:
public static <T, I> I get(T obj, String fieldName, Class<I> outputClass) { try { Field f1 = obj.getClass().getDeclaredField(fieldName); AccessController.doPrivileged(new PrivilegedAction<T>() { @Override public T run() { f1.setAccessible(true); return null; } }); return (I) f1.get(obj); } catch (NoSuchFieldException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } }

Target:
public static <T, I> I get(T obj, String fieldName, Class<I> outputClass) { try { Field field = obj.getClass().getDeclaredField(fieldName); if (!field.isAccessible()) { AccessController.doPrivileged(new PrivilegedAction<T>() { @Override public T run() { field.setAccessible(true); return null; } }); } return (I) field.get(obj); } catch (NoSuchFieldException | IllegalAccessException e) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } }
Source:
private void failDueToRunning() throws LifecycleException { final int managementPort = getContainerConfiguration().getManagementPort(); throw new LifecycleException( String.format("The port %1$d is already in use. It means that either the server might be already running " + "or there is another process using port %1$d.\n" + "Managed containers do not support connecting to running server instances due to the " + "possible harmful effect of connecting to the wrong server.\n" + "Please stop server (or another process) before running, " + "change to another type of container (e.g. remote) or use jboss.socket.binding.port-offset variable " + "to change the default port.\n" + "To disable this check and allow Arquillian to connect to a running server, " + "set allowConnectingToRunningServer to true in the container configuration", managementPort)); }

Target:
private void failDueToRunning() throws LifecycleException { final int managementPort = getContainerConfiguration().getManagementPort(); throw new LifecycleException( String.format("The port %1$d is already in use. It means that either the server might be already running " + "or there is another process using port %1$d.%n" + "Managed containers do not support connecting to running server instances due to the " + "possible harmful effect of connecting to the wrong server.%n" + "Please stop server (or another process) before running, " + "change to another type of container (e.g. remote) or use jboss.socket.binding.port-offset variable " + "to change the default port.%n" + "To disable this check and allow Arquillian to connect to a running server, " + "set allowConnectingToRunningServer to true in the container configuration", managementPort)); }
Source:
public static JdbcKeyValueService create(JdbcKeyValueConfiguration config) { JdbcDataSourceConfiguration dataSourceConfig = config.getDataSourceConfig(); SQLDialect sqlDialect = SQLDialect.valueOf(dataSourceConfig.getSqlDialect()); DataSource dataSource = dataSourceConfig.createDataSource(); Settings settings = new Settings(); settings.setRenderNameStyle(RenderNameStyle.AS_IS); final JdbcKeyValueService kvs = new JdbcKeyValueService(settings, config.getTablePrefix(), sqlDialect, dataSource, config.getBatchSizeForReads()); kvs.run(new Function<DSLContext, Void>() { @Override public Void apply(DSLContext ctx) { String partialSql = ctx.createTable(kvs.METADATA_TABLE) .column(TABLE_NAME, VARCHAR.nullable(false)) .column(METADATA, BLOB.nullable(false)) .getSQL(); int endIndex = partialSql.lastIndexOf(')'); String fullSql = partialSql.substring(0, endIndex) + "," + " CONSTRAINT pk_" + kvs.METADATA_TABLE.getName() + " PRIMARY KEY (" + TABLE_NAME.getName() + ")" + partialSql.substring(endIndex); try { ctx.execute(fullSql); } catch (DataAccessException e) { kvs.handleTableCreationException(e); } return null; } }); return kvs; }

Target:
public static JdbcKeyValueService create(JdbcKeyValueConfiguration config) { JdbcDataSourceConfiguration dataSourceConfig = config.getDataSourceConfig(); SQLDialect sqlDialect = SQLDialect.valueOf(dataSourceConfig.getSqlDialect()); DataSource dataSource = dataSourceConfig.createDataSource(); Settings settings = new Settings(); settings.setRenderNameStyle(RenderNameStyle.AS_IS); final JdbcKeyValueService kvs = new JdbcKeyValueService( settings, sqlDialect, dataSource, config.getTablePrefix(), config.getBatchSizeForReads()); kvs.run(new Function<DSLContext, Void>() { @Override public Void apply(DSLContext ctx) { String partialSql = ctx.createTable(kvs.METADATA_TABLE) .column(TABLE_NAME, VARCHAR.nullable(false)) .column(METADATA, BLOB.nullable(false)) .getSQL(); int endIndex = partialSql.lastIndexOf(')'); String fullSql = partialSql.substring(0, endIndex) + "," + " CONSTRAINT pk_" + kvs.METADATA_TABLE.getName() + " PRIMARY KEY (" + TABLE_NAME.getName() + ")" + partialSql.substring(endIndex); try { ctx.execute(fullSql); } catch (DataAccessException e) { kvs.handleTableCreationException(e); } return null; } }); return kvs; }
Source:
public String getDockerFileContent(String execCommand, int container) { String commandBuiler = EcsContext.PART1 + EcsContext.CMD; commandBuiler = commandBuiler + EcsContext.ECSNETWORK; commandBuiler = replacePortNumbers(container, commandBuiler); commandBuiler = commandBuiler.replaceAll("TOPOLOGY_NAME", EcsContext.topologyName(config)); commandBuiler = commandBuiler.replaceAll("container_number", "executor" + String.valueOf(container)); commandBuiler = commandBuiler.replace("heron_executor", execCommand); return commandBuiler; }

Target:
protected String getDockerFileContent(String execCommand, int container) throws IOException { String commandBuiler = new String(Files.readAllBytes( Paths.get(EcsContext.ecsComposeTemplate(config)))); commandBuiler = commandBuiler.replaceAll("TOPOLOGY_NAME", EcsContext.topologyName(config)); commandBuiler = commandBuiler.replaceAll("CONTAINER_NUMBER", "executor" + String.valueOf(container)); commandBuiler = commandBuiler.replace("HERON_EXECUTOR", execCommand); commandBuiler = commandBuiler.replace("FREEPORTS", nfreePorts); System.out.println("commandBuiler :\n" + commandBuiler); return commandBuiler; }
Source:
public void testPutFileParallel() throws InterruptedException, IOException, TimeoutException { File payloadFile = File.createTempFile("testPutFileParallel", "png"); Files.write(createTestInput(), payloadFile); final Payload testPayload = Payloads.newFilePayload(payloadFile); final byte[] md5 = md5Supplier(testPayload); testPayload.getContentMetadata().setContentType("image/png"); final AtomicInteger blobCount = new AtomicInteger(); final String container = getContainerName(); try { Map<Integer, ListenableFuture<?>> responses = Maps.newHashMap(); for (int i = 0; i < 10; i++) { responses.put(i, this.exec.submit(new Callable<Void>() { @Override public Void call() throws Exception { String name = blobCount.incrementAndGet() + ""; Blob blob = view.getBlobStore().blobBuilder(name).payload(testPayload).build(); view.getBlobStore().putBlob(container, blob); assertConsistencyAwareBlobExists(container, name); blob = view.getBlobStore().getBlob(container, name); assert Arrays.equals(md5Supplier(blob.getPayload()), md5) : String.format( "md5 didn't match on %s/%s", container, name); view.getBlobStore().removeBlob(container, name); assertConsistencyAwareBlobDoesntExist(container, name); return null; } })); } Map<Integer, Exception> exceptions = awaitCompletion(responses, exec, 30000l, Logger.CONSOLE, "putFileParallel"); assert exceptions.size() == 0 : exceptions; } finally { returnContainer(container); payloadFile.delete(); } }

Target:
public void testPutFileParallel() throws InterruptedException, IOException, TimeoutException { File payloadFile = File.createTempFile("testPutFileParallel", "png"); Files.write(createTestInput(), payloadFile); final Payload testPayload = Payloads.newFilePayload(payloadFile); final byte[] md5 = md5Supplier(testPayload); testPayload.getContentMetadata().setContentType("image/png"); final AtomicInteger blobCount = new AtomicInteger(); final String container = getContainerName(); try { Map<Integer, ListenableFuture<?>> responses = Maps.newHashMap(); for (int i = 0; i < 10; i++) { responses.put(i, this.exec.submit(new Callable<Void>() { @Override public Void call() throws Exception { String name = blobCount.incrementAndGet() + ""; Blob blob = view.getBlobStore().blobBuilder(name).payload(testPayload).build(); view.getBlobStore().putBlob(container, blob); assertConsistencyAwareBlobExists(container, name); blob = view.getBlobStore().getBlob(container, name); assert Arrays.equals(md5Supplier(blob.getPayload()), md5) : String.format( "md5 didn't match on %s/%s", container, name); view.getBlobStore().removeBlob(container, name); assertConsistencyAwareBlobDoesntExist(container, name); return null; } })); } Map<Integer, Exception> exceptions = awaitCompletion(responses, exec, 30000l, Logger.CONSOLE, "putFileParallel"); assert exceptions.size() == 0 : exceptions; } finally { payloadFile.delete(); returnContainer(container); } }
Source:
public void elementShouldBeFocused(String locator) { if (!isFocused(locator)) { throw new SeleniumLibraryNonFatalException(String.format("Element %s is disabled.", locator)); } }

Target:
public void elementShouldBeFocused(String locator) { if (!isFocused(locator)) { throw new SeleniumLibraryNonFatalException(String.format("Element %s is not focused.", locator)); } }