auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void componentOpened() { ApplicationUtils.deleteTempFiles(); CompletionProvider provider = createCompletionProvider(); autoCompletion = new AutoCompletion(provider); autoCompletion.install(rSyntaxTextArea); ApplicationSettings.INSTANCE.registerSettingListeners(this); String initFileDir = (String) ApplicationSettings.Setting.USER_LASTFILE.getValue(); File initFile = new File(initFileDir); if(initFile.exists() && initFile.isFile()) { String content = FileService.readFromFile(initFileDir); setEditorContent(content); setCurrentFile(initFile); } else { InputStream is = null; try { is = getClass().getResource("/openlatexstudio/welcome.tex").openStream(); String welcomeMessage = IOUtils.toString(is); rSyntaxTextArea.setText(welcomeMessage); setDirty(true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } finally { IOUtils.closeQuietly(is); } } }

Target:
public void componentOpened() { ApplicationUtils.deleteTempFiles(); CompletionProvider provider = createCompletionProvider(); autoCompletion = new AutoCompletion(provider); autoCompletion.install(rSyntaxTextArea); ApplicationSettings.INSTANCE.registerSettingListeners(this); String initFileDir = (String) ApplicationSettings.Setting.USER_LASTFILE.getValue(); File initFile = new File(initFileDir); if(initFile.exists() && initFile.isFile()) { String content = FileService.readFromFile(initFileDir); setEditorContent(content); setCurrentFile(initFile); } else { InputStream is = null; try { is = getClass().getResource("/openlatexstudio/welcome.tex").openStream(); String welcomeMessage = IOUtils.toString(is); setEditorContent(welcomeMessage); } catch (IOException ex) { Exceptions.printStackTrace(ex); } finally { IOUtils.closeQuietly(is); } } }
Source:
public void completeQuery(UUID queryId, ElideResponse response) { if (!startTime.containsKey(queryId)) { return; } long endTime; long start; endTime = System.currentTimeMillis(); synchronized (this) { start = startTime.get(queryId); startTime.remove(queryId); } long timeElapsed = endTime - start; int responseCode = response.getResponseCode(); log.info("Completed Query with RequestId: " + queryId + ". Query Execution Time: " + timeElapsed + " Response Status: " + responseCode); }

Target:
public void completeQuery(UUID queryId, ElideResponse response) { long endTime = System.currentTimeMillis(); int responseCode = response.getResponseCode(); log.debug("Completed Query with RequestId: " + queryId + ". End Time: " + endTime + " Response Status: " + responseCode); }
Source:
public void getDataCenterList(AsyncQuery aQuery, boolean doRefresh) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { if (source == null) { return new ArrayList<StoragePool>(); } return source; } }; Frontend.getInstance().runQuery(VdcQueryType.Search, doRefresh ? new SearchParameters("DataCenter: sortby name", SearchType.StoragePool) : new SearchParameters("DataCenter: sortby name", SearchType.StoragePool).withoutRefresh(), aQuery); }

Target:
public void getDataCenterList(AsyncQuery aQuery, boolean doRefresh) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { if (source == null) { return new ArrayList<StoragePool>(); } return source; } }; SearchParameters params = new SearchParameters("DataCenter: sortby name", SearchType.StoragePool); Frontend.getInstance().runQuery(VdcQueryType.Search, doRefresh ? params : params.withoutRefresh(), aQuery); }
Source:
public ProbeStatus run() { boolean started; if (started = TransactionHelper.isNoTransaction()) { TransactionHelper.startTransaction(); } try { List<String> repositories = getRepositoryName(); boolean success = !repositories.isEmpty(); for (String repository : repositories) { success = success && CoreInstance.doPrivileged(repository, (CoreSession session) -> { return session.exists(session.getRootDocument().getRef()); }); } if (success) { return ProbeStatus.newSuccess("Repository started"); } return ProbeStatus.newFailure("Repository not started corectly"); } finally { if (started) { TransactionHelper.commitOrRollbackTransaction(); } } }

Target:
public ProbeStatus run() { ProbeStatus status; status = TransactionHelper.runInTransaction(() -> { List<String> repositories = getRepositoryName(); boolean success = !repositories.isEmpty(); for (String repository : repositories) { success = success && CoreInstance.doPrivileged(repository, (CoreSession session) -> { return session.exists(session.getRootDocument().getRef()); }); } if (success) { return ProbeStatus.newSuccess("Repository started"); } else { return ProbeStatus.newFailure("Repository not started corectly"); } }); return status; }
Source:
public boolean equals(Object obj) { if (obj instanceof SecureStoreData) { SecureStoreData o = (SecureStoreData) obj; return storeName.equals(o.storeName); } return super.equals(obj); }

Target:
public boolean equals(Object obj) { if (obj instanceof SecureStoreData) { SecureStoreData o = (SecureStoreData) obj; return storeName.equals(o.storeName); } return false; }
Source:
protected RequestStatus abortRequestById(RequestExecution requestExecution, Long requestId) throws AmbariException { LOG.debug("Aborting request " + requestId); ResourceProvider provider = ambariContext.getClusterController().ensureResourceProvider(Resource.Type.Request); Map<String, Object> properties = new HashMap<>(); properties.put(RequestResourceProvider.REQUEST_CLUSTER_NAME_PROPERTY_ID, requestExecution.getClusterName()); properties.put(RequestResourceProvider.REQUEST_ABORT_REASON_PROPERTY_ID, "Request execution status changed to " + requestExecution.getStatus()); properties.put(RequestResourceProvider.REQUEST_ID_PROPERTY_ID, Long.toString(requestId)); properties.put(RequestResourceProvider.REQUEST_STATUS_PROPERTY_ID, HostRoleStatus.ABORTED.name()); org.apache.ambari.server.controller.spi.Request request = new RequestImpl(Collections.emptySet(), Collections.singleton(properties), Collections.emptyMap(), null); Predicate predicate = new PredicateBuilder() .property(RequestResourceProvider.REQUEST_CLUSTER_NAME_PROPERTY_ID) .equals(requestExecution.getClusterName()).and() .property(RequestResourceProvider.REQUEST_ID_PROPERTY_ID) .equals(Long.toString(requestId)).toPredicate(); try{ return provider.updateResources(request, predicate); } catch (Exception e) { throw new AmbariException("Error while aborting the request.", e); } }

