auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean step(IPointable result, IFrameWriter writer, int tupleIndex) throws AlgebricksException { if (indexPlace < indexLength) { nodeAbvs.reset(); try { doc = searcher.doc(hits[indexPlace].doc); fields = doc.getFields(); handler.setupElementWriter(writer, tupleIndex); parse(nodeAbvs); } catch (IOException e) { throw new AlgebricksException(e); } indexPlace += 1; result.set(nodeAbvs.getByteArray(), nodeAbvs.getStartOffset(), nodeAbvs.getLength()); return true; } return false; }

Target:
public boolean step(IPointable result, IFrameWriter writer, int tupleIndex) throws AlgebricksException { if (indexPlace < indexLength) { nodeAbvs.reset(); try { doc = searcher.doc(hits[indexPlace].doc); fields = doc.getFields(); handler.setupElementWriter(writer, tupleIndex); this.firstElement = true; parse(nodeAbvs); } catch (IOException e) { throw new AlgebricksException(e); } indexPlace += 1; result.set(nodeAbvs.getByteArray(), nodeAbvs.getStartOffset(), nodeAbvs.getLength()); return true; } return false; }
Source:
public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); adapter = new ExchangeRatesAdapter(); adapter.setRateBase(config.getBtcBase()); adapter.setDefaultCurrency(config.getExchangeCurrencyCode()); exchangeRatesViewModel = ViewModelProviders.of(this) .get(ExchangeRatesViewModel.class); exchangeRatesViewModel.isLoading().observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean isLoading) { loading.setVisibility(Boolean.TRUE.equals(isLoading) ? View.VISIBLE : View.GONE); } }); exchangeRatesViewModel.hasError().observe(this, new Observer<Boolean>() { @Override public void onChanged(@android.support.annotation.Nullable Boolean aBoolean) { if (Boolean.TRUE.equals(true)) { showOnly(loadingErrorView); } } }); exchangeRatesViewModel.getRates().observe(this, new Observer<List<de.schildbach.wallet.rates.ExchangeRate>>() { @Override public void onChanged(List<de.schildbach.wallet.rates.ExchangeRate> exchangeRates) { updateView(exchangeRates); } }); config.registerOnSharedPreferenceChangeListener(this); }

Target:
public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); adapter = new ExchangeRatesAdapter(); adapter.setRateBase(config.getBtcBase()); adapter.setDefaultCurrency(config.getExchangeCurrencyCode()); exchangeRatesViewModel = ViewModelProviders.of(this) .get(ExchangeRatesViewModel.class); exchangeRatesViewModel.isLoading().observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean isLoading) { loading.setVisibility(Boolean.TRUE.equals(isLoading) ? View.VISIBLE : View.GONE); } }); exchangeRatesViewModel.hasError().observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean hasError) { if (Boolean.TRUE.equals(hasError)) { showOnly(loadingErrorView); } } }); exchangeRatesViewModel.getRates().observe(this, new Observer<List<de.schildbach.wallet.rates.ExchangeRate>>() { @Override public void onChanged(List<de.schildbach.wallet.rates.ExchangeRate> exchangeRates) { updateView(exchangeRates); } }); config.registerOnSharedPreferenceChangeListener(this); }
Source:
protected void setResult(ISelection selection, Class<T> target) { List<T> selected = Collections.emptyList(); if (selection instanceof IStructuredSelection && target != null) { IStructuredSelection structured = (IStructuredSelection) selection; selected = ((List<?>) structured.toList()).stream().filter(p -> target.isInstance(p)) .map(p -> target.cast(p)).collect(Collectors.toList()); } setResult(selected); }

Target:
protected void setResult(ISelection selection, Class<T> target) { List<T> selected = null; if (selection instanceof IStructuredSelection && target != null) { IStructuredSelection structured = (IStructuredSelection) selection; selected = ((List<?>) structured.toList()).stream().filter(p -> target.isInstance(p)) .map(p -> target.cast(p)).collect(Collectors.toList()); } setResult(selected); }
Source:
public String getIP() { return "10.241.100.159"; }

Target:
public String getIP() { return ""; }
Source:
public void listTemplatesTest() throws Exception { Pages.getProjectsPage().goTo(); int numberOfTemplatesInDatabase = serviceManager.getTemplateService().getActiveTemplates().size(); int numberOfTemplatesDisplayed = Pages.getTemplatePage().countListedTemplates(); Thread.sleep(50000); Assert.assertEquals("Displayed wrong number of templates", numberOfTemplatesInDatabase, numberOfTemplatesDisplayed); }

Target:
public void listTemplatesTest() throws Exception { Pages.getProjectsPage().goTo(); int numberOfTemplatesInDatabase = serviceManager.getTemplateService().getActiveTemplates().size(); int numberOfTemplatesDisplayed = Pages.getProjectsPage().countListedTemplates(); Assert.assertEquals("Displayed wrong number of templates", numberOfTemplatesInDatabase, numberOfTemplatesDisplayed); }
Source:
private String extractSubject(HttpSession httpSession) { return Stream.of(httpSession.getAttribute(SecurityConstants.SAML_ASSERTION)) .map(SecurityTokenHolder.class::cast) .map(SecurityTokenHolder::getRealmTokenMap) .map(Map::values) .flatMap(Collection::stream) .map(this::extractSubject) .filter(Objects::nonNull) .map(SubjectUtils::getName) .findFirst() .orElse(null); }

