auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ClusterSearchShardsResponse getSearchShardsResponse(TransportClient client, ClusterSearchShardsRequest request) { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(maxRetryTime, 2.0) .run("getSearchShardsResponse", () -> { return client.admin() .cluster() .searchShards(request) .actionGet(requestTimeout.toMillis()); }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
private ClusterSearchShardsResponse getSearchShardsResponse(TransportClient client, ClusterSearchShardsRequest request) { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(maxRetryTime) .run("getSearchShardsResponse", () -> client.admin() .cluster() .searchShards(request) .actionGet(requestTimeout.toMillis())); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public static List<PostAggregator> pruneDependentPostAgg(List<PostAggregator> postAggregatorList, String postAggName) { LinkedList<PostAggregator> rv = Lists.newLinkedList(); Set<String> deps = new HashSet<>(); deps.add(postAggName); for (int i = postAggregatorList.size() - 1; i >= 0; i--) { PostAggregator agg = postAggregatorList.get(i); if (deps.contains(agg.getName())) { rv.addFirst(agg); deps.remove(agg.getName()); deps.addAll(agg.getDependentFields()); } } return rv; }

Target:
public static List<PostAggregator> pruneDependentPostAgg(List<PostAggregator> postAggregatorList, String postAggName) { LinkedList<PostAggregator> rv = Lists.newLinkedList(); Set<String> deps = new HashSet<>(); deps.add(postAggName); for (PostAggregator agg : Lists.reverse(postAggregatorList)) { if (deps.contains(agg.getName())) { rv.addFirst(agg); deps.remove(agg.getName()); deps.addAll(agg.getDependentFields()); } } return rv; }
Source:
protected abstract ProjectLauncher getProjectLauncher() throws CoreException; protected abstract void initialiseBndLauncher(ILaunchConfiguration configuration, Project model) throws Exception; protected abstract IStatus getLauncherStatus(); @Override public boolean buildForLaunch(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { BndPreferences prefs = new BndPreferences(); boolean result = !prefs.getBuildBeforeLaunch() || super.buildForLaunch(configuration, mode, monitor); try { model = LaunchUtils.getBndProject(configuration); for (Object service : launchListeners.getServices()) { if (service instanceof LaunchListener) { LaunchListener launchListener = (LaunchListener) service; try { launchListener.buildForLaunch(model); } catch (Throwable t) { logger.logError("Error in launch listener", t); } } } initialiseBndLauncher(configuration, model); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error initialising bnd launcher", e)); } return result; }

Target:
protected abstract ProjectLauncher getProjectLauncher() throws CoreException; protected abstract void initialiseBndLauncher(ILaunchConfiguration configuration, Project model) throws Exception; protected abstract IStatus getLauncherStatus(); @Override public boolean buildForLaunch(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { BndPreferences prefs = new BndPreferences(); boolean result = !prefs.getBuildBeforeLaunch() || super.buildForLaunch(configuration, mode, monitor); try { run = LaunchUtils.createRun(configuration); initialiseBndLauncher(configuration, run); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error initialising bnd launcher", e)); } return result; }
Source:
public void testLHSConflictsArePickedUpForEachFieldOfAPattern() throws Exception { final String xml = loadResource("GUVNOR-3513.gdst"); final GuidedDecisionTable52 table52 = GuidedDTXMLPersistence.getInstance() .unmarshal(xml); final Analyzer analyzer = analyzerProvider.makeAnalyser(table52); analyzer.resetChecks(); analyzer.analyze(); analyzerProvider.getAnalysisReport().stream().forEach(i->System.out.println(i.getCheckType())); assertTrue(analyzerProvider.getAnalysisReport().isEmpty()); }

Target:
public void testLHSConflictsArePickedUpForEachFieldOfAPattern() throws Exception { final String xml = loadResource("GUVNOR-3513.gdst"); final GuidedDecisionTable52 table52 = GuidedDTXMLPersistence.getInstance() .unmarshal(xml); final Analyzer analyzer = analyzerProvider.makeAnalyser(table52); analyzer.resetChecks(); analyzer.analyze(); assertResultIsEmpty(analyzerProvider.getAnalysisReport()); }
Source:
public void createFBInstance(final FBDeploymentData fbData, final Resource res) throws DeploymentException { Map<String, AdapterType> adapters = getAdapterTypes(fbData.getFb().getType().getInterfaceList()); if (!adapters.isEmpty()) { queryAdapterTypes(adapters, res); createAdapterTypes(adapters, res); } if (!getTypes().contains(fbData.getFb().getType().getName())) { try { createFBType(fbData.getFb().getType(), res); } catch (DeploymentException ce) { logger.error(MessageFormat.format(Messages.DTL_CreateTypeFailed, fbData.getFb().getType().getName())); } } super.createFBInstance(fbData, res); }

Target:
public void createFBInstance(final FBDeploymentData fbData, final Resource res) throws DeploymentException { Map<String, AdapterType> adapters = getAdapterTypes(fbData.getFb().getType().getInterfaceList()); if (!adapters.isEmpty()) { queryAdapterTypes(adapters, res); createAdapterTypes(adapters, res); } checkCreateFBType(fbData.getFb(), res); super.createFBInstance(fbData, res); }
Source:
public void oneHandlerEventOnSet() { addSampleItem(); CollectionEventHandlers.CountingHandler<String> counter = new CollectionEventHandlers.CountingHandler<>(); list.addHandler(counter); list.set(0, "abc"); assertEquals(1, counter.getCounter()); }

Target:
public void oneHandlerEventOnSet() { addSampleItem(); RecordingCollectionEventHandler<String> counter = new RecordingCollectionEventHandler<>(); list.addHandler(counter); list.set(0, "abc"); assertEquals(1, counter.getCounter()); assertEquals(SET, counter.getEvents().get(0).getType()); }
Source:
public Payment getPaymentByExternalKey(final String paymentExternalKey, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { final Payment payment = paymentProcessor.getPaymentByExternalKey(paymentExternalKey, withPluginInfo, properties, tenantContext, internalCallContextFactory.createInternalTenantContext(tenantContext)); if (payment == null) { throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT, paymentExternalKey); } return payment; }

Target:
public Payment getPaymentByExternalKey(final String paymentExternalKey, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { final Payment payment = paymentProcessor.getPaymentByExternalKey(paymentExternalKey, withPluginInfo, withAttempts, properties, tenantContext, internalCallContextFactory.createInternalTenantContext(tenantContext)); if (payment == null) { throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT, paymentExternalKey); } return payment; }
Source:
private String encoding(HttpServletRequest req) { String encoding = req.getCharacterEncoding(); if (encoding == null) encoding = "UTF-8"; return encoding; }

Target:
private String encoding(HttpServletRequest req) { return Objects.firstNonNull(req.getCharacterEncoding(), "UTF-8"); }
Source:
public static void waitForNetworkThreadExecutorToFinish() { try { Class syncManager = Class.forName("io.realm.SyncManager"); Field field = syncManager.getDeclaredField("NETWORK_POOL_EXECUTOR"); ThreadPoolExecutor pool = (ThreadPoolExecutor) field.get(null); pool.shutdownNow(); try { pool.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new AssertionError("NetworkPoolExecutor was not shut down in time:\n" + Util.getStackTrace(e)); } finally { field.set(null, new ThreadPoolExecutor( 10, 10, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100))); } } catch (ClassNotFoundException e) { } catch (NoSuchFieldException e) { throw new AssertionError("Could not find NETWORK_POOL_EXECUTOR field"); } catch (IllegalAccessException e) { throw new AssertionError(Util.getStackTrace(e)); } }

Target:
public static void waitForNetworkThreadExecutorToFinish() { if (networkPoolExecutorField == null) { return; } try { ThreadPoolExecutor pool = (ThreadPoolExecutor) networkPoolExecutorField.get(null); pool.shutdownNow(); try { pool.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new AssertionError("NetworkPoolExecutor was not shut down in time:\n" + Util.getStackTrace(e)); } finally { networkPoolExecutorField.set(null, new ThreadPoolExecutor( 10, 10, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100))); } } catch (IllegalAccessException e) { throw new AssertionError(Util.getStackTrace(e)); } }
Source:
private void postSystemEvent(Ack ack) { Status status = ack.getStatus(); CommandId commandId = commandIdFrom(ack); EventMessage systemEvent = systemEventFor(status, commandId); Command command = commands.get(commandId); checkState(command != null, "Unknown command ID encountered: %s", commandId.value()); Origin systemEventOrigin = CommandEnvelope.of(command) .asMessageOrigin(); writeSide.postEvent(systemEvent, systemEventOrigin); }

Target:
private void postSystemEvent(Ack ack) { Status status = ack.getStatus(); CommandId commandId = commandIdFrom(ack); EventMessage systemEvent = systemEventFor(status, commandId); Command command = commands.get(commandId); checkState(command != null, "Unknown command ID encountered: `%s`.", commandId.value()); Origin systemEventOrigin = CommandEnvelope.of(command) .asMessageOrigin(); writeSide.postEvent(systemEvent, systemEventOrigin); }
Source:
public String scheduleTimeout( Value request ) { final String uuid = UUID.randomUUID().toString(); TimeUnit unit; if (request.getFirstChild("timeunit") != null) { try { unit = TimeUnit.valueOf(request.getFirstChild("timeunit").strValue().toUpperCase()); } catch (Exception e) { System.err.println(e); System.err.println("Defaulting to timeunit seconds"); } finally { unit = TimeUnit.SECONDS; } } else { unit = TimeUnit.SECONDS; } tasks.add( uuid ); executor.schedule( () -> { if ( tasks.contains( uuid ) ) { sendMessage(CommMessage.createRequest(request.getFirstChild("operation").strValue(), "/", request.getFirstChild("message"))); tasks.remove(uuid); } }, request.intValue(), unit ); return uuid; }

Target:
public Long scheduleTimeout( Value request ) throws FaultException { final long timeoutId = atomicLong.getAndIncrement(); TimeUnit unit; if (request.hasChildren( "timeunit" )) { try { unit = TimeUnit.valueOf( request.getFirstChild( "timeunit" ).strValue().toUpperCase() ); } catch ( Exception e ) { throw new FaultException( "InvalidTimeUnit", e ); } } else { unit = TimeUnit.MILLISECONDS; } String operationName; if (request.hasChildren( "operation" )) { operationName = request.getFirstChild( "operation" ).strValue(); } else { operationName = "timeout"; } ScheduledFuture scheduledFuture = executor.schedule( () -> { sendMessage( CommMessage.createRequest( operationName, "/", request.getFirstChild( "message" ))); }, request.intValue(), unit ); scheduledFutureHashMap.put(timeoutId, scheduledFuture); return timeoutId; }
Source:
private static WorkItemDefinition parseWorkItemDefinitionObject(Queue<String> objectQueue) { WorkItemDefinition wid = emptyWid(); wid.setDependencies(new Dependencies()); String line = objectQueue.poll(); while (!isEndingObject(line) && !objectQueue.isEmpty()) { Pair<String, String> attributes = getAttribute(line); switch (attributes.getK1()) { case "name": wid.setName(attributes.getK2()); break; case "displayName": wid.setDisplayName(attributes.getK2()); break; case "icon": wid.getIconDefinition().setUri(attributes.getK2()); break; case "parameters": if (!isEndingObject(attributes.getK2())) { Collection<Pair<String, String>> parameters = retrieveParameters(objectQueue); wid.setParameters(parseParameters(parameters)); } break; case "results": if (!isEndingObject(attributes.getK2())) { Collection<Pair<String, String>> results = retrieveParameters(objectQueue); wid.setResults(parseParameters(results)); } break; case "category": wid.setCategory(attributes.getK2()); default: break; } line = objectQueue.poll(); } if (empty(wid.getCategory())) { wid.setCategory(BPMNCategories.SERVICE_TASKS); } return wid; }

Target:
private static WorkItemDefinition parseWorkItemDefinitionObject(Queue<String> objectQueue) { WorkItemDefinition wid = emptyWid(); wid.setDependencies(new Dependencies()); String line = objectQueue.poll(); while (!isEndingObject(line) && !objectQueue.isEmpty()) { Map.Entry<String, String> attributes = getAttribute(line); switch (attributes.getKey()) { case NAME: wid.setName(attributes.getValue()); break; case DISPLAY_NAME: wid.setDisplayName(attributes.getValue()); break; case ICON: wid.getIconDefinition().setUri(attributes.getValue()); break; case PARAMETERS: if (!isEndingObject(attributes.getValue())) { Collection<Map.Entry<String, String>> parameters = retrieveParameters(objectQueue); wid.setParameters(parseParameters(parameters)); } break; case RESULTS: if (!isEndingObject(attributes.getValue())) { Collection<Map.Entry<String, String>> results = retrieveParameters(objectQueue); wid.setResults(parseParameters(results)); } break; case CATEGORY: wid.setCategory(attributes.getValue()); default: break; } line = objectQueue.poll(); } if (empty(wid.getCategory())) { wid.setCategory(BPMNCategories.SERVICE_TASKS); } return wid; }
Source:
private String decorateRecordData(String line) { if (line == null && line.isEmpty()) { return null; } String[] strArr = line.split(","); if (strArr.length >= 2) { String openDateStr = strArr[0].substring(0, strArr[0].length() - 3); openDateStr = openDateStr.substring(0, 4) + "-" + openDateStr.substring(4, 6) + "-" + openDateStr.substring(6, 8); String issueNumStr = strArr[0].substring(strArr[0].length() - 3); int issueNum = Integer.parseInt(issueNumStr); int minutes = 0; int hours = 0; if (issueNum >= 24 && issueNum < 96) { int temp = (issueNum - 24) * 10; minutes = temp % 60; hours = temp / 60; hours += 10; } else if (issueNum >= 96 && issueNum <= 120) { int temp = (issueNum - 96) * 5; minutes = temp % 60; hours = temp / 60; hours += 22; } else { int temp = issueNum * 5; minutes = temp % 60; hours = temp / 60; } openDateStr = openDateStr + " " + hours + ":" + (minutes == 0 ? "00" : minutes) + ":00"; long openDateStrNum = 0; try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date midDate = formatter.parse(openDateStr); openDateStrNum = midDate.getTime(); } catch (Exception e) { throw new RuntimeException("the decorateRecordData function shows exception!", e.getCause()); } String lotteryValue = strArr[1]; lotteryValue = lotteryValue.replace("", ","); line = openDateStrNum + lotteryValue; } return line; }

Target:
private String decorateRecordData(String line) { if (line == null && line.isEmpty()) { return null; } String[] strArr = line.split(","); if (strArr.length >= 2) { String openDateStr = strArr[0].substring(0, strArr[0].length() - 3); openDateStr = openDateStr.substring(0, 4) + "-" + openDateStr.substring(4, 6) + "-" + openDateStr.substring(6, 8); String issueNumStr = strArr[0].substring(strArr[0].length() - 3); int issueNum = Integer.parseInt(issueNumStr); int minutes; int hours; if (issueNum >= 24 && issueNum < 96) { int temp = (issueNum - 24) * 10; minutes = temp % 60; hours = temp / 60; hours += 10; } else if (issueNum >= 96 && issueNum <= 120) { int temp = (issueNum - 96) * 5; minutes = temp % 60; hours = temp / 60; hours += 22; } else { int temp = issueNum * 5; minutes = temp % 60; hours = temp / 60; } openDateStr = openDateStr + " " + hours + ":" + (minutes == 0 ? "00" : minutes) + ":00"; long openDateStrNum = 0; try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date midDate = formatter.parse(openDateStr); openDateStrNum = midDate.getTime(); } catch (Exception e) { throw new RuntimeException("the decorateRecordData function shows exception!", e.getCause()); } String lotteryValue = strArr[1]; lotteryValue = lotteryValue.replace("", ","); line = openDateStrNum + lotteryValue; } return line; }
Source:
public void getMessages_should_request_message_search() throws MessagingException { setupFolderWith23Messages(); folder.getMessageCount(); String messagesXml = "<xml>MessagesXml</xml>"; HashMap<String, String> headers = new HashMap<>(); headers.put("Brief", "t"); headers.put("Range", "rows=13-23"); when(mockStore.getMessagesXml()).thenReturn(messagesXml); when(mockStore.processRequest(eq("https://localhost/webDavStoreUrl/testFolder"), eq("SEARCH"), eq(messagesXml), eq(headers))).thenReturn(mockDataSet); String[] uids = new String[]{"uid1","uid2","uid3","uid4","uid5"}; HashMap<String, String> uidToUrls = new HashMap<>(); uidToUrls.put("uid1","url1"); uidToUrls.put("uid2","url2"); uidToUrls.put("uid3","url3"); uidToUrls.put("uid4","url4"); uidToUrls.put("uid5","url5"); when(mockDataSet.getUids()).thenReturn(uids); when(mockDataSet.getUidToUrl()).thenReturn(uidToUrls); folder.getMessages(0, 10, new Date(), listener); verify(listener, times(5)).messageStarted(anyString(), anyInt(), eq(5)); verify(listener, times(5)).messageFinished(any(WebDavMessage.class), anyInt(), eq(5)); }

Target:
public void getMessages_should_request_message_search() throws MessagingException { int totalMessages = 23; int messageStart = 1; int messageEnd = 11; setupFolderWithMessages(totalMessages); String messagesXml = "<xml>MessagesXml</xml>"; buildSearchResponse(mockDataSet); when(mockStore.getMessagesXml()).thenReturn(messagesXml); when(mockStore.processRequest(eq("https://localhost/webDavStoreUrl/testFolder"), eq("SEARCH"), eq(messagesXml), Matchers.<Map<String, String>>any())).thenReturn(mockDataSet); folder.getMessages(1, 11, new Date(), listener); verify(listener, times(5)).messageStarted(anyString(), anyInt(), eq(5)); verify(listener, times(5)).messageFinished(any(WebDavMessage.class), anyInt(), eq(5)); }
Source:
public ConcurEventNotification convertConcurEventNotification(ConcurEventNotificationDTO concurEventNotificationDTO) { ConcurEventNotification concurEventNotification = new ConcurEventNotification(); concurEventNotification.setContext(concurEventNotificationDTO.getContext()); try { concurEventNotification.setEventDateTime(dateTimeService.convertToSqlDate(concurEventNotificationDTO.getEventDateTime())); } catch (ParseException e) { concurEventNotification.setEventDateTime(dateTimeService.getCurrentSqlDate()); } concurEventNotification.setEventType(concurEventNotificationDTO.getEventType()); concurEventNotification.setObjectType(concurEventNotificationDTO.getObjectType()); concurEventNotification.setObjectURI(concurEventNotificationDTO.getObjectURI()); return concurEventNotification; }

Target:
public ConcurEventNotification convertConcurEventNotification(ConcurEventNotificationDTO concurEventNotificationDTO) throws ParseException { ConcurEventNotification concurEventNotification = new ConcurEventNotification(); concurEventNotification.setContext(concurEventNotificationDTO.getContext()); concurEventNotification.setEventDateTime(dateTimeService.convertToSqlDate(concurEventNotificationDTO.getEventDateTime())); concurEventNotification.setEventType(concurEventNotificationDTO.getEventType()); concurEventNotification.setObjectType(concurEventNotificationDTO.getObjectType()); concurEventNotification.setObjectURI(concurEventNotificationDTO.getObjectURI()); return concurEventNotification; }
Source:
public void populateCreaturesMenu() { ColumnLayout creatureTabColumnLayout = (ColumnLayout) creatureTab; Iterator<UIWidget> iterator = creatureTab.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } EntityManager entityManager = CoreRegistry.get(EntityManager.class); }

Target:
public void populateCreaturesMenu() { ColumnLayout creatureTabColumnLayout = (ColumnLayout) creatureTab; Iterator<UIWidget> iterator = creatureTab.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } }
Source:
public void play() { try { new File((new File(entry.getFilePath()).getParentFile().list())[0]) .exists(); if (player.isPlaying()) { player.stop(); } this.paused = false; player.reset(); player.setDataSource(entry.getFilePath()); player.prepare(); player.start(); this.messagingService .getService() .sendPlayStatusMessage(this.entry, true); } catch (Exception e) { Log.wtf(TAG, "Unable to play song: " + entry.getFilePath()); e.printStackTrace(); } }

Target:
public void play() { if (isValidPath()) { try { if (player.isPlaying()) { player.stop(); } this.paused = false; player.reset(); player.setDataSource(entry.getFilePath()); player.prepare(); player.start(); this.messagingService.getService().sendPlayStatusMessage( this.entry, true); } catch (Exception e) { Log.wtf(TAG, "Unable to play song: " + entry.getFilePath()); } } else { Log.w(TAG, "File Path was not valid"); } }
Source:
protected void onHandleIntent(Intent intent) { String urlToDownload = intent.getStringExtra("url"); ResultReceiver receiver = (ResultReceiver) intent .getParcelableExtra("receiver"); try { URL url = new URL(urlToDownload); URLConnection connection = url.openConnection(); connection.connect(); int fileLength = connection.getContentLength(); InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream( intent.getStringExtra("destination")); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; Bundle resultData = new Bundle(); resultData.putInt("progress", (int) (total * 100 / fileLength)); receiver.send(UPDATE_PROGRESS, resultData); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } Bundle resultData = new Bundle(); resultData.putInt("progress", 100); receiver.send(UPDATE_PROGRESS, resultData); }

Target:
protected void onHandleIntent(Intent intent) { String urlToDownload = intent.getStringExtra("url"); mReceiver = (ResultReceiver) intent.getParcelableExtra("receiver"); try { copyFileFromUrl(urlToDownload, intent.getStringExtra("destination")); mReceiver.send(DOWNLOAD_COMPLETE, null); } catch (IOException e) { sendError(INTERNAL_ERROR, urlToDownload, e); e.printStackTrace(); } catch (HTTPException e) { sendError(HTTP_ERROR, urlToDownload, e); e.printStackTrace(); } }
Source:
public void testAttributeMap() { Map<String, List<String>> attributeMapping = new HashMap<>(); List<String> attributes = new ArrayList<>(); attributes.add("datamanager"); attributes.add("admin"); attributeMapping.put("invalid-state", attributes); plugin.setAttributeMap(attributeMapping); Map<String, List<String>> attributeMap = plugin.getAttributeMap(); assertEquals(true, attributeMap.containsKey("invalid-state")); assertEquals(2, attributeMap.get("invalid-state").size()); assertEquals(true, attributeMap.get("invalid-state").contains("datamanager")); assertEquals(true, attributeMap.get("invalid-state").contains("admin")); }

Target:
public void testAttributeMap() { Map<String, List<String>> attributeMapping = new HashMap<>(); List<String> attributes = new ArrayList<>(); attributes.add("data-manager"); attributes.add("system-admin"); attributeMapping.put("invalid-state", attributes); plugin.setAttributeMap(attributeMapping); Map<String, List<String>> attributeMap = plugin.getAttributeMap(); assertThat(attributeMap.containsKey("invalid-state"), is(true)); assertThat(attributeMap.get("invalid-state").size(), is(2)); assertThat(attributeMap.get("invalid-state").contains("data-manager"), is(true)); assertThat(attributeMap.get("invalid-state").contains("system-admin"), is(true)); }
Source:
public void run() { try { final long hardKillDeadline = System.nanoTime() + timeoutMillis * 1_000_000; long millisLeft; while (executerThread.isAlive() && (millisLeft = (hardKillDeadline - System.nanoTime()) / 1_000_000) > 0) { try { executerThread.join(millisLeft); } catch (InterruptedException ignored) { } } if (executerThread.isAlive()) { String msg = "Task did not exit gracefully within " + (timeoutMillis / 1000) + " + seconds."; taskManager.notifyFatalError(msg, new FlinkRuntimeException(msg)); } } catch (Throwable t) { ExceptionUtils.rethrowIfFatalError(t); log.error("Error in Task Cancellation Watch Dog", t); } }

Target:
public void run() { try { final long hardKillDeadline = System.nanoTime() + timeoutMillis * 1_000_000; long millisLeft; while (executerThread.isAlive() && (millisLeft = (hardKillDeadline - System.nanoTime()) / 1_000_000) > 0) { try { executerThread.join(millisLeft); } catch (InterruptedException ignored) { } } if (executerThread.isAlive()) { String msg = "Task did not exit gracefully within " + (timeoutMillis / 1000) + " + seconds."; taskManager.notifyFatalError(msg, new FlinkRuntimeException(msg)); } } catch (Throwable t) { throw new FlinkRuntimeException("Error in Task Cancellation Watch Dog", t); } }
Source:
protected void prepareClientInvocation() throws Exception { trustAllCertificates(); System.out.println("Trusting all certs"); }

Target:
protected void prepareClientInvocation() throws Exception { trustAllCertificates(); log.info("Trusting all certs"); }
Source:
void onComplete(PutOperation op) { Exception e = op.getOperationException(); String blobId = op.getBlobIdString(); op.maybeNotifyForBlobCreation(); if (blobId == null && e == null) { e = new RouterException("Operation failed, but exception was not set", RouterErrorCode.UnexpectedInternalError); routerMetrics.operationFailureWithUnsetExceptionCount.inc(); } if (e != null) { blobId = null; routerMetrics.onPutBlobError(e, op.isEncryptionEnabled(), op.isStitchOperation()); routerCallback.scheduleDeletes(op.getSuccessfullyPutChunkIdsIfCompositeDirectUpload(), op.getServiceId()); } else { updateChunkingAndSizeMetricsOnSuccessfulPut(op); } routerMetrics.operationDequeuingRate.mark(); long operationLatencyMs = time.milliseconds() - op.getSubmissionTimeMs(); Histogram latencyMetric; if (op.isStitchOperation()) { latencyMetric = op.isEncryptionEnabled() ? routerMetrics.stitchEncryptedBlobOperationLatencyMs : routerMetrics.stitchBlobOperationLatencyMs; } else { latencyMetric = op.isEncryptionEnabled() ? routerMetrics.putEncryptedBlobOperationLatencyMs : routerMetrics.putBlobOperationLatencyMs; } latencyMetric.update(operationLatencyMs); NonBlockingRouter.completeOperation(op.getFuture(), op.getCallback(), blobId, e); }

Target:
void onComplete(PutOperation op) { Exception e = op.getOperationException(); String blobId = op.getBlobIdString(); op.maybeNotifyForBlobCreation(); if (blobId == null && e == null) { e = new RouterException("Operation failed, but exception was not set", RouterErrorCode.UnexpectedInternalError); routerMetrics.operationFailureWithUnsetExceptionCount.inc(); } if (e != null) { blobId = null; routerMetrics.onPutBlobError(e, op.isEncryptionEnabled(), op.isStitchOperation()); routerCallback.scheduleDeletes(op.getSuccessfullyPutChunkIdsIfCompositeDirectUpload(), op.getServiceId()); } else { updateChunkingAndSizeMetricsOnSuccessfulPut(op); } routerMetrics.operationDequeuingRate.mark(); long operationLatencyMs = time.milliseconds() - op.getSubmissionTimeMs(); if (op.isStitchOperation()) { (op.isEncryptionEnabled() ? routerMetrics.stitchEncryptedBlobOperationLatencyMs : routerMetrics.stitchBlobOperationLatencyMs).update(operationLatencyMs); } else { (op.isEncryptionEnabled() ? routerMetrics.putEncryptedBlobOperationLatencyMs : routerMetrics.putBlobOperationLatencyMs).update(operationLatencyMs); } NonBlockingRouter.completeOperation(op.getFuture(), op.getCallback(), blobId, e); }
Source:
public void setName(String name) { this.name = new CaseInsensitiveString(name); }

Target:
public void setName(String name) { setName(new CaseInsensitiveString(name)); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_style_variable_text_placement); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(new Style.Builder().fromUrl(Style.LIGHT) .withSource(new GeoJsonSource(GEOJSON_SRC_ID)) .withLayer(new SymbolLayer(POI_LABELS_LAYER_ID, GEOJSON_SRC_ID) .withProperties( textField(get("description")), textSize(17f), textColor(Color.RED), textVariableAnchor( new String[]{TEXT_ANCHOR_TOP, TEXT_ANCHOR_BOTTOM, TEXT_ANCHOR_LEFT, TEXT_ANCHOR_RIGHT}), textJustify(TEXT_JUSTIFY_AUTO), textRadialOffset(0.5f))), new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull final Style style) { VariableLabelPlacementActivity.this.mapboxMap = mapboxMap; new LoadGeoJson(style,VariableLabelPlacementActivity.this).execute(); } }); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_style_variable_text_placement); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { GeoJsonSource source = new GeoJsonSource(GEOJSON_SRC_ID); source.setUrl("asset://poi_places.geojson"); mapboxMap.setStyle(new Style.Builder().fromUrl(Style.LIGHT) .withSource(source) .withLayer(new SymbolLayer(POI_LABELS_LAYER_ID, GEOJSON_SRC_ID) .withProperties( textField(get("description")), textSize(17f), textColor(Color.RED), textVariableAnchor( new String[]{TEXT_ANCHOR_TOP, TEXT_ANCHOR_BOTTOM, TEXT_ANCHOR_LEFT, TEXT_ANCHOR_RIGHT}), textJustify(TEXT_JUSTIFY_AUTO), textRadialOffset(0.5f))), new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull final Style style) { Toast.makeText(VariableLabelPlacementActivity.this, getString(R.string.zoom_map_in_and_out_variable_label_instruction), Toast.LENGTH_SHORT).show(); } }); } }); }
Source:
private String waitAndRetrieveContainerID(String deploymentName) { for (int i = 0; i < OPENSHIFT_WAIT_POD_TIMEOUT; i++) { try { Thread.sleep(OPENSHIFT_WAIT_POD_DELAY); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } PodList pods = openShiftClient.pods() .inNamespace(this.cheOpenShiftProjectName) .list(); for (Pod p : pods.getItems()) { String status = p.getStatus().getPhase(); String dc = p.getMetadata().getLabels().get(OPENSHIFT_DEPLOYMENT_LABEL); if (OPENSHIFT_POD_STATUS_RUNNING.equals(status) && deploymentName.equals(dc)) { String containerID = p.getStatus().getContainerStatuses().get(0).getContainerID(); String normalizedID = normalizeContainerID(containerID); openShiftClient.pods() .inNamespace(this.cheOpenShiftProjectName) .withName(p.getMetadata().getName()) .edit() .editMetadata() .addToLabels(CHE_CONTAINER_IDENTIFIER_LABEL_KEY, getLabelFromContainerID(normalizedID)) .endMetadata() .done(); return normalizedID; } } } return null; }

