auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCommitFailure() throws Exception { Properties props = createProps(); HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); String key = "key"; Schema schema = createSchema(); Struct record = createRecord(schema); Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(TOPIC, PARTITION, Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } HdfsWriter hdfsWriter = new HdfsWriter(connectorConfig, context, avroData); MemoryStorage storage = (MemoryStorage) hdfsWriter.getStorage(); storage.setFailAppend(true); hdfsWriter.write(sinkRecords); Map<String, List<Object>> data = Data.getData(); String logFile = FileUtils.logFileName(url, topicsDir, TOPIC_PARTITION); List<Object> content = data.get(logFile); assertEquals(null, content); hdfsWriter.write(new ArrayList<SinkRecord>()); for (String entry: data.keySet()) { System.out.println(entry); } content = data.get(logFile); assertEquals(2, content.size()); hdfsWriter.close(); }

Target:
public void testCommitFailure() throws Exception { Properties props = createProps(); HdfsSinkConnectorConfig connectorConfig = new HdfsSinkConnectorConfig(props); String key = "key"; Schema schema = createSchema(); Struct record = createRecord(schema); Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(TOPIC, PARTITION, Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } HdfsWriter hdfsWriter = new HdfsWriter(connectorConfig, context, avroData); MemoryStorage storage = (MemoryStorage) hdfsWriter.getStorage(); storage.setFailure(MemoryStorage.Failure.appendFailure); hdfsWriter.write(sinkRecords); assertEquals(context.backoff(), connectorConfig.getLong(HdfsSinkConnectorConfig.RETRY_BACKOFF_CONFIG)); Map<String, List<Object>> data = Data.getData(); String logFile = FileUtils.logFileName(url, topicsDir, TOPIC_PARTITION); List<Object> content = data.get(logFile); assertEquals(null, content); hdfsWriter.write(new ArrayList<SinkRecord>()); content = data.get(logFile); assertEquals(null, content); Thread.sleep(context.backoff()); hdfsWriter.write(new ArrayList<SinkRecord>()); content = data.get(logFile); assertEquals(2, content.size()); hdfsWriter.close(); }
Source:
public static StartupClusterConnectivityChecker create(long timeoutSecs, boolean blockForRemoteDcs) { if (timeoutSecs < 0) logger.warn("skipping block-for-peers due to negative timeout. You may encounter errors or timeouts on" + " the first user query"); if (timeoutSecs > 100) logger.warn("setting the block-for-peers timeout (in seconds) to might be a bit excessive, but using it nonetheless", timeoutSecs); long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSecs); return new StartupClusterConnectivityChecker(timeoutNanos, blockForRemoteDcs); }

Target:
public static StartupClusterConnectivityChecker create(long timeoutSecs, boolean blockForRemoteDcs) { if (timeoutSecs > 100) logger.warn("setting the block-for-peers timeout (in seconds) to might be a bit excessive, but using it nonetheless", timeoutSecs); long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSecs); return new StartupClusterConnectivityChecker(timeoutNanos, blockForRemoteDcs); }
Source:
public void onEvent(Event e) { if (isReloadConfigEvent(e)) { handleReloadEvent(e); return; } if (getName().equals(e.getSource())) { LOG.debug("onEvent: ignoring event with EventTranslator as source"); return; } List<Event> translated = m_config.translateEvent(e); if (translated != null) { if (translated.isEmpty()) { LOG.debug("onEvent: received event that matches no translations: \n", EventUtils.toString(e)); return; } LOG.debug("onEvent: received valid registered translation event: \n", EventUtils.toString(e)); Log log = new Log(); Events events = new Events(); for (Iterator<Event> iter = translated.iterator(); iter.hasNext();) { Event event = iter.next(); events.addEvent(event); LOG.debug("onEvent: sended translated event: \n", EventUtils.toString(event)); } log.setEvents(events); getEventManager().sendNow(log); } }

Target:
public void onEvent(Event e) { if (isReloadConfigEvent(e)) { handleReloadEvent(e); return; } if (getName().equals(e.getSource())) { LOG.debug("onEvent: ignoring event with EventTranslator as source"); return; } List<Event> translated = m_config.translateEvent(e); if (translated != null) { if (translated.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("onEvent: received event that matches no translations: {}", EventUtils.toString(e)); } return; } if (LOG.isDebugEnabled()) { LOG.debug("onEvent: received valid register ed translation event: {}", EventUtils.toString(e)); } Log log = new Log(); Events events = new Events(); for (Iterator<Event> iter = translated.iterator(); iter.hasNext();) { Event event = iter.next(); events.addEvent(event); if (LOG.isDebugEnabled()) { LOG.debug("onEvent: sended translated event: {}", EventUtils.toString(e)); } } log.setEvents(events); getEventManager().sendNow(log); } }
Source:
private static String computeProcessingID(final String dataSource, final List<DataSegment> segments) { final String segmentIDs = Joiner.on("_").join( Iterables.transform( Ordering.natural().sortedCopy(segments), new Function<DataSegment, String>() { @Override public String apply(DataSegment x) { return String.format( "%s_%s_%s_%s", x.getInterval().getStart(), x.getInterval().getEnd(), x.getVersion(), x.getShardSpec().getPartitionNum() ); } } ) ); return String.format("%s_%s", dataSource, DigestUtils.sha1Hex(segmentIDs).toLowerCase()); }