Target:
private String extractSubject(HttpSession httpSession) { return Stream.of(httpSession.getAttribute(SecurityConstants.SAML_ASSERTION)) .filter(SecurityTokenHolder.class::isInstance) .map(SecurityTokenHolder.class::cast) .map(SecurityTokenHolder::getRealmTokenMap) .map(Map::values) .flatMap(Collection::stream) .map(this::extractSubject) .filter(Objects::nonNull) .map(SubjectUtils::getName) .findFirst() .orElse(null); }
Source:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { if (!isConfigured()) { return; } String selfSignedCertSecretName = identity.getWorkspaceId() + CHE_SELF_SIGNED_CERT_SECRET_SUFFIX; k8sEnv .getSecrets() .put( selfSignedCertSecretName, new SecretBuilder() .withNewMetadata() .withName(selfSignedCertSecretName) .endMetadata() .withStringData(ImmutableMap.of(CA_CERT_FILE, certificate)) .build()); for (PodData pod : k8sEnv.getPodsData().values()) { if (pod.getRole() == PodRole.DEPLOYMENT) { Optional<Volume> certVolume = pod.getSpec() .getVolumes() .stream() .filter(v -> v.getName().equals(CHE_SELF_SIGNED_CERT_VOLUME)) .findAny(); if (!certVolume.isPresent()) { pod.getSpec().getVolumes().add(buildCertSecretVolume(selfSignedCertSecretName)); } } for (Container container : pod.getSpec().getInitContainers()) { provisionCertVolumeMountIfNeeded(container); } for (Container container : pod.getSpec().getContainers()) { provisionCertVolumeMountIfNeeded(container); } } }

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { if (!isConfigured()) { return; } String selfSignedCertSecretName = identity.getWorkspaceId() + CHE_SELF_SIGNED_CERT_SECRET_SUFFIX; k8sEnv .getSecrets() .put( selfSignedCertSecretName, new SecretBuilder() .withNewMetadata() .withName(selfSignedCertSecretName) .endMetadata() .withStringData(ImmutableMap.of(CA_CERT_FILE, certificate)) .build()); for (PodData pod : k8sEnv.getPodsData().values()) { if (pod.getRole() == PodRole.DEPLOYMENT) { if (pod.getSpec() .getVolumes() .stream() .noneMatch(v -> v.getName().equals(CHE_SELF_SIGNED_CERT_VOLUME))) { pod.getSpec().getVolumes().add(buildCertSecretVolume(selfSignedCertSecretName)); } } for (Container container : pod.getSpec().getInitContainers()) { provisionCertVolumeMountIfNeeded(container); } for (Container container : pod.getSpec().getContainers()) { provisionCertVolumeMountIfNeeded(container); } } }
Source:
private List<String> readCategory(VEvent vEvent) { PropertyList propertyCategoryList = vEvent.getProperties(Property.CATEGORIES); ArrayList<String> splittedCategoriesToReturn = new ArrayList<String>(); if (propertyCategoryList != null) { for (int categorieslinenum = 0; categorieslinenum < propertyCategoryList.size(); categorieslinenum++) { Property propertyCategory = propertyCategoryList.get(categorieslinenum); String categories = propertyCategory.getValue(); if (categories != null) { String[] categoriesSplit = StringUtils.split(categories, ","); for (String macategorie : categoriesSplit) { if (!splittedCategoriesToReturn.contains(macategorie)) { splittedCategoriesToReturn.add(macategorie); } } } } } return splittedCategoriesToReturn; }

Target:
private List<String> readCategory(VEvent vEvent) { PropertyList propertyCategoryList = vEvent.getProperties(Property.CATEGORIES); ArrayList<String> splittedCategoriesToReturn = new ArrayList<String>(); if (propertyCategoryList != null) { for (int categoriesLineNum = 0; categoriesLineNum < propertyCategoryList.size(); categoriesLineNum++) { Property propertyCategory = propertyCategoryList.get(categoriesLineNum); String categories = propertyCategory.getValue(); if (categories != null) { String[] categoriesSplit = StringUtils.split(categories, ","); for (String category : categoriesSplit) { if (!splittedCategoriesToReturn.contains(category)) { splittedCategoriesToReturn.add(category); } } } } } return splittedCategoriesToReturn; }
Source:
public void handlePost(ActionParameters params) throws ActionException { checkForAdminPermission(params); log.debug("Updating layer/group order"); JSONObject orderJSON = getOrderJSON(params.getRequest()); try { int parentID = orderJSON.getInt(KEY_PARENT); JSONArray orders = orderJSON.getJSONArray(KEY_ORDERS); if(parentID == -1){ for(int i=0;i<orders.length();i++){ JSONObject order = orders.getJSONObject(i); int groupId = order.getInt(KEY_ID); MaplayerGroup currentGroup = oskariMapLayerGroupService.find(groupId); currentGroup.setOrderNumber(i); oskariMapLayerGroupService.updateOrder(currentGroup); } } else { for(int i=0;i<orders.length();i++) { JSONObject order = orders.getJSONObject(i); String type = order.getString(KEY_TYPE); int id = order.getInt(KEY_ID); if(TYPE_LAYER.equals(type)) { if(order.has(KEY_OLD_PARENT)) { oskariLayerService.updateGroup(id, order.getInt(KEY_OLD_PARENT), parentID); } oskariLayerService.updateOrder(id, parentID, i); } else { MaplayerGroup currentGroup = oskariMapLayerGroupService.find(id); currentGroup.setOrderNumber(i); oskariMapLayerGroupService.updateOrder(currentGroup); if(order.has(KEY_OLD_PARENT)){ oskariMapLayerGroupService.updateGroupParent(id,parentID); } } } } } catch (JSONException e) { log.warn(e); throw new ActionException("Failed to read request!"); } ResponseHelper.writeResponse(params, orderJSON); }

Target:
public void handlePost(ActionParameters params) throws ActionException { params.requireAdminUser(); log.debug("Updating layer/group order"); JSONObject orderJSON = params.getPayLoadJSON(); try { int parentID = orderJSON.getInt(KEY_PARENT); JSONArray orders = orderJSON.getJSONArray(KEY_ORDERS); if (parentID == -1) { updateGroupOrder(orders); } else { updateLayerAndGroupOrders(orders, parentID); } } catch (JSONException e) { log.warn(e); throw new ActionParamsException("Cannot save orders!"); } }
Source:
void connectFails() { webSocketConnection.setClient( new WebSocketClient(URI.create("wss://server.invalid")) { @Override public void onOpen(final ServerHandshake handshake) @Override public void onMessage(final String message) @Override public void onClose(final int code, final String reason, final boolean remote) @Override public void onError(final Exception ex) }); assertThrows(RuntimeException.class, webSocketConnection::connect); }

