auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void defaultTunnelHandler(VirtualFile file, Response response) { try (InputStream in = file.createInputStream()) { if (in == null) { response.error(HttpResponseStatus.NOT_FOUND); return; } try (OutputStream out = response.outputStream(HttpResponseStatus.OK, MimeHelper.guessMimeType(file.name()))) { ByteStreams.copy(in, out); } } catch (IOException e) { response.error(HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); } }

Target:
private static void defaultTunnelHandler(VirtualFile file, Response response) { try (InputStream from = file.createInputStream()) { if (from == null) { response.error(HttpResponseStatus.NOT_FOUND); return; } try (OutputStream to = response.outputStream(HttpResponseStatus.OK, MimeHelper.guessMimeType(file.name()))) { ByteStreams.copy(from, to); } } catch (IOException e) { response.error(HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage()); } }
Source:
public void testModelTransformationFromAtoB() throws Exception { File watchfile1 = tempFolder.newFile("file1.csv"); File watchfile2 = tempFolder.newFile("file2.csv"); registerConnector("org.openengsb.domain.example.model.SourceModelA", watchfile1); registerConnector("org.openengsb.domain.example.model.SourceModelB", watchfile2); TransformationEngine transformationEngine = getOsgiService(TransformationEngine.class); ModelDescription modelDescriptionA = new ModelDescription(SourceModelA.class, "3.0.0.SNAPSHOT"); ModelDescription modelDescriptionB = new ModelDescription(SourceModelB.class, "3.0.0.SNAPSHOT"); TransformationDescription transfDescription = new TransformationDescription(modelDescriptionA, modelDescriptionB); transfDescription.forwardField("edbId", "edbId"); transfDescription.forwardField("name", "name"); transformationEngine.saveDescription(transfDescription); FileUtils.write(watchfile1, "\"foo\",\"bar\""); Thread.sleep(1500); String fileContents = FileUtils.readFileToString(watchfile2); assertThat(fileContents, is("\"foo\",\"bar\"")); }

Target:
public void testModelTransformationFromAtoB() throws Exception { TransformationEngine transformationEngine = getOsgiService(TransformationEngine.class); ModelDescription modelDescriptionA = new ModelDescription(SourceModelA.class, getExampleDomainVersion().toString()); ModelDescription modelDescriptionB = new ModelDescription(SourceModelB.class, getExampleDomainVersion().toString()); TransformationDescription transfDescription = new TransformationDescription(modelDescriptionA, modelDescriptionB); transfDescription.forwardField("edbId", "edbId"); transfDescription.forwardField("name", "name"); transformationEngine.saveDescription(transfDescription); File watchfile1 = tempFolder.newFile("file1.csv"); File watchfile2 = tempFolder.newFile("file2.csv"); registerConnector(SourceModelA.class.getName(), watchfile1); registerConnector(SourceModelB.class.getName(), watchfile2); getOsgiService(ExampleDomain.class, 30000L); Thread.sleep(5000); FileUtils.write(watchfile1, "foo,bar"); Thread.sleep(2000); String fileContents = FileUtils.readFileToString(watchfile2).trim(); assertThat(fileContents, is("foo,bar")); }
Source:
protected ILogData read(final long address, long readStartTime) { try { if (System.currentTimeMillis() - readStartTime < runtime.getParameters().getHoleFillTimeout().toMillis()) { return runtime.getAddressSpaceView().read(address, readOptions); } ReadOptions options = ReadOptions.builder() .ignoreTrim(readOptions.isIgnoreTrim()) .clientCachable(readOptions.isClientCachable()) .serverCachable(readOptions.isServerCachable()) .waitForHole(false) .build(); return runtime.getAddressSpaceView().read(address, options); } catch (TrimmedException te) { processTrimmedException(te); throw te; } }

Target:
protected ILogData read(final long address, long readStartTime) { try { if (System.currentTimeMillis() - readStartTime < runtime.getParameters().getHoleFillTimeout().toMillis()) { return runtime.getAddressSpaceView().read(address, readOptions); } ReadOptions options = readOptions.toBuilder() .waitForHole(false) .build(); return runtime.getAddressSpaceView().read(address, options); } catch (TrimmedException te) { processTrimmedException(te); throw te; } }
Source:
private void filterAsynchronousResponses(ArrayList<String> responses) throws ResponseException { for (String response : responses) { if (response.contains("HTTP/1.1 400")) { throw new ResponseException("ElasticSearch failed to add one or more documents!"); } } }

Target:
private void filterAsynchronousResponses(ArrayList<String> responses) throws ResponseException { for (String response : responses) { if (!(response.contains("HTTP/1.1 200") || response.contains("HTTP/1.1 201"))) { throw new ResponseException("ElasticSearch failed to add one or more documents! Reason: " + response); } } }
Source:
public int[] crc32(Context context) { for (int i = 0; i < SIZE; i++) { context.bb.rewind(); context.results[i] = U.calcCrc(context.bb, BUF_LEN); } return context.results; }

Target:
public int[] crc32(Context context) { for (int i = 0; i < SIZE; i++) { context.bb.rewind(); context.results[i] = FastCrc.calcCrc(context.bb, BUF_LEN); } return context.results; }
Source:
private void writeSavedConnectionResponse(HttpServletResponse response, DatabaseConfiguration savedConnection) throws IOException { Writer w = response.getWriter(); try { JsonGenerator writer = ParsingUtilities.mapper.getFactory().createGenerator(w); writer.writeStartObject(); writer.writeArrayFieldStart(DatabaseUtils.SAVED_CONNECTION_KEY); writer.writeStartObject(); String sanitizedConnName = Encode.forHtml(savedConnection.getConnectionName()); writer.writeStringField("connectionName", sanitizedConnName); writer.writeStringField("databaseType", savedConnection.getDatabaseType()); String sanitizedHost = Encode.forHtml(savedConnection.getDatabaseHost()); writer.writeStringField("databaseHost", sanitizedHost); writer.writeNumberField("databasePort", savedConnection.getDatabasePort()); String sanitizedDbName = Encode.forHtml(savedConnection.getDatabaseName()); writer.writeStringField("databaseName", sanitizedDbName); String dbPasswd = savedConnection.getDatabasePassword(); if(dbPasswd != null && !dbPasswd.isEmpty()) { dbPasswd = DatabaseUtils.decrypt(savedConnection.getDatabasePassword()); } writer.writeStringField("databasePassword", dbPasswd); writer.writeStringField("databaseSchema", savedConnection.getDatabaseSchema()); String sanitizedDbUser = Encode.forHtml(savedConnection.getDatabaseUser()); writer.writeStringField("databaseUser", sanitizedDbUser); logger.info("Input DB User:{}, SanitizedDbUser:{}", savedConnection.getDatabaseUser(), sanitizedDbUser); writer.writeEndObject(); writer.writeEndArray(); writer.writeEndObject(); writer.flush(); writer.close(); }finally { w.flush(); w.close(); } }