Target:
protected RequestStatus abortRequestById(RequestExecution requestExecution, Long requestId) throws AmbariException { LOG.debug("Aborting request " + requestId); ResourceProvider provider = AbstractControllerResourceProvider.getResourceProvider(Resource.Type.Request); Map<String, Object> properties = new HashMap<>(); properties.put(RequestResourceProvider.REQUEST_CLUSTER_NAME_PROPERTY_ID, requestExecution.getClusterName()); properties.put(RequestResourceProvider.REQUEST_ABORT_REASON_PROPERTY_ID, "Request execution status changed to " + requestExecution.getStatus()); properties.put(RequestResourceProvider.REQUEST_ID_PROPERTY_ID, Long.toString(requestId)); properties.put(RequestResourceProvider.REQUEST_STATUS_PROPERTY_ID, HostRoleStatus.ABORTED.name()); org.apache.ambari.server.controller.spi.Request request = new RequestImpl(Collections.emptySet(), Collections.singleton(properties), Collections.emptyMap(), null); Predicate predicate = new PredicateBuilder() .property(RequestResourceProvider.REQUEST_CLUSTER_NAME_PROPERTY_ID) .equals(requestExecution.getClusterName()).and() .property(RequestResourceProvider.REQUEST_ID_PROPERTY_ID) .equals(Long.toString(requestId)).toPredicate(); try{ return provider.updateResources(request, predicate); } catch (Exception e) { throw new AmbariException("Error while aborting the request.", e); } }
Source:
public SeatmapResponse getAllSeats() { List<Seat> all = seatRespository.findAll(); Map<String, List<Seat>> seatMapResponse = new HashMap<>(); for (Seat seat : all) { if (seatMapResponse.containsKey(seat.getSeatGroup())) { seatMapResponse.get(seat.getSeatGroup()).add(seat); } else { List<Seat> seats = new ArrayList<>(); seats.add(seat); seatMapResponse.put(seat.getSeatGroup(), seats); } } return new SeatmapResponse(seatMapResponse); }

Target:
public SeatmapResponse getAllSeats() { List<Seat> all = seatRepository.findAll(); Map<String, List<Seat>> seatMapGroups = all.stream().collect(Collectors.groupingBy(Seat::getSeatGroup)); return new SeatmapResponse(seatMapGroups); }
Source:
public Path getFileName() { int index = pathString.lastIndexOf(SEPARATOR); if (index == -1) { return new Path(pathString); } else { if(index == pathString.length() - 1) { return null; } else { return new Path(pathString.substring(index + 1)); } } }

Target:
public Path getFileName() { int index = pathString.lastIndexOf(SEPARATOR); if (index == -1) { return new Path(pathString); } else { if(index == pathString.length() - 1) { if (index == 0) { return null; } else { int secondLastIndex = pathString.lastIndexOf(SEPARATOR, index - 1); return new Path(pathString.substring(secondLastIndex + 1, index)); } } else { return new Path(pathString.substring(index + 1)); } } }
Source:
public boolean isChildPolicyAllowed(SchedulingPolicy childPolicy) throws AllocationConfigurationException { return true; }

Target:
public boolean isChildPolicyAllowed(SchedulingPolicy childPolicy) { return true; }
Source:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("imageTicket", ticket.getOps()) .append("size", ticket.getSize()) .append("url", ticket.getUrl()) .append("filename", ticket.getFilename()) .append("sparse", ticket.isSparse()) .append("transferId", Guid.createGuidFromString(ticket.getTransferId())) .append("dirty", ticket.isDirty()); }

Target:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("operations", ticket.getOps()) .append("size", ticket.getSize()) .append("url", ticket.getUrl()) .append("filename", ticket.getFilename()) .append("sparse", ticket.isSparse()) .append("transferId", ticket.getTransferId()) .append("dirty", ticket.isDirty()); }
Source:
protected void afterTestsStopped() throws Exception { BPlusTree.pageHndWrapper = regularPageHndWrapper == null ? ((tree, hnd) -> hnd) : regularPageHndWrapper; }

Target:
protected void afterTestsStopped() throws Exception { }
Source:
protected void limitTotalNumberOfCnxns() throws IOException { if (maxCnxns <= 0) { return; } int cnxns = getNumAliveConnections(); if (cnxns >= maxCnxns) { throw new IOException("Too many connections " + cnxns + " - max is " + maxCnxns); } }

Target:
protected boolean limitTotalNumberOfCnxns() { if (maxCnxns <= 0) { return false; } int cnxns = getNumAliveConnections(); if (cnxns >= maxCnxns) { LOG.error("Too many connections " + cnxns + " - max is " + maxCnxns); return true; } return false; }
Source:
void flush() { Producer<K, V> producer; try { _producerLock.lock(); producer = _kafkaProducer; } finally { _producerLock.unlock(); } try { if (producer != null) { producer.flush(_producerFlushTimeoutMs, TimeUnit.MILLISECONDS); } } catch (InterruptException | TimeoutException e) { if (producer == _kafkaProducer) { _log.warn("Kafka producer flush interrupted/timed out, closing producer {}.", producer); shutdownProducer(); } else { _log.warn("Kafka producer flush interrupted/timed out, producer already closed.", producer); } throw e; } }

