auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { log.debug("HostProcess.run"); try { hostProcessStartTime = System.currentTimeMillis(); pluginFactory.reset(); synchronized (mapPluginStats) { for (Plugin plugin : pluginFactory.getPending()) { mapPluginStats.put(plugin.getId(), new PluginStats(plugin.getName())); } } for (StructuralNode startNode : startNodes) { traverse( startNode, true, node -> { if (canScanNode(node) && bestNodeForUrl(node)) { messagesIdsToAppScan.add(node.getHistoryReference().getHistoryId()); } }); getAnalyser().start(startNode); } nodeInScopeCount = messagesIdsToAppScan.size(); if (!messagesIdsToAppScan.isEmpty()) { messageIdToHostScan = messagesIdsToAppScan.get(0); } logScanInfo(); Plugin plugin; while (!isStop() && pluginFactory.existPluginToRun()) { checkPause(); if (isStop()) { break; } plugin = pluginFactory.nextPlugin(); if (plugin != null) { plugin.setDelayInMs(this.scannerParam.getDelayInMs()); plugin.setTechSet(this.techSet); processPlugin(plugin); } else { Util.sleep(1000); } } threadPool.waitAllThreadComplete(300000); } catch (Exception e) { log.error("An error occurred while active scanning:", e); stop(); } finally { notifyHostProgress(null); notifyHostComplete(); getHttpSender().shutdown(); } }

Target:
public void run() { log.debug("HostProcess.run"); try { hostProcessStartTime = System.currentTimeMillis(); pluginFactory.reset(); synchronized (mapPluginStats) { for (Plugin plugin : pluginFactory.getPending()) { mapPluginStats.put(plugin.getId(), new PluginStats(plugin.getName())); } } for (StructuralNode startNode : startNodes) { Map<String, Integer> historyIdsToAdd = new LinkedHashMap<>(); traverse( startNode, true, node -> { if (canScanNode(node)) { int nodeHistoryId = node.getHistoryReference().getHistoryId(); if (node.getMethod().equals(HttpRequestHeader.GET)) { boolean nodeSeen = historyIdsToAdd.containsKey(nodeHash(node)); if (!nodeSeen || !isTemporary(node)) { historyIdsToAdd.put(nodeHash(node), nodeHistoryId); } } else { messagesIdsToAppScan.add(nodeHistoryId); } } }); messagesIdsToAppScan.addAll(historyIdsToAdd.values()); getAnalyser().start(startNode); } nodeInScopeCount = messagesIdsToAppScan.size(); if (!messagesIdsToAppScan.isEmpty()) { messageIdToHostScan = messagesIdsToAppScan.get(0); } logScanInfo(); Plugin plugin; while (!isStop() && pluginFactory.existPluginToRun()) { checkPause(); if (isStop()) { break; } plugin = pluginFactory.nextPlugin(); if (plugin != null) { plugin.setDelayInMs(this.scannerParam.getDelayInMs()); plugin.setTechSet(this.techSet); processPlugin(plugin); } else { Util.sleep(1000); } } threadPool.waitAllThreadComplete(300000); } catch (Exception e) { log.error("An error occurred while active scanning:", e); stop(); } finally { notifyHostProgress(null); notifyHostComplete(); getHttpSender().shutdown(); } }
Source:
public String sanitizePath(@Nullable String path) { path = Strings.trim(path); if (Strings.isEmpty(path)) { return ""; } if (path.contains("\\")) { path = path.replace("\\", "/"); } if (path.contains(" path = path.replaceAll("/+", "/"); } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; }

Target:
public String sanitizePath(@Nullable String path) { path = Strings.trim(path); if (Strings.isEmpty(path)) { return ""; } path = SANITIZE_SLASHES.matcher(path).replaceAll("/"); if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; }
Source:
private void doVisitToken(FullIdent ident, boolean isStatic, boolean previous) { final String name = ident.getText(); final int groupIdx = getGroupNumber(name); final int line = ident.getLineNo(); if (groupIdx == lastGroup || !beforeFirstImport && isAlphabeticallySortableStaticImport(isStatic)) { doVisitTokenInSameGroup(isStatic, previous, name, line); } else if (groupIdx > lastGroup) { if (!beforeFirstImport && separated && line - lastImportLine < 2) { log(line, MSG_SEPARATION, name); } } else { log(line, MSG_ORDERING, name); } checkRedundantSeparation(groupIdx, isStatic, line, name); lastGroup = groupIdx; lastImport = name; }

Target:
private void doVisitToken(FullIdent ident, boolean isStatic, boolean previous) { final String name = ident.getText(); final int groupIdx = getGroupNumber(name); final int line = ident.getLineNo(); if (groupIdx == lastGroup || !beforeFirstImport && isAlphabeticallySortableStaticImport(isStatic)) { doVisitTokenInSameGroup(isStatic, previous, name, line); } else if (groupIdx > lastGroup) { if (!beforeFirstImport && separated && line - lastImportLine < 2) { log(line, MSG_SEPARATION, name); } } else { log(line, MSG_ORDERING, name); } if (checkSeparatorInGroup(groupIdx, isStatic, line)) { log(line, MSG_SEPARATED_IN_GROUP, name); } lastGroup = groupIdx; lastImport = name; }
Source:
protected void executeCommand() { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { setVdsStatus(VDSStatus.Installing); try (final VdsDeploy vdsDeploy = new VdsDeploy("ovirt-host-mgmt", getVds(), false)) { vdsDeploy.addUnit( new VdsDeployPKIUnit(), new VdsDeployVmconsoleUnit(true) ); String correlationId = CorrelationIdTracker.getCorrelationId(); if (StringUtils.isEmpty(correlationId)) { correlationId = LoggedUtils.getObjectId(getVds()); } vdsDeploy.setCorrelationId(correlationId); vdsDeploy.useDefaultKeyPair(); vdsDeploy.execute(); logEvent(AuditLogType.HOST_CERTIFICATION_ENROLLMENT); } catch (final Exception e) { log.error("Failed to enroll certificate for host '{}': {}", getVds().getName(), e.getMessage()); log.error("Exception", e); logEvent(AuditLogType.HOST_CERTIFICATION_ENROLLMENT_FAILED); } finally { setVdsStatus(VDSStatus.Maintenance); } } private void logEvent(AuditLogType eventType) { AuditLogableBase event = new AuditLogableBase(); event.setVds(getVds()); event.setUserName(getUserName()); auditLogDirector.log(event, eventType); } }); setSucceeded(true); }

Target:
protected void executeCommand() { CommandCoordinatorUtil.executeAsyncCommand(VdcActionType.HostEnrollCertificateInternal, getParameters(), cloneContextAndDetachFromParent()); setSucceeded(true); }
Source:
private byte[] stringToByte(String mediaId) { if (!mHmap.containsValue(mediaId)) { int key = mHmap.size() + 1; mHmap.put(key, mediaId); return intToByteArray(key); } else { for (int key : mHmap.keySet()) { if (mHmap.get(key).equals(mediaId)) { return intToByteArray(key); } } } return null; }

Target:
private byte[] stringToByte(String mediaId) { if (!mHmap.containsValue(mediaId)) { int uid = mHmap.size(); mHmap.put(uid, mediaId); return intToByteArray(uid); } else { for (int uid : mHmap.keySet()) { if (mHmap.get(uid).equals(mediaId)) { return intToByteArray(uid); } } } return null; }
Source:
public void testEncodeIllegalCharacters() throws WriterException { int illegalArgument = 0; try { BitMatrix result = new EAN8Writer().encode("96385abc", BarcodeFormat.EAN_8, 0, 0); } catch (IllegalArgumentException e) { illegalArgument = 1; } assertEquals(illegalArgument, 1); }

Target:
public void testEncodeIllegalCharacters() throws WriterException { new EAN8Writer().encode("96385abc", BarcodeFormat.EAN_8, 0, 0); }
Source:
private File createTemporaryCopyOf(File file) throws IOException { File tempFolder = Files.createTempDir(); FileUtils.copyDirectory(file, tempFolder); return tempFolder; }

Target:
private File createTemporaryCopyOf(File file) throws IOException { File tempFolder = Files.createTempDir(); FileUtils.copyDirectory(file, tempFolder); tempFolder.deleteOnExit(); return tempFolder; }
Source:
public WebSocketClientWrapper(final URI uri, final Proxy proxy, final WebSocketListener webSocketListener) throws SSLException { super(uri); if (uri.getScheme().equals(WSS_SCHEME)) { try { SSLContext sslContext = null; sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); final SSLSocketFactory factory = sslContext.getSocketFactory(); setSocket(factory.createSocket()); } catch (final IOException e) { throw new SSLException(e); } catch (final NoSuchAlgorithmException e) { throw new SSLException(e); } catch (final KeyManagementException e) { throw new SSLException(e); } } this.webSocketListener = webSocketListener; if (proxy != null){ this.setProxy(proxy); } }