Target:
private String waitAndRetrieveContainerID(String deploymentName) { for (int i = 0; i < OPENSHIFT_WAIT_POD_TIMEOUT; i++) { try { Thread.sleep(OPENSHIFT_WAIT_POD_DELAY); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } PodList pods = openShiftClient.pods() .inNamespace(this.openShiftCheProjectName) .list(); for (Pod p : pods.getItems()) { String status = p.getStatus().getPhase(); String dc = p.getMetadata().getLabels().get(OPENSHIFT_DEPLOYMENT_LABEL); if (OPENSHIFT_POD_STATUS_RUNNING.equals(status) && deploymentName.equals(dc)) { String containerID = p.getStatus().getContainerStatuses().get(0).getContainerID(); String normalizedID = normalizeContainerID(containerID); openShiftClient.pods() .inNamespace(this.openShiftCheProjectName) .withName(p.getMetadata().getName()) .edit() .editMetadata() .addToLabels(CHE_CONTAINER_IDENTIFIER_LABEL_KEY, getLabelFromContainerID(normalizedID)) .endMetadata() .done(); return normalizedID; } } } return null; }
Source:
SetAnonymousAuthenticationConfiguration(final AuthenticationConfiguration parent) { super(parent.without(SetCallbackHandlerAuthenticationConfiguration.class).useName(AnonymousPrincipal.getInstance().getName())); }