Target:
void flush() { Producer<K, V> producer; try { _producerLock.lock(); producer = _kafkaProducer; } finally { _producerLock.unlock(); } if (producer != null) { try { producer.flush(_producerFlushTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptException | TimeoutException e) { try { _producerLock.lock(); if (producer == _kafkaProducer) { _log.warn("Kafka producer flush interrupted/timed out, closing producer {}.", producer); shutdownProducer(); } else { _log.warn("Kafka producer flush interrupted/timed out, producer already closed.", producer); } throw e; } finally { _producerLock.unlock(); } } } }
Source:
private void loadExchangeInfo() throws ExchangeManagerException { exInfo = getExchangeInfoDAO().loadExchangeInfo(); if (exInfo != null) { synchronized (exCache) { exCache.clear(); if (null != exInfo.getExchanges() && CollectionUtils.isNotEmpty(exInfo.getExchanges().getExchange())) { for (ExchangeType ex : exInfo.getExchanges().getExchange()) { if (isOverrideExchange(ex)) { overrideExchange = ex; } else { updateExchangeCache(ex); } } exCacheLoaded = true; exFileLastUpdateTime = getExchangeInfoDAO().getLastModified(); } } } else { LOG.error("No Exchange Information found"); } }

Target:
private void loadExchangeInfo() throws ExchangeManagerException { exInfo = getExchangeInfoDAO().loadExchangeInfo(); overrideExchange = null; if (exInfo != null) { synchronized (exCache) { exCache.clear(); if (null != exInfo.getExchanges() && CollectionUtils.isNotEmpty(exInfo.getExchanges().getExchange())) { for (ExchangeType ex : exInfo.getExchanges().getExchange()) { if (isOverrideExchange(ex)) { if (null != overrideExchange) { LOG.warn( "Found more than one overrides exchange type .. overwriting the previous exchange"); } overrideExchange = ex; } else { updateExchangeCache(ex); } } exCacheLoaded = true; exFileLastUpdateTime = getExchangeInfoDAO().getLastModified(); } } } else { LOG.error("No Exchange Information found"); } }
Source:
RecordedEventSerializer(EntityManager entityManager) { ReflectionReflectFactory reflectFactory = new ReflectionReflectFactory(); CopyStrategyLibrary copyStrategyLibrary = new CopyStrategyLibrary(reflectFactory); this.typeSerializationLibrary = TypeSerializationLibrary.createDefaultLibrary(reflectFactory, copyStrategyLibrary); typeSerializationLibrary.add(EntityRef.class, new EntityRefTypeHandler((EngineEntityManager) entityManager)); typeSerializationLibrary.add(MouseAxisEvent.MouseAxis.class, new EnumTypeHandler<>(MouseAxisEvent.MouseAxis.class)); typeSerializationLibrary.add(ButtonState.class, new EnumTypeHandler<>(ButtonState.class)); typeSerializationLibrary.add(Keyboard.Key.class, new EnumTypeHandler<>(Keyboard.Key.class)); typeSerializationLibrary.add(MouseInput.class, new EnumTypeHandler<>(MouseInput.class)); this.entityManager = entityManager; }

Target:
RecordedEventSerializer(EntityManager entityManager) { ReflectionReflectFactory reflectFactory = new ReflectionReflectFactory(); CopyStrategyLibrary copyStrategyLibrary = new CopyStrategyLibrary(reflectFactory); this.typeSerializationLibrary = TypeSerializationLibrary.createDefaultLibrary(reflectFactory, copyStrategyLibrary); typeSerializationLibrary.add(EntityRef.class, new EntityRefTypeHandler((EngineEntityManager) entityManager)); typeSerializationLibrary.add(MouseAxisEvent.MouseAxis.class, new EnumTypeHandler<>(MouseAxisEvent.MouseAxis.class)); typeSerializationLibrary.add(ButtonState.class, new EnumTypeHandler<>(ButtonState.class)); typeSerializationLibrary.add(Keyboard.Key.class, new EnumTypeHandler<>(Keyboard.Key.class)); typeSerializationLibrary.add(MouseInput.class, new EnumTypeHandler<>(MouseInput.class)); typeSerializationLibrary.add(MovementMode.class, new EnumTypeHandler<>(MovementMode.class)); this.entityManager = entityManager; }
Source:
public String description() { return format( "Produce heuristic memory setting recommendations for the Neo4j JVM heap and pagecache. The " + "heuristic is based on the total memory of the system the command is running on, or on the amount of " + "memory specified with the --memory argument. The heuristic assumes that the system is dedicated to " + "running Neo4j. If this is not the case, then use the --memory argument to specify how much memory " + "can be expected to be dedicated to Neo4j.%n" + "%n" + "By default, the command will print its recommendations to the console in a human readable form. " + "The command can alternatively print what the neo4j.conf file would look like with the new settings " + "by specifying --print-conf, and those updated settings can be written back to the conf file " + "(updated in-place) by specifying --update-conf. Any existing settings already enabled in the file " + "will not be updated unless --overwrite is specified.%n" + "%n" + "If --print-conf or --update-conf is specified, then the command will by default look for, and work " + "on, the standard neo4j.conf file. A different file can be specified with the --conf-file argument." ); }

Target:
public String description() { return format( "Print heuristic memory setting recommendations for the Neo4j JVM heap and pagecache. The " + "heuristic is based on the total memory of the system the command is running on, or on the amount of " + "memory specified with the --memory argument. The heuristic assumes that the system is dedicated to " + "running Neo4j. If this is not the case, then use the --memory argument to specify how much memory " + "can be expected to be dedicated to Neo4j.%n" + "%n" + "The output is formatted such that it can be copy-posted into the neo4j.conf file." ); }
Source:
public void bulkCancelJobsDependingOnStatusTest() { final String serverTemplateTest = "serverTemplateTest"; presenter.setSelectedServerTemplate(serverTemplateTest); String deploymentId = "deploymentId"; String key = "key"; Long jobId_1 = new Random().nextLong(); Long jobId_2 = jobId_1 +1; Long jobId_3 = jobId_2 +1; ArrayList<RequestSummary> requestSummaries= new ArrayList<>(); requestSummaries.add(createRequestSummary(jobId_1, key, deploymentId, RequestStatus.QUEUED)); requestSummaries.add(createRequestSummary(jobId_2, key, deploymentId, RequestStatus.QUEUED)); requestSummaries.add(createRequestSummary(jobId_3, key, deploymentId, RequestStatus.ERROR)); presenter.bulkCancel(requestSummaries); verify(executorServiceMock).cancelRequest(anyString(),anyString(),eq(jobId_1)); verify(executorServiceMock).cancelRequest(anyString(),anyString(),eq(jobId_2)); verify(executorServiceMock,never()).cancelRequest(anyString(),anyString(),eq(jobId_3)); verify(viewMock).displayNotification(Constants.INSTANCE.RequestCanceled(jobId_1)); verify(viewMock).displayNotification(Constants.INSTANCE.RequestCanceled(jobId_2)); verify(viewMock).displayNotification(Constants.INSTANCE.Job_Can_Not_Be_Cancelled(jobId_3)); }

Target:
public void bulkCancelJobsDependingOnStatusTest() { final String serverTemplateTest = "serverTemplateTest"; presenter.setSelectedServerTemplate(serverTemplateTest); String deploymentId = "deploymentId"; String key = "key"; Long jobId_1 = new Random().nextLong(); Long jobId_2 = jobId_1 + 1; Long jobId_3 = jobId_2 + 1; ArrayList<RequestSummary> requestSummaries = new ArrayList<>(); requestSummaries.add(createRequestSummary(jobId_1, key, deploymentId, RequestStatus.QUEUED)); requestSummaries.add(createRequestSummary(jobId_2, key, deploymentId, RequestStatus.RUNNING)); requestSummaries.add(createRequestSummary(jobId_3, key, deploymentId, RequestStatus.ERROR)); presenter.bulkCancel(requestSummaries); verify(executorServiceMock).cancelRequest(anyString(), anyString(), eq(jobId_1)); verify(executorServiceMock).cancelRequest(anyString(), anyString(), eq(jobId_2)); verify(executorServiceMock, never()).cancelRequest(anyString(), anyString(), eq(jobId_3)); verify(viewMock).displayNotification(Constants.INSTANCE.RequestCanceled(jobId_1)); verify(viewMock).displayNotification(Constants.INSTANCE.RequestCanceled(jobId_2)); verify(viewMock).displayNotification(Constants.INSTANCE.Job_Can_Not_Be_Cancelled(jobId_3)); }
Source:
public FeedbackSessionQuestionsBundle getFeedbackSessionQuestionsForStudent( String feedbackSessionName, String courseId, String userEmail) throws EntityDoesNotExistException { FeedbackSessionAttributes fsa = fsDb.getFeedbackSession( courseId, feedbackSessionName); StudentAttributes student = studentsLogic.getStudentForEmail(courseId, userEmail); if (fsa == null) { throw new EntityDoesNotExistException( "Trying to get a feedback session that does not exist."); } if (student == null) { throw new EntityDoesNotExistException( "Trying to get a feedback session for student that does not exist."); } Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> bundle = new HashMap<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>(); Map<String, Map<String, String>> recipientList = new HashMap<String, Map<String, String>>(); List<FeedbackQuestionAttributes> questions = fqLogic.getFeedbackQuestionsForStudents(feedbackSessionName, courseId); Set<String> hiddenInstructorEmails = getHiddenInstrutorEmails(courseId); InstructorAttributes instructorGiver = null; StudentAttributes studentGiver = student; for (FeedbackQuestionAttributes question : questions) { updateBundleAndRecipientListWithResponsesForStudent(userEmail, student, bundle, recipientList, question, instructorGiver, studentGiver, hiddenInstructorEmails); } return new FeedbackSessionQuestionsBundle(fsa, bundle, recipientList); }

Target:
public FeedbackSessionQuestionsBundle getFeedbackSessionQuestionsForStudent( String feedbackSessionName, String courseId, String userEmail) throws EntityDoesNotExistException { FeedbackSessionAttributes fsa = fsDb.getFeedbackSession( courseId, feedbackSessionName); StudentAttributes student = studentsLogic.getStudentForEmail(courseId, userEmail); if (fsa == null) { throw new EntityDoesNotExistException( "Trying to get a feedback session that does not exist."); } if (student == null) { throw new EntityDoesNotExistException( "Trying to get a feedback session for student that does not exist."); } Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> bundle = new HashMap<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>(); Map<String, Map<String, String>> recipientList = new HashMap<String, Map<String, String>>(); List<FeedbackQuestionAttributes> questions = fqLogic.getFeedbackQuestionsForStudents(feedbackSessionName, courseId); Set<String> hiddenInstructorEmails = null; for (FeedbackQuestionAttributes question : questions) { if (question.getRecipientType() == FeedbackParticipantType.INSTRUCTORS) { hiddenInstructorEmails = getHiddenInstructorEmails(courseId); break; } } for (FeedbackQuestionAttributes question : questions) { updateBundleAndRecipientListWithResponsesForStudent(userEmail, student, bundle, recipientList, question, hiddenInstructorEmails); } return new FeedbackSessionQuestionsBundle(fsa, bundle, recipientList); }
Source:
public void testCodec() { try { FileInputStream inputStream = new FileInputStream("src\\main\\jni\\test_sound_mono_48.pcm"); FileOutputStream outputStream = new FileOutputStream("src\\main\\jni\\test_sound_mono_48_decoded.pcm", false); OpusJni opus = new OpusJni(); opus.setOpusObserverNative(this); opus.sayHelloNative(); opus.initNative(); try { byte[] input = new byte[960]; short[] inputData = new short[480]; byte[] output = new byte[960]; while (inputStream.read(input) == 960) { ByteBuffer.wrap(input).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(inputData); byte[] encodedData = opus.encodeNative(inputData); short[] decodedData = opus.decodeNative(encodedData); ByteBuffer.wrap(output).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(decodedData); outputStream.write(output); } } finally { inputStream.close(); outputStream.close(); opus.closeNative(); } } catch (IOException exc) { System.out.println("IOException: " + exc.getMessage()); return; } org.restcomm.media.spi.dsp.Codec compressor = new Encoder(); long s = System.nanoTime(); compressor.process(buffer); long f = System.nanoTime(); System.out.println("Duration=" + (f-s)); org.restcomm.media.spi.dsp.Codec decompressor = new Decoder(); s = System.nanoTime(); decompressor.process(buffer); f = System.nanoTime(); System.out.println("Duration=" + (f-s)); }

Target:
public void testCodec() throws Exception { boolean testPassed = false; try { OpusJni opus = new OpusJni(); opus.initNative(); final int packetSize = 480; File outputFile = File.createTempFile("opustest", ".tmp"); byte[] output = new byte[2 * packetSize]; try (FileInputStream inputStream = new FileInputStream("src\\test\\resources\\test_sound_mono_48.pcm"); FileOutputStream outputStream = new FileOutputStream(outputFile, false)) { byte[] input = new byte[packetSize]; short[] inputData = new short[packetSize]; while (inputStream.read(input) == 2 * packetSize) { ByteBuffer.wrap(input).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(inputData); byte[] encodedData = opus.encodeNative(inputData); short[] decodedData = opus.decodeNative(encodedData); ByteBuffer.wrap(output).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(decodedData); outputStream.write(output); } testPassed = true; } opus.closeNative(); outputFile.delete(); } catch (IOException exc) { log.error("IOException: " + exc.getMessage()); fail("Opus test file access error"); } assertTrue(testPassed); }
Source:
public static AsanaError mapException(HttpResponseException exception) throws AsanaError { switch (exception.getStatusCode()) { case ForbiddenError.STATUS: String constructedErrorMsg = constructMessage("", exception); String premiumOnlyStr = "not available for free"; if (constructedErrorMsg != null && constructedErrorMsg.contains(premiumOnlyStr)) { return new PremiumOnlyError(exception); } return new ForbiddenError(exception); case InvalidRequestError.STATUS: return new InvalidRequestError(exception); case InvalidTokenError.STATUS: return new InvalidTokenError(exception); case NoAuthorizationError.STATUS: return new NoAuthorizationError(exception); case NotFoundError.STATUS: return new NotFoundError(exception); case PremiumOnlyError.STATUS: return new PremiumOnlyError(exception); case RateLimitEnforcedError.STATUS: return new RateLimitEnforcedError(exception); case ServerError.STATUS: return new ServerError(exception); default: return new AsanaError(exception.getStatusMessage(), exception.getStatusCode(), exception); } }

Target:
public static AsanaError mapException(HttpResponseException exception) throws AsanaError { switch (exception.getStatusCode()) { case ForbiddenError.STATUS: String constructedErrorMsg = constructMessage("", exception); String premiumOnlyStr = "not available for free"; if (constructedErrorMsg.contains(premiumOnlyStr)) { return new PremiumOnlyError(exception); } return new ForbiddenError(exception); case InvalidRequestError.STATUS: return new InvalidRequestError(exception); case InvalidTokenError.STATUS: return new InvalidTokenError(exception); case NoAuthorizationError.STATUS: return new NoAuthorizationError(exception); case NotFoundError.STATUS: return new NotFoundError(exception); case PremiumOnlyError.STATUS: return new PremiumOnlyError(exception); case RateLimitEnforcedError.STATUS: return new RateLimitEnforcedError(exception); case ServerError.STATUS: return new ServerError(exception); default: return new AsanaError(exception.getStatusMessage(), exception.getStatusCode(), exception); } }
Source:
public void testErrorWhileInitializing() throws Exception { TestContext testContext = createTestContext(Dispatcher.ExecutionType.SUBMISSION); DispatcherJob dispatcherJob = testContext.dispatcherJob; RuntimeException exception = new RuntimeException("Artificial failure in runner initialization"); testContext.failInitialization(exception); Assert.assertThat(dispatcherJob.isInitialized(), is(true)); assertJobStatus(dispatcherJob, JobStatus.FAILED); ArchivedExecutionGraph aeg = dispatcherJob.getResultFuture().get(); Assert.assertThat(aeg.getFailureInfo().getException().deserializeError(ClassLoader.getSystemClassLoader()), is(exception)); Assert.assertTrue(dispatcherJob.closeAsync().isDone() && dispatcherJob.closeAsync().isCompletedExceptionally()); }

Target:
public void testErrorWhileInitializing() throws Exception { TestContext testContext = createTestContext(); DispatcherJob dispatcherJob = testContext.getDispatcherJob(); RuntimeException exception = new RuntimeException("Artificial failure in runner initialization"); testContext.failInitialization(exception); assertThat(dispatcherJob.isInitialized(), is(true)); assertJobStatus(dispatcherJob, JobStatus.FAILED); ArchivedExecutionGraph aeg = dispatcherJob.getResultFuture().get().getArchivedExecutionGraph(); assertThat(aeg.getFailureInfo().getException().deserializeError(ClassLoader.getSystemClassLoader()), is(exception)); }
Source:
public void enforceSnapshotSync(DiscoveryServiceEvent event) { for (CorfuLogReplicationRuntime standbyRuntime : runtimeToRemoteCluster.values()) { standbyRuntime.getSourceManager().stopLogReplication(); standbyRuntime.getSourceManager().startSnapshotSync(); log.info("Enforce Start full snapshot sync for cluster with uuid {}", standbyRuntime.getRemoteClusterId(), event.getEventUUID()); } event.getCf().complete(event.getEventUUID()); }

Target:
public void enforceSnapshotSync(DiscoveryServiceEvent event) { CorfuLogReplicationRuntime standbyRuntime = runtimeToRemoteCluster.get(event.getRemoteClusterInfo().getClusterId()); if (standbyRuntime == null) { log.warn("Failed to start enforceSnapshotSync for cluster as it is not on the standby list.", event.getRemoteClusterInfo()); } else { log.info("EnforceSnapshotSync for cluster {}", standbyRuntime.getRemoteClusterId()); standbyRuntime.getSourceManager().stopLogReplication(); standbyRuntime.getSourceManager().startSnapshotSync(); } }
Source:
public FormInstance build() { List<FormValue> formValues = new ArrayList<>(); List<FormElement> formElements = formDefinition.getFormElements(); for (FormElement formElement : formElements) { Object value = params.get(formElement.getName()); if (value != null && !(formElement.getType().equals(FieldTypeConstants.SELECT) && ((List<String>) value).size() == 0)) { formValues.add(buildFormElementValueByType(formElement, value)); } } FormInstance formInstance = new FormInstance(formDefinition.getTitle(), formDefinition.getConfigurationName(), instanceId); formInstance.setFormValues(formValues); return formInstance; }

Target:
public FormInstance build() throws FormInstanceBuilderException { List<FormValue> formValues = new ArrayList<>(); List<FormElement> formElements = formDefinition.getFormElements(); for (FormElement formElement : formElements) { Object value = params.get(formElement.getName()); if (value != null && !(formElement.getType().equals(FieldTypeConstants.SELECT) && ((List<String>) value).size() == 0)) { formValues.add(buildFormElementValueByType(formElement, value)); } } FormInstance formInstance = new FormInstance(formDefinition.getTitle(), formDefinition.getConfigurationName(), instanceId); formInstance.setFormValues(formValues); return formInstance; }
Source:
public void cleanUp() { try { ProjectModelTestData.deleteProject(fixture); } catch (CoreException e) { fail(e.getMessage()); } }

Target:
public void cleanUp() { ProjectModelTestData.deleteProject(fixture); }
Source:
public static void main(final String[] args) { String jobName = null; String jobGroup = "systemJobs"; switch (args.length) { case 0: System.out.println("Job names:"); break; case 2: jobGroup = args[1]; case 1: jobName = args[0]; break; default: System.out.println("Expects 0, 1, or 2 arguments"); System.exit(1); } if (!StringUtils.isEmpty(jobName) && !StringUtils.isEmpty(jobGroup)) { try { StdSchedulerFactory sf = new StdSchedulerFactory(); sf.initialize("quartz.properties"); Scheduler scheduler = sf.getScheduler(); TriggerKey triggerId = triggerKey("triggerJobNow_" + new Date().getTime(), "triggerJob"); JobKey jobId = jobKey(jobName, jobGroup); Trigger qzTrigger = newTrigger() .withIdentity(triggerId) .startNow() .forJob(jobId) .build(); scheduler.scheduleJob(qzTrigger); scheduler.shutdown(); } catch (SchedulerException se) { se.printStackTrace(); } } else { try { StdSchedulerFactory sf = new StdSchedulerFactory(); sf.initialize("quartz.properties"); Scheduler scheduler = sf.getScheduler(); for (String group: scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(groupEquals(group))) { System.out.println("Found job: \"" + jobKey.getName() + "\" in group: \"" + jobKey.getGroup() + "\""); } } scheduler.shutdown(); } catch (SchedulerException se) { se.printStackTrace(); } } }