Target:
private static String computeProcessingID(final String dataSource, final List<DataSegment> segments) { final String segmentIDs = Joiner.on("_").join( Iterables.transform( Ordering.natural().sortedCopy(segments), new Function<DataSegment, String>() { @Override public String apply(DataSegment x) { return String.format( "%s_%s_%s_%s", x.getInterval().getStart(), x.getInterval().getEnd(), x.getVersion(), x.getShardSpec().getPartitionNum() ); } } ) ); return String.format( "%s_%s", dataSource, Hashing.sha1().hashString(segmentIDs, Charsets.UTF_8).toString().toLowerCase() ); }
Source:
public NodeValue getAccValue() { double mode= Double.NaN; if ( count == 0 ) return noValuesToMode ; if ( super.errorCount != 0 ) return null ; int indexsize = collection.size(); double[] arrDouble = new double[indexsize]; for(int i=0; i<indexsize; i++){ arrDouble[i] = collection.get(i).getDouble(); } HashMap<Double,Integer> amode = new HashMap<Double,Integer>(); int max = 0; for(int i = 0; i < arrDouble.length; i++) { if (amode.get(arrDouble[i]) != null) { int count = amode.get(arrDouble[i]); count++; amode.put(arrDouble[i], count); if(count > max) { max = count; mode = arrDouble[i]; } } else { amode.put(arrDouble[i],1); if(mode==0) { mode = arrDouble[i]; } } } for (Map.Entry<Double, Integer> entry: amode.entrySet()) { if (entry.getValue() == max) { System.out.println("Print all max: "+entry.getKey()+" Count: "+entry.getValue()); } } return (NodeValue.makeDecimal(mode)); }

Target:
public NodeValue getAccValue() { double mode= Double.NaN; if ( count == 0 ) return noValuesToMode ; if ( super.errorCount != 0 ) return null ; int indexsize = collection.size(); double[] arrDouble = new double[indexsize]; for(int i=0; i<indexsize; i++){ arrDouble[i] = collection.get(i).getDouble(); } HashMap<Double,Integer> amode = new HashMap<Double,Integer>(); int max = 0; for(int i = 0; i < arrDouble.length; i++) { if (amode.get(arrDouble[i]) != null) { int count = amode.get(arrDouble[i]); count++; amode.put(arrDouble[i], count); if(count > max) { max = count; mode = arrDouble[i]; } } else { amode.put(arrDouble[i],1); if(mode==0) { mode = arrDouble[i]; } } } return NodeValue.makeDecimal(mode); }
Source:
public void testAddItem() { final Element enumerationItem = mock(Element.class); final DragAndDropHelper helper = mock(DragAndDropHelper.class); items.childNodes = mock(NodeList.class); doReturn(helper).when(view).getDragAndDropHelper(); view.addItem(enumerationItem); verify(items).appendChild(enumerationItem); verify(helper).refreshItemsPosition(); }

Target:
public void testAddItem() { final Element enumerationItem = mock(Element.class); final DragAndDropHelper helper = mock(DragAndDropHelper.class); items.childNodes = mock(NodeList.class); doReturn(helper).when(view).getDragAndDropHelper(); view.addItem(enumerationItem); verify(items).appendChild(enumerationItem); verify(helper).refreshItemsPosition(); verify(enumerationItem).setAttribute(DATA_POSITION, 0); }
Source:
public void testFreestyleWithIOExceptionPublisher() throws IOException, ExecutionException, InterruptedException { FreeStyleProject p = j.createFreeStyleProject(); p.getPublishersList().add(new TrueFalsePublisher(true)); p.getPublishersList().add(new IOExceptionPublisher()); p.getPublishersList().add(new ResultWriterPublisher("result.txt")); p.getPublishersList().add(new ArtifactArchiver("result.txt", "", false)); FreeStyleBuild b = p.scheduleBuild2(0).get(); assertEquals("Build must fail, because we used FalsePublisher", b.getResult(), Result.FAILURE); File file = new File(b.getArtifactsDir(), "result.txt"); assertTrue("ArtifactArchiver is executed even prior publisher fails.", file.exists()); assertTrue("Second publisher must see FAILURE status", FileUtils.readFileToString(file).equals(Result.FAILURE.toString())); }

Target:
public void testFreestyleWithIOExceptionPublisher() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.getPublishersList().add(new TrueFalsePublisher(true)); p.getPublishersList().add(new IOExceptionPublisher()); p.getPublishersList().add(new ResultWriterPublisher("result.txt")); final ArtifactArchiver artifactArchiver = new ArtifactArchiver("result.txt"); artifactArchiver.setOnlyIfSuccessful(false); p.getPublishersList().add(artifactArchiver); FreeStyleBuild b = p.scheduleBuild2(0).get(); assertEquals("Build must fail, because we used FalsePublisher", b.getResult(), Result.FAILURE); j.assertLogContains("\tat hudson.model.utils.IOExceptionPublisher", b); j.assertLogContains("Threw IOException from publisher!", b); File file = new File(b.getArtifactsDir(), "result.txt"); assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists()); assertTrue("Third publisher must see FAILURE status", FileUtils.readFileToString(file).equals(Result.FAILURE.toString())); }
Source:
} catch (IntrospectionException ie) { ie.printStackTrace(); }

Target:
} catch (IntrospectionException ie) { LOG.warn("Failed to introspect OnmsAssetRecord when initializing due to {}", ie.getLocalizedMessage()); }
Source:
public void execute() throws FluoCommandException { if (args.size() < 2) { throw new FluoCommandException("Usage: fluo exec <app> <class> args..."); } final String applicationName = args.get(0); final String className = args.get(1); FluoConfiguration fluoConfig = CommandUtil.resolveFluoConfig(); fluoConfig.setApplicationName(applicationName); CommandUtil.verifyAppInitialized(fluoConfig); fluoConfig = FluoAdminImpl.mergeZookeeperConfig(fluoConfig); try { Class<?> clazz = Class.forName(className); Guice.createInjector(new FluoConfigModule(clazz, fluoConfig)); Method method = clazz.getMethod("main", String[].class); method.invoke(null, args.subList(2, args.size())); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new FluoCommandException(String.format("Class %s must have a main method", className), e); } catch (ClassNotFoundException e) { throw new FluoCommandException(String.format("Class %s not found", className), e); } }