Target:
void connectFails() throws Exception { doCallRealMethod().when(webSocketClient).connectBlocking(anyLong(), any()); doCallRealMethod().when(webSocketClient).connect(); doCallRealMethod().when(webSocketClient).run(); final SocketFactory factory = mock(SocketFactory.class); when(factory.createSocket()).thenThrow(new IOException("Test Connection Failure")); doCallRealMethod().when(webSocketClient).setSocketFactory(any()); webSocketClient.setSocketFactory(factory); assertThrows(CouldNotConnect.class, webSocketConnection::connect); verify(webSocketClient).onError(any()); }
Source:
public void testAccessingValuesUsingDecoder() throws Exception { FieldAccessor accessor = new FieldAccessor(); accessor.registerDecoder("TargetValue", new OafFieldDecoder()); String rawSetId = "rawset-id"; String agentId = "agent-id"; String agentName = "agent-name"; AtomicAction action = new AtomicAction(rawSetId, new Agent(agentId, agentName, Agent.AGENT_TYPE.service)); byte[] decodedTargetValue = decodeTargetValue(new String(IOUtils.readBytesFromStream(FieldAccessorTest.class .getResourceAsStream("/eu/dnetlib/iis/wf/export/actionmanager/sequencefile/resultProject.json")), "utf8")); action.setTargetValue(decodedTargetValue); assertEquals(rawSetId, accessor.getValue("RawSet", action).toString()); assertEquals(agentId, accessor.getValue("Agent.Id", action).toString()); assertEquals(agentName, accessor.getValue("Agent.Name", action).toString()); assertEquals(Agent.AGENT_TYPE.service.toString(), accessor.getValue("Agent.Type", action).toString()); assertEquals("relation", accessor.getValue("$TargetValue.Kind", action).toString()); assertEquals("resultProject", accessor.getValue("$TargetValue.Rel.RelType", action).toString()); }

Target:
public void testAccessingValuesUsingDecoder() throws Exception { FieldAccessor accessor = new FieldAccessor(); accessor.registerDecoder("targetValue", new OafFieldDecoder()); String rawSetId = "rawset-id"; String agentId = "agent-id"; String agentName = "agent-name"; AtomicAction action = new AtomicAction(rawSetId, new Agent(agentId, agentName, Agent.AGENT_TYPE.service)); byte[] decodedTargetValue = decodeTargetValue(new String( IOUtils.toByteArray(FieldAccessorTest.class .getResourceAsStream("/eu/dnetlib/iis/wf/export/actionmanager/sequencefile/resultProject.json")), "utf8")); action.setTargetValue(decodedTargetValue); assertEquals(rawSetId, accessor.getValue("rawSet", action)); assertEquals(agentId, accessor.getValue("agent.id", action)); assertEquals(agentName, accessor.getValue("agent.name", action)); assertEquals(Agent.AGENT_TYPE.service, accessor.getValue("agent.type", action)); assertEquals("relation", accessor.getValue("$targetValue.kind", action).toString()); assertEquals("resultProject", accessor.getValue("$targetValue.rel.relType", action).toString()); }
Source:
public <U> ColumnConstraint<U> map(Function<? super T, ? extends U> mapper) { return new CheckColumnConstraint(name, columnName, expression, expressionStr); }

Target:
public <U> ColumnConstraint<U> map(Function<? super T, ? extends U> mapper) { return new CheckColumnConstraint<>(name, columnName, mapper.apply(expression), expressionStr); }
Source:
public void checkout(@Nonnull Run<?, ?> build, @Nonnull Launcher launcher, @Nonnull FilePath workspace, @Nonnull TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState baseline) throws IOException, InterruptedException { AccurevServer server = getServer(); boolean serverDisabled = server != null && server.isServerDisabled(); if (!serverDisabled) { boolean checkout = AccurevMode.findDelegate(this).checkout(build, launcher, workspace, listener, changelogFile); if (checkout) listener.getLogger().println("Checkout done"); else listener.getLogger().println("Checkout failed"); } else { listener.getLogger().println("Checkout skipped"); } }

Target:
public void checkout(@Nonnull Run<?, ?> build, @Nonnull Launcher launcher, @Nonnull FilePath workspace, @Nonnull TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState baseline) throws IOException, InterruptedException { final AccurevServer server = getServer(); boolean serverDisabled = server != null && server.isServerDisabled(); if (!serverDisabled) { boolean checkout = AccurevMode.findDelegate(this).checkout(build, launcher, workspace, listener, changelogFile); if (checkout) listener.getLogger().println("Checkout done"); else listener.getLogger().println("Checkout failed"); }else{ listener.getLogger().println("Checkout skipped due to server disabled"); throw new InterruptedException(); } }
Source:
public boolean isMetric(String fieldName) { return getColumns(Metric.class).stream().anyMatch(metric -> metric.getName().equals(fieldName)); }

Target:
public boolean isMetric(String fieldName) { return getMetric(fieldName) != null; }
Source:
public Pair<String, String[]> processPrivilegePayloadForActivatedPrivileges (String privilegePayloadJson) throws PrivilagePayloadException{ try { JSONObject obj = new JSONObject(privilegePayloadJson); int version; if(obj.has("version")) { version = obj.getInt("version"); } else { if(obj.has("flag")) { version = 1; } else { throw new UnrecognizedPayloadVersionException(); } } switch(version) { case 1: return processAndValidateV1Payload(obj); case 2: return processAndValidateV2Payload(obj); default: throw new UnrecognizedPayloadVersionException(); } } catch (JSONException e) { throw new MalformedPayloadException(e); } }