Target:
public static void main(final String[] args) { String jobName = null; String jobGroup = "systemJobs"; switch (args.length) { case 0: break; case 2: jobGroup = args[1]; case 1: jobName = args[0]; break; default: LOGGER.error("Expects 0, 1, or 2 arguments." + "\n 0 arguments: outputs all Jobs in system" + "\n 1st argument: job name" + "\n 2nd argument: group name (defaults to \"systemJobs\" if not provided)"); System.exit(1); } if (!StringUtils.isEmpty(jobName) && !StringUtils.isEmpty(jobGroup)) { try { StdSchedulerFactory sf = new StdSchedulerFactory(); sf.initialize("quartz.properties"); Scheduler scheduler = sf.getScheduler(); TriggerKey triggerId = triggerKey("triggerJobNow_" + new Date().getTime(), "triggerJob"); JobKey jobId = jobKey(jobName, jobGroup); Trigger qzTrigger = newTrigger() .withIdentity(triggerId) .startNow() .forJob(jobId) .build(); scheduler.scheduleJob(qzTrigger); scheduler.shutdown(); } catch (SchedulerException se) { se.printStackTrace(); } } else { try { StdSchedulerFactory sf = new StdSchedulerFactory(); sf.initialize("quartz.properties"); Scheduler scheduler = sf.getScheduler(); StringBuilder output = new StringBuilder(); output.append("Found jobs:\n"); for (String group: scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(groupEquals(group))) { output.append(" Job: [" + jobKey.getName() + "] Group: [" + jobKey.getGroup() + "]\n"); } } scheduler.shutdown(); LOGGER.info(output.toString()); } catch (SchedulerException se) { se.printStackTrace(); } } }
Source:
public void onBlocked() { super.onBlocked(); playPauseButton.setImageResource(R.drawable.ic_pause_white); animatePlayButtons(false, 100); getRootView().setKeepScreenOn(false); service.resetNotification(); service.updateNotification(R.drawable.ic_play_arrow_white); }