Target:
SetAnonymousAuthenticationConfiguration(final AuthenticationConfiguration parent) { super(parent.without(SetCallbackHandlerAuthenticationConfiguration.class).without(SetNamePrincipalAuthenticationConfiguration.class)); }
Source:
public boolean isAnyExpression() { return "*".equals(ecl); }

Target:
public boolean isAnyExpression() { return Ecl.ANY.equals(ecl); }
Source:
public void testSTPoints() { assertFunction("transform(ST_Points(ST_GeometryFromText('LINESTRING (8 4)')), x -> ST_AsText(x))", new ArrayType(VARCHAR), ImmutableList.of("POINT (8 4)", "POINT (8 4)")); assertFunction("transform(ST_Points(ST_GeometryFromText('LINESTRING (8 4, 3 9, 5 6)')), x -> ST_AsText(x))", new ArrayType(VARCHAR), ImmutableList.of("POINT (8 4)", "POINT (3 9)", "POINT (5 6)")); assertInvalidFunction("transform(ST_Points(ST_GeometryFromText('POLYGON ((8 4, 3 9, 5 6))')), x -> ST_AsText(x))", "ST_Points only applies to LINE_STRING. Input type is: POLYGON"); }

Target:
public void testSTPoints() { assertFunction("ST_Points(ST_GeometryFromText('LINESTRING EMPTY'))", new ArrayType(GEOMETRY), null); assertSTPoints("LINESTRING (0 0, 0 0)", "0 0", "0 0"); assertSTPoints("LINESTRING (8 4, 3 9, 8 4)", "8 4", "3 9", "8 4"); assertSTPoints("LINESTRING (8 4, 3 9, 5 6)", "8 4", "3 9", "5 6"); assertSTPoints("LINESTRING (8 4, 3 9, 5 6, 3 9, 8 4)", "8 4", "3 9", "5 6", "3 9", "8 4"); assertInvalidFunction("ST_Points(ST_GeometryFromText('POLYGON ((8 4, 3 9, 5 6))'))", "ST_Points only applies to LINE_STRING. Input type is: POLYGON"); }
Source:
private void getDirectionsRoute(Point origin, Point destination) { mapboxDirectionsClient = MapboxDirections.builder() .origin(origin) .destination(destination) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_DRIVING) .geometries(GEOMETRY_POLYLINE) .alternatives(true) .steps(true) .accessToken(getString(R.string.access_token)) .build(); mapboxDirectionsClient.enqueueCall(new Callback<DirectionsResponse>() { @Override public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) { if (response.body() == null) { Timber.d( "No routes found, make sure you set the right user and access token."); return; } else if (response.body().routes().size() < 1) { Timber.d( "No routes found"); return; } DirectionsRoute currentRoute = response.body().routes().get(0); runnable = new DrawRouteRunnable(mapboxMap, currentRoute.legs().get(0).steps(), handler = new Handler()); handler.postDelayed(runnable, DRAW_SPEED_MILLISECONDS); } @Override public void onFailure(Call<DirectionsResponse> call, Throwable throwable) { Toast.makeText(SnakingDirectionsRouteActivity.this, R.string.snaking_directions_activity_error, Toast.LENGTH_SHORT).show(); } }); }

