auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void addAllMedia(List<Uri> mediaUris) { for (Uri mediaUri : mediaUris) { <START> if (mediaUri == null) { <END> Toast.makeText(EditPostActivity.this, getString(R.string.gallery_error), Toast.LENGTH_SHORT).show(); continue; } if (!addMedia(mediaUri)) { Toast.makeText(EditPostActivity.this, getResources().getText(R.string.gallery_error), Toast.LENGTH_SHORT).show(); } } }</code><technical_language>conditions show toast, this if (mediaUri == null || !addMedia(mediaUri))</technical_language>

Target:
private void addAllMedia(List<Uri> mediaUris) { boolean isErrorAddingMedia = false; for (Uri mediaUri : mediaUris) { if (mediaUri == null || !addMedia(mediaUri)) { isErrorAddingMedia = true; } } if (isErrorAddingMedia) { Toast.makeText(EditPostActivity.this, getResources().getText(R.string.gallery_error), Toast.LENGTH_SHORT).show(); } }
Source:
<code>private void getNoteByRevisionForCompare(NotebookSocket conn, Notebook notebook, Message fromMessage) throws IOException { String noteId = (String) fromMessage.get("noteId"); String revisionId = (String) fromMessage.get("revisionId"); String position = (String) fromMessage.get("position"); AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); Note revisionNote; if (revisionId.equals("Head")) { <START> revisionNote = notebook.loadNoteFromRepo(noteId, subject); <END> } else { revisionNote = notebook.getNoteByRevision(noteId, revisionId, subject); } conn.send(serializeMessage( new Message(OP.NOTE_REVISION_FOR_COMPARE).put("noteId", noteId) .put("revisionId", revisionId).put("position", position).put("note", revisionNote))); }</code><technical_language>for this case, i notebook.getNote(noteId) latest note in memory</technical_language>

Target:
private void getNoteByRevisionForCompare(NotebookSocket conn, Notebook notebook, Message fromMessage) throws IOException { String noteId = (String) fromMessage.get("noteId"); String revisionId = (String) fromMessage.get("revisionId"); String position = (String) fromMessage.get("position"); AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); Note revisionNote; if (revisionId.equals("Head")) { revisionNote = notebook.getNote(noteId); } else { revisionNote = notebook.getNoteByRevision(noteId, revisionId, subject); } conn.send(serializeMessage( new Message(OP.NOTE_REVISION_FOR_COMPARE).put("noteId", noteId) .put("revisionId", revisionId).put("position", position).put("note", revisionNote))); }
Source:
<code>public EventHubClient build() { this.configuration = this.configuration == null ? ConfigurationManager.getConfiguration().clone() : this.configuration; this.proxyConfiguration = constructDefaultProxyConfiguration(this.configuration); if (this.credentials == null) { <START> String connStr = this.configuration.get(AZURE_EVENT_HUB_CONNECTION_STRING); <END> this.credentials = new CredentialInfo(connStr); } if (this.duration == null) { this.duration = Duration.ofSeconds(5); } if (this.scheduler == null) { this.scheduler = Schedulers.elastic(); } return new EventHubClient(); }</code><technical_language>Is environment variable is set? if (ImplUtils.IsNullOrEmpty(connStr)) { // throw here. }</technical_language>

Target:
public EventHubClient build() { configuration = configuration == null ? ConfigurationManager.getConfiguration().clone() : configuration; if (credentials == null) { String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING); if (ImplUtils.isNullOrEmpty(connectionString)) { throw new IllegalArgumentException("Connection string is null or empty."); } credentials = CredentialInfo.from(connectionString); } if (timeout == null) { timeout = Duration.ofSeconds(60); } final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); final SharedAccessSignatureTokenProvider tokenProvider; try { tokenProvider = new SharedAccessSignatureTokenProvider(credentials.sharedAccessKeyName(), credentials.sharedAccessKey()); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new AzureException("Could not create token provider."); } if (retry == null) { retry = Retry.getDefaultRetry(); } proxyConfiguration = constructDefaultProxyConfiguration(configuration); if (scheduler == null) { scheduler = Schedulers.elastic(); } ConnectionParameters connectionParameters = new ConnectionParameters(credentials, timeout, tokenProvider, transport, retry, proxyConfiguration, scheduler); return new EventHubClient(connectionParameters, tokenProvider, provider, handlerProvider, scheduler); }
Source:
<code>public void setVisible(boolean visible) { if (visible) { <START> if (!isPage2Visited) { <END> this.modelName.setText(extractModelName(firstPage.getProjectName())); } isPage2Visited = visible; } super.setVisible(visible); }</code><technical_language>Wrong test: critetion test is page visible, wether user entered explicit file name</technical_language>

Target:
public void setVisible(boolean visible) { if (visible) { if (!isVsmNameChanged) { this.modelName.setText(extractModelName(firstPage.getProjectName())); } } super.setVisible(visible); }
Source:
<code>private String readJSONFile(File src) throws IOException { BufferedReader br = null; try { String line = null; StringBuilder builder = new StringBuilder(); br = new BufferedReader(new FileReader(src)); while ((line = br.readLine()) != null) { builder.append(line); } return builder.toString(); } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { <START> Timber.e(ex, "Exception thrown while closing an input stream due to: %s ", ex.getMessage()); <END> } } }</code><technical_language>While here, consider changing this a try-with-resources easier read Timber.e call</technical_language>

Target:
private String readJSONFile(File src) throws IOException { StringBuilder builder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(src))) { String line; while ((line = br.readLine()) != null) { builder.append(line); } return builder.toString(); } }
Source:
<code><START> public void doPostCleanup(BibEntry entry) { <END> new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()).cleanup(entry); new FieldFormatterCleanup(StandardField.URL, new ClearFormatter()).cleanup(entry); }</code><technical_language>This public</technical_language>