Target:
public void onBlocked() { super.onBlocked(); playPauseButton.setImageResource(R.drawable.ic_play_arrow_white_24dp); animatePlayButtons(false, 100); getRootView().setKeepScreenOn(false); service.resetNotification(); service.updateNotification(R.drawable.exo_controls_play); }
Source:
public void createPartControl(Composite parent) { parentControl = parent; if (error != null) { new StatusPart(getSite(), parent, error); } }

Target:
public void createPartControl(Composite parent) { parentControl = parent; if (error != null) { new StatusPart(parent, error); } }
Source:
public MetadataExtension parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws IOException, XmlPullParserException { List<MetadataInfo> metadataInfos = null; List<MetadataPointer> pointers = null; while (true) { XmlPullParser.Event eventType = parser.next(); if (eventType == XmlPullParser.Event.START_ELEMENT) { if (parser.getName().equals("info")) { if (metadataInfos == null) { metadataInfos = new ArrayList<>(); } MetadataInfo info = parseInfo(parser); if (info.getId() != null) { metadataInfos.add(info); } } if (parser.getName().equals("pointer")) { if (pointers == null) { pointers = new ArrayList<>(); } pointers.add(parsePointer(parser)); } } else if (eventType == XmlPullParser.Event.END_ELEMENT) { if (parser.getDepth() == initialDepth) { break; } } } return new MetadataExtension(metadataInfos, pointers); }