Target:
private void writeSavedConnectionResponse(HttpServletResponse response, DatabaseConfiguration savedConnection) throws IOException { Writer w = response.getWriter(); try { JsonGenerator writer = ParsingUtilities.mapper.getFactory().createGenerator(w); writer.writeStartObject(); writer.writeArrayFieldStart(DatabaseUtils.SAVED_CONNECTION_KEY); writer.writeStartObject(); writer.writeStringField("connectionName", savedConnection.getConnectionName()); writer.writeStringField("databaseType", savedConnection.getDatabaseType()); writer.writeStringField("databaseHost", savedConnection.getDatabaseHost()); writer.writeNumberField("databasePort", savedConnection.getDatabasePort()); writer.writeStringField("databaseName", savedConnection.getDatabaseName()); String dbPasswd = savedConnection.getDatabasePassword(); if(dbPasswd != null && !dbPasswd.isEmpty()) { dbPasswd = DatabaseUtils.decrypt(savedConnection.getDatabasePassword()); } writer.writeStringField("databasePassword", dbPasswd); writer.writeStringField("databaseSchema", savedConnection.getDatabaseSchema()); writer.writeStringField("databaseUser", savedConnection.getDatabaseUser()); writer.writeEndObject(); writer.writeEndArray(); writer.writeEndObject(); writer.flush(); writer.close(); }finally { w.flush(); w.close(); } }
Source:
public void testGenericImageExtraction() { org.atlasapi.media.entity.Series extractedGenericImage = extractor.extract(seriesWithGenericImage()); Image genericImage = Iterables.getOnlyElement(extractedGenericImage.getImages()); Assert.assertEquals("<LINK_0>", extractedGenericImage.getImage()); Assert.assertEquals(ImageType.GENERIC_IMAGE_CONTENT_ORIGINATOR, genericImage.getType()); }

Target:
public void testGenericImageExtraction() { org.atlasapi.media.entity.Series extractedGenericImage = extractor.extract(seriesWithGenericImage()); Image genericImage = Iterables.getOnlyElement(extractedGenericImage.getImages()); assertEquals("<LINK_0>", extractedGenericImage.getImage()); assertEquals(ImageType.GENERIC_IMAGE_CONTENT_ORIGINATOR, genericImage.getType()); }
Source:
protected boolean setAndValidateDiskProfiles() { Map<DiskImage, Guid> map = new HashMap<>(); if (diskInfoDestinationMap != null) { for (DiskImage diskImage : diskInfoDestinationMap.values()) { map.put(diskImage, diskImage.getStorageIds().get(0)); } } return validate(DiskProfileHelper.setAndValidateDiskProfiles(map)); }

Target:
protected boolean setAndValidateDiskProfiles() { if (diskInfoDestinationMap != null) { Map<DiskImage, Guid> map = new HashMap<>(); for (DiskImage diskImage : diskInfoDestinationMap.values()) { map.put(diskImage, diskImage.getStorageIds().get(0)); } return validate(DiskProfileHelper.setAndValidateDiskProfiles(map)); } return true; }
Source:
public void testSingleRollingFileFailedWrite1() { SingleHDFSExactlyOnceWriter writer = new SingleHDFSExactlyOnceWriter(); writer.setFilePath(testMeta.getDir()); writer.setMaxLength(4); writer.setAlwaysWriteToTmp(testMeta.writeToTmp); writer.setup(testMeta.testOperatorContext); writer.beginWindow(0); writer.input.put(0); writer.input.put(1); writer.input.put(2); writer.endWindow(); writer.beginWindow(1); writer.input.put(3); writer.input.put(4); writer.endWindow(); AbstractFileOutputOperator checkPointWriter = checkpoint(writer, 0); AbstractFileOutputOperator checkPointWriter1 = checkpoint(writer, -1); LOG.debug("Checkpoint endOffsets={}", checkPointWriter.endOffsets); writer.beginWindow(2); writer.input.put(5); writer.teardown(); restoreCheckPoint(checkPointWriter, writer); LOG.debug("Checkpoint endOffsets={}", checkPointWriter.endOffsets); writer.setup(testMeta.testOperatorContext); writer.beginWindow(2); writer.input.put(5); writer.endWindow(); writer.beginWindow(3); writer.input.put(6); writer.input.put(7); writer.input.put(8); writer.endWindow(); writer.teardown(); restoreCheckPoint(checkPointWriter1, writer); writer.setup(testMeta.testOperatorContext); writer.committed(2); String singleFilePath = testMeta.getDir() + File.separator + SINGLE_FILE; String correctContents = "0\n" + "1\n" + "2\n"; checkOutput(0, singleFilePath, correctContents); correctContents = "3\n" + "4\n"; checkOutput(1, singleFilePath, correctContents); }