Target:
public Pair<String, String[]> processPrivilegePayloadForActivatedPrivileges (String privilegePayloadJson) throws PrivilagePayloadException { try { JSONObject obj = new JSONObject(privilegePayloadJson); int version = getPayloadVersion(obj); switch (version) { case 1: return processAndValidateV1Payload(obj); case 2: return processAndValidateV2Payload(obj); default: throw new UnrecognizedPayloadVersionException(); } } catch (JSONException e) { throw new MalformedPayloadException(e); } }
Source:
public void setUp() { sprite = Mockito.mock(Sprite.class); spriteLook = Mockito.mock(Look.class); sprite.look = spriteLook; embroideryPatternManager = Mockito.mock(EmbroideryPatternManager.class); StageActivity.stageListener = Mockito.mock(StageListener.class); StageActivity.stageListener.embroideryPatternManager = embroideryPatternManager; final int density = 5; final int height = 10; zigZagRunningStitch = new ZigZagRunningStitch(sprite, density, height); }

Target:
public void setUp() { sprite = Mockito.mock(Sprite.class); spriteLook = Mockito.mock(Look.class); sprite.look = spriteLook; embroideryPatternManager = Mockito.mock(EmbroideryPatternManager.class); StageActivity.stageListener = Mockito.mock(StageListener.class); StageActivity.stageListener.embroideryPatternManager = embroideryPatternManager; final int width = 5; final int height = 10; zigZagRunningStitch = new ZigZagRunningStitch(sprite, width, height); }
Source:
protected BluetoothConnectionSettingHandler getHandler(Context context) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); return bluetoothAdapter == null ? null : new BluetoothConnectionSettingHandler(context, bluetoothAdapter); }

Target:
protected BluetoothConnectionSettingHandler getHandler(Context context) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { String errorMessage = "No default bluetooth adapter found"; Log.e(TAG, errorMessage); setResultData(errorMessage); return null; } return new BluetoothConnectionSettingHandler(context, bluetoothAdapter); }
Source:
public void shouldSaveDiagnosis() { CodedOrFreeText codedOrFreeText = new CodedOrFreeText(new Concept(4), new ConceptName(5089), "non coded"); Date date = new Date(); int id = 5; String uuid = "4e663d96-6b78-11e0-93c3-18a9b5e044dc"; int rank = 2; ConditionVerificationStatus certainty = ConditionVerificationStatus.CONFIRMED; User creator = new User(1); Condition condition = new Condition(); Patient patient = new Patient(2); Encounter encounter = new Encounter(3); Diagnosis diagnosis = new Diagnosis(); diagnosis.setEncounter(encounter); diagnosis.setRank(rank); diagnosis.setId(id); diagnosis.setCertainty(certainty); diagnosis.setPatient(patient); diagnosis.setCondition(condition); diagnosis.setDiagnosis(codedOrFreeText); diagnosis.setUuid(uuid); diagnosis.setCreator(creator); diagnosis.setVoided(false); diagnosis.setDateCreated(date); diagnosisDAO.saveDiagnosis(diagnosis); Diagnosis savedDiagnosis = diagnosisDAO.getDiagnosisById(id); assertEquals(uuid, diagnosis.getUuid()); assertEquals(false, diagnosis.getVoided()); assertEquals(rank, (int) diagnosis.getRank()); assertEquals(certainty, diagnosis.getCertainty()); assertEquals(creator, diagnosis.getCreator()); assertEquals(condition, diagnosis.getCondition()); assertEquals(patient, diagnosis.getPatient()); assertEquals(encounter, diagnosis.getEncounter()); }

Target:
public void shouldSaveDiagnosis() { CodedOrFreeText codedOrFreeText = new CodedOrFreeText(new Concept(4), new ConceptName(5089), "non coded"); int diagnosisId = 5; Diagnosis diagnosis = new Diagnosis(); diagnosis.setEncounter(new Encounter(3)); diagnosis.setRank(2); diagnosis.setId(diagnosisId); diagnosis.setCertainty(ConditionVerificationStatus.CONFIRMED); diagnosis.setPatient(new Patient(2)); diagnosis.setCondition(new Condition()); diagnosis.setDiagnosis(codedOrFreeText); diagnosis.setUuid("4e663d96-6b78-11e0-93c3-18a9b5e044dc"); diagnosis.setCreator(new User(1)); diagnosis.setVoided(false); diagnosis.setDateCreated(new Date()); diagnosisDAO.saveDiagnosis(diagnosis); Diagnosis savedDiagnosis = diagnosisDAO.getDiagnosisById(diagnosisId); assertEquals(diagnosis.getUuid(), savedDiagnosis.getUuid()); assertEquals(diagnosis.getVoided(), savedDiagnosis.getVoided()); assertEquals(diagnosis.getRank(), savedDiagnosis.getRank()); assertEquals(diagnosis.getCertainty(), savedDiagnosis.getCertainty()); assertEquals(diagnosis.getCreator(), savedDiagnosis.getCreator()); assertEquals(diagnosis.getCondition(), savedDiagnosis.getCondition()); assertEquals(diagnosis.getPatient(), savedDiagnosis.getPatient()); assertEquals(diagnosis.getEncounter(), savedDiagnosis.getEncounter()); }
Source:
FrameDesc update(RawPacket pkt, long nowMs) { rateStatistics.update(pkt.getLength(), nowMs); long ts = pkt.getTimestamp(); FrameDesc frame = frames.get(ts); if (frame == null) { synchronized (frames) { frames.put(ts, frame = new FrameDesc(this, ts)); } lastStableBitrateBps = getBitrateBps(nowMs); } boolean frameChanged = frame.update(pkt); if (frameChanged) { Map.Entry<Long, FrameDesc> ceilingEntry = frames.ceilingEntry((ts + 1) & 0xFFFFFFFFL); if (ceilingEntry != null) { FrameDesc ceilingFrame = ceilingEntry.getValue(); long tsDiff = (ceilingFrame.getTimestamp() - ts) & 0xFFFFFFFFL; if (tsDiff < (1L<<31) && (ceilingFrame.getStart() != -1 || frame.getEnd() != -1)) { int minSeen = ceilingFrame.getMinSeen(); int maxSeen = frame.getMaxSeen(); int snDiff = (minSeen - maxSeen) & 0xFFFF; if (snDiff < 3) { frame.setEnd((maxSeen + 1) & 0xFFFF); ceilingFrame.setStart((minSeen - 1) & 0xFFFF); } } } Map.Entry<Long, FrameDesc> floorEntry = frames.floorEntry((ts - 1) & 0xFFFFFFFFL); if (floorEntry != null) { FrameDesc floorFrame = floorEntry.getValue(); long tsDiff = (floorFrame.getTimestamp() - ts) & 0xFFFFFFFFL; if (tsDiff < (1L<<31) && (floorFrame.getEnd() != -1 || frame.getStart() != -1)) { int minSeen = frame.getMinSeen(); int maxSeen = floorFrame.getMaxSeen(); int snDiff = (minSeen - maxSeen) & 0xFFFF; if (snDiff < 3) { frame.setStart((minSeen - 1) & 0xFFFF); floorFrame.setEnd((maxSeen + 1) & 0xFFFF); } } } } return frameChanged ? frame : null; }