Target:
public MetadataExtension parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws IOException, XmlPullParserException { List<MetadataInfo> metadataInfos = null; List<MetadataPointer> pointers = null; outerloop: while (true) { XmlPullParser.TagEvent eventType = parser.nextTag(); switch (eventType) { case START_ELEMENT: if (parser.getName().equals("info")) { if (metadataInfos == null) { metadataInfos = new ArrayList<>(); } MetadataInfo info = parseInfo(parser); if (info.getId() != null) { metadataInfos.add(info); } } if (parser.getName().equals("pointer")) { if (pointers == null) { pointers = new ArrayList<>(); } pointers.add(parsePointer(parser)); } break; case END_ELEMENT: if (parser.getDepth() == initialDepth) { break outerloop; } } } return new MetadataExtension(metadataInfos, pointers); }
Source:
public List<WorkflowAction> findActions(List<WorkflowStep> steps, User user) throws DotDataException, DotSecurityException { List<WorkflowAction> actions = new ArrayList<>(); for(WorkflowStep step : steps) { actions.addAll(workFlowFactory.findActions(step)); } actions = APILocator.getPermissionAPI().filterCollection(actions, PermissionAPI.PERMISSION_USE, true, user); return actions; }

Target:
public List<WorkflowAction> findActions(List<WorkflowStep> steps, User user) throws DotDataException, DotSecurityException { final ImmutableList.Builder<WorkflowAction> actions = new ImmutableList.Builder<>(); for(WorkflowStep step : steps) { actions.addAll(workFlowFactory.findActions(step)); } return APILocator.getPermissionAPI().filterCollection(actions.build(), PermissionAPI.PERMISSION_USE, true, user); }
Source:
private List<String> split(String input) { List<String> result=new ArrayList<>(); String[] split = input.split(SEPARATOR); for (String string : split) { if(string != null && string.trim().length()>0) { result.add(string.trim()); } } return result; }