Target:
public WebSocketClientWrapper(final URI uri, final Proxy proxy, final WebSocketListener webSocketListener) throws SSLException { super(uri); if (uri.getScheme().equals(WSS_SCHEME)) { try { SSLContext sslContext = null; sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); final SSLSocketFactory factory = sslContext.getSocketFactory(); setSocket(factory.createSocket()); } catch (final IOException e) { throw new SSLException(e); } catch (final NoSuchAlgorithmException e) { throw new SSLException(e); } catch (final KeyManagementException e) { throw new SSLException(e); } } this.webSocketListener = webSocketListener; setProxy(proxy); }
Source:
public synchronized boolean recover(TaskId taskId) { checkState(groupedLifespanScheduler.isPresent(), "Non grouped execution is not recoverable"); if (anySourceSchedulingFinished) { throw new UnsupportedOperationException("Recover after any source scheduling finished is not supported"); } return groupedLifespanScheduler.get().retryFailedTask(taskId.getId(), sourceSchedulers); }

Target:
public synchronized void recover(TaskId taskId) { checkState(groupedLifespanScheduler.isPresent(), "groupedLifespanScheduler is not present for recoverable grouped execution"); if (anySourceSchedulingFinished) { throw new IllegalStateException("Recover after any source scheduling finished is not supported"); } groupedLifespanScheduler.get().onTaskFailed(taskId.getId(), sourceSchedulers); }
Source:
protected Iterator<ServiceRecord> getServiceRecords(MarketoService marketoService, PluginTask task) { List<String> extractedFields = task.getExtractedFields(); Iterable<ObjectNode> requestLists; if (isUserInputLists(task)) { final String[] idsStr = StringUtils.split(task.getListIds().get(), ID_LIST_SEPARATOR_CHAR); Function<Set<String>, Iterable<ObjectNode>> getListIds = (ids) -> marketoService.getListsByIds(ids); requestLists = super.getObjectsByIds(idsStr, task.getSkipInvalidList(), getListIds); } else { requestLists = marketoService.getLists(); } extractedFields.remove(MarketoUtils.LIST_ID_COLUMN_NAME); return FluentIterable.from(marketoService.getAllListLead(extractedFields, requestLists)).transform(MarketoUtils.TRANSFORM_OBJECT_TO_JACKSON_SERVICE_RECORD_FUNCTION).iterator(); }

Target:
protected Iterator<ServiceRecord> getServiceRecords(MarketoService marketoService, PluginTask task) { List<String> extractedFields = task.getExtractedFields(); Iterable<ObjectNode> listsToRequest; if (isUserInputLists(task)) { final String[] idsStr = StringUtils.split(task.getListIds().get(), ID_LIST_SEPARATOR_CHAR); Function<Set<String>, Iterable<ObjectNode>> getListIds = (ids) -> marketoService.getListsByIds(ids); listsToRequest = super.getObjectsByIds(idsStr, getListIds); } else { listsToRequest = marketoService.getLists(); } extractedFields.remove(MarketoUtils.LIST_ID_COLUMN_NAME); return FluentIterable.from(marketoService.getAllListLead(extractedFields, listsToRequest)).transform(MarketoUtils.TRANSFORM_OBJECT_TO_JACKSON_SERVICE_RECORD_FUNCTION).iterator(); }
Source:
public boolean isWms() { return (this.getService().equalsIgnoreCase(OgcNaming.SERVICE_WMS)) ? true : false; }