Target:
public void testSingleRollingFileFailedWrite1() { SingleHDFSExactlyOnceWriter writer = new SingleHDFSExactlyOnceWriter(); writer.setFilePath(testMeta.getDir()); writer.setMaxLength(4); writer.setAlwaysWriteToTmp(testMeta.writeToTmp); writer.setup(testMeta.testOperatorContext); writer.beginWindow(0); writer.input.put(0); writer.input.put(1); writer.input.put(2); writer.endWindow(); writer.beginWindow(1); writer.input.put(3); writer.input.put(4); writer.endWindow(); AbstractFileOutputOperator checkPointWriter = checkpoint(writer, Stateless.WINDOW_ID); AbstractFileOutputOperator checkPointWriter1 = checkpoint(writer, Stateless.WINDOW_ID); LOG.debug("Checkpoint endOffsets={}", checkPointWriter.endOffsets); writer.beginWindow(2); writer.input.put(5); writer.teardown(); restoreCheckPoint(checkPointWriter, writer); LOG.debug("Checkpoint endOffsets={}", checkPointWriter.endOffsets); writer.setup(testMeta.testOperatorContext); writer.beginWindow(2); writer.input.put(5); writer.endWindow(); writer.beginWindow(3); writer.input.put(6); writer.input.put(7); writer.input.put(8); writer.endWindow(); writer.teardown(); restoreCheckPoint(checkPointWriter1, writer); writer.setup(testMeta.testOperatorContext); writer.committed(2); String singleFilePath = testMeta.getDir() + File.separator + SINGLE_FILE; String correctContents = "0\n" + "1\n" + "2\n"; checkOutput(0, singleFilePath, correctContents); correctContents = "3\n" + "4\n"; checkOutput(1, singleFilePath, correctContents); }
Source:
public List<UserDeveloperMapDTO> getByDeveloperId(final Long developerId) { Query query = entityManager.createQuery( "from UserDeveloperMapEntity udm " + "join fetch udm.developer developer " + "join fetch udm.user u " + "join fetch u.permission perm " + "join fetch u.contact contact " + "where (udm.deleted != true) " + "AND (cb.id = :developerId) ", UserDeveloperMapEntity.class); query.setParameter("developerId", developerId); List<UserDeveloperMapEntity> result = query.getResultList(); List<UserDeveloperMapDTO> dtos = new ArrayList<UserDeveloperMapDTO>(); for (UserDeveloperMapEntity entity : result) { dtos.add(new UserDeveloperMapDTO(entity)); } return dtos; }

Target:
public List<UserDeveloperMapDTO> getByDeveloperId(final Long developerId) { Query query = entityManager.createQuery( "from UserDeveloperMapEntity udm " + "join fetch udm.developer developer " + "join fetch udm.user u " + "join fetch u.permission perm " + "join fetch u.contact contact " + "where (udm.deleted != true) " + "AND (developer.id = :developerId) ", UserDeveloperMapEntity.class); query.setParameter("developerId", developerId); List<UserDeveloperMapEntity> result = query.getResultList(); List<UserDeveloperMapDTO> dtos = new ArrayList<UserDeveloperMapDTO>(); for (UserDeveloperMapEntity entity : result) { dtos.add(new UserDeveloperMapDTO(entity)); } return dtos; }
Source:
public void testGetAnalysisRequirements() { Iterable<TmfAnalysisRequirement> requirements = fUstAnalysisModule.getAnalysisRequirements(); assertNotNull(requirements); TmfAnalysisRequirement eventReq = null; TmfAnalysisRequirement domainReq = null; int numberOfRequirement = 0; for (TmfAnalysisRequirement requirement : requirements) { ++numberOfRequirement; if (requirement.getType().equals(SessionConfigStrings.CONFIG_ELEMENT_EVENT)) { eventReq = requirement; } else if (requirement.getType().equals(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN)) { domainReq = requirement; } } assertNotNull(eventReq); assertNotNull(domainReq); assertEquals(2, numberOfRequirement); assertEquals(1, domainReq.getValues().size()); for (String domain : domainReq.getValues()) { assertEquals(SessionConfigStrings.CONFIG_DOMAIN_TYPE_UST, domain); } String[] events = { UstMemoryStrings.MALLOC, UstMemoryStrings.FREE, UstMemoryStrings.CALLOC, UstMemoryStrings.REALLOC, UstMemoryStrings.MEMALIGN, UstMemoryStrings.POSIX_MEMALIGN }; List<String> expectedEvents = Arrays.asList(events); assertEquals(6, eventReq.getValues().size()); for (String event : eventReq.getValues()) { assertTrue("Unexpected event " + event, expectedEvents.contains(event)); } Set<String> infos = eventReq.getInformation(); assertEquals(2, infos.size()); }

Target:
public void testGetAnalysisRequirements() { Iterable<TmfAnalysisRequirement> requirements = fUstAnalysisModule.getAnalysisRequirements(); assertNotNull(requirements); assertTrue(requirements.iterator().hasNext()); TmfAnalysisRequirement eventReq = null; TmfAnalysisRequirement domainReq = null; int numberOfRequirement = 0; for (TmfAnalysisRequirement requirement : requirements) { ++numberOfRequirement; if (requirement.getType().equals(SessionConfigStrings.CONFIG_ELEMENT_EVENT)) { eventReq = requirement; } else if (requirement.getType().equals(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN)) { domainReq = requirement; } } assertNotNull(eventReq); assertNotNull(domainReq); assertEquals(2, numberOfRequirement); assertEquals(1, domainReq.getValues().size()); for (String domain : domainReq.getValues()) { assertEquals(SessionConfigStrings.CONFIG_DOMAIN_TYPE_UST, domain); } List<String> expectedEvents = ImmutableList.of( UstMemoryStrings.MALLOC, UstMemoryStrings.FREE, UstMemoryStrings.CALLOC, UstMemoryStrings.REALLOC, UstMemoryStrings.MEMALIGN, UstMemoryStrings.POSIX_MEMALIGN ); assertEquals(6, eventReq.getValues().size()); for (String event : eventReq.getValues()) { assertTrue("Unexpected event " + event, expectedEvents.contains(event)); } Set<String> infos = eventReq.getInformation(); assertEquals(2, infos.size()); }
Source:
void onShinyRecordTest() { checkTestPackageDependencies( new Command() { @Override public void execute() { String shinyAppPath = FilePathUtils.dirFromFile(docUpdateSentinel_.getPath()); if (fileType_.canKnitToHTML()) { shinyAppPath = docUpdateSentinel_.getPath(); } String code = "shinytest::recordTest(\"" + shinyAppPath + "\")"; events_.fireEvent(new SendToConsoleEvent(code, true)); } }, false ); }