Target:
private void doPostCleanup(BibEntry entry) { new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()).cleanup(entry); new FieldFormatterCleanup(StandardField.URL, new ClearFormatter()).cleanup(entry); }
Source:
<code>protected Boolean doInBackground(Void... params) { if (mEditPostRepository.postHasEdits()) { mEditPostRepository.updateInTransaction(postModel -> { <START> updatePostContentNewEditor(postModel); <END> return true; }); mViewModel.savePostToDb(EditPostActivity.this, mEditPostRepository, mShowAztecEditor); ENDING`. This happens in this scenario: ENDING` ENDING`, the Post List will indefinitely show a “Queued post” ENDING` for WPCom because the app will automatically mDispatcher.dispatch(UploadActionBuilder.newCancelPostAction(mEditPostRepository.getEditablePost())); PendingDraftsNotificationsUtils .scheduleNextNotifications(EditPostActivity.this, mEditPostRepository.getId(), mEditPostRepository.getDateLocallyChanged()); } return true; }</code><technical_language>a bit confused, methods called updatePostContentNewEditor - in EPA in VM. Is intentional</technical_language>

Target:
protected Boolean doInBackground(Void... params) { if (mEditPostRepository.postHasEdits()) { mEditPostRepository.updateInTransaction(postModel -> { updatePostLocallyChangedOnStatusOrMediaChange(postModel); return true; }); mViewModel.savePostToDb(EditPostActivity.this, mEditPostRepository, mShowAztecEditor); ENDING`. This happens in this scenario: ENDING` ENDING`, the Post List will indefinitely show a “Queued post” ENDING` for WPCom because the app will automatically mDispatcher.dispatch(UploadActionBuilder.newCancelPostAction(mEditPostRepository.getEditablePost())); PendingDraftsNotificationsUtils .scheduleNextNotifications(EditPostActivity.this, mEditPostRepository.getId(), mEditPostRepository.getDateLocallyChanged()); } return true; }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SEARCH_REQUEST_ADD_A_LANGUAGE) { if (resultCode == Activity.RESULT_OK) { int position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); setUpLanguageScroll(position); if (app.language().getAppLanguageCodes().size() == 1) { <START> searchResultsFragment.startSearch(query, <END> query != null && query.length() > 1); } } } }</code><technical_language>reason for local startSearch() function here</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SEARCH_REQUEST_ADD_A_LANGUAGE) { if (resultCode == Activity.RESULT_OK) { int position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); setUpLanguageScroll(position); if (app.language().getAppLanguageCodes().size() == 1) { startSearch(query, query != null && query.length() > 1); } } } }
Source:
<code>public void testGeneratePartitions() { <START> Set<Set<Integer>> partitions = generatePartitions(4); <END> assertEquals(partitions, ImmutableSet.of( ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(0, 2), ImmutableSet.of(0, 3), ImmutableSet.of(0, 1, 2), ImmutableSet.of(0, 1, 3), ImmutableSet.of(0, 2, 3))); partitions = generatePartitions(3); assertEquals(partitions, ImmutableSet.of( ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(0, 2))); }</code><technical_language>inline</technical_language>

Target:
public void testGeneratePartitions() { assertEquals(generatePartitions(4), ImmutableSet.of( ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(0, 2), ImmutableSet.of(0, 3), ImmutableSet.of(0, 1, 2), ImmutableSet.of(0, 1, 3), ImmutableSet.of(0, 2, 3))); assertEquals(generatePartitions(3), ImmutableSet.of( ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(0, 2))); }
Source:
<code>private void registerListener() { if (!PlatformUI.isWorkbenchRunning()) { return; } final IWorkbench wb = PlatformUI.getWorkbench(); <START> final IWorkbenchPage activePage = wb.getActiveWorkbenchWindow().getActivePage(); <END> IViewPart view = activePage.findView(CriticalPathView.ID); if (view != null) { if (activePage.isPartVisible(view)) { toggleActive(true); } } view = activePage.findView(ControlFlowView.ID); if (view != null) { view.getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(fSelListener); view.getSite().getWorkbenchWindow().getPartService().addPartListener(fPartListener); } }</code><technical_language>For fix is enough. continues I get a null pointer exception in this line. Adding lines fixed for me: if ((wb == null) || (wb.getActiveWorkbenchWindow() == null)) { return; }</technical_language>

Target:
private void registerListener() { if (!PlatformUI.isWorkbenchRunning()) { return; } IWorkbench wb = PlatformUI.getWorkbench(); if (wb == null) { return; } IWorkbenchWindow wbw = wb.getActiveWorkbenchWindow(); if (wbw == null) { return; } final IWorkbenchPage activePage = wbw.getActivePage(); if (activePage == null) { return; } IViewPart view = activePage.findView(CriticalPathView.ID); if (view != null) { if (activePage.isPartVisible(view)) { toggleActive(true); } } view = activePage.findView(ControlFlowView.ID); if (view != null) { view.getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(fSelListener); view.getSite().getWorkbenchWindow().getPartService().addPartListener(fPartListener); } }
Source:
<code>public long getAbsSendTime(RawPacket pkt) { long absSendTime = -1L; HeaderExtension header = hasAbsoluteSendTimeExtension(pkt); if (header != null) { int offSet = header.getOffset() + 1; if (header.getExtLength() == EXT_LENGTH) { absSendTime = (header.getBuffer()[offSet] & 0xFF) << 16 | (header.getBuffer()[offSet + 1] & 0xFF) << 8 <START> | (header.getBuffer()[offSet + 2] & 0xFF); <END> } } return absSendTime; }</code><technical_language>RTPUtils.readUint24AsInt() utility</technical_language>

Target:
public long getAbsSendTime(RawPacket pkt) { long absSendTime = -1L; HeaderExtension header = getAbsoluteSendTimeExtension(pkt); if (header != null) { int offSet = header.getOffset() + 1; if (header.getExtLength() == EXT_LENGTH) { absSendTime = RTPUtils.readUint24AsInt(header.getBuffer(),offSet); } } return absSendTime; }
Source:
<code>public String format(Date date, String... args) { if (date == null) { return null; } String format; if (args.length > 0) { <START> format = args[0]; <END> } else { format = DEFAULT_FORMAT; } SimpleDateFormat sdf; try { sdf = new SimpleDateFormat(format); } catch (IllegalArgumentException e) { sdf = new SimpleDateFormat(DEFAULT_FORMAT); } return sdf.format(date); }</code><technical_language>important able a Locale</technical_language>