Target:
public boolean isWms() { return this.getService() != null && this.getService().equalsIgnoreCase(OgcNaming.SERVICE_WMS); }
Source:
public void checkpointAndTrimStandby() { String metadataTableName = LogReplicationMetadataManager.TABLE_PREFIX_NAME + DefaultClusterManager.DEFAULT_STANDBY_CLUSTER_NAME; CorfuTable<LogReplicationMetadata.LogReplicationMetadataKey, LogReplicationMetadata.LogReplicationMetadataVal> metadataTableStandby = standbyRuntime.getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<LogReplicationMetadata.LogReplicationMetadataKey, LogReplicationMetadata.LogReplicationMetadataVal>>() { }) .setStreamName(TableRegistry.getFullyQualifiedTableName(LogReplicationMetadataManager.NAMESPACE, metadataTableName)) .open(); List<CorfuTable> toCheckpoint = new ArrayList<>(); toCheckpoint.add(mapAStandby); toCheckpoint.add(metadataTableStandby); System.out.println("**** Checkpoint and trim ... on standby"); CorfuRuntime standbyCPRuntime = new CorfuRuntime(standbyEndpoint).connect(); checkpoint(standbyCPRuntime, toCheckpoint); }

Target:
public void checkpointAndTrimStandby() { String metadataTableName = LogReplicationMetadataManager.TABLE_PREFIX_NAME + DefaultClusterManager.DEFAULT_STANDBY_CLUSTER_NAME; CorfuTable<LogReplicationMetadata.LogReplicationMetadataKey, LogReplicationMetadata.LogReplicationMetadataVal> metadataTableStandby = standbyRuntime.getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<LogReplicationMetadata.LogReplicationMetadataKey, LogReplicationMetadata.LogReplicationMetadataVal>>() { }) .setStreamName(TableRegistry.getFullyQualifiedTableName(LogReplicationMetadataManager.NAMESPACE, metadataTableName)) .open(); List<CorfuTable> toCheckpoint = new ArrayList<>(); toCheckpoint.add(mapAStandby); toCheckpoint.add(metadataTableStandby); System.out.println("**** Checkpoint and trim ... on standby"); CorfuRuntime standbyCPRuntime = new CorfuRuntime(standbyEndpoint).connect(); checkpointAndTrim(standbyCPRuntime, toCheckpoint); }
Source:
if (System.getProperty("opensim.port") != null) { int port = Integer.parseInt(System.getProperty("opensim.port")); if (port > 80 && port < 9000) { SERVER_PORT = port; } }

Target:
if (System.getProperty("opensim.port") != null) { int port = Integer.parseInt(System.getProperty("opensim.port")); if (port > 80 && port < 9000) { SERVER_PORT = port; } else System.out.println("Port number outside range (80 , 9000): port 8002 will be used"); }
Source:
public SetSesssionSoftLimitCommandParameters() { super(); }

Target:
SetSesssionSoftLimitCommandParameters() { super(); }
Source:
private EngineLock createLockForRunVmCommand(Guid vmId) { return new EngineLock( Collections.singletonMap( vmId.toString(), LockMessagesMatchUtil.makeLockingPair( LockingGroup.VM, VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED.name())), null); }

Target:
private EngineLock createLockForRunVmCommand(Guid vmId) { return new RunVmCommandBase.RunVmLock(vmId); }
Source:
private void removeDocker() throws Exception{ if (docker != null) { docker.killContainer(widlflyContId); docker.removeContainer(widlflyContId); docker.close(); } }