Target:
void onShinyRecordTest() { checkTestPackageDependencies( new Command() { @Override public void execute() { String shinyAppPath = FilePathUtils.dirFromFile(docUpdateSentinel_.getPath()); if (fileType_.canKnitToHTML()) { shinyAppPath = docUpdateSentinel_.getPath(); } String code = "shinytest::recordTest(\"" + shinyAppPath.replace("\"", "\\\"") + "\")"; events_.fireEvent(new SendToConsoleEvent(code, true)); } }, false ); }
Source:
private Map<String, Object> contextWithSqlId(Map<String, Object> queryContext) { Map<String, Object> newContext = new HashMap<>(); if (queryContext != null) { newContext.putAll(queryContext); } newContext.putIfAbsent(PlannerContext.CTX_SQL_QUERY_ID, UUID.randomUUID().toString()); return newContext; }

Target:
private Map<String, Object> contextWithSqlId(Map<String, Object> queryContext) { Map<String, Object> newContext = new HashMap<>(); if (queryContext != null) { newContext.putAll(queryContext); } newContext.computeIfAbsent(PlannerContext.CTX_SQL_QUERY_ID, k -> UUID.randomUUID().toString()); return newContext; }
Source:
protected void prepareURLs() { UrlBuilder urlBuilder = new UrlBuilder(config.getEnv()); wikiURL = urlBuilder.getUrlForWiki(config.getWikiName()); wikiCorporateURL = urlBuilder.getUrlForWiki("wikia"); wikiCorpSetupURL = urlBuilder.getUrlForWiki("corp"); printProperties(); }

Target:
protected void prepareURLs() { urlBuilder = new UrlBuilder(config.getEnv()); wikiURL = urlBuilder.getUrlForWiki(config.getWikiName()); wikiCorporateURL = urlBuilder.getUrlForWiki("wikia"); printProperties(); }
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); ModelNode modelNode = context.readResourceFromRoot(address).getModel(); ModelNode configuredApplication = modelNode.get(ModelDescriptionConstants.CONFIGURED_APPLICATION); final ModelNode value = operation.require(VALUE); final ApplicationTypeConfigResource resource = (ApplicationTypeConfigResource)context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS); final ApplicationTypeConfig classification = resource.applicationType; classification.setConfiguredApplication(readValue(context, value, CONFIGURED_APPLICATION)); context.completeStep(new OperationContext.RollbackHandler() { @Override public void handleRollback(OperationContext context, ModelNode operation) { try { classification.setConfiguredApplication(readValue(context, configuredApplication, CONFIGURED_APPLICATION)); } catch (OperationFailedException e) { throw new RuntimeException(e); } } }); }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { final ModelNode value = operation.require(VALUE); final ApplicationTypeConfigResource resource = (ApplicationTypeConfigResource) context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS); final ModelNode modelNode = resource.getModel(); final ModelNode configuredApplication = modelNode.get(ModelDescriptionConstants.CONFIGURED_APPLICATION); final ApplicationTypeConfig classification = resource.applicationType; classification.setConfiguredApplication(readValue(context, value, CONFIGURED_APPLICATION)); context.completeStep(new OperationContext.RollbackHandler() { @Override public void handleRollback(OperationContext context, ModelNode operation) { try { classification.setConfiguredApplication(readValue(context, configuredApplication, CONFIGURED_APPLICATION)); } catch (OperationFailedException e) { throw new RuntimeException(e); } } }); }
Source:
public String getDefaultDunningCampaignCode() { String parameterDunningCampaignCode = ""; if (getParameterService().parameterExists(DunningCampaign.class, ArConstants.DEFAULT_DUNNING_CAMPAIGN_PARAMETER)) { parameterDunningCampaignCode = getParameterService().getParameterValueAsString(DunningCampaign.class, ArConstants.DEFAULT_DUNNING_CAMPAIGN_PARAMETER); } return parameterDunningCampaignCode; }

Target:
public String getDefaultDunningCampaignCode() { return getParameterService().getParameterValueAsString(DunningCampaign.class, ArConstants.DEFAULT_DUNNING_CAMPAIGN_PARAMETER,""); }
Source:
private static NetworkInterface findNetworkInterface() { Enumeration<NetworkInterface> interfaces; try { interfaces = NetworkInterface.getNetworkInterfaces(); } catch (final SocketException ex) { throw new HostException(ex); } List<NetworkInterface> validNetworkInterfaces = new LinkedList<>(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (ignoreNetworkInterface(networkInterface)) { continue; } validNetworkInterfaces.add(networkInterface); } NetworkInterface networkInterface = null; for (NetworkInterface item : validNetworkInterfaces) { if (isPreferredNetworkInterface(item)) { networkInterface = item; break; } } if (networkInterface == null) { networkInterface = getFirstNetworkInterface(validNetworkInterfaces); } return networkInterface; }

Target:
private static NetworkInterface findNetworkInterface() { Enumeration<NetworkInterface> interfaces; try { interfaces = NetworkInterface.getNetworkInterfaces(); } catch (final SocketException ex) { throw new HostException(ex); } List<NetworkInterface> validNetworkInterfaces = new LinkedList<>(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (ignoreNetworkInterface(networkInterface)) { continue; } validNetworkInterfaces.add(networkInterface); } NetworkInterface result = null; for (NetworkInterface each : validNetworkInterfaces) { if (isPreferredNetworkInterface(each)) { result = each; break; } } if (null == result) { result = getFirstNetworkInterface(validNetworkInterfaces); } return result; }
Source:
public static String constrainLevel( RolapLevel level, SqlQuery query, RolapCube baseCube, AggStar aggStar, String[] columnValue, boolean caseSensitive) { RolapStar.Column column = null; if (level instanceof RolapCubeLevel) { column = ((RolapCubeLevel)level).getBaseStarKeyColumn(baseCube); } String columnString; Dialect.Datatype datatype; if (column != null) { if (column.getNameColumn() == null) { datatype = level.getDatatype(); } else { column = column.getNameColumn(); datatype = Dialect.Datatype.String; } if (aggStar != null) { int bitPos = column.getBitPosition(); AggStar.Table.Column aggColumn = aggStar.lookupColumn(bitPos); if(aggColumn == null){ LOG.warn("Aggregate table: A constraint will not be generated because name column is not the same as key column"); return ""; } columnString = aggColumn.generateExprString(query); } else { columnString = column.generateExprString(query); } } else { assert (aggStar == null); MondrianDef.Expression exp = level.getNameExp(); if (exp == null) { exp = level.getKeyExp(); datatype = level.getDatatype(); } else { datatype = Dialect.Datatype.String; } columnString = exp.getExpression(query); } String constraint; constraint = getColumnValueConstraint( query, columnValue, caseSensitive, columnString, datatype); return constraint; }