Target:
private void getDirectionsRoute(Point origin, Point destination) { mapboxDirectionsClient = MapboxDirections.builder() .origin(origin) .destination(destination) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_DRIVING) .geometries(GEOMETRY_POLYLINE) .alternatives(true) .steps(true) .accessToken(getString(R.string.access_token)) .build(); mapboxDirectionsClient.enqueueCall(new Callback<DirectionsResponse>() { @Override public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) { if (response.body() == null) { Timber.d("No routes found, make sure you set the right user and access token."); return; } else if (response.body().routes().size() < 1) { Timber.d("No routes found"); return; } DirectionsRoute currentRoute = response.body().routes().get(0); runnable = new DrawRouteRunnable(mapboxMap, currentRoute.legs().get(0).steps(), handler); handler.postDelayed(runnable, DRAW_SPEED_MILLISECONDS); } @Override public void onFailure(Call<DirectionsResponse> call, Throwable throwable) { Toast.makeText(SnakingDirectionsRouteActivity.this, R.string.snaking_directions_activity_error, Toast.LENGTH_SHORT).show(); } }); }
Source:
public void selectTargetBoard(TargetBoard targetBoard) { for (int i = 0; i < boardMenu.getItemCount(); i++) { JMenuItem menuItem = boardMenu.getItem(i); if (!(menuItem instanceof JRadioButtonMenuItem)) { continue; } JRadioButtonMenuItem radioButtonMenuItem = ((JRadioButtonMenuItem) menuItem); if (targetBoard.getName().equals(radioButtonMenuItem.getText())) { radioButtonMenuItem.setSelected(true); break; } } BaseNoGui.selectBoard(targetBoard); filterVisibilityOfSubsequentBoardMenus(boardsCustomMenus, targetBoard, 1); onBoardOrPortChange(); rebuildImportMenu(Editor.importMenu); rebuildExamplesMenu(Editor.examplesMenu); try { rebuildRecentBoardsMenu(); } catch (Exception e) { e.printStackTrace(); } }