Target:
private void removeDocker() throws Exception{ if (docker != null) { docker.killContainer(widlflyContId); docker.removeContainer(widlflyContId); docker.removeImage(config.imageName()); docker.close(); } }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CrumbIssuer crumbIssuer = getCrumbIssuer(); if (crumbIssuer == null || !(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if ("POST".equals(httpRequest.getMethod())) { for (CrumbExclusion e : CrumbExclusion.all()) { if (e.process(httpRequest,httpResponse,chain)) return; } String crumbFieldName = crumbIssuer.getDescriptor().getCrumbRequestField(); String crumbSalt = crumbIssuer.getDescriptor().getCrumbSalt(); boolean valid = false; String crumb = extractCrumbFromRequest(httpRequest, crumbFieldName); if (crumb == null) { extractCrumbFromRequest(httpRequest, ".crumb"); } Level level = Jenkins.getAuthentication() == Jenkins.ANONYMOUS ? Level.FINE : Level.WARNING; if (crumb != null) { if (crumbIssuer.validateCrumb(httpRequest, crumbSalt, crumb)) { valid = true; } else { LOGGER.log(level, "Found invalid crumb {0}. Will check remaining parameters for a valid one...", crumb); } } if (valid) { chain.doFilter(request, response); } else { LOGGER.log(level, "No valid crumb was included in request for {0}. Returning {1}.", new Object[] {httpRequest.getRequestURI(), HttpServletResponse.SC_FORBIDDEN}); httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,"No valid crumb was included in the request"); } } else { chain.doFilter(request, response); } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CrumbIssuer crumbIssuer = getCrumbIssuer(); if (crumbIssuer == null || !(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if ("POST".equals(httpRequest.getMethod())) { for (CrumbExclusion e : CrumbExclusion.all()) { if (e.process(httpRequest,httpResponse,chain)) return; } String crumbFieldName = crumbIssuer.getDescriptor().getCrumbRequestField(); String crumbSalt = crumbIssuer.getDescriptor().getCrumbSalt(); boolean valid = false; String crumb = extractCrumbFromRequest(httpRequest, crumbFieldName); if (crumb == null) { extractCrumbFromRequest(httpRequest, ".crumb"); } Level level = Jenkins.getAuthentication() instanceof AnonymousAuthenticationToken ? Level.FINE : Level.WARNING; if (crumb != null) { if (crumbIssuer.validateCrumb(httpRequest, crumbSalt, crumb)) { valid = true; } else { LOGGER.log(level, "Found invalid crumb {0}. Will check remaining parameters for a valid one...", crumb); } } if (valid) { chain.doFilter(request, response); } else { LOGGER.log(level, "No valid crumb was included in request for {0} by {1}. Returning {2}.", new Object[] {httpRequest.getRequestURI(), Jenkins.getAuthentication().getName(), HttpServletResponse.SC_FORBIDDEN}); httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,"No valid crumb was included in the request"); } } else { chain.doFilter(request, response); } }
Source:
public StopVmCommandBase(T parameters) { super(parameters); setStoragePoolId(getVm().getstorage_pool_id()); }

Target:
public StopVmCommandBase(T parameters) { super(parameters); }
Source:
public JavaSymbolicKRun(Context context) throws KRunExecutionException { definition = (Definition) BinaryLoader.load( new File(context.kompiled, JavaSymbolicBackend.DEFINITION_FILENAME).toString()); if (definition == null) { throw new KRunExecutionException("cannot load definition"); } builtins = new BuiltinFunction(definition); this.context = definition.context(); this.context.kompiled = context.kompiled; this.context.globalOptions = context.globalOptions; transformer = new KILtoBackendJavaKILTransformer(this.context); }

Target:
public JavaSymbolicKRun(Context context) throws KRunExecutionException { definition = (Definition) BinaryLoader.load( new File(context.kompiled, JavaSymbolicBackend.DEFINITION_FILENAME).toString()); if (definition == null) { throw new KRunExecutionException("cannot load definition"); } this.context = definition.context(); this.context.kompiled = context.kompiled; this.context.globalOptions = context.globalOptions; transformer = new KILtoBackendJavaKILTransformer(this.context); }
Source:
public void testInvalidTopologyId() { TriangleOrderManager triangleOrderManager = new TriangleOrderManager(); triangleOrderManager.updateCacheTopology(mockCacheTopology(1)); try { triangleOrderManager.next(0, 0); fail("Exception expected!"); } catch (OutdatedTopologyException e) { log.debug("exception", e); } try { triangleOrderManager.next(1, 2); fail("Exception expected!"); } catch (OutdatedTopologyException e) { log.debug("exception", e); } try { triangleOrderManager.next(newSegmentMap(), 0); fail("Exception expected!"); } catch (OutdatedTopologyException e) { log.debug("exception", e); } try { triangleOrderManager.next(newSegmentMap(), 2); fail("Exception expected!"); } catch (OutdatedTopologyException e) { log.debug("exception", e); } }

Target:
public void testInvalidTopologyId() { TriangleOrderManager triangleOrderManager = new TriangleOrderManager(4); triangleOrderManager.updateCacheTopology(mockCacheTopology(1)); try { triangleOrderManager.next(0, 0); fail("Exception expected!"); } catch (OutdatedTopologyException e) { Exceptions.assertException(OutdatedTopologyException.class, e); } try { triangleOrderManager.next(1, 2); fail("Exception expected!"); } catch (OutdatedTopologyException e) { Exceptions.assertException(OutdatedTopologyException.class, e); } try { triangleOrderManager.next(newSegmentMap(), 0); fail("Exception expected!"); } catch (OutdatedTopologyException e) { Exceptions.assertException(OutdatedTopologyException.class, e); } try { triangleOrderManager.next(newSegmentMap(), 2); fail("Exception expected!"); } catch (OutdatedTopologyException e) { Exceptions.assertException(OutdatedTopologyException.class, e); } }
Source:
public Put getNextDataRowState(ImmutableBytesPtr rowKeyPtr) { Pair<Put, Put> rowState = dataRowStates.get(rowKeyPtr); if (rowState != null) { return dataRowStates.get(rowKeyPtr).getSecond(); } return null; }

Target:
public Put getNextDataRowState(ImmutableBytesPtr rowKeyPtr) { Pair<Put, Put> rowState = dataRowStates.get(rowKeyPtr); if (rowState != null) { return rowState.getSecond(); } return null; }
Source:
public static IType unmarshal(short firstBytes, ITypeMarshalBuffer buffer) throws CoreException { final short SECOND_LAST_FLAG= ITypeMarshalBuffer.LAST_FLAG / 2; final boolean haveModifiers= (firstBytes & ITypeMarshalBuffer.LAST_FLAG) != 0; final boolean haveAssociatedNumericalValue= (firstBytes & SECOND_LAST_FLAG) != 0; int modifiers= 0; int kind= (firstBytes & (SECOND_LAST_FLAG - 1)) / ITypeMarshalBuffer.FIRST_FLAG; if (haveModifiers) modifiers= buffer.getByte(); CPPBasicType result = new CPPBasicType(Kind.values()[kind], modifiers); if (haveAssociatedNumericalValue) result.setAssociatedNumericalValue(buffer.getLong()); return result; }

Target:
public static IType unmarshal(short firstBytes, ITypeMarshalBuffer buffer) throws CoreException { final boolean haveModifiers= (firstBytes & ITypeMarshalBuffer.LAST_FLAG) != 0; final boolean haveAssociatedNumericalValue= (firstBytes & ITypeMarshalBuffer.SECOND_LAST_FLAG) != 0; int modifiers= 0; int kind= (firstBytes & (ITypeMarshalBuffer.SECOND_LAST_FLAG - 1)) / ITypeMarshalBuffer.FIRST_FLAG; if (haveModifiers) modifiers= buffer.getByte(); CPPBasicType result = new CPPBasicType(Kind.values()[kind], modifiers); if (haveAssociatedNumericalValue) result.setAssociatedNumericalValue(buffer.getLong()); return result; }
Source:
public void testFnCalendarOperation() throws OperationException { try (OperationContext ctx = new OperationContext(session)) { ctx.setInput(new Date()); Object result = automationService.run(ctx, "Scripting.TestFnCalendar"); assertTrue(result instanceof DateWrapper); } }

Target:
public void testFnCalendarOperation() throws OperationException { try (OperationContext ctx = new OperationContext(session)) { Date now = new Date(); ctx.setInput(now); DateWrapper result = (DateWrapper) automationService.run(ctx, "Scripting.TestFnCalendar"); assertEquals(now, result.getDate()); } }
Source:
public void testFailingPreRebaseHookBlocksRebase() throws Exception { assumeSupportedPlatform(); Hook h = Hook.PRE_REBASE; writeHookFile(h.getName(), "#!/bin/sh\necho \"test\"\n\necho 1>&2 \"stderr\"\nexit 1"); Git git = Git.wrap(db); RevCommit first = git.commit().setMessage("initial commit").call(); createBranch(first, "refs/heads/branch1"); git.commit().setMessage("second commit").call(); checkoutBranch("refs/heads/branch1"); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { git.rebase().setUpstream("refs/heads/master") .setHookOutputStream(new PrintStream(out)).call(); fail("expected pre-rebase hook to abort commit"); } catch (RejectRebaseException e) { assertEquals("unexpected error message from pre-rebase hook", "Rebase rejected by \"pre-rebase\" hook.\nstderr\n", e.getMessage()); assertEquals("unexpected output from pre-rebase hook", "test\n", out.toString()); } catch (Throwable e) { fail("unexpected exception thrown by pre-rebase hook: " + e); } }

Target:
public void testFailingPreRebaseHookBlocksRebase() throws Exception { assumeSupportedPlatform(); Hook h = Hook.PRE_REBASE; writeHookFile(h.getName(), "#!/bin/sh\necho \"test\"\n\necho 1>&2 \"stderr\"\nexit 1"); Git git = Git.wrap(db); RevCommit first = git.commit().setMessage("initial commit").call(); createBranch(first, "refs/heads/branch1"); git.commit().setMessage("second commit").call(); checkoutBranch("refs/heads/branch1"); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { git.rebase().setUpstream("refs/heads/master") .setHookOutputStream(new PrintStream(out)).call(); fail("expected pre-rebase hook to abort commit"); } catch (RejectRebaseException e) { assertEquals("unexpected error message from pre-rebase hook", "Rebase rejected by \"pre-rebase\" hook.\nstderr\n", e.getMessage()); assertEquals("unexpected output from pre-rebase hook", "test\n", out.toString()); } }
Source:
private ChangeLink createParentChangeLink() { PatchSet.Id parentChange = patchList.get(0).getKey().getParentKey(); return parentChange != null ? new ChangeLink("Back to the patch", psid.getParentKey()) : null; }

Target:
private ChangeLink createParentChangeLink() { return new ChangeLink(PatchUtil.C.upToChange(), psid.getParentKey()); }
Source:
public String changePublisherConfiguration(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, @PathVariable("appSlug") String slug) throws IOException { Reader reader = new InputStreamReader(request.getInputStream()); Gson deserializer = new GsonBuilder() .registerTypeAdapter(Publisher.class, new PublisherKeyDeserializer()) .create(); PublisherConfiguration configuration = deserializer.fromJson(reader, PublisherConfiguration.class); Application app = manager.setPublisherConfiguration(slug, configuration); model.put("application", modelBuilder.build(app)); return APPLICATION_TEMPLATE; }

Target:
public String changePublisherConfiguration(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, @PathVariable("appSlug") String slug) throws IOException { Reader reader = new InputStreamReader(request.getInputStream()); PublisherConfiguration configuration = publisherKeyDeserializer.fromJson(reader, PublisherConfiguration.class); Application app = manager.setPublisherConfiguration(slug, configuration); model.put("application", modelBuilder.build(app)); return APPLICATION_TEMPLATE; }
Source:
public void updateForLocation(String pid, String location, Map<String, Object> configurationTable) throws IOException { if (pid == null || pid.length() < 1) { throw new IOException("Argument pid cannot be null or empty"); } if (configurationTable == null) { throw new IOException("Argument configurationTable cannot be null"); } for (Entry<String, Object> curEntry : configurationTable.entrySet()) { Object value = curEntry.getValue(); if (value instanceof JSONArray && ((JSONArray)value).size() == 0) { curEntry.setValue(""); } else if (value == null) { curEntry.setValue(""); } } Dictionary<String, Object> configurationProperties = new Hashtable<String, Object>( configurationTable); Configuration config = configurationAdmin.getConfiguration(pid, location); config.update(configurationProperties); }

Target:
public void updateForLocation(String pid, String location, Map<String, Object> configurationTable) throws IOException { if (pid == null || pid.length() < 1) { throw new IOException("Argument pid cannot be null or empty"); } if (configurationTable == null) { throw new IOException("Argument configurationTable cannot be null"); } for (Entry<String, Object> curEntry : configurationTable.entrySet()) { Object value = curEntry.getValue(); if (value == null || (value instanceof ArrayList && CollectionUtils.sizeIsEmpty(value))) { curEntry.setValue(""); } } Dictionary<String, Object> configurationProperties = new Hashtable<String, Object>( configurationTable); Configuration config = configurationAdmin.getConfiguration(pid, location); config.update(configurationProperties); }
Source:
public <T> T get(int index) { throw new UnsupportedOperationException("Should not be called."); }

Target:
public <T> T get(int index) { throw new IndexOutOfBoundsException(getClass().getName() + " has no columns"); }
Source:
public String update(MetaModel metaModel, Map<String, Object> attributes) { StringBuilder query = new StringBuilder().append("UPDATE ").append(metaModel.getTableName()).append(' '); if (attributes.isEmpty()) { appendEmptyRow(metaModel, query); } else { query.append("SET "); Iterator<String> keysetIt = attributes.keySet().iterator(); Iterator<Object> valueIt = attributes.values().iterator(); while (valueIt.hasNext()) { query.append(keysetIt.next() + " = "); appendValue(query, valueIt.next()); if (valueIt.hasNext()) { query.append(", "); } else{ query.append(" "); } } String idName = metaModel.getIdName(); query.append("WHERE ").append(idName).append(" = " + attributes.get(idName)); } return query.toString(); }

Target:
public String update(MetaModel metaModel, Map<String, Object> attributes) { StringBuilder query = new StringBuilder().append("UPDATE ").append(metaModel.getTableName()).append(' '); if (attributes.isEmpty()) { throw new NoSuchElementException("No attributes set, can't create an update statement."); } else { query.append("SET "); String idName = metaModel.getIdName(); Map<String, Object> attributesWithoutId = new CaseInsensitiveMap<Object>(); attributesWithoutId.putAll(attributes); attributesWithoutId.remove(idName); Iterator<Entry<String, Object>> attributesIt = attributesWithoutId.entrySet().iterator(); for (;;) { Entry<String, Object> attribute = attributesIt.next(); String key = attribute.getKey(); Object val = attribute.getValue(); query.append(key + " = "); appendValue(query, val); if (attributesIt.hasNext()) { query.append(", "); } else { break; } } query.append(" WHERE ").append(idName).append(" = " + attributes.get(idName)); } return query.toString(); }
Source:
public void shouldFormatUniquenessConstraints() { final int[] propertyKeyIds = new int[]{42}; assertEquals( "new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, 42 ) )", formatArgument( new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, propertyKeyIds ) ) ) ); }