Target:
public String format( Date date, String... args ) { if( date == null ) { return ""; } if( args.length == 0 ) { throw new JGivenWrongUsageException( String.format( "A SimpleDateFormat pattern is expected as first argument" ) ); } String pattern = args[0]; Locale locale = Locale.getDefault(); if( args.length > 1 ) { locale = new Locale( args[1] ); } SimpleDateFormat sdf; try { sdf = new SimpleDateFormat( pattern, locale ); } catch( IllegalArgumentException e ) { throw new JGivenWrongUsageException( String.format( "A valid SimpleDateFormat pattern is expected (was '%s')", pattern ) ); } return sdf.format( date ); }
Source:
<code>public void executeBatch(OperationsQueue operationsQueue) { <START> log.tracef( "Executing batch" ); <END> try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } }</code><technical_language>move if body, execute batch...</technical_language>

Target:
public void executeBatch(OperationsQueue operationsQueue) { try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { log.tracef( "Executing batch" ); super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } }
Source:
<code>public static boolean waitFor(File file, int timeout) { long stopAt = System.currentTimeMillis() + timeout; while (!file.exists()) { if (System.currentTimeMillis() > stopAt) { return false; } try { Thread.sleep(100); } <START> catch (InterruptedException ignore) { <END> } catch (Exception ex) { break; } } return true; }</code><technical_language>ignore interrupted exception, in tests (at need call: Thread.currentThread().interrupt();)</technical_language>

Target:
public static boolean waitFor(File file, int timeout) { long stopAt = System.currentTimeMillis() + timeout; while (!file.exists()) { if (System.currentTimeMillis() > stopAt) { return false; } try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception ex) { break; } } return true; }
Source:
<code>public Optional<TableReference> chooseNextTableToSweep(Transaction tx, long conservativeSweepTs) { if (hasRemappedStreamStoreValueTable) { <START> Preconditions.checkState(previousStreamStoreValueTable != null, <END> "we should have set previousStreamStoreValueTable on the previous iteration"); hasRemappedStreamStoreValueTable = false; return Optional.of(previousStreamStoreValueTable); } Optional<TableReference> tableReferenceOptional = delegate.chooseNextTableToSweep(tx, conservativeSweepTs); if (!tableReferenceOptional.isPresent()) { return tableReferenceOptional; } TableReference tableReference = tableReferenceOptional.get(); if (!StreamTableType.isStreamStoreValueTable(tableReference)) { return Optional.of(tableReference); } previousStreamStoreValueTable = tableReference; hasRemappedStreamStoreValueTable = true; return Optional.of(StreamTableType.getIndexFromValue(tableReference)); }</code><technical_language>If this fails catch Exception retrying break loop. Check precondition if get a bad state reset everything</technical_language>

Target:
public Optional<TableReference> chooseNextTableToSweep(Transaction tx, long conservativeSweepTs) { if (hasRemappedStreamStoreValueTable) { hasRemappedStreamStoreValueTable = false; return Optional.of(previousStreamStoreValueTable); } Optional<TableReference> tableReferenceOptional = delegate.chooseNextTableToSweep(tx, conservativeSweepTs); if (!tableReferenceOptional.isPresent()) { return tableReferenceOptional; } TableReference tableReference = tableReferenceOptional.get(); if (!StreamTableType.isStreamStoreValueTable(tableReference)) { return Optional.of(tableReference); } previousStreamStoreValueTable = tableReference; hasRemappedStreamStoreValueTable = true; return Optional.of(StreamTableType.getIndexTableFromValueTable(tableReference)); }
Source:
<code>public Repository getRepository() { <START> return(repo); <END> }</code><technical_language>style: extra parentheses</technical_language>

Target:
public Repository getRepository() { return repo; }
Source:
<code>protected void obtainResource() throws Exception { <START> this.zkClient = new ZkClient(zkConnectString, 5000, 5000, new ZkStringSerializer()); <END> if (ZkUtils.getAllBrokersInCluster(zkClient).size() == 0) { throw new RuntimeException("Kafka server not available on localhost"); }; }</code><technical_language>Is checking zookeeper enough? In extension, I check zk kafka ports listening... <LINK_0> fast produce log garbage down</technical_language>

Target:
protected void obtainResource() throws Exception { try { this.zkClient = new ZkClient(zkConnectString, 5000, 5000, ZKStringSerializer$.MODULE$); if (ZkUtils.getAllBrokersInCluster(zkClient).size() == 0) { throw new RuntimeException("Kafka server not available on localhost"); } } catch (Exception e) { throw new RuntimeException("Issues connecting to ZK server"); } }
Source:
<code><START> public void onMomPolicyChange(@Observes @MomPolicyUpdate final MomPolicyUpdateParams policyParams) { <END> if (policyParams == null || policyParams.cluster == null || policyParams.allHostsInCluster == null) return; List<Callable<VDSReturnValue>> callables = new LinkedList<>(); for (final VDS vds : policyParams.allHostsInCluster) { if (vds.getStatus() == VDSStatus.Up) { callables.add(new Callable<VDSReturnValue>() { @Override public VDSReturnValue call() { return runUpdateMomPolicy(policyParams.cluster, vds); } }); } } if (callables.size() > 0) ThreadPoolUtil.invokeAll(callables); }</code><technical_language>TODO this event handling called in a separate thread. I need event async some infra glue code</technical_language>