Target:
public void selectTargetBoard(TargetBoard targetBoard) { for (int i = 0; i < boardMenu.getItemCount(); i++) { JMenuItem menuItem = boardMenu.getItem(i); if (!(menuItem instanceof JRadioButtonMenuItem)) { continue; } JRadioButtonMenuItem radioButtonMenuItem = ((JRadioButtonMenuItem) menuItem); if (targetBoard.getName().equals(radioButtonMenuItem.getText())) { radioButtonMenuItem.setSelected(true); break; } } BaseNoGui.selectBoard(targetBoard); filterVisibilityOfSubsequentBoardMenus(boardsCustomMenus, targetBoard, 1); onBoardOrPortChange(); rebuildImportMenu(Editor.importMenu); rebuildExamplesMenu(Editor.examplesMenu); try { rebuildRecentBoardsMenu(); } catch (Exception e) { } }
Source:
public void setDenominator(final long value) { denominator.dec(denominator.getCount()); denominator.inc(value); }

Target:
public void setDenominator(final long value) { denominator.set(value); }
Source:
public List<FragmentItemModel> getFragmentItems() { ArrayList<FragmentItemModel> items = new ArrayList<>(); items.add(new FragmentItemModel(MyCoursesListFragment.class, getResources().getString(R.string.label_my_courses), FontAwesomeIcons.fa_list_alt, new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { environment.getAnalyticsRegistry().trackScreenView(Analytics.Screens.MY_COURSES); } })); if (environment.getConfig().getProgramConfig().isEnabled() && (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT || environment.getConfig().getProgramConfig().isKitKatEnabled())) { items.add(new FragmentItemModel(WebViewProgramFragment.class, getResources().getString(R.string.label_my_programs), FontAwesomeIcons.fa_clone, WebViewProgramFragment.makeArguments(environment.getConfig().getProgramConfig().getUrl(), null, true), new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { } })); } if (environment.getConfig().getCourseDiscoveryConfig().isCourseDiscoveryEnabled()) { items.add(new FragmentItemModel( environment.getConfig().getCourseDiscoveryConfig().isWebviewCourseDiscoveryEnabled() ? WebViewDiscoverCoursesFragment.class : NativeFindCoursesFragment.class, getResources().getString(R.string.label_discovery), FontAwesomeIcons.fa_search, new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { environment.getAnalyticsRegistry().trackScreenView(Analytics.Screens.FIND_COURSES); } })); } return items; }