Target:
public void shouldFormatUniquenessConstraints() { assertEquals( "new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, 42 ) )", formatArgument( new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, 42 ) ) ) ); }
Source:
public Map<String, Double> toMap() { Map<String, Double> metricValues = new HashMap<>(); for (Field field : this.getClass().getDeclaredFields()) try { metricValues.put(field.getName(), field.getDouble(this)); } catch (IllegalAccessException e) { e.printStackTrace(); } return metricValues; }

Target:
public Map<String, Double> toMap() { Map<String, Double> metricValues = new HashMap<>(); for (Field field : getClass().getDeclaredFields()) try { metricValues.put(field.getName(), field.getDouble(this)); } catch (IllegalAccessException e) { e.printStackTrace(); } return metricValues; }
Source:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int lastVisibleItem = firstVisibleItem + visibleItemCount; int size = getCards().size(); if ((size > 0) && (firstVisibleItem < size) && ((lastVisibleItem - 1) < size)) { String firstAns = getCards().get(firstVisibleItem).get("answer"); String lastAns = getCards().get(lastVisibleItem - 1).get("answer"); if (firstAns != null && "".equals(firstAns) || lastAns != null && lastAns.equals("")) { showProgressBar(); long currentTime = SystemClock.elapsedRealtime (); if ((currentTime - mLastRenderStart > 300 || lastVisibleItem >= totalItemCount)) { mLastRenderStart = currentTime; DeckTask.cancelTask(DeckTask.TASK_TYPE_RENDER_BROWSER_QA); DeckTask.launchDeckTask(DeckTask.TASK_TYPE_RENDER_BROWSER_QA, mRenderQAHandler, new DeckTask.TaskData(new Object[]{getCards(), firstVisibleItem, visibleItemCount})); } } } }