Target:
public void onMomPolicyChange(@Observes @MomPolicyUpdate final MomPolicyUpdateParams policyParams) { if (policyParams == null || policyParams.cluster == null || policyParams.allHostsInCluster == null) return; List<Callable<VDSReturnValue>> callables = new LinkedList<>(); for (final VDS vds : policyParams.allHostsInCluster) { if (vds.getStatus() == VDSStatus.Up) { callables.add(new Callable<VDSReturnValue>() { @Override public VDSReturnValue call() { VDSReturnValue returnValue = new VDSReturnValue(); if (policyParams.cluster.getCompatibilityVersion().compareTo(Version.v3_4) >= 0) { try { returnValue = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.SetMOMPolicyParameters, new MomPolicyVDSParameters(vds, policyParams.cluster.isEnableBallooning(), policyParams.cluster.isEnableKsm(), policyParams.cluster.isKsmMergeAcrossNumaNodes()) ); } catch (VdcBLLException e) { log.error("Could not update MoM policy on host '{}'", vds.getName()); returnValue.setSucceeded(false); } } return returnValue; } }); } } if (callables.size() > 0) ThreadPoolUtil.invokeAll(callables); }
Source:
<code><START> private Map<String, Map<String, Map<String, String>>> getToolFromQuay(Tool tool) { <END> final String repo = tool.getNamespace() + '/' + tool.getName(); final String repoUrl = QUAY_URL + "repository/" + repo; final Optional<String> asStringBuilds = ResourceUtilities.asString(repoUrl, quayToken.getContent(), client); if (asStringBuilds.isPresent()) { final String json = asStringBuilds.get(); Gson gson = new Gson(); Map<String, Map<String, Map<String, String>>> map = new HashMap<>(); map = (Map<String, Map<String, Map<String, String>>>)gson.fromJson(json, map.getClass()); return map; } return null; }</code><technical_language>I necessarily change this for PR, I suggest habit of returning Optional a function return null. is clear in signature caller check if exists not</technical_language>

Target:
private Optional<Map<String, Map<String, Map<String, String>>>> getToolFromQuay(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final String repoUrl = QUAY_URL + "repository/" + repo; final Optional<String> asStringBuilds = ResourceUtilities.asString(repoUrl, quayToken.getContent(), client); if (asStringBuilds.isPresent()) { final String json = asStringBuilds.get(); Gson gson = new Gson(); Map<String, Map<String, Map<String, String>>> map = new HashMap<>(); map = (Map<String, Map<String, Map<String, String>>>)gson.fromJson(json, map.getClass()); return Optional.of(map); } return Optional.empty(); }
Source:
<code>private static URI createURI(List<Integer> proxyPorts) { Optional<String> reduce = proxyPorts.stream() .map(port -> "localhost:" + port) <START> .reduce((x1, x2) -> x1 + STRIPE_SEPARATOR + x2); <END> String uri = "terracotta://" + reduce.get(); return URI.create(uri); }</code><technical_language>do this instead. proxyPorts.stream() .map(port -> "localhost:" + port) .collect(Collectors.joining(",", "terracotta://", ""));</technical_language>

Target:
private static URI createURI(List<Integer> proxyPorts) { String uri = proxyPorts.stream() .map(port -> "localhost:" + port) .collect(Collectors.joining(",", "terracotta://", "")); return URI.create(uri); }
Source:
<code>void shouldNotFailOnDeleteByEntityWithNullVersion(@Autowired VersionedThingWithAssignedIdRepository repository) { try (Session session = driver.session()) { session.writeTransaction(tx -> { <START> tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume(); return null; <END> }); } VersionedThingWithAssignedId thing = repository.findById(1L).get(); repository.delete(thing); try (Session session = driver.session()) { long count = session.readTransaction(tx -> tx.run("MATCH (v:VersionedThingWithAssignedId) return count(v) as vCount").next() .get("vCount").asLong()); assertThat(count).isEqualTo(0); } }</code><technical_language>suggestion return tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume();</technical_language>

Target:
void shouldNotFailOnDeleteByEntityWithNullVersion(@Autowired VersionedThingWithAssignedIdRepository repository) { try (Session session = driver.session()) { session.writeTransaction(tx -> tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume()); } VersionedThingWithAssignedId thing = repository.findById(1L).get(); repository.delete(thing); try (Session session = driver.session()) { long count = session.readTransaction(tx -> tx.run("MATCH (v:VersionedThingWithAssignedId) return count(v) as vCount").next() .get("vCount").asLong()); assertThat(count).isEqualTo(0); } }
Source:
<code>private AuthenticationException onError(JwtException e) { <START> if (logger.isDebugEnabled()) { <END> logger.debug("Authentication error for Jwt Token: " + e.getMessage()); } if (e instanceof BadJwtException) { return new InvalidBearerTokenException(e.getMessage(), e); } else { return new AuthenticationServiceException(e.getMessage(), e); } }</code><technical_language>added benefit of this AuthenticationWebFilter displays information. Is necessary</technical_language>

Target:
private AuthenticationException onError(JwtException e) { if (e instanceof BadJwtException) { return new InvalidBearerTokenException(e.getMessage(), e); } else { return new AuthenticationServiceException(e.getMessage(), e); } }
Source:
<code>public void testInitializationTimestampForwardedToExecutionGraph() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); dispatcherGateway.submitJob(jobGraph, TIMEOUT).get(); CommonTestUtils.waitUntilCondition(() -> dispatcherGateway.requestJobStatus(jobGraph.getJobID(), TIMEOUT).get() == JobStatus.RUNNING, <START> Deadline.fromNow(Duration.of(10, ChronoUnit.SECONDS)), 5L); <END> ArchivedExecutionGraph result = dispatcher.requestJob(jobGraph.getJobID(), TIMEOUT).get(); assertThat(result.getStatusTimestamp(JobStatus.INITIALIZING), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.CREATED), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.RUNNING), greaterThan(0L)); }</code><technical_language>suggestion Deadline.fromNow(Duration.ofSeconds(10), 5L);</technical_language>