Target:
public void execute() throws FluoCommandException { if (args.size() < 2) { throw new FluoCommandException("Usage: fluo exec <app> <class> args..."); } final String applicationName = args.get(0); final String className = args.get(1); FluoConfiguration fluoConfig = CommandUtil.resolveFluoConfig(); fluoConfig.setApplicationName(applicationName); CommandUtil.verifyAppInitialized(fluoConfig); fluoConfig = FluoAdminImpl.mergeZookeeperConfig(fluoConfig); try { Class<?> clazz = Class.forName(className); Guice.createInjector(new FluoConfigModule(clazz, fluoConfig)); Method method = clazz.getMethod("main", String[].class); List<String> execArgs = args.subList(2, args.size()); method.invoke(null, (Object) execArgs.toArray(new String[execArgs.size()])); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new FluoCommandException(String.format("Class %s must have a main method", className), e); } catch (ClassNotFoundException e) { throw new FluoCommandException(String.format("Class %s not found", className), e); } }
Source:
public void addConnection(PhoenixConnection connection) throws SQLException { if (returnSequenceValues || shouldThrottleNumConnections) { synchronized (connectionCountLock) { if(shouldThrottleNumConnections) { int futureConnections = 1 + ( connection.isInternalConnection() ? internalConnectionCount : connectionCount); int allowedConnections = connection.isInternalConnection() ? maxInternalConnectionsAllowed : maxConnectionsAllowed; if(allowedConnections != 0 && futureConnections > allowedConnections) { GLOBAL_PHOENIX_CONNECTIONS_THROTTLED_COUNTER.increment(); throw new SQLExceptionInfo.Builder(SQLExceptionCode.NEW_CONNECTION_THROTTLED). build().buildException(); } } if(!connection.isInternalConnection()) { connectionCount++; } else { internalConnectionCount++; } } } if (isRenewingLeasesEnabled()) { connectionQueues.get(getQueueIndex(connection)).add(new WeakReference<PhoenixConnection>(connection)); } }

Target:
public void addConnection(PhoenixConnection connection) throws SQLException { if (returnSequenceValues || shouldThrottleNumConnections) { synchronized (connectionCountLock) { if(shouldThrottleNumConnections) { int futureConnections = 1 + ( connection.isInternalConnection() ? internalConnectionCount : connectionCount); int allowedConnections = connection.isInternalConnection() ? maxInternalConnectionsAllowed : maxConnectionsAllowed; if(allowedConnections != 0 && futureConnections > allowedConnections) { GLOBAL_PHOENIX_CONNECTIONS_THROTTLED_COUNTER.increment(); if(connection.isInternalConnection()) { throw new SQLExceptionInfo.Builder(SQLExceptionCode.NEW_INTERNAL_CONNECTION_THROTTLED). build().buildException(); } throw new SQLExceptionInfo.Builder(SQLExceptionCode.NEW_CONNECTION_THROTTLED). build().buildException(); } } if(!connection.isInternalConnection()) { connectionCount++; } else { internalConnectionCount++; } } } if (isRenewingLeasesEnabled()) { connectionQueues.get(getQueueIndex(connection)).add(new WeakReference<PhoenixConnection>(connection)); } }
Source:
private void createNewExperimentNameGroup(Composite parent) { Font font = parent.getFont(); Composite folderGroup = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; folderGroup.setLayout(layout); folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; String name = fExperiment.getName(); Label newExperimentLabel = new Label(folderGroup, SWT.NONE); newExperimentLabel.setFont(font); newExperimentLabel.setText(Messages.RenameExperimentDialog_ExperimentNewName); fNewExperimentName = new Text(folderGroup, SWT.BORDER); data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; fNewExperimentName.setLayoutData(data); fNewExperimentName.setFont(font); fNewExperimentName.setFocus(); fNewExperimentName.setText(name); fNewExperimentName.setSelection(0, name.length()); fNewExperimentName.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateNewExperimentName(); } }); }

Target:
private void createNewExperimentNameGroup(Composite parent) { Font font = parent.getFont(); Composite folderGroup = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; folderGroup.setLayout(layout); folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); String name = fExperiment.getName(); Label newExperimentLabel = new Label(folderGroup, SWT.NONE); newExperimentLabel.setFont(font); newExperimentLabel.setText(Messages.RenameExperimentDialog_ExperimentNewName); fNewExperimentName = new Text(folderGroup, SWT.BORDER); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; fNewExperimentName.setLayoutData(data); fNewExperimentName.setFont(font); fNewExperimentName.setFocus(); fNewExperimentName.setText(name); fNewExperimentName.setSelection(0, name.length()); fNewExperimentName.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateNewExperimentName(); } }); }
Source:
private boolean isImagesExists() { for (DiskImage diskImage : getSourceImages()) { if (diskImage.getDiskStorageType() == DiskStorageType.IMAGE) { return true; } } return false; }