Target:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int lastVisibleItem = firstVisibleItem + visibleItemCount; int size = getCards().size(); if ((size > 0) && (firstVisibleItem < size) && ((lastVisibleItem - 1) < size)) { String firstAns = getCards().get(firstVisibleItem).get("answer"); String lastAns = getCards().get(lastVisibleItem - 1).get("answer"); if ("".equals(firstAns) || "".equals(lastAns)) { showProgressBar(); long currentTime = SystemClock.elapsedRealtime (); if ((currentTime - mLastRenderStart > 300 || lastVisibleItem >= totalItemCount)) { mLastRenderStart = currentTime; DeckTask.cancelTask(DeckTask.TASK_TYPE_RENDER_BROWSER_QA); DeckTask.launchDeckTask(DeckTask.TASK_TYPE_RENDER_BROWSER_QA, mRenderQAHandler, new DeckTask.TaskData(new Object[]{getCards(), firstVisibleItem, visibleItemCount})); } } } }
Source:
@Override public void error(@NonNull Throwable caught) { if (caught instanceof OfflineClient.OfflineException) { appendCard(new OfflineCard()); } requestNextCard(wiki); }

Target:
@Override public void error(@NonNull Throwable caught) { requestNextCard(wiki); }
Source:
private void filterIndexCheckerMutations(Map<TableInfo, List<Mutation>> mutationMap, Map<TableInfo, List<Mutation>> unverifiedIndexMutations, Map<TableInfo, List<Mutation>> verifiedOrDeletedIndexMutations) throws SQLException { Iterator<Entry<TableInfo, List<Mutation>>> mapIter = mutationMap.entrySet().iterator(); while (mapIter.hasNext()) { Entry<TableInfo, List<Mutation>> pair = mapIter.next(); TableInfo tableInfo = pair.getKey(); if (IndexUtil.isGlobalIndexCheckerEnabled(connection, tableInfo.getHTableName())) { PTable table = tableInfo.getOrigTableRef().getTable(); byte[] emptyCF = SchemaUtil.getEmptyColumnFamily(table); byte[] emptyCQ = EncodedColumnsUtil.getEmptyKeyValueInfo(table).getFirst(); List<Mutation> mutations = pair.getValue(); if (mutations.size() == 0) { continue; } for (Mutation m : mutations) { if (m instanceof Delete) { Put put = new Put(m.getRow()); put.addColumn(emptyCF, emptyCQ, m.getTimestamp(), IndexRegionObserver.UNVERIFIED_BYTES); addToMap(unverifiedIndexMutations, tableInfo, put); addToMap(verifiedOrDeletedIndexMutations, tableInfo, m); } else { addToMap(unverifiedIndexMutations, tableInfo, m); Put put = new Put(m.getRow()); put.addColumn(emptyCF, emptyCQ, m.getTimestamp(), IndexRegionObserver.VERIFIED_BYTES); addToMap(verifiedOrDeletedIndexMutations, tableInfo, put); } } mapIter.remove(); } } }

Target:
private void filterIndexCheckerMutations(Map<TableInfo, List<Mutation>> mutationMap, Map<TableInfo, List<Mutation>> unverifiedIndexMutations, Map<TableInfo, List<Mutation>> verifiedOrDeletedIndexMutations) throws SQLException { Iterator<Entry<TableInfo, List<Mutation>>> mapIter = mutationMap.entrySet().iterator(); while (mapIter.hasNext()) { Entry<TableInfo, List<Mutation>> pair = mapIter.next(); TableInfo tableInfo = pair.getKey(); if (IndexUtil.isGlobalIndexCheckerEnabled(connection, tableInfo.getHTableName())) { PTable table = tableInfo.getOrigTableRef().getTable(); byte[] emptyCF = SchemaUtil.getEmptyColumnFamily(table); byte[] emptyCQ = EncodedColumnsUtil.getEmptyKeyValueInfo(table).getFirst(); List<Mutation> mutations = pair.getValue(); for (Mutation m : mutations) { if (m == null) { continue; } if (m instanceof Delete) { Put put = new Put(m.getRow()); put.addColumn(emptyCF, emptyCQ, IndexRegionObserver.getMaxTimestamp(m), IndexRegionObserver.UNVERIFIED_BYTES); addToMap(unverifiedIndexMutations, tableInfo, put); addToMap(verifiedOrDeletedIndexMutations, tableInfo, m); } else if (m instanceof Put) { long timestamp = IndexRegionObserver.getMaxTimestamp(m); if (m.has(emptyCF, emptyCQ)) { ((Put) m).addColumn(emptyCF, emptyCQ, timestamp, IndexRegionObserver.UNVERIFIED_BYTES); addToMap(unverifiedIndexMutations, tableInfo, m); } else { Put unverifiedPut = new Put((Put)m); unverifiedPut.addColumn(emptyCF, emptyCQ, timestamp, IndexRegionObserver.UNVERIFIED_BYTES); addToMap(verifiedOrDeletedIndexMutations, tableInfo, unverifiedPut); } Put verifiedPut = new Put(m.getRow()); verifiedPut.addColumn(emptyCF, emptyCQ, timestamp, IndexRegionObserver.VERIFIED_BYTES); addToMap(verifiedOrDeletedIndexMutations, tableInfo, verifiedPut); } else { addToMap(unverifiedIndexMutations, tableInfo, m); } } mapIter.remove(); } } }
Source:
public static void validateClusterName(String clusterName) { if (clusterName == null) { throw new IllegalArgumentException("Invalid arguments, cluster name should not be null"); } if (clusterName.isEmpty()) { throw new IllegalArgumentException("Invalid arguments, cluster name should not be empty"); } Pattern clusterNamePtrn = Pattern.compile(CLUSTER_NAME_VALIDATION_REGEXP); Matcher mtch = clusterNamePtrn.matcher(clusterName); if(!mtch.matches()){ throw new IllegalArgumentException("Invalid arguments, cluster name should contains only alphabetical, numeric, '_' and '-' characters and length 1-100 characters"); } }