Target:
public void testInitializationTimestampForwardedToExecutionGraph() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); dispatcherGateway.submitJob(jobGraph, TIMEOUT).get(); CommonTestUtils.waitUntilCondition( () -> dispatcherGateway.requestJobStatus(jobGraph.getJobID(), TIMEOUT).get() == JobStatus.RUNNING, Deadline.fromNow(Duration.ofSeconds(10)), 5L); ArchivedExecutionGraph result = dispatcher.requestJob(jobGraph.getJobID(), TIMEOUT).get(); assertThat(result.getStatusTimestamp(JobStatus.INITIALIZING), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.CREATED), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.RUNNING), greaterThan(0L)); assertThat(result.getStatusTimestamp(JobStatus.INITIALIZING) <= result.getStatusTimestamp(JobStatus.CREATED), is(true)); }
Source:
<code>private static TypedResource extractTypedItems(XpathResourceXmlLoader.XmlNode xmlNode, ResType arrayResType, XmlLoader.XmlContext xmlContext) { final List<TypedResource> items = new ArrayList<>(); for (XpathResourceXmlLoader.XmlNode item : xmlNode.selectElements("item")) { final String itemString = item.getTextContent(); <START> ResType itemResType = null; <END> if (Pattern.matches("\\d+", itemString)) { itemResType = ResType.INTEGER; } else if (itemString.charAt(0) == '#') { itemResType = ResType.COLOR; } else if (itemString.contains("px") || itemString.contains("sp") || itemString.contains("dp")) { itemResType = ResType.DIMEN; } else if (Pattern.matches("\\d+.+?", itemString)) { itemResType = ResType.FLOAT; } else if (itemString.equals("true") || itemString.equals("false")) { itemResType = ResType.BOOLEAN; } else if (!(itemString.charAt(0) == '@' && itemString.contains("/"))) { itemResType = ResType.CHAR_SEQUENCE; } items.add(new TypedResource<>(itemString, itemResType, xmlContext)); } final TypedResource[] typedResources = items.toArray(new TypedResource[items.size()]); return new TypedResource<>(typedResources, arrayResType, xmlContext); }</code><technical_language>(some) code for inferring a type in ResType.inferType() I called, reuse perhaps</technical_language>

Target:
private static TypedResource extractTypedItems(XpathResourceXmlLoader.XmlNode xmlNode, ResType arrayResType, XmlLoader.XmlContext xmlContext) { final List<TypedResource> items = new ArrayList<>(); for (XpathResourceXmlLoader.XmlNode item : xmlNode.selectElements("item")) { final String itemString = item.getTextContent(); ResType itemResType = inferFromValue(itemString); if (itemResType == ResType.CHAR_SEQUENCE) { if (ResourceValue.isStyleReference(itemString)) { itemResType = ResType.STYLE; } else if (itemString.equals("@null")) { itemResType = ResType.NULL; } else if (ResourceValue.isResourceReference(itemString)) { itemResType = null; } } items.add(new TypedResource<>(itemString, itemResType, xmlContext)); } final TypedResource[] typedResources = items.toArray(new TypedResource[items.size()]); return new TypedResource<>(typedResources, arrayResType, xmlContext); }
Source:
<code>public void onMyLocationChange(@Nullable Location location) { WritableMap event = Arguments.createMap(); WritableMap src = Arguments.createMap(); if (location == null) { src.putString("message", "Could not get user location"); event.putMap("src", src); emitEvent("onLocateUserFailed", event); return; } src.putDouble("latitude", location.getLatitude()); src.putDouble("longitude", location.getLongitude()); src.putDouble("magneticHeading", location.getBearing()); src.putDouble("trueHeading", location.getBearing()); <START> src.putDouble("headingAccuracy", 10.0); <END> src.putBoolean("isUpdating", true); event.putMap("src", src); emitEvent("onUpdateUserLocation", event); }</code><technical_language>this hard coded 10.0</technical_language>

Target:
public void onMyLocationChange(@Nullable Location location) { WritableMap event = Arguments.createMap(); WritableMap src = Arguments.createMap(); if (location == null) { src.putString("message", "Could not get user location"); event.putMap("src", src); emitEvent("onLocateUserFailed", event); return; } src.putDouble("latitude", location.getLatitude()); src.putDouble("longitude", location.getLongitude()); if (location.hasAccuracy()) { src.putDouble("verticalAccuracy", location.getAccuracy()); src.putDouble("horizontalAccuracy", location.getAccuracy()); } GeomagneticField geoField = new GeomagneticField( (float)location.getLatitude(), (float)location.getLongitude(), location.hasAltitude() ? (float)location.getAltitude() : 0.0f, System.currentTimeMillis() ); src.putDouble("magneticHeading", location.getBearing()); src.putDouble("trueHeading", location.getBearing() + geoField.getDeclination()); event.putMap("src", src); emitEvent("onUpdateUserLocation", event); }
Source:
<code>public void moveWater() { if (this.sourceBlock != null) { if (this.sourceBlock.getWorld().equals(this.player.getWorld())) { this.targetDestination = getTargetLocation(this.player, this.range); if (this.targetDestination.distanceSquared(this.location) <= 1) { this.progressing = false; this.targetDestination = null; this.remove(); return; } else { this.progressing = true; this.settingUp = true; this.firstDestination = this.getToEyeLevel(); this.firstDirection = GeneralMethods.getDirection(this.sourceBlock.getLocation(), this.firstDestination).normalize(); this.targetDestination = GeneralMethods.getPointOnLine(this.firstDestination, this.targetDestination, this.range); this.targetDirection = GeneralMethods.getDirection(this.firstDestination, this.targetDestination).normalize(); if (isPlant(this.sourceBlock) || isSnow(this.sourceBlock)) { new PlantRegrowth(this.player, this.sourceBlock); <START> } else if (!isIce(this.sourceBlock)) { <END> addWater(this.sourceBlock); } } } this.bPlayer.addCooldown(this); } }</code><technical_language>I this is a leftover change previous, unincluded PlantRegrowth rewrite. stops plant sources set air utilized</technical_language>