Target:
FrameDesc update(RawPacket pkt, long nowMs) { rateStatistics.update(pkt.getLength(), nowMs); long ts = pkt.getTimestamp(); FrameDesc frame = frames.get(ts); if (frame == null) { synchronized (frames) { frames.put(ts, frame = new FrameDesc(this, ts)); } lastStableBitrateBps = getBitrateBps(nowMs); } boolean frameChanged = frame.update(pkt); if (frameChanged) { Map.Entry<Long, FrameDesc> ceilingEntry = frames.ceilingEntry((ts + 1) & 0xFFFFFFFFL); if (ceilingEntry != null) { applyFrameBoundsHeuristics(frame, ceilingEntry.getValue()); } Map.Entry<Long, FrameDesc> floorEntry = frames.floorEntry((ts - 1) & 0xFFFFFFFFL); if (floorEntry != null) { applyFrameBoundsHeuristics(floorEntry.getValue(), frame); } } return frameChanged ? frame : null; }
Source:
private ClusterCompositionResponse processRoutingResponse( RoutingProcedureResponse response ) { if ( !response.isSuccess() ) { return new ClusterCompositionResponse.Failure( new ServiceUnavailableException( format( "Failed to run '%s' on server. " + "Please make sure that there is a Neo4j 3.1+ causal cluster up running.", invokedProcedureString( response ) ), response.error() ) ); } List<Record> records = response.records(); if ( log.isDebugEnabled() ) { log.debug( "Received response from %s procedure: %s", invokedProcedureString( response ), records ); } long now = clock.millis(); if ( records.size() != 1 ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "records received '%s' is too few or too many.", invokedProcedureString( response ), records.size() ) ) ); } ClusterComposition cluster; try { cluster = ClusterComposition.parse( records.get( 0 ), now ); } catch ( ValueException e ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "unparsable record received.", invokedProcedureString( response ) ), e ) ); } if ( !cluster.hasRoutersAndReaders() ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "no router or reader found in response.", invokedProcedureString( response ) ) ) ); } return new ClusterCompositionResponse.Success( cluster ); }

Target:
private ClusterCompositionResponse processRoutingResponse( RoutingProcedureResponse response ) { if ( !response.isSuccess() ) { return new ClusterCompositionResponse.Failure( new ServiceUnavailableException( format( "Failed to run '%s' on server. " + "Please make sure that there is a Neo4j 3.1+ causal cluster up running.", invokedProcedureString( response ) ), response.error() ) ); } List<Record> records = response.records(); log.info( "Received response from %s procedure: %s", invokedProcedureString( response ), records ); long now = clock.millis(); if ( records.size() != 1 ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "records received '%s' is too few or too many.", invokedProcedureString( response ), records.size() ) ) ); } ClusterComposition cluster; try { cluster = ClusterComposition.parse( records.get( 0 ), now ); } catch ( ValueException e ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "unparsable record received.", invokedProcedureString( response ) ), e ) ); } if ( !cluster.hasRoutersAndReaders() ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "no router or reader found in response.", invokedProcedureString( response ) ) ) ); } return new ClusterCompositionResponse.Success( cluster ); }
Source:
private void assertQueryStringEquals(String first, String second) { List<NameValuePair> firstList = URLEncodedUtilsHC4.parse(first, Charset.forName("utf8")); List<NameValuePair> secondList = URLEncodedUtilsHC4.parse(second, Charset.forName("utf8")); assertEquals(new HashSet(firstList), new HashSet(secondList)); }

Target:
private void assertQueryStringEquals(String first, String second) { Set<NameValuePair> firstList = new HashSet(URLEncodedUtilsHC4.parse(first, Charset.forName("utf8"))); Set<NameValuePair> secondList = new HashSet(URLEncodedUtilsHC4.parse(second, Charset.forName("utf8"))); assertEquals(firstList, secondList); }
Source:
void lowCollisionBroadcast(Control event) { if (System.currentTimeMillis() > lastLowCollisionBroadcast + minTimeBetweenBroadcast) { try { WebSocketBroadcast.Message message = WebSocketBroadcast.newMessage(getClass(), event); eventBus.post(message); lastLowCollisionBroadcast = System.currentTimeMillis(); log.info("Sent low collision broadcast"); } catch (JsonProcessingException ex) { log.error("Unable to convert control message", ex); } } }