Target:
public static String constrainLevel( RolapLevel level, SqlQuery query, RolapCube baseCube, AggStar aggStar, String[] columnValue, boolean caseSensitive) { RolapStar.Column column = null; if (level instanceof RolapCubeLevel) { column = ((RolapCubeLevel)level).getBaseStarKeyColumn(baseCube); } String columnString; Dialect.Datatype datatype; if (column != null) { if (column.getNameColumn() == null) { datatype = level.getDatatype(); } else { column = column.getNameColumn(); datatype = Dialect.Datatype.String; } if (aggStar != null) { int bitPos = column.getBitPosition(); AggStar.Table.Column aggColumn = aggStar.lookupColumn(bitPos); if(aggColumn == null){ LOG.warn(mres.AggTableNoConstraintGenerated.str(aggStar.getFactTable().getName())); return ""; } columnString = aggColumn.generateExprString(query); } else { columnString = column.generateExprString(query); } } else { assert (aggStar == null); MondrianDef.Expression exp = level.getNameExp(); if (exp == null) { exp = level.getKeyExp(); datatype = level.getDatatype(); } else { datatype = Dialect.Datatype.String; } columnString = exp.getExpression(query); } String constraint; constraint = getColumnValueConstraint( query, columnValue, caseSensitive, columnString, datatype); return constraint; }
Source:
public void testKillArguments() { assertParseArgsThrows("Expected type of resource to kill.", "--kill"); assertParseArgsThrows("Expected compute task id.", "--kill", "compute"); assertParseArgsThrows("Invalid UUID string: not_a_uuid", IllegalArgumentException.class, "--kill", "compute", "not_a_uuid"); assertParseArgsThrows("Expected service name.", "--kill", "service"); assertParseArgsThrows("Expected transaction id.", "--kill", "tx"); assertParseArgsThrows("Expected SQL query id.", "--kill", "sql"); assertParseArgsThrows("Expected global query id. " + EXPECTED_GLOBAL_QRY_ID_FORMAT, "--kill", "sql", "not_sql_id"); }

Target:
public void testKillArguments() { assertParseArgsThrows("Expected type of resource to kill.", "--kill"); assertParseArgsThrows("Expected compute task id.", "--kill", "compute"); assertParseArgsThrows("Invalid UUID string: not_a_uuid", IllegalArgumentException.class, "--kill", "compute", "not_a_uuid"); assertParseArgsThrows("Expected service name.", "--kill", "service"); assertParseArgsThrows("Expected transaction id.", "--kill", "transaction"); assertParseArgsThrows("Expected SQL query id.", "--kill", "sql"); assertParseArgsThrows("Expected global query id. " + EXPECTED_GLOBAL_QRY_ID_FORMAT, "--kill", "sql", "not_sql_id"); }
Source:
private void checkInitialDB() throws IOException { assertThat(getWorkflows().size()).isEqualTo(0); assertThat(getTools().size()).isEqualTo(4); }

Target:
private void checkInitialDB() throws IOException { List<Workflow> currentWorkflows = getWorkflows(); assertThat(currentWorkflows.size()).isGreaterThanOrEqualTo(0); List<Tool> currentTools = getTools(); List<Tool> dockstore2Tools = currentTools.parallelStream().filter(tool -> tool.getNamespace().equals("dockstore2")) .collect(Collectors.toList()); List<Tool> dockstoretestuser2Tools = currentTools.parallelStream().filter(tool -> tool.getNamespace().equals("dockstoretestuser2")) .collect(Collectors.toList()); assertThat(dockstore2Tools.size()).isGreaterThanOrEqualTo(1); assertThat(dockstoretestuser2Tools.size()).isGreaterThanOrEqualTo(3); assertThat(currentTools.size()).isGreaterThanOrEqualTo(4); previousTools = currentTools; previousWorkflows = currentWorkflows; }
Source:
protected boolean set(Entity dataHolder, Integer value) { dataHolder.hurtResistantTime = value; if (dataHolder instanceof EntityLivingBase) ((EntityLivingBase) dataHolder).hurtTime = value; return true; }

Target:
protected boolean set(Entity dataHolder, Integer value) { dataHolder.hurtResistantTime = value; if (dataHolder instanceof EntityLivingBase) { ((EntityLivingBase) dataHolder).hurtTime = value; } return true; }
Source:
private static PropertyDescriptor[] getPropertiesHelper(Class type, boolean read, boolean write) { try { BeanInfo info = Introspector.getBeanInfo(type, Object.class); PropertyDescriptor[] all = info.getPropertyDescriptors(); if (read && write) { return all; } List properties = new ArrayList(all.length); for (int i = 0; i < all.length; i++) { PropertyDescriptor pd = all[i]; if ((read && pd.getReadMethod() != null) || (write && pd.getWriteMethod() != null)) { properties.add(pd); } } return (PropertyDescriptor[]) properties.toArray(new PropertyDescriptor[0]); } catch (IntrospectionException e) { throw new CodeGenerationException(e); } }

Target:
private static PropertyDescriptor[] getPropertiesHelper(Class type, boolean read, boolean write) { try { BeanInfo info = Introspector.getBeanInfo(type, Object.class); PropertyDescriptor[] all = info.getPropertyDescriptors(); if (read && write) { return all; } List properties = new ArrayList(all.length); for (int i = 0; i < all.length; i++) { PropertyDescriptor pd = all[i]; if ((read && pd.getReadMethod() != null) || (write && pd.getWriteMethod() != null)) { properties.add(pd); } } return (PropertyDescriptor[]) properties.toArray(new PropertyDescriptor[properties.size()]); } catch (IntrospectionException e) { throw new CodeGenerationException(e); } }
Source:
public Stock getStockForSymbol(String symbol) { if (stockList.containsKey(symbol)) { return stockList.get(symbol); } return null; }