Target:
public void moveWater() { if (this.sourceBlock != null) { if (this.sourceBlock.getWorld().equals(this.player.getWorld())) { this.targetDestination = getTargetLocation(this.player, this.range); if (this.targetDestination.distanceSquared(this.location) <= 1) { this.progressing = false; this.targetDestination = null; this.remove(); return; } else { this.progressing = true; this.settingUp = true; this.firstDestination = this.getToEyeLevel(); this.firstDirection = GeneralMethods.getDirection(this.sourceBlock.getLocation(), this.firstDestination).normalize(); this.targetDestination = GeneralMethods.getPointOnLine(this.firstDestination, this.targetDestination, this.range); this.targetDirection = GeneralMethods.getDirection(this.firstDestination, this.targetDestination).normalize(); if (isPlant(this.sourceBlock) || isSnow(this.sourceBlock)) { new PlantRegrowth(this.player, this.sourceBlock); this.sourceBlock.setType(Material.AIR); } else if (!isIce(this.sourceBlock)) { addWater(this.sourceBlock); } } } this.bPlayer.addCooldown(this); } }
Source:
<code>public void initialise( Properties userProps ) { final VersioningState vState = session.getState( VersioningState.class ); restURL = userProps.getProperty( "restURL" ); String repositoryGroup = userProps.getProperty( "restRepositoryGroup", "" ); int restMaxSize = Integer.parseInt( userProps.getProperty( "restMaxSize", "-1" ) ); int restMinSize = Integer.parseInt( userProps.getProperty( "restMinSize", String.valueOf( DefaultTranslator.CHUNK_SPLIT_COUNT ) ) ); restSuffixAlign = Boolean.parseBoolean( userProps.getProperty( "restSuffixAlign", "true" ) ); <START> restEndpoint = new DefaultTranslator( restURL, restMaxSize, restMinSize, repositoryGroup, vState.getIncrementalSerialSuffix(), session.getHeaders() ); <END> }</code><technical_language>I retrieve values user properties</technical_language>

Target:
public void initialise( Properties userProps ) { final VersioningState vState = session.getState( VersioningState.class ); restURL = userProps.getProperty( "restURL" ); String repositoryGroup = userProps.getProperty( "restRepositoryGroup", "" ); int restMaxSize = Integer.parseInt( userProps.getProperty( "restMaxSize", "-1" ) ); int restMinSize = Integer.parseInt( userProps.getProperty( "restMinSize", String.valueOf( DefaultTranslator.CHUNK_SPLIT_COUNT ) ) ); restSuffixAlign = Boolean.parseBoolean( userProps.getProperty( "restSuffixAlign", "true" ) ); String restHeadersProperty = userProps.getProperty( "restHeaders", "" ); if ( !StringUtils.isEmpty( restHeadersProperty ) ) { restHeaders = Arrays.stream( restHeadersProperty.split( "," ) ) .map( h -> h.split( ":", 2 ) ) .filter( h -> h.length > 0 && StringUtils.isNotEmpty( h[0] ) ) .collect( Collectors.toMap( h -> h[0], h -> h.length > 1 ? h[1] : "", ( x, y ) -> y, LinkedHashMap::new ) ); } restEndpoint = new DefaultTranslator( restURL, restMaxSize, restMinSize, repositoryGroup, vState.getIncrementalSerialSuffix(), restHeaders ); }
Source:
<code>private void writeTarget() throws TransferException { OutputStream out = null; if ( response != null ) { InputStream in = null; try { final HttpEntity entity = response.getEntity(); Header[] headers = response.getHeaders( "Content-Length" ); Collection<Integer> successStatuses = Collections.singleton( HttpStatus.SC_OK ); if ( headers[0] !=null && !headers[0].getValue().equals( "" )) { long contentLength = Long.parseLong( headers[0].getValue().toString() ); long targetLength = target.length(); <START> if ( contentLength != targetLength && successStatuses.contains( response.getStatusLine().getStatusCode() ) ) <END> { target.delete(); throw new TransferContentException( target.getResource(), "Target: %s's Content-Length mismatch (expected: %s, got: %s)", target.getFullPath(), contentLength, targetLength ); } } in = entity.getContent(); out = target.openOutputStream( TransferOperation.DOWNLOAD, true, eventMetadata, deleteFilesOnPath ); copy( in, out ); logger.info( "Ensuring all HTTP data is consumed..." ); EntityUtils.consume( entity ); logger.info( "All HTTP data was consumed." ); } catch ( final IOException e ) { throw new TransferException( "Failed to write to local proxy store: {}\nOriginal URL: {}. Reason: {}", e, target, url, e.getMessage() ); } finally { closeQuietly( in ); logger.info( "Closing output stream: {}", out ); closeQuietly( out ); } } }</code><technical_language>I *think* call writeTarget() a success status...in other words, checked for 200 status get here. If true, need check again, right</technical_language>

Target:
private void writeTarget() throws TransferException { OutputStream out = null; if ( response != null ) { InputStream in = null; try { final HttpEntity entity = response.getEntity(); in = entity.getContent(); out = target.openOutputStream( TransferOperation.DOWNLOAD, true, eventMetadata, deleteFilesOnPath ); copy( in, out ); logger.info( "Ensuring all HTTP data is consumed..." ); EntityUtils.consume( entity ); logger.info( "All HTTP data was consumed." ); closeQuietly( in ); closeQuietly( out ); long contentLength = transferSizes.get( target ); if ( contentLength > 0 ) { if ( contentLength != target.length() ) { target.delete(); throw new TransferContentException( target.getResource(), "Target: %s's Content-Length mismatch (expected: %s, got: %s)", target.getFullPath(), contentLength, target.length() ); } } } catch ( final IOException e ) { throw new TransferException( "Failed to write to local proxy store: {}\nOriginal URL: {}. Reason: {}", e, target, url, e.getMessage() ); } finally { closeQuietly( in ); logger.info( "Closing output stream: {}", out ); closeQuietly( out ); } } }
Source:
<code>private void checkCompletionContent(final Table completionProposalList) { <START> new DisplayHelper() { <END> @Override protected boolean condition() { return completionProposalList.getItemCount() == 1; } }.waitForCondition(completionProposalList.getDisplay(), 200); final TableItem computingItem = completionProposalList.getItem(0); assertTrue("Missing computing info entry", computingItem.getText().contains("Computing")); assertEquals(1, completionProposalList.getItemCount()); final TableItem quickAssistItem = completionProposalList.getItem(0); assertTrue("Missing quick assist proposal", quickAssistItem.getText().contains("fixme")); }</code><technical_language>Usually, good wrap "new DisplayHelper(...)" in assertTrue, assertTrue("No item found", new DisplayHelper() { ... }).waitForCondition(...));</technical_language>