Target:
void lowCollisionBroadcast(Control event) { long now = System.currentTimeMillis(); long lastCheckTimeExpected = lastLowCollisionBroadcast.get(); if (now > lastCheckTimeExpected + minTimeBetweenBroadcast && lastLowCollisionBroadcast.compareAndSet(lastCheckTimeExpected, now)) { try { WebSocketBroadcast.Message message = WebSocketBroadcast.newMessage(getClass(), event); eventBus.post(message); log.info("Sent low collision broadcast"); } catch (JsonProcessingException ex) { log.error("Unable to convert control message", ex); } } }
Source:
public PromotionProcess createProcessFromXml(final String name, InputStream xml) throws IOException { owner.checkPermission(Item.CONFIGURE); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); if (getItem(name) != null) { throw new IllegalArgumentException(owner.getDisplayName() + " already contains an item '" + name + "'"); } File configXml = Items.getConfigFile(getRootDirFor(name)).getFile(); File dir = configXml.getParentFile(); if (!dir.mkdirs()) { throw new IIOException("Cannot create directories for "+dir); } try { IOUtils.copy(xml, configXml); PromotionProcess result = Items.whileUpdatingByXml(new Callable<PromotionProcess,IOException>() { @Override public PromotionProcess call() throws IOException { setOwner(owner); return getItem(name); } }); if (result == null) { throw new IOException("failed to load from " + configXml); } ItemListener.fireOnCreated(result); return result; } catch (IOException e) { Util.deleteRecursive(dir); throw e; } }

Target:
public PromotionProcess createProcessFromXml(final String name, InputStream xml) throws IOException { owner.checkPermission(Item.CONFIGURE); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); if (getItem(name) != null) { throw new IllegalArgumentException(owner.getDisplayName() + " already contains an item '" + name + "'"); } File configXml = Items.getConfigFile(getRootDirFor(name)).getFile(); File dir = configXml.getParentFile(); if (!dir.mkdirs()) { throw new IOException("Cannot create directories for "+dir); } try { IOUtils.copy(xml, configXml); PromotionProcess result = Items.whileUpdatingByXml(new Callable<PromotionProcess,IOException>() { @Override public PromotionProcess call() throws IOException { setOwner(owner); return getItem(name); } }); if (result == null) { throw new IOException("failed to load from " + configXml); } ItemListener.fireOnCreated(result); return result; } catch (IOException e) { Util.deleteRecursive(dir); throw e; } }
Source:
private AppConfiguration() throws ConfigurationException { this.transactionStore = loadTransactionStoreConfig(); this.websitePath = loadWebsitePathConfig(); this.enableVerifyPublish = loadEnableVerifyPublishContentFeatureFlag(); this.fileUploadsTmpDir = createTmpFileUploadsDir(); this.publishThreadPoolSize = getIntegerEnvVar(THREAD_POOL_SIZE_ENV_KEY); this.port = getIntegerEnvVar(PORT_ENV_KEY); this.maxFileUploadSize = getLongEnvVar(MAX_FILE_UPLOAD_SIZE_MB); this.maxRequestSize = getLongEnvVar(MAX_REQUEST_SIZE_MB); this.fileThresholdSize = getIntegerEnvVar(FILE_THRESHOLD_SIZE_MB); info().data(TRANSACTION_STORE_ENV_KEY, transactionStore) .data(WEBSITE_ENV_KEY, websitePath) .data(THREAD_POOL_SIZE_ENV_KEY, publishThreadPoolSize) .data(PORT_ENV_KEY, port) .data(ENABLE_VERIFY_PUBLISH_CONTENT, enableVerifyPublish) .data(FILE_UPLOADS_TMP_DIR, fileUploadsTmpDir) .data(MAX_FILE_UPLOAD_SIZE_MB, maxFileUploadSize) .data(MAX_REQUEST_SIZE_MB, maxRequestSize) .data(FILE_THRESHOLD_SIZE_MB, FileUtils.byteCountToDisplaySize(fileThresholdSize)) .log("successfully load application configuration"); }

Target:
private AppConfiguration() throws ConfigurationException { this.transactionStore = loadTransactionStoreConfig(); this.websitePath = loadWebsitePathConfig(); this.enableVerifyPublish = loadEnableVerifyPublishContentFeatureFlag(); this.fileUploadsTmpDir = createTmpFileUploadsDir(); this.publishThreadPoolSize = getIntegerEnvVar(THREAD_POOL_SIZE_ENV_KEY); this.port = getIntegerEnvVar(PORT_ENV_KEY); this.maxFileUploadSize = getLongEnvVar(MAX_FILE_UPLOAD_SIZE_MB); this.maxRequestSize = getLongEnvVar(MAX_REQUEST_SIZE_MB); this.fileThresholdSize = getIntegerEnvVar(FILE_THRESHOLD_SIZE_MB); info().data(TRANSACTION_STORE_ENV_KEY, transactionStore) .data(WEBSITE_ENV_KEY, websitePath) .data(THREAD_POOL_SIZE_ENV_KEY, publishThreadPoolSize) .data(PORT_ENV_KEY, port) .data(ENABLE_VERIFY_PUBLISH_CONTENT, enableVerifyPublish) .data(FILE_UPLOADS_TMP_DIR, fileUploadsTmpDir) .data(MAX_FILE_UPLOAD_SIZE_MB, maxFileUploadSize) .data(MAX_REQUEST_SIZE_MB, maxRequestSize) .data(FILE_THRESHOLD_SIZE_MB, fileThresholdSize + " MB") .log("successfully load application configuration"); }
Source:
public boolean isSubscribedToApp(APIIdentifier apiIdentifier, String userId, int applicationId) throws APIManagementException { boolean isSubscribed; try { isSubscribed = apiMgtDAO.isSubscribedToApp(apiIdentifier, userId, applicationId); } catch (APIManagementException e) { String msg = "Failed to check if user(" + userId + ") has subscribed to " + apiIdentifier; log.error(msg, e); throw new APIManagementException(msg, e); } return isSubscribed; }