Target:
public Stock getStockForSymbol(String symbol) { if (stockList.containsKey(symbol)) { return stockList.get(symbol); } throw new StockMarketExpection( "Tried to enter a key that is invalid (" + stock.getSymbol() + ")"); }
Source:
public void onMediaRetryClicked(String mediaId) { MediaModel media = mMediaStore.getMediaWithLocalId(Integer.valueOf(mediaId)); if (media == null) { AppLog.e(T.MEDIA, "Can't find media with local id: " + mediaId); return; } if (UploadState.valueOf(media.getUploadState()) == UploadState.UPLOADED) { if (mEditorMediaUploadListener != null) { mEditorMediaUploadListener.onMediaUploadSucceeded(String.valueOf(media.getId()), FluxCUtils.mediaFileFromMediaModel(media)); } } else { media.setUploadState(UploadState.QUEUED.name()); mDispatcher.dispatch(MediaActionBuilder.newUpdateMediaAction(media)); mPendingUploads.add(media); startMediaUploadService(); } AnalyticsTracker.track(Stat.EDITOR_UPLOAD_MEDIA_RETRIED); }

Target:
public void onMediaRetryClicked(String mediaId) { if (TextUtils.isEmpty(mediaId)) { AppLog.e(T.MEDIA, "Invalid media id passed to onMediaRetryClicked"); return; } MediaModel media = mMediaStore.getMediaWithLocalId(Integer.valueOf(mediaId)); if (media == null) { AppLog.e(T.MEDIA, "Can't find media with local id: " + mediaId); return; } if (UploadState.valueOf(media.getUploadState()) == UploadState.UPLOADED) { if (mEditorMediaUploadListener != null) { mEditorMediaUploadListener.onMediaUploadSucceeded(String.valueOf(media.getId()), FluxCUtils.mediaFileFromMediaModel(media)); } } else { media.setUploadState(UploadState.QUEUED.name()); mDispatcher.dispatch(MediaActionBuilder.newUpdateMediaAction(media)); mPendingUploads.add(media); startMediaUploadService(); } AnalyticsTracker.track(Stat.EDITOR_UPLOAD_MEDIA_RETRIED); }
Source:
public void insertRowsFromTsvFileWithHeader() { File dataFile = new File("src/test/resources/examples/dataWithHeader1.tsv"); TsvFileParser parser = new TsvFileParser().withHeader(true); String[] header = parser.parseHeader(dataFile); shell.insertInto("source_db", "test_table") .withColumns(header) .addRowsFrom(dataFile, parser) .commit(); printResult(shell.executeStatement("select * from source_db.test_table")); }

Target:
public void insertRowsFromTsvFileWithHeader() { File dataFile = new File("src/test/resources/examples/dataWithHeader1.tsv"); TsvFileParser parser = new TsvFileParser().withHeader(); shell.insertInto("source_db", "test_table") .addRowsFrom(dataFile, parser) .commit(); printResult(shell.executeStatement("select * from source_db.test_table")); }
Source:
public void run() { while(keepRunning) { try { List<String> messages = Lists.newArrayList(); Set<ObjectName> beans = server.queryNames(null, null); for(ObjectName name : beans) { String item = objectMapper.writeValueAsString(name); Broadcast broadcast = null; if(name.getKeyPropertyList().get("type") != null) { if (name.getKeyPropertyList().get("type").equals("ThroughputQueue")) { broadcast = objectMapper.readValue(item, ThroughputQueueBroadcast.class); } else if (name.getKeyPropertyList().get("type").equals("StreamsTaskCounter")) { broadcast = objectMapper.readValue(item, StreamsTaskCounterBroadcast.class); } else if (name.getKeyPropertyList().get("type").equals("DatumStatusCounter")) { broadcast = objectMapper.readValue(item, DatumStatusCounterBroadcast.class); } else if (name.getKeyPropertyList().get("type").equals("Memory")) { broadcast = objectMapper.readValue(item, MemoryUsageBroadcast.class); } if(broadcast != null) { messages.add(objectMapper.writeValueAsString(broadcast)); } } } messagePersister.persistMessages(messages); Thread.sleep(DEFAULT_WAIT_TIME); } catch (InterruptedException e) { LOGGER.error("Interrupted!: {}", e); } catch (Exception e) { LOGGER.error("Exception: {}", e); } } }

Target:
public void run() { while(keepRunning) { try { List<String> messages = Lists.newArrayList(); Set<ObjectName> beans = server.queryNames(null, null); for(ObjectName name : beans) { String item = objectMapper.writeValueAsString(name); Broadcast broadcast = null; if(name.getKeyPropertyList().get("type") != null) { if (name.getKeyPropertyList().get("type").equals("ThroughputQueue")) { broadcast = objectMapper.readValue(item, ThroughputQueueBroadcast.class); } else if (name.getKeyPropertyList().get("type").equals("StreamsTaskCounter")) { broadcast = objectMapper.readValue(item, StreamsTaskCounterBroadcast.class); } else if (name.getKeyPropertyList().get("type").equals("DatumStatusCounter")) { broadcast = objectMapper.readValue(item, DatumStatusCounterBroadcast.class); } else if (name.getKeyPropertyList().get("type").equals("Memory")) { broadcast = objectMapper.readValue(item, MemoryUsageBroadcast.class); } if(broadcast != null) { messages.add(objectMapper.writeValueAsString(broadcast)); } } } messagePersister.persistMessages(messages); Thread.sleep(waitTime); } catch (InterruptedException e) { LOGGER.error("Interrupted!: {}", e); } catch (Exception e) { LOGGER.error("Exception: {}", e); } } }
Source:
public void verifyAnswerableForStudent(FeedbackQuestionAttributes feedbackQuestionAttributes) { verifyNotNull(feedbackQuestionAttributes, "feedback session's course ID"); if (feedbackQuestionAttributes.getGiverType() != FeedbackParticipantType.STUDENTS && feedbackQuestionAttributes.getGiverType() != FeedbackParticipantType.TEAMS) { throw new UnauthorizedAccessException("Feedback question is not answerable for students"); } }