Target:
private void checkCompletionContent(final Table completionProposalList) { assertTrue("No item found", new DisplayHelper() { @Override protected boolean condition() { return completionProposalList.getItemCount() == 1; } }.waitForCondition(completionProposalList.getDisplay(), 100)); assertEquals(1, completionProposalList.getItemCount()); final TableItem quickAssistItem = completionProposalList.getItem(0); assertTrue("Missing quick assist proposal", quickAssistItem.getText().contains("fixme")); }
Source:
<code>private DownloadError convertError(FilePersistenceResult status) { switch (status) { case ERROR_UNKNOWN_TOTAL_FILE_SIZE: return DownloadErrorFactory.createTotalSizeRequestFailedError(downloadFileId, url); case ERROR_INSUFFICIENT_SPACE: return DownloadErrorFactory.createInsufficientFreeSpaceError(downloadFileStatus); case ERROR_EXTERNAL_STORAGE_NON_WRITABLE: return DownloadErrorFactory.createStorageNotAvailableError(filePersistence); case ERROR_OPENING_FILE: return DownloadErrorFactory.createCannotWriteToFileError(downloadFileStatus); default: Logger.e("Status " + status + " missing to be processed"); break; } <START> return DownloadErrorFactory.createUnknownError(); <END> }</code><technical_language>this in default branch of switch</technical_language>

Target:
private DownloadError convertError(FilePersistenceResult status) { switch (status) { case ERROR_UNKNOWN_TOTAL_FILE_SIZE: return DownloadErrorFactory.createTotalSizeRequestFailedError(downloadFileId, url); case ERROR_INSUFFICIENT_SPACE: return DownloadErrorFactory.createInsufficientFreeSpaceError(downloadFileStatus); case ERROR_EXTERNAL_STORAGE_NON_WRITABLE: return DownloadErrorFactory.createStorageNotAvailableError(filePersistence); case ERROR_OPENING_FILE: return DownloadErrorFactory.createCannotWriteToFileError(downloadFileStatus); default: Logger.e("Status " + status + " missing to be processed"); return DownloadErrorFactory.createUnknownErrorFor(status); } }
Source:
<code>public MachineSet claim(int count, ReusableMachineTemplate t) { init(); synchronized (this) { <START> MachineSet mm = ensureUnclaimed(count, t); <END> Set<NodeMetadata> claiming = new LinkedHashSet<NodeMetadata>(); Iterator<NodeMetadata> mmi = mm.iterator(); for (int i=0; i<count; i++) claiming.add(mmi.next()); MachineSet result = new MachineSet(claiming); claimedMachines = claimedMachines.added(result); return result; } }</code><technical_language>Do want synchronize this while calling ensureUnclaimed? potentially create new machines, I presume minutes</technical_language>

Target:
public MachineSet claim(int count, ReusableMachineTemplate t) { init(); Set<NodeMetadata> claiming = new LinkedHashSet<NodeMetadata>(); while (claiming.size() < count) { MachineSet mm = ensureUnclaimed(count - claiming.size(), t); for (NodeMetadata m : mm) { synchronized (this) { if (!claimedMachines.contains(m)) { claiming.add(m); claimedMachines = claimedMachines.added(new MachineSet(m)); } } } } MachineSet result = new MachineSet(claiming); return result; }
Source:
<code>public void openDrawer(Side side) { <START> if (side==Side.RIGHT) { <END> rightDrawer.openDrawer(Gravity.END); } else if (side==Side.LEFT&&leftDrawer!=null) { if (isDrawerVisible(Side.RIGHT)) closeDrawer(Side.RIGHT); leftDrawer.openDrawer(Gravity.START); } openDrawer = side; }</code><technical_language>question here, null check is correct</technical_language>