Target:
private boolean isImagesExists() { List<DiskImage> disks = ImagesHandler.filterImageDisks(getSourceImages(), true, false, true); return !disks.isEmpty(); }
Source:
public Future<String> asyncRemoteCancelMethod() throws InterruptedException { try { System.out.println("ASYNC REMOTE "); String result; result = ctx.wasCancelCalled() ? "true" : "false"; System.out.println("DO COUNTDOWN "); synchronizeBean.latchCountDown(); long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { if (ctx.wasCancelCalled()) { break; } Thread.sleep(50); } result += ";"; result += ctx.wasCancelCalled() ? "true" : "false"; return new AsyncResult<String>(result); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }

Target:
public Future<String> asyncRemoteCancelMethod() throws InterruptedException { String result; result = ctx.wasCancelCalled() ? "true" : "false"; synchronizeBean.latchCountDown(); long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { if (ctx.wasCancelCalled()) { break; } Thread.sleep(50); } result += ";"; result += ctx.wasCancelCalled() ? "true" : "false"; return new AsyncResult<String>(result); }
Source:
private void writeHierarchyInfo( SaxWriter writer, List<Hierarchy> hierarchies, List<Property> props) { writer.startSequence(null, "HierarchyInfo"); for (Hierarchy hierarchy : hierarchies) { writer.startElement( "HierarchyInfo", "name", hierarchy.getName()); for (final Property prop : props) { if (prop instanceof IMondrianOlap4jProperty) { IMondrianOlap4jProperty currentProperty = (IMondrianOlap4jProperty) prop; String thisHierarchiName = hierarchy.getName(); String thatHierarchiName = currentProperty.getLevel() .getHierarchy().getName(); if (thisHierarchiName.equals(thatHierarchiName)) { final String encodedProp = encoder .encode(prop.getName()); final Object[] attributes = getAttributes( prop, hierarchy); writer.element(encodedProp, attributes); } } else { final String encodedProp = encoder.encode( prop.getName()); final Object[] attributes = getAttributes( prop, hierarchy); writer.element(encodedProp, attributes); } } writer.endElement(); } writer.endSequence(); }

Target:
private void writeHierarchyInfo( SaxWriter writer, List<Hierarchy> hierarchies, List<Property> props) { writer.startSequence(null, "HierarchyInfo"); for (Hierarchy hierarchy : hierarchies) { writer.startElement( "HierarchyInfo", "name", hierarchy.getName()); for (final Property prop : props) { if (prop instanceof IMondrianOlap4jProperty) { writeProperty(writer, hierarchy, prop); } else { writeElement(writer, hierarchy, prop); } } writer.endElement(); } writer.endSequence(); }
Source:
public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.contains("RESOURCE_NOT_FOUND") || message.contains("OPERATION_NOT_SUPPORTED")) { exception = new ResourceNotFoundException(message, exception); } else if (message.contains("INVALID_INPUT_DATA") || message.contains("ORGANIZATION_NOT_VERIFIED") || (message.contains("SYSTEM_ERROR") && !message.contains("RETRYABLE_SYSTEM_ERROR")) || message .contains("CPU_SPEED_NOT_AVAILABLE") || message.contains("CONFIGURATION_NOT_SUPPORTED")) { exception = new IllegalStateException(message, exception); } else if (message.contains("RESOURCE_BUSY") || message.contains("UNEXPECTED_ERROR")) { exception = new ResourceNotFoundException(message, exception); } else if (message.contains("NAME_NOT_UNIQUE")) { exception = new ResourceAlreadyExistsException(message, exception); } break; case 401: exception = new AuthorizationException(message, exception); break; case 403: exception = new AuthorizationException(message, exception); break; case 404: exception = new IllegalStateException(message, exception); break; } command.setException(exception); }

Target:
public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: if (message.contains("RESOURCE_NOT_FOUND")) { exception = new ResourceNotFoundException(message, exception); } else if (message.contains("OPERATION_NOT_SUPPORTED")) { exception = new UnsupportedOperationException(message, exception); } else if (message.contains("RESOURCE_BUSY")) { exception = new ConcurrentModificationException(message, exception); } else if (message.contains("RESOURCE_LOCKED")) { exception = new IllegalStateException(message, exception); } else if (message.contains("NAME_NOT_UNIQUE")) { exception = new ResourceAlreadyExistsException(message, exception); } else if (message.contains("UNEXPECTED_ERROR") || message.contains("RETRYABLE_SYSTEM_ERROR") || message.contains("SYSTEM_ERROR")) { break; } else { exception = new IllegalArgumentException(message, exception); } break; case 401: exception = new AuthorizationException(message, exception); break; case 403: exception = new AuthorizationException(message, exception); break; case 404: exception = new IllegalArgumentException(message, exception); break; } command.setException(exception); }
Source:
public void onResume(ClientContext context) throws InsertException, ResumeFailedException { assert(persistent); synchronized(this) { if(resumed) return; resumed = true; } this.context = context; try { raf.onResume(context); originalData.onResume(context); this.storage = new SplitFileInserterStorage(raf, originalData, this, context.fastWeakRandom, context.memoryLimitedJobRunner, context.getJobRunner(true), context.ticker, context.getChkInsertScheduler(realTime).fetchingKeys(), context.persistentFG, context.persistentFileTracker, context.getPersistentMasterSecret()); storage.onResume(context); synchronized(this) { this.sender = new SplitFileInserterSender(this, storage); } schedule(context); } catch (IOException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } catch (StorageFormatException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } catch (ChecksumFailedException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } }

Target:
public void onResume(ClientContext context) throws InsertException, ResumeFailedException { assert(persistent); synchronized(this) { if(resumed) return; resumed = true; } this.context = context; try { raf.onResume(context); originalData.onResume(context); this.storage = new SplitFileInserterStorage(raf, originalData, this, context.fastWeakRandom, context.memoryLimitedJobRunner, context.getJobRunner(true), context.ticker, context.getChkInsertScheduler(realTime).fetchingKeys(), context.persistentFG, context.persistentFileTracker, context.getPersistentMasterSecret()); storage.onResume(context); this.sender = new SplitFileInserterSender(this, storage); schedule(context); } catch (IOException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } catch (StorageFormatException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } catch (ChecksumFailedException e) { Logger.error(this, "Resume failed: "+e, e); raf.close(); raf.free(); originalData.close(); if(freeData) originalData.free(); throw new InsertException(InsertExceptionMode.BUCKET_ERROR, e, null); } }
Source:
public void setUserPattern(String userPattern) { this.userPattern = Util.fixEmptyAndTrim(userPattern); if (this.userPattern != null) { this.userPat = Pattern.compile(this.userPattern); } else { this.userPat = null; } }