Target:
public boolean isSubscribedToApp(APIIdentifier apiIdentifier, String userId, int applicationId) throws APIManagementException { boolean isSubscribed; try { isSubscribed = apiMgtDAO.isSubscribedToApp(apiIdentifier, userId, applicationId); } catch (APIManagementException e) { String msg = "Failed to check if user(" + userId + ") with appId " + applicationId + " has subscribed to " + apiIdentifier; log.error(msg, e); throw new APIManagementException(msg, e); } return isSubscribed; }
Source:
public SWTBotShell maximize(final boolean maximize) throws TimeoutException { boolean isMaximizedState = isMaximizedState(); if ((maximize && isMaximizedState) || (!maximize && !isMaximizedState)) { log.debug(MessageFormat.format("Shell {0} is already in expected state, not resizing again.", this)); return this; } final Point initialSize = new Point(getBounds().width, getBounds().height); activate(); syncExec(new VoidResult() { @Override public void run() { widget.setMaximized(maximize); } }); notify(SWT.Resize); notify(SWT.Move); notify(SWT.Paint); new SWTBot().waitUntil(new DefaultCondition() { @Override public String getFailureMessage() { return "Timed out waiting for " + SWTUtils.toString(widget) + " to get maximized/unmaximized"; } @Override public boolean test() throws Exception { if (maximize) return isMaximizedState() && isResized(initialSize); else return !isMaximizedState() && isResized(initialSize); } }); return this; }

Target:
public SWTBotShell maximize(final boolean maximize) throws TimeoutException { if (maximize == isMaximizedState()) { log.debug(MessageFormat.format("{0} is already in expected state, not resizing again.", this)); return this; } final Rectangle initialRectangle = getBounds(); activate(); syncExec(new VoidResult() { @Override public void run() { widget.setMaximized(maximize); } }); new SWTBot().waitUntil(new DefaultCondition() { @Override public String getFailureMessage() { return "Timed out waiting for " + SWTUtils.toString(widget) + " to get maximized/unmaximized"; } @Override public boolean test() throws Exception { if (maximize) { return isMaximizedState() && isResized(initialRectangle); } else { return !isMaximizedState() && isResized(initialRectangle); } } }); return this; }
Source:
public void processSubCommand(ICommandSender sender, String[] args) { if (args.length < 1) { printHelp(sender); return; } World world; if (args.length == 2) world = CommandHelpers.getWorld(sender, this, args, 0); else world = CommandHelpers.getWorld(sender, this); String desired = args[args.length - 1]; IBeekeepingMode mode = PluginApiculture.beeInterface.getBeekeepingMode(desired); if (mode == null) throw new CommandException(StringUtil.localize("chat.bees.command.beekeeping.error"), desired); PluginApiculture.beeInterface.setBeekeepingMode(world, mode.getName()); CommandHelpers.sendLocalizedChatMessage(sender, StringUtil.localize("chat.bees.command.beekeeping.set"), mode.getName()); }

Target:
public void processSubCommand(ICommandSender sender, String[] args) { if (args.length == 0 || args.length > 2) { printHelp(sender); return; } World world; if (args.length == 2) world = CommandHelpers.getWorld(sender, this, args, 0); else world = CommandHelpers.getWorld(sender, this); String desired = args[args.length - 1]; IBeekeepingMode mode = PluginApiculture.beeInterface.getBeekeepingMode(desired); if (mode == null) { CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.beekeeping.mode.set.error", desired); printHelp(sender); return; } PluginApiculture.beeInterface.setBeekeepingMode(world, mode.getName()); CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.beekeeping.mode.set.success", mode.getName()); }
Source:
public ImmutableSpongeBlockItemData(BlockState value) { super(ImmutableBlockItemData.class, value, Keys.ITEM_BLOCKSTATE); this.state = new ImmutableSpongeValue<>(Keys.ITEM_BLOCKSTATE, BlockTypes.STONE.getDefaultState(), value); }

Target:
public ImmutableSpongeBlockItemData(BlockState value) { super(ImmutableBlockItemData.class, value, Keys.ITEM_BLOCKSTATE); this.state = new ImmutableSpongeValue<>(Keys.ITEM_BLOCKSTATE, DataConstants.DEFAULT_BLOCK_STATE, value); }
Source:
public static String getCertKeyIdAuthority(X509Certificate cert) { if (null == cert) { return null; } byte[] akiBytes = cert.getExtensionValue(AUTHORITY_KEY_ID); String aki = null; try { if (akiBytes != null) { DERDecoder extValA = new DERDecoder(akiBytes); extValA.skip(6); aki = Hex.encodeHexString(extValA.getBytes(20)); } } catch (WSSecurityException e) { LOG.error("Unable to convert AIK into human readable {}", e.getLocalizedMessage(), e); } return aki; }

Target:
public static String getCertKeyIdAuthority(X509Certificate cert) { String aki = null; if (null != cert) { byte[] akiBytes = cert.getExtensionValue(AUTHORITY_KEY_ID); try { if (akiBytes != null) { DERDecoder extValA = new DERDecoder(akiBytes); extValA.skip(6); aki = Hex.encodeHexString(extValA.getBytes(20)); } } catch (WSSecurityException e) { LOG.error("Unable to decode certificate authority {}", e.getLocalizedMessage(), e); } } return aki; }
Source:
public void upgradeSmokes() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.RUN_SCRIPTS, Jenkins.READ, Item.READ).everywhere().to("runScriptsUser"). grant(Jenkins.READ, Item.READ).everywhere().to("otherUser")); FreeStyleProject p = r.createFreeStyleProject(); p.getPublishersList().add(new TestGroovyRecorder( new SecureGroovyScript("jenkins.model.Jenkins.instance", true, null))); r.assertLogNotContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: " + "Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", r.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0).get())); }