Target:
private List<String> split(String input) { List<String> result = new ArrayList<>(); String[] split = input.split(SEPARATOR); for (String string : split) { if (string != null) { String trimmed = string.trim(); if (trimmed.length() > 0) { result.add(trimmed); } } } return result; }
Source:
public void testActiveTransactionCancellation() { DataStoreTransaction dtx = elide.getDataStore().beginTransaction(); transactionRegistry.addRunningTransaction(UUID.fromString("edc4a871-dff2-4054-804e-d80075cf828d"), dtx); AsyncQuery asyncQuery1 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf828d", 1577883600000L, QueryStatus.QUEUED); AsyncQuery asyncQuery2 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf827d", 1577883600000L, QueryStatus.QUEUED); Collection<AsyncQuery> asyncCollection = new ArrayList<AsyncQuery>(); asyncCollection.add(asyncQuery1); asyncCollection.add(asyncQuery2); when(cancelThread.getAsyncQueryDao().loadAsyncQueryCollection(any())).thenReturn(asyncCollection); cancelThread.cancelAsyncQuery(); ArgumentCaptor<FilterExpression> filterCaptor = ArgumentCaptor.forClass(FilterExpression.class); verify(asyncQueryDao, times(1)).updateStatusAsyncQueryCollection(filterCaptor.capture(), any()); assertEquals("asyncQuery.id IN [[edc4a871-dff2-4054-804e-d80075cf828d]]", filterCaptor.getValue().toString()); }