Target:
public void setUserPattern(String userPattern) { this.userPattern = Util.fixEmptyAndTrim(userPattern); if (this.userPattern == null) { this.userPat = null; } else { this.userPat = Pattern.compile(this.userPattern); } }
Source:
private void verifyPerspectiveIsLoaded(String perspectiveID, By elementInPerspective) { try { Waits.elementPresent(elementInPerspective, 10); } catch (WebDriverException ex) { Assertions.fail("The perspective with ID " + perspectiveID + " could not be loaded."); } }

Target:
private void verifyPerspectiveIsLoaded(String perspectiveID, By elementInPerspective) { try { Waits.elementPresent(elementInPerspective, 10); } catch (WebDriverException exception) { Assertions.fail("The perspective with ID " + perspectiveID + " could not be loaded.", exception); } }
Source:
private void assembleDataImport() { server_.assembleDataImport(getOptions(), new ServerRequestCallback<DataImportAssembleResponse>() { @Override public void onResponseReceived(DataImportAssembleResponse response) { if (response.getErrorMessage() != null) { progressIndicator_.onError(response.getErrorMessage()); return; } codePreview_ = response.getImportCode(); dataImportOptionsUi_.setAssembleResponse(response); codeArea_.setCode(codePreview_); codeArea_.getEditor().getSession().setEditorMode(EditorLanguage.LANG_R.getParserName(), false); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage(codePreviewErrorMessage_, error.getMessage()); } }); }

Target:
private void assembleDataImport() { server_.assembleDataImport(getOptions(), new ServerRequestCallback<DataImportAssembleResponse>() { @Override public void onResponseReceived(DataImportAssembleResponse response) { if (response.getErrorMessage() != null) { progressIndicator_.onError(response.getErrorMessage()); return; } codePreview_ = response.getImportCode(); dataImportOptionsUi_.setAssembleResponse(response); codeArea_.getEditor().getSession().setEditorMode(EditorLanguage.LANG_R.getParserName(), false); codeArea_.getEditor().getRenderer().setShowGutter(false); codeArea_.setCode(codePreview_); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage(codePreviewErrorMessage_, error.getMessage()); } }); }
Source:
public void sendRequestToCatalog(String endpoint, RequestCallback callback) { String endpointToAddToCatalogUrl = endpoint; if (endpoint.startsWith("/")) { endpointToAddToCatalogUrl = endpoint.substring(1); } RequestBuilder request = new RequestBuilder(RequestBuilder.GET, this.catalogUrl + "/" + endpointToAddToCatalogUrl); request.setHeader(SESSION_ID_PARAMETER_NAME, LoginModel.getInstance().getSessionId()); request.setCallback(callback); try { request.send(); } catch (RequestException e) { this.importFromCatalogPanelFeeder.setNodeSourceWindowLabelWithError("Request sent to catalog failed", e); } }

Target:
public void sendRequestToCatalog(String endpoint, RequestCallback callback) { RequestBuilder request = new RequestBuilder(RequestBuilder.GET, this.catalogUrl + "/" + endpoint); request.setHeader(CatalogConstants.SESSION_ID_PARAM, LoginModel.getInstance().getSessionId()); request.setCallback(callback); try { request.send(); } catch (RequestException e) { this.importFromCatalogPanelFeeder.setNodeSourceWindowLabelWithError("Request sent to catalog failed", e); } }
Source:
private long roundToNextMinute(long timeInMillis) { Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(timeInMillis); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MINUTE, 1); return calendar.getTimeInMillis(); }

Target:
private long roundToNextMinute(long timeInMillis) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timeInMillis); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MINUTE, 1); return calendar.getTimeInMillis(); }
Source:
public Optional<ElderData> build(DataView container) throws InvalidDataException { if (container.contains(Keys.ELDER_GUARDIAN.getQuery())) { Optional<Boolean> elder = container.getBoolean(Keys.ELDER_GUARDIAN.getQuery()); if (elder.isPresent()) { return Optional.<ElderData>of(new SpongeElderData(elder.get())); } } return Optional.absent(); }

Target:
public Optional<ElderData> build(DataView container) throws InvalidDataException { if(container.contains(Keys.ELDER_GUARDIAN.getQuery())) { return Optional.of(new SpongeElderData(DataUtil.getData(container, Keys.ELDER_GUARDIAN))); } return Optional.empty(); }
Source:
public void info(String message, Object... objects) { LOG.warn(message, objects); }

Target:
public void info(String message, Object... objects) { LOG.info(message, objects); }
Source:
private EventHandler<ActiveContext> getSecondContextActiveHandlerForWorker() { return new EventHandler<ActiveContext>() { @Override public void onNext(final ActiveContext activeContext) { LOG.log(Level.INFO, "Worker-side ParameterWorker context - {0}", activeContext); final int workerIndex = Integer.parseInt(activeContext.getId().substring(WORKER_CONTEXT.length() + 1)); final Configuration taskConf = TaskConfiguration.CONF .set(TaskConfiguration.IDENTIFIER, AsyncWorkerTask.TASK_ID_PREFIX + "-" + workerIndex) .set(TaskConfiguration.TASK, AsyncWorkerTask.class) .build(); final Configuration emIdConf = Tang.Factory.getTang().newConfigurationBuilder() .bindImplementation(DataIdFactory.class, BaseCounterDataIdFactory.class).build(); activeContext.submitTask(Configurations.merge(taskConf, workerConf, emIdConf)); } }; }