Target:
public void upgradeSmokes() throws Exception { FreeStyleProject p = r.createFreeStyleProject(); p.getPublishersList().add(new TestGroovyRecorder( new SecureGroovyScript("jenkins.model.Jenkins.instance", true, null))); r.assertLogNotContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: " + "Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", r.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0).get())); }
Source:
private List<RemoteTask> scheduleTasks(int count) { if (count == 0) { return ImmutableList.of(); } List<Node> nodes = nodeSelector.selectRandomNodes(count, scheduledNodes); checkCondition(!scheduledNodes.isEmpty() || !nodes.isEmpty(), NO_NODES_AVAILABLE, "No nodes available to run query"); ImmutableList.Builder<RemoteTask> tasks = ImmutableList.builder(); for (Node node : nodes) { Optional<RemoteTask> remoteTask = stage.scheduleTask(node, scheduledNodes.size(), OptionalInt.empty()); remoteTask.ifPresent(element -> { tasks.add(element); scheduledNodes.add(node); }); } return tasks.build(); }

Target:
private List<RemoteTask> scheduleTasks(int count) { if (count == 0) { return ImmutableList.of(); } List<Node> nodes = nodeSelector.selectRandomNodes(count, scheduledNodes); checkCondition(!scheduledNodes.isEmpty() || !nodes.isEmpty(), NO_NODES_AVAILABLE, "No nodes available to run query"); ImmutableList.Builder<RemoteTask> tasks = ImmutableList.builder(); for (Node node : nodes) { Optional<RemoteTask> remoteTask = stage.scheduleTask(node, scheduledNodes.size(), OptionalInt.empty()); remoteTask.ifPresent(task -> { tasks.add(task); scheduledNodes.add(node); }); } return tasks.build(); }
Source:
protected long releaseMemory() { long memoryFreed = 0; while (!windowsForFreeMemory.isEmpty()) { long windowId = windowsForFreeMemory.poll(); long originSize = keyStream.size() + valueStream.size(); keyStream.resetUpToWindow(windowId); valueStream.resetUpToWindow(windowId); memoryFreed += originSize - (keyStream.size() + valueStream.size()); } if (memoryFreed > 0) { LOG.debug("Total freed memory size: {}", memoryFreed); sizeInBytes.getAndAdd(0 - memoryFreed); } return memoryFreed; }

Target:
protected long releaseMemory() { long memoryFreed = 0; while (!windowsForFreeMemory.isEmpty()) { long windowId = windowsForFreeMemory.poll(); long originSize = keyStream.size() + valueStream.size(); keyStream.resetUpToWindow(windowId); valueStream.resetUpToWindow(windowId); memoryFreed += originSize - (keyStream.size() + valueStream.size()); } if (memoryFreed > 0) { LOG.debug("Total freed memory size: {}", memoryFreed); sizeInBytes.getAndAdd(-memoryFreed); } return memoryFreed; }
Source:
private void runLoop() { subscribeConsumer(); while (isRunning()) { try { runOnce(); if (assignmentErrorCode.get() == AssignorError.VERSION_PROBING.code()) { log.info("Version probing detected. Rejoin the consumer group to trigger a new rebalance."); assignmentErrorCode.set(AssignorError.NONE.code()); enforceRebalance(); } } catch (final TaskCorruptedException e) { log.warn("Detected the states of tasks are corrupted. " + "Will close the task as dirty and re-create and bootstrap from scratch.", e.corruptedTaskIds()); taskManager.handleCorruption(e.corruptedTaskIds()); } catch (final TaskMigratedException e) { log.warn("Detected that the thread is being fenced. " + "This implies that this thread missed a rebalance and dropped out of the consumer group. " + "Will migrate out all assigned tasks and rejoin the consumer group."); enforceRebalance(); } } }

Target:
private void runLoop() { subscribeConsumer(); while (isRunning()) { try { runOnce(); if (assignmentErrorCode.get() == AssignorError.VERSION_PROBING.code()) { log.info("Version probing detected. Rejoining the consumer group to trigger a new rebalance."); assignmentErrorCode.set(AssignorError.NONE.code()); enforceRebalance(); } } catch (final TaskCorruptedException e) { log.warn("Detected the states of tasks are corrupted. " + "Will close the task as dirty and re-create and bootstrap from scratch.", e.corruptedTaskWithChangelogs()); taskManager.handleCorruption(e.corruptedTaskWithChangelogs()); } catch (final TaskMigratedException e) { log.warn("Detected that the thread is being fenced. " + "This implies that this thread missed a rebalance and dropped out of the consumer group. " + "Will close out all assigned tasks and rejoin the consumer group."); taskManager.handleLostAll(); enforceRebalance(); } } }
Source:
protected void preparePreviousAttemptWorkers() { testingYarnAMRMClientAsyncBuilder.setRegisterApplicationMasterFunction((ignored1, ignored2, ignored3) -> RegisterApplicationMasterResponse.newInstance( Resource.newInstance(0, 0), Resource.newInstance(Integer.MAX_VALUE, Integer.MAX_VALUE), Collections.emptyMap(), null, Collections.singletonList(testingContainer), null, Collections.emptyList())); }

Target:
protected void preparePreviousAttemptWorkers() { testingYarnAMRMClientAsyncBuilder.setRegisterApplicationMasterFunction( (ignored1, ignored2, ignored3) -> new TestingRegisterApplicationMasterResponse(() -> Collections.singletonList(testingContainer))); }
Source:
public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled()) { AbstractBuildContext config = AbstractBuildContext.createContextFromMap(taskDefinition.getConfiguration()); if ((config != null) && config.releaseManagementContext.isReleaseMgmtEnabled()) { return taskDefinition; } } } } return null; }

Target:
public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled() && isReleaseMgmtEnabled(taskDefinition)) { return taskDefinition; } } } return null; }
Source:
private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { if (entry.enabled) { try { Extension extension = (Extension) lookupService( Extension.class, entry.getConfig().getProperty(CLASS), loadModule(entry.getConfig().getProperty(MODULE)) ).newInstance(); extension.setContext(entry.context); extension.init(); entry.setExtension(extension); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException ex ) { log.error(String.format("Error in activating extension %1$s. Exception message is " + entry.getName()), ex.getMessage()); if (log.isDebugEnabled()) { log.error("", ex); } } } } }

Target:
private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { if (entry.enabled) { try { Extension extension = (Extension) lookupService( Extension.class, entry.getConfig().getProperty(CLASS), entry.getConfig().getProperty(MODULE) ).newInstance(); extension.setContext(entry.context); extension.init(); entry.setExtension(extension); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException ex ) { log.error(String.format("Error in activating extension %1$s. Exception message is " + entry.getName()), ex.getMessage()); if (log.isDebugEnabled()) { log.error("", ex); } } } } }