Target:
public void verifyAnswerableForStudent(FeedbackQuestionAttributes feedbackQuestionAttributes) { verifyNotNull(feedbackQuestionAttributes, "feedback question"); if (feedbackQuestionAttributes.getGiverType() != FeedbackParticipantType.STUDENTS && feedbackQuestionAttributes.getGiverType() != FeedbackParticipantType.TEAMS) { throw new UnauthorizedAccessException("Feedback question is not answerable for students"); } }
Source:
private void startTransferThread() { try { final byte[] keyBytes = key.getBytes("UTF-8"); Runnable transferFromQueueToSystem = () -> { while (!Thread.currentThread().isInterrupted()) { try { sendEventToSystemProducer(logQueue.take()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { metrics.logMessagesErrors.inc(); log.error("Error sending " + getName() + " event to SystemProducer", t); } } }; transferThread = new Thread(transferFromQueueToSystem); transferThread.setDaemon(true); transferThread.setName("Samza " + getName() + " Producer " + transferThread.getName()); transferThread.start(); } catch (UnsupportedEncodingException e) { throw new SamzaException(String.format( "Container name: %s could not be encoded to bytes. %s cannot proceed.", key, getName()), e); } }

Target:
private void startTransferThread() { Runnable transferFromQueueToSystem = () -> { while (!Thread.currentThread().isInterrupted()) { try { sendEventToSystemProducer(logQueue.take()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { metrics.logMessagesErrors.inc(); System.err.println("Error sending " + getName() + " event to SystemProducer " + t); } } }; transferThread = new Thread(transferFromQueueToSystem); transferThread.setDaemon(true); transferThread.setName("Samza " + getName() + " Producer " + transferThread.getName()); transferThread.start(); }
Source:
public WatchPageObject unfollowArticle(String wikiURL) { String url = URLsContent.buildUrl(wikiURL, "title="+articleTitle.getText()); url = URLsContent.buildUrl(url, "&action=unwatch"); getUrl(url); return new WatchPageObject(driver); }

Target:
public WatchPageObject unfollowArticle(String wikiURL) { String url = URLsContent.buildUrl(wikiURL, "title=" + articleTitle.getText()); url = URLsContent.buildUrl(url, URLsContent.unfollowParameter); getUrl(url); return new WatchPageObject(driver); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubchainInfo that = (SubchainInfo) o; if (storageDomainId != null ? !storageDomainId.equals(that.storageDomainId) : that.storageDomainId != null) { return false; } if (imageGroupId != null ? !imageGroupId.equals(that.imageGroupId) : that.imageGroupId != null) { return false; } if (baseImageId != null ? !baseImageId.equals(that.baseImageId) : that.baseImageId != null) { return false; } if (topImageId != null ? !topImageId.equals(that.topImageId) : that.topImageId != null) { return false; } if (baseImageGeneration != null ? !baseImageGeneration.equals(that.baseImageGeneration) : that.baseImageGeneration != null) { return false; } if (baseImage != null ? !baseImage.equals(that.baseImage) : that.baseImage != null) { return false; } return topImage != null ? topImage.equals(that.topImage) : that.topImage == null; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SubchainInfo that = (SubchainInfo) o; return Objects.equals(storageDomainId, that.storageDomainId) && Objects.equals(imageGroupId, that.imageGroupId) && Objects.equals(baseImageId, that.baseImageId) && Objects.equals(topImageId, that.topImageId) && Objects.equals(baseImageGeneration, that.baseImageGeneration) && Objects.equals(baseImage, that.baseImage) && Objects.equals(topImage, that.topImage); }
Source:
private void setAttribute() { ITmfStateSystemBuilder ss = (ITmfStateSystemBuilder) fContainer.getStateSystem(); int startingNodeQuark = fScenarioInfo.getQuark(); String subPath = ATTRIBUTE_PATH; int attributeQuark; try { attributeQuark = ss.getQuarkRelative(startingNodeQuark, subPath); } catch (AttributeNotFoundException e) { fAttribute = UUID.randomUUID().toString(); return; } ITmfStateValue sValue = ss.queryOngoingState(attributeQuark); fAttribute = NonNullUtils.nullToEmptyString(String.valueOf(sValue.unboxInt())); }

Target:
private void setAttribute() { ITmfStateSystemBuilder ss = (ITmfStateSystemBuilder) fContainer.getStateSystem(); int startingNodeQuark = fScenarioInfo.getQuark(); String subPath = ATTRIBUTE_PATH; int attributeQuark = ss.optQuarkRelative(startingNodeQuark, subPath); if (attributeQuark != ITmfStateSystem.INVALID_ATTRIBUTE) { fAttribute = UUID.randomUUID().toString(); } else { ITmfStateValue sValue = ss.queryOngoingState(attributeQuark); fAttribute = String.valueOf(sValue.unboxInt()); } }
Source:
public void init(LogFeederProps logFeederProps) { checkPointExtension = logFeederProps.getCheckPointExtension(); LOG.info("Determining valid checkpoint folder"); boolean isCheckPointFolderValid = false; checkPointFolder = logFeederProps.getCheckpointFolder(); if (!StringUtils.isEmpty(checkPointFolder)) { checkPointFolderFile = new File(checkPointFolder); isCheckPointFolderValid = verifyCheckPointFolder(checkPointFolderFile); } if (!isCheckPointFolderValid) { checkPointFolderFile = new File(logFeederProps.getTmpDir(), CHECKPOINT_SUBFOLDER_NAME); LOG.info("Checking if tmp folder can be used for checkpoints. Folder=" + checkPointFolderFile); isCheckPointFolderValid = verifyCheckPointFolder(checkPointFolderFile); if (isCheckPointFolderValid) { LOG.warn("Using tmp folder " + checkPointFolderFile + " to store check points. This is not recommended." + "Please set logfeeder.checkpoint.folder property"); } } if (isCheckPointFolderValid) { LOG.info("Using folder " + checkPointFolderFile + " for storing checkpoints"); Thread checkpointCleanupThread = new Thread(new CheckpointCleanupMonitor(this, 2000),"checkpoint_cleanup"); checkpointCleanupThread.setDaemon(true); checkpointCleanupThread.start(); } else { throw new IllegalStateException("Could not determine the checkpoint folder."); } }

Target:
public void init(LogFeederProps logFeederProps) { checkPointExtension = logFeederProps.getCheckPointExtension(); LOG.info("Determining valid checkpoint folder"); boolean isCheckPointFolderValid = false; String checkPointFolder = logFeederProps.getCheckpointFolder(); if (!StringUtils.isEmpty(checkPointFolder)) { checkPointFolderFile = new File(checkPointFolder); isCheckPointFolderValid = verifyCheckPointFolder(checkPointFolderFile); } if (!isCheckPointFolderValid) { checkPointFolderFile = new File(logFeederProps.getTmpDir(), CHECKPOINT_SUBFOLDER_NAME); LOG.info("Checking if tmp folder can be used for checkpoints. Folder=" + checkPointFolderFile); isCheckPointFolderValid = verifyCheckPointFolder(checkPointFolderFile); if (isCheckPointFolderValid) { LOG.warn("Using tmp folder " + checkPointFolderFile + " to store check points. This is not recommended." + "Please set logfeeder.checkpoint.folder property"); } } if (isCheckPointFolderValid) { LOG.info("Using folder " + checkPointFolderFile + " for storing checkpoints"); Thread checkpointCleanupThread = new Thread(new CheckpointCleanupMonitor(this, 2000),"checkpoint_cleanup"); checkpointCleanupThread.setDaemon(true); checkpointCleanupThread.start(); } else { throw new IllegalStateException("Could not determine the checkpoint folder."); } }
Source:
public void testBroadcastSerialDataReceiveSubscribedRx64() throws Exception { Mockito.when(rx64Packet.getReceiveOptions()).thenReturn(RECEIVE_OPTIONS_BROADCAST); dataReader.addSerialDatatReceiveListener(receiveSerialDataListener); Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, rx64Packet); PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_SERIAL_DATA_RECEIVED_METHOD, XBEE_64BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES, IS_BROADCAST_DATA); Mockito.verify(receiveSerialDataListener, Mockito.times(1)).broadcastSerialDataReceived(XBEE_64BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES); assertEquals(XBEE_64BIT_ADDRESS.toString(), receiveSerialDataListener.getAddress()); assertArrayEquals(RECEIVED_DATA_BYTES, receiveSerialDataListener.getSerialData()); }

Target:
public void testBroadcastSerialDataReceiveSubscribedRx64() throws Exception { Mockito.when(rx64Packet.getReceiveOptions()).thenReturn(RECEIVE_OPTIONS_BROADCAST); dataReader.addSerialDatatReceiveListener(receiveSerialDataListener); Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, rx64Packet); PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_SERIAL_DATA_RECEIVED_METHOD, XBEE_64BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES, IS_BROADCAST_DATA); Mockito.verify(receiveSerialDataListener, Mockito.times(1)).broadcastSerialDataReceived(XBEE_64BIT_ADDRESS.toString(), RECEIVED_DATA_BYTES); Mockito.verify(receiveSerialDataListener, Mockito.never()).serialDataReceived(Mockito.anyString(), (byte[])Mockito.any()); assertEquals(XBEE_64BIT_ADDRESS.toString(), receiveSerialDataListener.getAddress()); assertArrayEquals(RECEIVED_DATA_BYTES, receiveSerialDataListener.getSerialData()); }
Source:
public ExtensionInstanceList getInstances( @PathParam("job-name") final String jobName, @QueryParam("start") final String nominalStart, @QueryParam("end") final String nominalEnd, @DefaultValue("") @QueryParam("instanceStatus") String instanceStatus, @DefaultValue("") @QueryParam("fields") String fields, @DefaultValue("") @QueryParam("orderBy") String orderBy, @DefaultValue("") @QueryParam("sortOrder") String sortOrder, @DefaultValue("0") @QueryParam("offset") final Integer offset, @QueryParam("numResults") Integer resultsPerPage, @DefaultValue("") @QueryParam("doAs") String doAsUser) { LOG.error("instances is not supported on falcon extensions. Use falcon instance api on individual entities."); throw FalconWebException.newAPIException("instances is not supported on falcon extensions. Use falcon instance " + "api on individual entities."); }