Target:
private EventHandler<ActiveContext> getSecondContextActiveHandlerForWorker() { return new EventHandler<ActiveContext>() { @Override public void onNext(final ActiveContext activeContext) { LOG.log(Level.INFO, "Worker-side ParameterWorker context - {0}", activeContext); final int workerIndex = Integer.parseInt(activeContext.getId().substring(WORKER_CONTEXT.length() + 1)); final Configuration taskConf = TaskConfiguration.CONF .set(TaskConfiguration.IDENTIFIER, AsyncWorkerTask.TASK_ID_PREFIX + "-" + workerIndex) .set(TaskConfiguration.TASK, AsyncWorkerTask.class) .build(); final Configuration emDataIdConf = Tang.Factory.getTang().newConfigurationBuilder() .bindImplementation(DataIdFactory.class, BaseCounterDataIdFactory.class).build(); activeContext.submitTask(Configurations.merge(taskConf, workerConf, emDataIdConf)); } }; }
Source:
public View getView(int position, View convertView, ViewGroup parent) { View element = super.getView(position, convertView, parent); PlaylistEntry entry = super.getItem(position); if (!entry.isLoaded()) { element.setBackgroundColor(getResources().getColor(R.color.abs__bright_foreground_disabled_holo_light)); element.findViewById(R.id.progress).setVisibility(View.VISIBLE); } else if (entry.isPlayed()) { element.setBackgroundColor(getResources().getColor(R.color.used)); } else { element.setBackgroundColor(getResources().getColor(com.actionbarsherlock.R.color.abs__background_holo_light)); element.findViewById(R.id.progress).setVisibility(View.INVISIBLE); } final GestureDetectorCompat songGesture = new GestureDetectorCompat(getActivity(), new PlaylistSongGestureListener(element, entry)); element.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return songGesture.onTouchEvent(event); } }); ImageButton delete = (ImageButton)element.findViewById(R.id.btn_remove_from_playlist); delete.setOnClickListener(new DeleteSongListener(entry)); delete.setVisibility(View.VISIBLE); return element; }

Target:
public View getView(int position, View convertView, ViewGroup parent) { View element = super.getView(position, convertView, parent); PlaylistEntry entry = super.getItem(position); if (!entry.isLoaded()) { element.setBackgroundColor(getResources().getColor(R.color.abs__bright_foreground_disabled_holo_light)); element.findViewById(R.id.progress).setVisibility(View.VISIBLE); element.findViewById(R.id.now_playing).setVisibility(View.INVISIBLE); } else if (entry.isPlayed()) { element.setBackgroundColor(getResources().getColor(R.color.used)); element.findViewById(R.id.now_playing).setVisibility(View.INVISIBLE); } else { element.setBackgroundColor(getResources().getColor(com.actionbarsherlock.R.color.abs__background_holo_light)); element.findViewById(R.id.progress).setVisibility(View.INVISIBLE); if(entry.equals(getPlaylistService().getCurrentEntry())){ element.findViewById(R.id.now_playing).setVisibility(View.VISIBLE); } else{ element.findViewById(R.id.now_playing).setVisibility(View.INVISIBLE); } } final GestureDetectorCompat songGesture = new GestureDetectorCompat(getActivity(), new PlaylistSongGestureListener(element, entry)); element.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return songGesture.onTouchEvent(event); } }); return element; }
Source:
public void toStream(@NonNull JsonStream writer) throws IOException { writer.beginObject(); writer.name("osName").value("android"); writer.name("manufacturer").value(android.os.Build.MANUFACTURER); writer.name("brand").value(android.os.Build.BRAND); writer.name("model").value(android.os.Build.MODEL); writer.name("id").value(id); writer.name("apiLevel").value(android.os.Build.VERSION.SDK_INT); writer.name("osVersion").value(android.os.Build.VERSION.RELEASE); writer.name("osBuild").value(android.os.Build.DISPLAY); writer.name("locale").value(locale); writer.name("totalMemory").value(totalMemory); writer.name("jailbroken").value(rooted); writer.name("screenDensity").value(screenDensity); writer.name("dpi").value(dpi); writer.name("screenResolution").value(screenResolution); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { writer.name("cpuAbi").value(Arrays.toString(Build.SUPPORTED_ABIS)); } else { writer.name("cpuAbi").value(Build.CPU_ABI); } writer.endObject(); }

Target:
public void toStream(@NonNull JsonStream writer) throws IOException { writer.beginObject(); writer.name("osName").value("android"); writer.name("manufacturer").value(android.os.Build.MANUFACTURER); writer.name("brand").value(android.os.Build.BRAND); writer.name("model").value(android.os.Build.MODEL); writer.name("id").value(id); writer.name("apiLevel").value(android.os.Build.VERSION.SDK_INT); writer.name("osVersion").value(android.os.Build.VERSION.RELEASE); writer.name("osBuild").value(android.os.Build.DISPLAY); writer.name("locale").value(locale); writer.name("totalMemory").value(totalMemory); writer.name("jailbroken").value(rooted); writer.name("screenDensity").value(screenDensity); writer.name("dpi").value(dpi); writer.name("screenResolution").value(screenResolution); String cpuAbi = Build.CPU_ABI; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cpuAbi = Arrays.toString(Build.SUPPORTED_ABIS); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { cpuAbi = Arrays.toString(new String[]{Build.CPU_ABI,Build.CPU_ABI2}); } writer.name("cpuAbi").value(cpuAbi); writer.endObject(); }
Source:
public static void main(final String[] args) throws Exception { LoggerUtil.addAppender("apexclient"); final ApexCli shell = new ApexCli(); shell.preImpersonationInit(args); String hadoopUserName = System.getenv("HADOOP_USER_NAME"); if (UserGroupInformation.isSecurityEnabled() && StringUtils.isNotBlank(hadoopUserName) && !hadoopUserName.equals(UserGroupInformation.getLoginUser().getUserName())) { LOG.info("You ({}) are running as user {}", UserGroupInformation.getLoginUser().getUserName(), hadoopUserName); UserGroupInformation ugi = UserGroupInformation.createProxyUser(hadoopUserName, UserGroupInformation.getLoginUser()); ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { shell.mainHelper(); return null; } }); } else { shell.mainHelper(); } }