Target:
public static void validateClusterName(String clusterName) { if (clusterName == null) { throw new IllegalArgumentException("Invalid arguments, cluster name should not be null"); } if (clusterName.isEmpty()) { throw new IllegalArgumentException("Invalid arguments, cluster name should not be empty"); } Matcher mtch = CLUSTER_NAME_PTRN.matcher(clusterName); if(!mtch.matches()){ throw new IllegalArgumentException("Invalid arguments, cluster name should contains only alphabetical, numeric, '_' and '-' characters and length 1-100 characters"); } }
Source:
public String getVendor() { if (_vendor == null) { int[] mib = { SystemB.CTL_MACHDEP, SystemB.MACHDEP_CPU, SystemB.MACHDEP_CPU_VENDOR }; IntByReference size = new IntByReference(100); Pointer p = new Memory(size.getValue()); SystemB.INSTANCE.sysctl(mib, mib.length, p, size, null, 0); _vendor = p.getString(0); } return _vendor; }

Target:
public String getVendor() { if (_vendor == null) { int[] mib = { SystemB.CTL_MACHDEP, SystemB.MACHDEP_CPU, SystemB.MACHDEP_CPU_VENDOR }; IntByReference size = new IntByReference(); if (0 != SystemB.INSTANCE.sysctl(mib, mib.length, null, size, null, 0)) throw new LastErrorException("Error code: " + Native.getLastError()); Pointer p = new Memory(size.getValue() + 1); if (0 != SystemB.INSTANCE.sysctl(mib, mib.length, p, size, null, 0)) throw new LastErrorException("Error code: " + Native.getLastError()); _vendor = p.getString(0); } return _vendor; }
Source:
public SecretCreateResponse createSecret(final SecretSpec secret) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.25"); final WebTarget resource = resource().path("secrets").path("create"); try { return request(POST, SecretCreateResponse.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.json(secret)); } catch (final DockerRequestException ex) { switch (ex.status()) { case 406: throw new DockerException("Server not part of swarm.", ex); case 409: throw new ConflictException("Name conflicts with an existing object.", ex); default: throw ex; } } }

Target:
public SecretCreateResponse createSecret(final SecretSpec secret) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.25"); final WebTarget resource = resource().path("secrets").path("create"); try { return request(POST, SecretCreateResponse.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.json(secret)); } catch (final DockerRequestException ex) { switch (ex.status()) { case 406: throw new NonSwarmNodeException("Server not part of swarm.", ex); case 409: throw new ConflictException("Name conflicts with an existing object.", ex); default: throw ex; } } }
Source:
private Schema.Builder loadSchemaObject(JsonObject o) { Schema.Builder builder; if (ls.schemaJson().containsKey("enum")) { builder = buildEnumSchema(); } else if (ls.schemaJson().containsKey("const") && (config.specVersion != DRAFT_4)) { builder = buildConstSchema(); } else if (config.specVersion.compareTo(DRAFT_6) > 0 && schemaHasAnyOf(CONDITIONAL_SCHEMA_KEYWORDS)) { builder = buildConditionalSchema(); } else { builder = new CombinedSchemaLoader(ls, this).load() .orElseGet(() -> { if (!ls.schemaJson().containsKey("type") || ls.schemaJson().containsKey("$ref")) { return buildSchemaWithoutExplicitType(); } else { return loadForType(ls.schemaJson().require("type")); } }); } loadCommonSchemaProperties(builder); return builder; }

Target:
private Schema.Builder loadSchemaObject(JsonObject o) { Schema.Builder builder; if (ls.schemaJson().containsKey("enum")) { builder = buildEnumSchema(); } else if (ls.schemaJson().containsKey("const") && (config.specVersion != DRAFT_4)) { builder = buildConstSchema(); } else { builder = new CombinedSchemaLoader(ls, this).load() .orElseGet(() -> { if (!ls.schemaJson().containsKey("type") || ls.schemaJson().containsKey("$ref")) { return buildSchemaWithoutExplicitType(); } else { return loadForType(ls.schemaJson().require("type")); } }); } loadCommonSchemaProperties(builder); return builder; }
Source:
private int getNewTaskCount() { if (scheduledNodes.isEmpty()) { return 1; } double fullTasks = sourceTasksProvider.get().stream() .filter(task -> !task.getState().isDone()) .map(TaskStatus::isOutputBufferOverutilized) .mapToDouble(full -> full ? 1.0 : 0.0) .average().orElse(0.0); long writtenBytes = writerTasksProvider.get().stream() .map(TaskStatus::getPhysicalWrittenDataSize) .mapToLong(DataSize::toBytes) .sum(); if ((fullTasks >= 0.5) && (writtenBytes >= (writerMinSizeBytes * scheduledNodes.size()))) { return 1; } if (optimizedScaleWriterProducerBuffer) { double totalProducerBufferUtilization = sourceTasksProvider.get().stream() .filter(task -> !task.getState().isDone()) .mapToDouble(TaskStatus::getOutputBufferUtilization) .sum(); if (noMoreTaskScheduledRoundCount >= SCHEDULED_ROUND_REQUIRED_FOR_EQUILIBRIUM && totalProducerBufferUtilization >= scheduledNodes.size() * MAX_PRODUCER_BUFFER_UTILIZATION_TO_CONSUMER_RATIO && writtenBytes >= writerMinSizeBytes * scheduledNodes.size()) { return 1; } } return 0; }