Target:
public void testActiveTransactionCancellation() { DataStoreTransaction dtx = elide.getDataStore().beginTransaction(); transactionRegistry.addRunningTransaction(UUID.fromString("edc4a871-dff2-4054-804e-d80075cf828d"), dtx); AsyncQuery asyncQuery1 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf828d", 1577883600000L, QueryStatus.QUEUED); AsyncQuery asyncQuery2 = createAsyncQueryTestObject("edc4a871-dff2-4054-804e-d80075cf827d", 1577883600000L, QueryStatus.QUEUED); Collection<AsyncQuery> asyncCollection = new ArrayList<AsyncQuery>(); asyncCollection.add(asyncQuery1); asyncCollection.add(asyncQuery2); when(cancelThread.getAsyncQueryDao().loadAsyncQueryCollection(any())).thenReturn(asyncCollection); cancelThread.cancelAsyncQuery(); ArgumentCaptor<FilterExpression> filterCaptor = ArgumentCaptor.forClass(FilterExpression.class); ArgumentCaptor<QueryStatus> statusCaptor = ArgumentCaptor.forClass(QueryStatus.class); verify(asyncQueryDao, times(1)).loadAsyncQueryCollection(any()); verify(asyncQueryDao, times(1)).updateStatusAsyncQueryCollection(filterCaptor.capture(), statusCaptor.capture()); assertEquals("asyncQuery.id IN [[edc4a871-dff2-4054-804e-d80075cf828d]]", filterCaptor.getValue().toString()); assertEquals("CANCEL_COMPLETE", statusCaptor.getValue().toString()); }
Source:
public static Settings getDepartmentsSettings() { Settings.Builder settingsBuilder = Settings.builder(). loadFromStream("departments-index-config.yml", Indexer.class.getResourceAsStream("/search/departments/departments-index-config.yml")); return settingsBuilder.build(); }

Target:
public static Settings getDepartmentsSettings() throws IOException { try (InputStream inputStream = ZebedeeContentIndexer.class.getResourceAsStream("/search/departments/departments-index-config.yml")) { Settings.Builder settingsBuilder = Settings.builder(). loadFromStream("departments-index-config.yml", inputStream); return settingsBuilder.build(); } }
Source:
public void testAnnouncementUnexpectedMessage() throws InterruptedException { String TOPIC_NAME = "topic1"; ChannelMonitorAgent channelMonitorAgent = new DefaultChannelMonitorAgent(msbContext); CountDownLatch announcementReceived = new CountDownLatch(1); Callback<AggregatorStats> handler = stats -> { assertTrue(stats.getTopicInfoMap().containsKey(TOPIC_NAME)); assertEquals(1, stats.getTopicInfoMap().get(TOPIC_NAME).getProducers().size()); announcementReceived.countDown(); }; MockAdapter.pushRequestMessage(Utils.TOPIC_ANNOUNCE, Utils.toJson(TestUtils.createMsbRequestMessageWithSimplePayload(Utils.TOPIC_ANNOUNCE), msbContext.getPayloadMapper())); ChannelMonitorAggregator channelMonitorAggregator = msbContext.getObjectFactory().createChannelMonitorAggregator(handler); channelMonitorAggregator.start(false, ChannelMonitorAggregator.DEFAULT_HEARTBEAT_INTERVAL_MS, ChannelMonitorAggregator.DEFAULT_HEARTBEAT_TIMEOUT_MS); channelMonitorAgent.producerTopicCreated(TOPIC_NAME); assertTrue("Announcement was not received", announcementReceived.await(RequesterResponderIT.MESSAGE_TRANSMISSION_TIME * 2, TimeUnit.MILLISECONDS)); }

Target:
public void testAnnouncementUnexpectedMessage() throws InterruptedException { String TOPIC_NAME = "topic2"; CountDownLatch announcementReceived = monitorPrepareAwaitOnAnnouncement(TOPIC_NAME); MockAdapter.pushRequestMessage(Utils.TOPIC_ANNOUNCE, Utils.toJson(TestUtils.createMsbRequestMessageWithSimplePayload(Utils.TOPIC_ANNOUNCE), msbContext.getPayloadMapper())); assertFalse("Broken announcement was handled", announcementReceived.await(RequesterResponderIT.MESSAGE_TRANSMISSION_TIME / 2, TimeUnit.MILLISECONDS)); ChannelMonitorAgent channelMonitorAgent = new DefaultChannelMonitorAgent(msbContext); channelMonitorAgent.producerTopicCreated(TOPIC_NAME); assertTrue("Announcement was not received", announcementReceived.await(RequesterResponderIT.MESSAGE_TRANSMISSION_TIME, TimeUnit.MILLISECONDS)); }
Source:
public void processRecord(MetricsRecord record) { String[] sources = record.getSource().split("/"); String source; if (sources.length > 2) { source = includeServiceNamespace ? String.format("%s/%s/%s", topologyName, sources[1], sources[2]) : String.format("/%s/%s", sources[1], sources[2]); } else { source = includeServiceNamespace ? String.format("%s/%s", topologyName, record.getSource()) : String.format("/%s", record.getSource()); } if (isFlatMetrics) { processMetrics(source + "/", record.getMetrics(), metrics); } else { Map<String, Object> sourceMap = new HashMap<>(); processMetrics("", record.getMetrics(), sourceMap); metrics.put(source, sourceMap); } }

Target:
public void processRecord(MetricsRecord record) { String[] sources = record.getSource().split("/"); String source; if (sources.length > 2) { source = includeTopologyName ? String.format("%s/%s/%s", topologyName, sources[1], sources[2]) : String.format("/%s/%s", sources[1], sources[2]); } else { source = includeTopologyName ? String.format("%s/%s", topologyName, record.getSource()) : String.format("/%s", record.getSource()); } if (isFlatMetrics) { metricsCache.putAll(processMetrics(source + "/", record.getMetrics())); } else { Map<String, Double> sourceMap = processMetrics("", record.getMetrics()); metricsCache.put(source, sourceMap); } }
Source:
public List<TupleValueExpression> findAllTupleValueSubexpressions() { ArrayList<TupleValueExpression> collected = new ArrayList<>(); findAllSubexpressionsOfClass_recurse(TupleValueExpression.class, collected); return collected; }

Target:
public List<TupleValueExpression> findAllTupleValueSubexpressions() { return findAllSubexpressionsOfClass(TupleValueExpression.class); }
Source:
protected void processPacket(QuorumPacket qp) throws IOException{ switch (qp.getType()) { case Leader.PING: ping(qp); break; case Leader.PROPOSAL: TxnHeader hdr = new TxnHeader(); Record txn = SerializeUtils.deserializeTxn(qp.getData(), hdr); if (hdr.getZxid() != lastQueued + 1) { LOG.warn("Got zxid 0x" + Long.toHexString(hdr.getZxid()) + " expected 0x" + Long.toHexString(lastQueued + 1)); } lastQueued = hdr.getZxid(); fzk.logRequest(hdr, txn); break; case Leader.COMMIT: fzk.commit(qp.getZxid()); break; case Leader.UPTODATE: LOG.error("Received an UPTODATE message after Follower started"); break; case Leader.REVALIDATE: revalidate(qp); break; case Leader.SYNC: fzk.sync(); break; default: LOG.error("Invalid packet type received by Observer: " + qp.getType()); } }

Target:
protected void processPacket(QuorumPacket qp) throws IOException{ switch (qp.getType()) { case Leader.PING: ping(qp); break; case Leader.PROPOSAL: TxnHeader hdr = new TxnHeader(); Record txn = SerializeUtils.deserializeTxn(qp.getData(), hdr); if (hdr.getZxid() != lastQueued + 1) { LOG.warn("Got zxid 0x" + Long.toHexString(hdr.getZxid()) + " expected 0x" + Long.toHexString(lastQueued + 1)); } lastQueued = hdr.getZxid(); fzk.logRequest(hdr, txn); break; case Leader.COMMIT: fzk.commit(qp.getZxid()); break; case Leader.UPTODATE: LOG.error("Received an UPTODATE message after Follower started"); break; case Leader.REVALIDATE: revalidate(qp); break; case Leader.SYNC: fzk.sync(); break; default: LOG.error("Invalid packet type: received by Observer", qp.getType()); } }
Source:
public List<Object> serializeFieldList(Schema fieldSchema, Object fieldValue) { List<Object> sFL = new ArrayList(); switch (fieldSchema.getType()) { case ARRAY: List<?> ls = (List<?>) fieldValue; for (Object lsValue : ls) { Object lsValue_ = serializeFieldValue(fieldSchema.getElementType(), lsValue); sFL.add(lsValue_); } break; default: throw new AssertionError(fieldSchema.getType().name()); } return sFL; }

Target:
public List<Object> serializeFieldList(Schema fieldSchema, Object fieldValue) { List<Object> serializedList = new ArrayList(); switch (fieldSchema.getType()) { case ARRAY: List<?> rawdataList = (List<?>) fieldValue; rawdataList.stream().map((lsValue) -> serializeFieldValue(fieldSchema.getElementType(), lsValue)).forEachOrdered((lsValue_) -> { serializedList.add(lsValue_); }); break; default: throw new AssertionError(fieldSchema.getType().name()); } return serializedList; }
Source:
private void shareApplication() { try { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, String.format(getString(R.string.whatsapp_promo_msg_template), String.format(getString(R.string.app_share_url),getPackageName()))); startActivity(Intent.createChooser(shareIntent, "Share via")); } catch (Exception e) { Snackbar.make(mainFrame, getString(R.string.error_msg_retry), Snackbar.LENGTH_SHORT).show(); } }

Target:
private void shareApplication() { try { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, String.format(getString(R.string.whatsapp_promo_msg_template), String.format(getString(R.string.app_share_url),getPackageName()))); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_via))); } catch (Exception e) { Snackbar.make(mainFrame, getString(R.string.error_msg_retry), Snackbar.LENGTH_SHORT).show(); } }