Target:
public static void main(final String[] args) throws Exception { LoggerUtil.addAppenders(); final ApexCli shell = new ApexCli(); shell.preImpersonationInit(args); String hadoopUserName = System.getenv("HADOOP_USER_NAME"); if (UserGroupInformation.isSecurityEnabled() && StringUtils.isNotBlank(hadoopUserName) && !hadoopUserName.equals(UserGroupInformation.getLoginUser().getUserName())) { LOG.info("You ({}) are running as user {}", UserGroupInformation.getLoginUser().getUserName(), hadoopUserName); UserGroupInformation ugi = UserGroupInformation.createProxyUser(hadoopUserName, UserGroupInformation.getLoginUser()); ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { shell.mainHelper(); return null; } }); } else { shell.mainHelper(); } }
Source:
public ObjStoreBrowserImpl(ObjStoreBrowser osb) { try { printStream = new PrintStream(System.out, true, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 is not supported"); } this.osb = osb; }

Target:
public ObjStoreBrowserImpl(ObjStoreBrowser osb) { try { printStream = new PrintStream(System.out, true, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { System.err.println("Encoding " + StandardCharsets.UTF_8.name() + " is not supported"); throw new IllegalStateException(StandardCharsets.UTF_8.name() + " is not supported"); } this.osb = osb; }
Source:
public void setStarred(TaskRepository taskRepository, String taskID, boolean starred) throws CoreException { GerritClient client = getClient(taskRepository); SaveStarredRequest saveStarRequest = new SaveStarredRequest(taskRepository, taskID, starred); try { client.setStarred(saveStarRequest.getReviewId(), starred, null); } catch (GerritException e) { Status status = new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, "Unable to set the starred, received", e); throw new CoreException(status); } }

Target:
public void setStarred(TaskRepository taskRepository, String taskID, boolean starred) throws CoreException { GerritClient client = getClient(taskRepository); SaveStarredRequest saveStarRequest = new SaveStarredRequest(taskRepository, taskID, starred); try { client.setStarred(saveStarRequest.getReviewId(), starred, null); } catch (GerritException e) { Status status = new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, "Unable to set the starred flag, the following Status is received", e); throw new CoreException(status); } }
Source:
private static SortedMap<String, List<String>> asMap(final String query) { final SortedMap<String, List<String>> params = new TreeMap<String, List<String>>(); if (query != null) { final String[] pairs = query.split("&"); for (final String pair : pairs) { final String[] parts = pair.split("=", 2); final String key = Href.decode(parts[0]); final String value; if (parts.length > 1) { value = Href.decode(parts[1]); } else { value = ""; } if (!params.containsKey(key)) { params.put(key, new LinkedList<String>()); } params.get(key).add(value); } } return params; }

Target:
private static SortedMap<String, List<String>> asMap(final String query) { final SortedMap<String, List<String>> params = new TreeMap<>(); if (query != null) { for (final String pair : query.split("&")) { final String[] parts = pair.split("=", 2); final String key = Href.decode(parts[0]); final String value; if (parts.length > 1) { value = Href.decode(parts[1]); } else { value = ""; } if (!params.containsKey(key)) { params.put(key, new LinkedList<String>()); } params.get(key).add(value); } } return params; }
Source:
public boolean isDown() { boolean down = false; if (hardDown) { down = true; } else if (failureCount.get() >= failureCountThreshold) { if (SystemTime.getInstance().milliseconds() < downUntil.get()) { down = true; } } logger.trace("Resource is {}; failureCount: {}; failureCountThreshold: {}; remaining time: {}; hard down: {}", resource, (down ? "down" : "not down"), failureCount.get(), failureCountThreshold, (downUntil.get() - SystemTime.getInstance().milliseconds()), hardDown); return down; }

Target:
public boolean isDown() { boolean down = false; if (hardDown) { down = true; } else if (failureCount.get() >= failureCountThreshold) { if (SystemTime.getInstance().milliseconds() < downUntil.get()) { down = true; } } if (down) { logger .trace("Resource is down; failureCount: {}; failureCountThreshold: {}; remaining time: {}; hard down: {}", resource, failureCount.get(), failureCountThreshold, downUntil.get() - SystemTime.getInstance().milliseconds(), hardDown); } else { logger.trace("Resource is not down; failureCount: {}; failureCountThreshold: {}", resource, failureCount.get(), failureCountThreshold); } return down; }
Source:
public boolean mkdir(String remoteDirectory) throws IOException { try { this.channel.mkdir(remoteDirectory); } catch (SftpException ex) { if (ex.id == ChannelSftp.SSH_FX_FAILURE && exists(remoteDirectory)) { return false; } else { throw new NestedIOException("failed to create remote directory '" + remoteDirectory + "'.", ex); } } return true; }

Target:
public boolean mkdir(String remoteDirectory) throws IOException { try { this.channel.mkdir(remoteDirectory); } catch (SftpException ex) { if (ex.id != ChannelSftp.SSH_FX_FAILURE || !exists(remoteDirectory)) { throw new NestedIOException("failed to create remote directory '" + remoteDirectory + "'.", ex); } } return true; }
Source:
public void testDoubleNaNInfinity() throws Exception { tester.testRoundTrip(DOUBLE, ImmutableList.of(1000.0, -1.0, Double.POSITIVE_INFINITY)); tester.testRoundTrip(DOUBLE, ImmutableList.of(-1000.0, Double.NEGATIVE_INFINITY, 1.0)); tester.testRoundTrip(DOUBLE, ImmutableList.of(0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)); tester.testRoundTrip(DOUBLE, ImmutableList.of(Double.NaN, -1.0, 1.0)); tester.testRoundTrip(DOUBLE, ImmutableList.of(Double.NaN, -1.0, Double.POSITIVE_INFINITY)); tester.testRoundTrip(DOUBLE, ImmutableList.of(Double.NaN, Double.NEGATIVE_INFINITY, 1.0)); tester.testRoundTrip(DOUBLE, ImmutableList.of(Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)); }

Target:
public void testDoubleNaNInfinity() throws Exception { List<Map<Integer, TupleDomainFilter>> filters = ImmutableList.of( ImmutableMap.of(0, DoubleRange.of(0, false, false, 1_000, false, false, false)), ImmutableMap.of(0, IS_NULL), ImmutableMap.of(0, IS_NOT_NULL)); tester.testRoundTrip(DOUBLE, ImmutableList.of(1000.0, -1.0, Double.POSITIVE_INFINITY), filters); tester.testRoundTrip(DOUBLE, ImmutableList.of(-1000.0, Double.NEGATIVE_INFINITY, 1.0), filters); tester.testRoundTrip(DOUBLE, ImmutableList.of(0.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), filters); tester.testRoundTrip(DOUBLE, ImmutableList.of(Double.NaN, -1.0, 1.0), filters); tester.testRoundTrip(DOUBLE, ImmutableList.of(Double.NaN, -1.0, Double.POSITIVE_INFINITY), filters); tester.testRoundTrip(DOUBLE, ImmutableList.of(Double.NaN, Double.NEGATIVE_INFINITY, 1.0), filters); tester.testRoundTrip(DOUBLE, ImmutableList.of(Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), filters); }
Source:
@Override public void onResume() { super.onResume(); if( getArguments().getString("state").equalsIgnoreCase("From Favourite")) { setUpFavTriggers(); } else { BackendClient.of(this).getTriggers(new TriggersCallback()); } }

Target:
public void onResume() { super.onResume(); if( getArguments().getString("state").equalsIgnoreCase("From Favourite")) { setUpFavTriggers(); } else { BackendClient.of(this).getTriggers(new TriggersCallback()); } }
Source:
protected void log(Object... params) { int sampleRate = WikipediaApp.getInstance().getRemoteConfig().getConfig() .optInt("linkPreviewLogSampleRate", WikipediaApp.getInstance().getReleaseType() == WikipediaApp.RELEASE_PROD ? DEFAULT_SAMPLE_RATE : 1); super.log(title.getSite(), sampleRate, params); }

Target:
protected void log(Object... params) { int sampleRate = WikipediaApp.getInstance().getRemoteConfig().getConfig() .optInt("linkPreviewLogSampleRate", WikipediaApp.getInstance().isProdRelease() ? DEFAULT_SAMPLE_RATE : 1); super.log(title.getSite(), sampleRate, params); }
Source:
public String getHtmlPage() { return htmlPage; }

Target:
public String getHtmlPage() { return parent1; }
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("first_name", firstName) .add("middle_name", middleName) .add("last_name", lastName) .add("gender", gender) .add("verified", verified) .toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("firstName", firstName) .add("middleName", middleName) .add("lastName", lastName) .add("gender", gender) .add("verified", verified) .toString(); }
Source:
private void initializeBridge() { bridgeProperties = new HashMap<>(); bridge = BridgeBuilder.create(new ThingTypeUID("iota", "test-bridge"), "testbridge").withLabel("Test Bridge") .withConfiguration(new Configuration(bridgeProperties)).build(); IotaUtilsImpl mockUtils = mock(IotaUtilsImpl.class); when(mockUtils.checkAPI()).thenReturn(true); iotaBridgeHandler = new IotaBridgeHandler(bridge, mockUtils); bridge.setHandler(iotaBridgeHandler); ThingHandlerCallback bridgeHandler = mock(ThingHandlerCallback.class); doAnswer(answer -> { ((Thing) answer.getArgument(0)).setStatusInfo(answer.getArgument(1)); return null; }).when(bridgeHandler).statusUpdated(any(), any()); iotaBridgeHandler.setCallback(bridgeHandler); iotaBridgeHandler.initialize(); }

Target:
protected Bridge initializeBridge() { bridgeProperties = new HashMap<>(); bridge = BridgeBuilder.create(new ThingTypeUID("iota", "test-bridge"), "testbridge").withLabel("Test Bridge") .withConfiguration(new Configuration(bridgeProperties)).build(); IotaUtilsImpl mockUtils = Mockito.mock(IotaUtilsImpl.class); when(mockUtils.checkAPI()).thenReturn(true); iotaBridgeHandler = new IotaBridgeHandler(bridge, mockUtils); bridge.setHandler(iotaBridgeHandler); ThingHandlerCallback bridgeHandlerCallback = mock(ThingHandlerCallback.class); doAnswer(answer -> { ((Thing) answer.getArgument(0)).setStatusInfo(answer.getArgument(1)); return null; }).when(bridgeHandlerCallback).statusUpdated(any(), any()); iotaBridgeHandler.setCallback(bridgeHandlerCallback); iotaBridgeHandler.initialize(); return bridge; }