Target:
public List<FragmentItemModel> getFragmentItems() { ArrayList<FragmentItemModel> items = new ArrayList<>(); items.add(new FragmentItemModel(MyCoursesListFragment.class, getResources().getString(R.string.label_my_courses), FontAwesomeIcons.fa_list_alt, new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { environment.getAnalyticsRegistry().trackScreenView(Analytics.Screens.MY_COURSES); } })); if (environment.getConfig().getProgramConfig().isEnabled()) { items.add(new FragmentItemModel(WebViewProgramFragment.class, getResources().getString(R.string.label_my_programs), FontAwesomeIcons.fa_clone, WebViewProgramFragment.makeArguments(environment.getConfig().getProgramConfig().getUrl(), null, true), new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { } })); } if (environment.getConfig().getCourseDiscoveryConfig().isCourseDiscoveryEnabled()) { items.add(new FragmentItemModel( environment.getConfig().getCourseDiscoveryConfig().isWebviewCourseDiscoveryEnabled() ? WebViewDiscoverCoursesFragment.class : NativeFindCoursesFragment.class, getResources().getString(R.string.label_discovery), FontAwesomeIcons.fa_search, new FragmentItemModel.FragmentStateListener() { @Override public void onFragmentSelected() { environment.getAnalyticsRegistry().trackScreenView(Analytics.Screens.FIND_COURSES); } })); } return items; }
Source:
private VmDevice createVmDevice() { return new VmDevice(new VmDeviceId(Guid.newGuid(), vm.getId()), VmDeviceGeneralType.DISK, "device", "address", 1, new HashMap<String, Object>(), true, true, true, "alias", new HashMap<String, String>(), Guid.newGuid(), "logical", true); }