Target:
public void openDrawer(Side side) { if (side==Side.RIGHT) { rightDrawer.openDrawer(Gravity.END); } else if (side==Side.LEFT&&leftDrawer!=null) { if (rightDrawer.isDrawerVisible(Gravity.END)) rightDrawer.closeDrawers(); leftDrawer.openDrawer(Gravity.START); } }
Source:
<code>public Cursor getImageAuthenticationCursor(final String imageUrl) { String downloadUrl = DatabaseUtils.sqlEscapeString(imageUrl); final String query = "" + "SELECT " + KEY_USERNAME + "," + KEY_PASSWORD + " FROM " + TABLE_NAME_FEED_ITEMS + " INNER JOIN " + TABLE_NAME_FEEDS <START> + " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + " = " + TABLE_NAME_FEEDS + "." + KEY_ID <END> + " WHERE " + TABLE_NAME_FEED_ITEMS + "." + KEY_IMAGE_URL + "=" + downloadUrl; return db.rawQuery(query, null); }</code><technical_language>Regression Image authentication: logic supports images of FeedItem, images of Feed</technical_language>

Target:
public Cursor getImageAuthenticationCursor(final String imageUrl) { String downloadUrl = DatabaseUtils.sqlEscapeString(imageUrl); final String query = "" + "SELECT " + KEY_USERNAME + "," + KEY_PASSWORD + " FROM " + TABLE_NAME_FEED_ITEMS + " INNER JOIN " + TABLE_NAME_FEEDS + " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + " = " + TABLE_NAME_FEEDS + "." + KEY_ID + " WHERE " + TABLE_NAME_FEED_ITEMS + "." + KEY_IMAGE_URL + "=" + downloadUrl + " UNION SELECT " + KEY_USERNAME + "," + KEY_PASSWORD + " FROM " + TABLE_NAME_FEEDS + " WHERE " + TABLE_NAME_FEEDS + "." + KEY_IMAGE_URL + "=" + downloadUrl; return db.rawQuery(query, null); }
Source:
<code><START> public void testSetscopedInstance_nonRoot() throws InterruptedException { <END> AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); app.getTomcat().getComponent().installerName( Constants.TARGET_INSTALLER ); Assert.assertNull( processor.scopedInstance ); processor.processMessage( new MsgCmdSetScopedInstance( app.getTomcat())); Assert.assertEquals( app.getTomcat(), processor.scopedInstance ); Assert.assertEquals( InstanceStatus.DEPLOYED_STARTED, processor.scopedInstance.getStatus()); Assert.assertEquals( "Expected a message for Tomcat and the WAR.", 1, this.client.messagesForAgents.size()); }</code><technical_language>No, this method throw interrupted exceptions</technical_language>

Target:
public void testSetscopedInstance_nonRoot() { AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); app.getTomcat().getComponent().installerName( Constants.TARGET_INSTALLER ); Assert.assertNull( processor.scopedInstance ); processor.processMessage( new MsgCmdSetScopedInstance( app.getTomcat())); Assert.assertEquals( app.getTomcat(), processor.scopedInstance ); Assert.assertEquals( InstanceStatus.DEPLOYED_STARTED, processor.scopedInstance.getStatus()); Assert.assertEquals( "Expected a message for Tomcat and the WAR.", 1, this.client.messagesForAgents.size()); }
Source:
<code>public void testTypeTypo() { Map<String, Object> greaterMap = ImmutableMap.<String, Object>of( <START> "type", "greaterThn", <END> "aggregation", "agg", "value", 1.3 ); ObjectMapper mapper = new DefaultObjectMapper(); HavingSpec spec = mapper.convertValue (greaterMap, HavingSpec.class); }</code><technical_language>type "nonExistingType" is clear IAE is expected</technical_language>

Target:
public void testTypeTypo() { Map<String, Object> greaterMap = ImmutableMap.<String, Object>of( "type", "nonExistingType", "aggregation", "agg", "value", 1.3 ); ObjectMapper mapper = new DefaultObjectMapper(); HavingSpec spec = mapper.convertValue (greaterMap, HavingSpec.class); }
Source:
<code><START> public String getAttributeValue(String property) { <END> switch (property) { case UserStoreConfigConstants.groupIDAttribute: return getUniqueGroupID(); case UserStoreConfigConstants.groupCreatedDateAttribute: case UserStoreConfigConstants.groupModifiedDateAttribute: Date createdTime = Calendar.getInstance().getTime(); return createdTime.toString(); default: return null; } }</code><technical_language>add a method description(java-doc) here</technical_language>

Target:
public static String getAttributeValue(String property) { switch (property) { case UserStoreConfigConstants.GROUP_ID_ATTRIBUTE: return getUniqueGroupID(); case UserStoreConfigConstants.GROUP_CREATED_DATE_ATTRIBUTE: case UserStoreConfigConstants.GROUP_MODIFIED_DATE_ATTRIBUTE: Date createdTime = Calendar.getInstance().getTime(); return createdTime.toString(); default: return null; } }
Source:
<code>private static String ssh(String keystore, String password, String alias) { String bReturn = null; FileInputStream input = null; try { KeyStore ks = KeyStore.getInstance("jks"); input = new FileInputStream(keystore); ks.load(input, password.toCharArray()); Key key = ks.getKey(alias, password.toCharArray()); if (key instanceof PrivateKey) { Certificate cert = ks.getCertificate(alias); key = cert.getPublicKey(); } RSAPublicKey publicKey = (RSAPublicKey) key; byte[] exponentBytes = publicKey.getPublicExponent().toByteArray(); byte[] modulusBytes = publicKey.getModulus().toByteArray(); ByteArrayOutputStream binaryOut = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(binaryOut); dataOut.write(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x07, (byte) 0x73, (byte) 0x73, (byte) 0x68, (byte) 0x2D, (byte) 0x72, (byte) 0x73, (byte) 0x61, }); <START> <END> int exponentLength = exponentBytes.length; boolean exponentPad = (exponentBytes[0] & 0x80) != 0; if (exponentPad) { exponentLength++; } dataOut.writeInt(exponentLength); if (exponentPad) { dataOut.write(0); } dataOut.write(exponentBytes); int modulusLength = modulusBytes.length; boolean modulusPad = (modulusBytes[0] & 0x80) != 0; if (modulusPad) { modulusLength++; } dataOut.writeInt(modulusLength); if (modulusPad) { dataOut.write(0); } dataOut.write(modulusBytes); binaryOut.close(); byte[] resultBytes = binaryOut.toByteArray(); Base64 encoder = new Base64(0); String encoding = encoder.encodeToString(resultBytes); bReturn = "ssh-rsa " + encoding + " " + alias; } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } return bReturn; }</code><technical_language>This part easier read if like: byte[] bData = "ssh-rsa".getBytes();</technical_language>

Target:
private static String ssh(String keystore, String password, String alias) { String bReturn = null; FileInputStream input = null; try { KeyStore ks = KeyStore.getInstance("jks"); input = new FileInputStream(keystore); ks.load(input, password.toCharArray()); Key key = ks.getKey(alias, password.toCharArray()); if (key instanceof PrivateKey) { Certificate cert = ks.getCertificate(alias); key = cert.getPublicKey(); } return OpenSSHUtils.getKeyString((PublicKey) key, alias); } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } return bReturn; }