Target:
private int getNewTaskCount() { if (scheduledNodes.isEmpty()) { return 1; } double fullTasks = sourceTasksProvider.get().stream() .filter(task -> !task.getState().isDone()) .map(TaskStatus::isOutputBufferOverutilized) .mapToDouble(full -> full ? 1.0 : 0.0) .average().orElse(0.0); long writtenBytes = writerTasksProvider.get().stream() .map(TaskStatus::getPhysicalWrittenDataSize) .mapToLong(DataSize::toBytes) .sum(); if ((fullTasks >= 0.5) && (writtenBytes >= (writerMinSizeBytes * scheduledNodes.size()))) { return 1; } if (optimizedScaleWriterProducerBuffer) { double totalProducerBufferUtilization = sourceTasksProvider.get().stream() .filter(task -> !task.getState().isDone()) .mapToDouble(TaskStatus::getOutputBufferUtilization) .sum(); if (totalProducerBufferUtilization >= scheduledNodes.size() && writtenBytes >= writerMinSizeBytes * scheduledNodes.size()) { return 1; } } return 0; }
Source:
public String getPropertyValue(String property){ String paramProperty = getParamProperty(property); if (!item.containsKey(paramProperty)) return null; Object value = item.get(paramProperty); if (value instanceof List<?>) { List<?> values = (List<?>)value; if (values.size() == 0) return null; String paramPropertyIndex = getPropertyValue(paramProperty + "id"); int propertyIndex = 0; if (!StringUtils.isEmpty(paramPropertyIndex)) { try { propertyIndex = Integer.parseInt(paramPropertyIndex); } catch (NumberFormatException e) { return null; } if (propertyIndex < 0 || propertyIndex >= values.size()) return null; } value = values.get(propertyIndex); } if (value == null) return null; return value.toString(); }

Target:
public String getPropertyValue(String property){ String paramProperty = getParamProperty(property); if (!item.containsKey(paramProperty)) return null; Object value = item.get(paramProperty); if (value instanceof List<?>) { List<?> values = (List<?>)value; if (values.size() == 0) return null; String paramPropertyIndex = getPropertyValue(paramProperty + "id"); int propertyIndex; if (!StringUtils.isEmpty(paramPropertyIndex)) { try { propertyIndex = Integer.parseInt(paramPropertyIndex); } catch (NumberFormatException e) { return null; } if (propertyIndex < 0 || propertyIndex >= values.size()) return null; } else { propertyIndex = 0; } value = values.get(propertyIndex); } if (value == null) return null; return value.toString(); }
Source:
public void indexMembers() throws InterruptedException { MassIndexer mi = Search.getFullTextEntityManager(em).createIndexer(Member.class); mi.startAndWait(); Search.getFullTextEntityManager(em).flushToIndexes(); }

Target:
public void indexMembers() throws InterruptedException { MassIndexer mi = Search.getFullTextEntityManager(em).createIndexer(Member.class); mi.startAndWait(); }
Source:
private boolean hasAcceptMessagePropertyEnabled(XmlCheckContext context, Node bean) { return hasAttributeValue(bean, "p:acceptMessagesWhileStopping") || hasPropertyAsChild(context, bean, acceptMessageWhileStoppingPropertyExpression); }

Target:
private boolean hasAcceptMessagePropertyEnabled(XmlCheckContext context, Node bean) { return hasAttributeValue(bean, "acceptMessagesWhileStopping") || hasPropertyAsChild(context, bean, acceptMessageWhileStoppingPropertyExpression); }
Source:
public List<? extends Certificate> getCertificateChain() { if (!isSecured()) { return null; } else { HttpsURLConnection conn = null; final List<X509Certificate> chain = new ArrayList<X509Certificate>(); try { SSLContext ctx; ctx = SSLContext.getInstance(SSL_PROTOCOL); ctx.init( null, new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } public void checkClientTrusted( X509Certificate[] certs, String authType ) { } public void checkServerTrusted( X509Certificate[] certs, String authType ) { for (X509Certificate cert : certs) { chain.add(cert); } } } }, null ); conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ctx.getSocketFactory()); conn.connect(); return chain; } catch (SSLHandshakeException e) { return chain; } catch (NoSuchAlgorithmException e) { handleException(VdcBllErrors.PROVIDER_FAILURE, e); } catch (KeyManagementException e) { handleException(VdcBllErrors.PROVIDER_FAILURE, e); } catch (IOException e) { handleException(VdcBllErrors.PROVIDER_FAILURE, e); } finally { if (conn != null) { conn.disconnect(); } } } return null; }

Target:
public List<? extends Certificate> getCertificateChain() { if (!isSecured()) { return null; } HttpsURLConnection conn = null; final List<X509Certificate> chain = new ArrayList<X509Certificate>(); try { SSLContext ctx; ctx = SSLContext.getInstance(SSL_PROTOCOL); ctx.init(null, createTrustManager(chain), null); conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ctx.getSocketFactory()); conn.connect(); return chain; } catch (SSLHandshakeException e) { return chain; } catch (NoSuchAlgorithmException e) { handleException(e); } catch (KeyManagementException e) { handleException(e); } catch (IOException e) { handleException(e); } finally { if (conn != null) { conn.disconnect(); } } return null; }
Source:
public void closeJob(GeneralSecurityException gse) { callback.onCompletion(new DecryptJobResult(blobId, null, null), gse); }

Target:
public void closeJob(GeneralSecurityException gse) { callback.onCompletion(null, gse); }
Source:
public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean hasSelection = (getSelectedItemPosition() >= 0); menu.findItem(MENU_ADD).setVisible(true); menu.findItem(MENU_EDIT).setVisible(hasSelection); menu.findItem(MENU_DELETE).setVisible(hasSelection); menu.findItem(MENU_DIAL).setVisible(hasSelection && carrierConfig.getBoolean("config_fdn_direct_dial")); return true; }

Target:
public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean hasSelection = (getSelectedItemPosition() >= 0); menu.findItem(MENU_ADD).setVisible(true); menu.findItem(MENU_EDIT).setVisible(hasSelection); menu.findItem(MENU_DELETE).setVisible(hasSelection); menu.findItem(MENU_DIAL).setVisible(hasSelection && mFdnDialDirectlySupported); return true; }