Target:
private VmDevice createVmDevice() { return new VmDevice(new VmDeviceId(Guid.Empty, vm.getId()), VmDeviceGeneralType.DISK, "device", "address", 1, new HashMap<String, Object>(), true, true, true, "alias", new HashMap<String, String>(), Guid.newGuid(), "logical", true); }
Source:
public void run() { @SuppressWarnings("resource") AbstractApplicationContext ctx = new ClassPathXmlApplicationContext( "testIp-in-context.xml", UdpUnicastEndToEndTests.class); UnicastReceivingChannelAdapter inbound = ctx.getBean(UnicastReceivingChannelAdapter.class); int n = 0; try { while (!inbound.isListening()) { Thread.sleep(100); if (n++ > 100) { throw new RuntimeException("Failed to start listening"); } } } catch (Exception e) { } while (okToRun) { try { readyToReceive.countDown(); sentFirst.await(); } catch (InterruptedException e) { e.printStackTrace(); } QueueChannel channel = ctx.getBean("udpOutChannel", QueueChannel.class); finalMessage = (Message<byte[]>) channel.receive(); MessageHistory history = MessageHistory.read(finalMessage); Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "udpReceiver", 0); assertNotNull(componentHistoryRecord); assertEquals("ip:udp-inbound-channel-adapter", componentHistoryRecord.get("type")); firstReceived.countDown(); try { doneProcessing.await(); } catch (InterruptedException e) { e.printStackTrace(); } } ctx.stop(); ctx.close(); ctx.destroy(); }