Target:
public ExtensionInstanceList getInstances( @PathParam("job-name") final String jobName, @QueryParam("start") final String nominalStart, @QueryParam("end") final String nominalEnd, @DefaultValue("") @QueryParam("instanceStatus") String instanceStatus, @DefaultValue("") @QueryParam("fields") String fields, @DefaultValue("") @QueryParam("orderBy") String orderBy, @DefaultValue("") @QueryParam("sortOrder") String sortOrder, @DefaultValue("0") @QueryParam("offset") final Integer offset, @QueryParam("numResults") Integer resultsPerPage, @DefaultValue("") @QueryParam("doAs") String doAsUser) { LOG.error("instances is not supported on Falcon extensions. Use Falcon instance api on individual entities."); throw FalconWebException.newAPIException("instances is not supported on Falcon extensions. Use Falcon instance " + "api on individual entities."); }
Source:
public Mono<Response<Flux<ByteBuffer>>> download() { return this.download(null, null, false, null, null); }

Target:
public Mono<Response<Flux<ByteBuffer>>> download() { return this.download(null, null, false, null); }
Source:
public void shutdown() { stopped = true; deadWatchers.clear(); cleaners.stop(); super.interrupt(); }

Target:
public void shutdown() { stopped = true; deadWatchers.clear(); cleaners.stop(); this.interrupt(); if (LOG.isInfoEnabled()) { LOG.info("WatcherCleaner thread shutdown is initiated"); } }
Source:
public void resultReturned(int requestCode, int resultCode, Intent data) { if (requestCode == this.requestCode && resultCode == Activity.RESULT_OK) { if (data.hasExtra(RecognizerIntent.EXTRA_RESULTS)) { ArrayList<String> results = data.getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS); result = results.get(0); speechListener.onResult(result); } else { result = ""; } } }

Target:
public void resultReturned(int requestCode, int resultCode, Intent data) { if (requestCode == this.requestCode && resultCode == Activity.RESULT_OK) { if (data.hasExtra(RecognizerIntent.EXTRA_RESULTS)) { ArrayList<String> results = data.getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS); result = results.get(0); } else { result = ""; } speechListener.onResult(result); } }