Target:
public void run() { @SuppressWarnings("resource") AbstractApplicationContext ctx = new ClassPathXmlApplicationContext( "testIp-in-context.xml", UdpUnicastEndToEndTests.class); UnicastReceivingChannelAdapter inbound = ctx.getBean(UnicastReceivingChannelAdapter.class); int n = 0; try { while (!inbound.isListening()) { Thread.sleep(100); if (n++ > 100) { throw new RuntimeException("Failed to start listening"); } } } catch (Exception e) { } while (okToRun) { try { readyToReceive.countDown(); sentFirst.await(); } catch (InterruptedException e) { e.printStackTrace(); } QueueChannel channel = ctx.getBean("udpOutChannel", QueueChannel.class); finalMessage = (Message<byte[]>) channel.receive(); MessageHistory history = MessageHistory.read(finalMessage); Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "udpReceiver", 0); assertNotNull(componentHistoryRecord); assertEquals("ip:udp-inbound-channel-adapter", componentHistoryRecord.get("type")); firstReceived.countDown(); try { doneProcessing.await(); } catch (InterruptedException e) { e.printStackTrace(); } } ctx.stop(); ctx.close(); }
Source:
double stringToMeter(String value) { value = value.toLowerCase().replaceAll(" ", "").replaceAll("(meters|meter|mtrs|mtr|mt|m\\.)", "m"); double factor = 1; double offset = 0; value = value.replaceAll("(\\\"|\'\')", "in").replaceAll("(\'|feet)", "ft"); if (value.endsWith("in")) { int startIndex = value.indexOf("ft"); String inchValue; if (startIndex < 0) { startIndex = 0; } else { startIndex += 2; } inchValue = value.substring(startIndex, value.length() - 2); value = value.substring(0, startIndex); offset = Double.parseDouble(inchValue) * 0.0254; } if (value.endsWith("ft")) { value = value.substring(0, value.length() - 2); factor *= 0.3048; } else if (value.endsWith("m")) { value = value.substring(0, value.length() - 1); } if (value.isEmpty()) { return offset; } else { return Double.parseDouble(value) * factor + offset; } }

Target:
public static double stringToMeter(String value) { value = value.toLowerCase().replaceAll(" ", "").replaceAll("(meters|meter|mtrs|mtr|mt|m\\.)", "m"); double factor = 1; double offset = 0; value = value.replaceAll("(\\\"|\'\')", "in").replaceAll("(\'|feet)", "ft"); if (value.startsWith("~") || value.contains("approx")) { value = value.replaceAll("(\\~|approx)", "").trim(); factor = 0.8; } if (value.endsWith("in")) { int startIndex = value.indexOf("ft"); String inchValue; if (startIndex < 0) { startIndex = 0; } else { startIndex += 2; } inchValue = value.substring(startIndex, value.length() - 2); value = value.substring(0, startIndex); offset = Double.parseDouble(inchValue) * 0.0254; } if (value.endsWith("ft")) { value = value.substring(0, value.length() - 2); factor *= 0.3048; } else if (value.endsWith("m")) { value = value.substring(0, value.length() - 1); } if (value.isEmpty()) { return offset; } else { return Double.parseDouble(value) * factor + offset; } }
Source:
public String getMimeTypeForStoreResponse(String id) { String mimeType = null; try (Connection connection = getConnection(); PreparedStatement mySelectSQL = connection.prepareStatement(selectionString)) { mySelectSQL.setString(SELECT_COLUMN_RESPONSE, id); try (ResultSet rs = mySelectSQL.executeQuery()) { if (null == rs || !rs.next()) { LOGGER.warn("No response found for request id " + id); } else { mimeType = rs.getString(2); } } } catch (SQLException ex) { LOGGER.error("Could not look up response in database", ex); } return mimeType; }

Target:
public String getMimeTypeForStoreResponse(String id) { String mimeType = null; try (Connection connection = getConnection(); PreparedStatement selectStatement = connection.prepareStatement(selectionString)) { selectStatement.setString(SELECTION_STRING_REQUEST_ID_PARAM_INDEX, id); try (ResultSet rs = selectStatement.executeQuery()) { if (null == rs || !rs.next()) { LOGGER.warn("No response found for request id " + id); } else { mimeType = rs.getString(SELECTION_STRING_RESPONSE_MIMETYPE_COLUMN_INDEX); } } } catch (SQLException ex) { LOGGER.error("Could not look up response in database", ex); } return mimeType; }
Source:
public void testMissingOperation() throws Exception { Map<String, String> expectedResponseHeaders = new HashMap<String, String>(); expectedResponseHeaders.put("Cache-Control", "must-revalidate,no-cache,no-store"); expectedResponseHeaders.put("Content-Type", "text/html;charset=ISO-8859-1"); expectedResponseHeaders.put("Content-Length", "1327"); expectedResponseHeaders.put("Server", "Jetty(7.6.4.v20120524)"); String expectedResponseBody = "<html>\n" + "<head>\n" + "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n" + "<title>Error 400 Missing \"operation\" parameter.</title>\n" + "</head>\n" + "<body>\n" + "<h2>HTTP ERROR: 400</h2>\n" + "<p>Problem accessing /scep/pkiclient.exe. Reason:\n" + "<pre> Missing \"operation\" parameter.</pre></p>\n" + "<hr /><i><small>Powered by Jetty://</small></i>\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "</body>\n" + "</html>\n"; verifyResponse(getURL(), 400, "Missing \"operation\" parameter.", expectedResponseHeaders, expectedResponseBody); }

Target:
public void testMissingOperation() throws Exception { Map<String, String> expectedResponseHeaders = new HashMap<String, String>(); expectedResponseHeaders.put("Cache-Control", "must-revalidate,no-cache,no-store"); expectedResponseHeaders.put("Content-Type", "text/html;charset=ISO-8859-1"); expectedResponseHeaders.put("Content-Length", "1327"); expectedResponseHeaders.put("Server", "Jetty(7.6.4.v20120524)"); String errorMessage = "Missing \"operation\" parameter."; String response = verifyResponse(getURL(), 400, errorMessage, expectedResponseHeaders); assertThat(response, containsString(errorMessage)); assertThat(response, containsString("Jetty")); }