auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void executeCommand() { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.Disk, getParameters().getImageGroupId())); Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = null; try { vdsReturnValue = runVdsCommand(VDSCommandType.DestroyImage, createVDSParameters()); } catch (EngineException e) { log.error("Failed to delete image {}/{}. Retrying ...", getParameters().getImageGroupId(), getParameters().getImageList().stream().findFirst(), e); setSucceeded(true); setCommandStatus(CommandStatus.ACTIVE); return; } if (vdsReturnValue != null && vdsReturnValue.getCreationInfo() != null) { getParameters().setVdsmTaskIds(new ArrayList<>()); Guid result = createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId()); getReturnValue().getInternalVdsmTaskIdList().add(result); getReturnValue().getVdsmTaskIdList().add(result); getParameters().getVdsmTaskIds().add(result); setSucceeded(vdsReturnValue.getSucceeded()); setCommandStatus(CommandStatus.SUCCEEDED); log.info("Successfully started task to remove orphaned volumes resulting from live merge"); } }

Target:
public void executeCommand() { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.Disk, getParameters().getImageGroupId())); Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = null; try { vdsReturnValue = runVdsCommand(VDSCommandType.DestroyImage, createVDSParameters()); } catch (EngineException e) { log.error("Failed to delete image {}/{}", getParameters().getImageGroupId(), getParameters().getImageList().stream().findFirst(), e); } if (vdsReturnValue != null && vdsReturnValue.getCreationInfo() != null) { getParameters().setVdsmTaskIds(new ArrayList<>()); Guid result = createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId()); getReturnValue().getInternalVdsmTaskIdList().add(result); getReturnValue().getVdsmTaskIdList().add(result); getParameters().getVdsmTaskIds().add(result); setSucceeded(vdsReturnValue.getSucceeded()); setCommandStatus(CommandStatus.SUCCEEDED); log.info("Successfully started task to remove orphaned volumes resulting from live merge"); } else { log.info("Retrying deleting image {}/{}", getParameters().getImageGroupId(), getParameters().getImageList().stream().findFirst()); setSucceeded(true); setCommandStatus(CommandStatus.ACTIVE); } }
Source:
protected CoverageAgendaListener createCoverageAgendaListenerWithData(Map<String, Integer> rulesToNumberOfTimes) { CoverageAgendaListener coverageAgendaListener = new CoverageAgendaListener(); for (Map.Entry<String, Integer> ruleToNumberOfTimes : rulesToNumberOfTimes.entrySet()) { BeforeMatchFiredEvent beforeMatchFiredEventMock = createBeforeMatchFiredEventMock(ruleToNumberOfTimes.getKey()); IntStream.range(0, ruleToNumberOfTimes.getValue()).forEach(i -> coverageAgendaListener.beforeMatchFired(beforeMatchFiredEventMock)); } ; return coverageAgendaListener; }

Target:
protected CoverageAgendaListener createCoverageAgendaListenerWithData(Map<String, Integer> rulesToNumberOfTimes) { CoverageAgendaListener coverageAgendaListener = new CoverageAgendaListener(); for (Map.Entry<String, Integer> ruleToNumberOfTimes : rulesToNumberOfTimes.entrySet()) { BeforeMatchFiredEvent beforeMatchFiredEventMock = createBeforeMatchFiredEventMock(ruleToNumberOfTimes.getKey()); IntStream.range(0, ruleToNumberOfTimes.getValue()).forEach(i -> coverageAgendaListener.beforeMatchFired(beforeMatchFiredEventMock)); } return coverageAgendaListener; }
Source:
public double[] getTagRatioOfHtml(String html) { html = html.replaceAll("(?s)<!--.*?-->", ""); html = html.replaceAll("(?s)<script.*?>.*?</script>", ""); html = html.replaceAll("(?s)<SCRIPT.*?>.*?</SCRIPT>", ""); html = html.replaceAll("(?s)<style.*?>.*?</style>", ""); try{ Parser p = new Parser(html); NodeList nl = p.parse(null); BufferedReader br = new BufferedReader(new StringReader(nl.toHtml())); int numLines = 0; while (br.readLine() != null) { numLines++; } br.close(); linkTagList = new double[numLines]; HashMap<String, String> metaTagsMap = new HashMap<String, String>(); String line; double threshold = 10; StringBuffer sb = new StringBuffer(); double tagRatio = 0.0; int count = 0; br = new BufferedReader(new StringReader(nl.toHtml())); for (int i = 0; i < linkTagList.length; i++) { line = br.readLine(); line = line.trim(); if (line.equals("")) { continue; } linkTagList[i] = computeTextToTagRatio(line); populateMetaTags(line, metaTagsMap); if(linkTagList[i] != 0 && linkTagList[i] >= threshold){ sb.append(line); sb.append("\n"); tagRatio += linkTagList[i]; count++; } } JSONObject obj = new JSONObject(); obj.put("avgTagRatio", (tagRatio/count)); obj.put("content", sb.toString()); JSONArray array = new JSONArray(); array.put(metaTagsMap); obj.put("meta-tags", array); br.close(); }catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserException e) { e.printStackTrace(); return linkTagList; } return linkTagList; }

Target:
public double[] getTagRatioOfHtml(String html) throws MalformedURLException { html = html.replaceAll("(?s)<!--.*?-->", ""); html = html.replaceAll("(?s)<script.*?>.*?</script>", ""); html = html.replaceAll("(?s)<SCRIPT.*?>.*?</SCRIPT>", ""); html = html.replaceAll("(?s)<style.*?>.*?</style>", ""); try{ Parser p = new Parser(html); NodeList nl = p.parse(null); BufferedReader br = new BufferedReader(new StringReader(nl.toHtml())); int numLines = 0; while (br.readLine() != null) { numLines++; } br.close(); linkTagList = new double[numLines]; HashMap<String, String> metaTagsMap = new HashMap<String, String>(); String line; double threshold = 10; StringBuffer sb = new StringBuffer(); double tagRatio = 0.0; int count = 0; br = new BufferedReader(new StringReader(nl.toHtml())); for (int i = 0; i < linkTagList.length; i++) { line = br.readLine(); line = line.trim(); if (line.equals("")) { continue; } linkTagList[i] = computeTextToTagRatio(line); populateMetaTags(line, metaTagsMap); if(linkTagList[i] != 0 && linkTagList[i] >= threshold){ sb.append(line); sb.append("\n"); tagRatio += linkTagList[i]; count++; } } JSONObject obj = new JSONObject(); obj.put("avgTagRatio", (tagRatio/count)); obj.put("content", sb.toString()); JSONArray array = new JSONArray(); array.put(metaTagsMap); obj.put("meta-tags", array); br.close(); }catch (IOException|ParserException e) { e.printStackTrace(); } return linkTagList; }
Source:
public void changePlotType(PlotPreferences.PlotType plotType) { try { preferences.getSedPreferences(currentSed).getPlotPreferences().setPlotType(plotType); env.setValue(PlotPreferences.X_LOG, preferences.getSedPreferences(currentSed).getPlotPreferences().getXlog()); env.setValue(PlotPreferences.Y_LOG, preferences.getSedPreferences(currentSed).getPlotPreferences().getYlog()); setupForPlotDisplayChange(); display = createPlotComponent(env, false); } catch (EnumConstantNotPresentException ex) { logger.log(Level.WARNING, ex.getMessage()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } updatePlotDisplay(); }

Target:
public void changePlotType(PlotPreferences.PlotType plotType) { try { this.getPlotPreferences().setPlotType(plotType); reset(currentSed, DATA_MAY_CHANGE); } catch (EnumConstantNotPresentException ex) { logger.log(Level.WARNING, ex.getMessage()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private JsonNode mapDataObjectToInputColumnsByName(JsonNode item, List<ConfiguredPropertyDescriptor> inputColProperties) { JsonNodeFactory json = Serializator.getJacksonObjectMapper().getNodeFactory(); ArrayNode values = json.arrayNode(); ITER: for(ConfiguredPropertyDescriptor inputColPropDesc: inputColProperties) { JsonNode value = item.get(inputColPropDesc.getName()); if(value != null) { values.add(value); continue; } String[] aliases = inputColPropDesc.getAliases(); if(aliases != null) { for (String alias : aliases) { value = item.get(alias); if(value != null) { values.add(value); continue ITER; } } } values.add(json.nullNode()); } return values; }

Target:
private JsonNode mapDataObjectToInputColumnsByName(JsonNode item, List<ConfiguredPropertyDescriptor> inputColProperties) { final JsonNodeFactory json = Serializator.getJacksonObjectMapper().getNodeFactory(); final ArrayNode values = json.arrayNode(); for (ConfiguredPropertyDescriptor inputColPropDesc: inputColProperties) { JsonNode value = findPropertyByColumnNameOrAlias(item, inputColPropDesc); if (value == null) { value = json.nullNode(); } values.add(value); } return values; }
Source:
public String generateTOTPToken(String secretKey) throws TOTPException { long token = 0; byte[] secretkey; String encoding = "Base32"; try { encoding = TOTPUtil.getEncodingMethod(); } catch (IdentityApplicationManagementException e) { log.error("Error when fetching the encoding method"); } if ("Base32".equals(encoding)) { Base32 codec32 = new Base32(); secretkey = codec32.decode(secretKey); } else { Base64 code64 = new Base64(); secretkey = code64.decode(secretKey); } try { token = getCode(secretkey, getTimeIndex()); } catch (NoSuchAlgorithmException e) { throw new TOTPException("TOTPTokenGenerator can't find the configured hashing algorithm", e); } catch (InvalidKeyException e) { throw new TOTPException("Secret key is not valid", e); } return Long.toString(token); }

Target:
public String generateTOTPToken(String secretKey) throws TOTPException { long token = 0; byte[] secretkey; String encoding = "Base32"; try { encoding = TOTPUtil.getEncodingMethod(); } catch (IdentityApplicationManagementException e) { throw new TOTPException("Error when fetching the encoding method",e); } if ("Base32".equals(encoding)) { Base32 codec32 = new Base32(); secretkey = codec32.decode(secretKey); } else { Base64 code64 = new Base64(); secretkey = code64.decode(secretKey); } try { token = getCode(secretkey, getTimeIndex()); } catch (NoSuchAlgorithmException e) { throw new TOTPException("TOTPTokenGenerator can't find the configured hashing algorithm", e); } catch (InvalidKeyException e) { throw new TOTPException("Secret key is not valid", e); } return Long.toString(token); }
Source:
private Diagram getGMFDiagram(Notification notification) { Diagram gmfDiagram = null; DDiagram dDiagram = null; Object notifier = notification.getNotifier(); if (notifier instanceof DDiagram) { dDiagram = (DDiagram) notifier; } else if (notifier instanceof DDiagramElement && ((EObject) notifier).eContainer() != null) { dDiagram = ((DDiagramElement) notifier).getParentDiagram(); } else if (notification.getOldValue() instanceof DDiagramElement) { DDiagramElement oldValue = (DDiagramElement) notification.getOldValue(); dDiagram = DDiagramElementSpecOperations.getParentDiagram(oldValue); } if (dDiagram != null && dDiagram.eResource() != null) { DiagramCreationUtil diagramCreationUtil = new DiagramCreationUtil(dDiagram); if (diagramCreationUtil.findAssociatedGMFDiagram()) { gmfDiagram = diagramCreationUtil.getAssociatedGMFDiagram(); } else { Resource diagramResource = dDiagram.eResource(); gmfDiagram = getDiagramFromResource(dDiagram, diagramResource); } } return gmfDiagram; }

Target:
private Diagram getGMFDiagram(Notification notification) { Diagram gmfDiagram = null; DDiagram dDiagram = null; Object notifier = notification.getNotifier(); if (notifier instanceof DDiagram) { dDiagram = (DDiagram) notifier; } else if (notifier instanceof DDiagramElement && ((EObject) notifier).eContainer() != null) { dDiagram = ((DDiagramElement) notifier).getParentDiagram(); } else if (notification.getOldValue() instanceof DDiagramElement) { DDiagramElement oldValue = (DDiagramElement) notification.getOldValue(); dDiagram = DDiagramElementSpecOperations.getParentDiagram(oldValue); } Resource diagramResource = dDiagram.eResource(); if (dDiagram != null && diagramResource != null) { DiagramCreationUtil diagramCreationUtil = new DiagramCreationUtil(dDiagram); if (diagramCreationUtil.findAssociatedGMFDiagram()) { gmfDiagram = diagramCreationUtil.getAssociatedGMFDiagram(); } else { gmfDiagram = getDiagramFromResource(dDiagram, diagramResource); } } return gmfDiagram; }
Source:
public void destroySession(String sessionName, IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_DESTROY_SESSION, sessionName); ICommandResult result = executeCommand(command, monitor, false); List<String> errorOutput = result.getErrorOutput(); if (isError(result) && (errorOutput.size() > 0)) { if (ignoredPattern(errorOutput, LTTngControlServiceConstants.SESSION_NOT_FOUND_ERROR_PATTERN)) { return; } throw new ExecutionException(Messages.TraceControl_CommandError + " " + toCommandString(command) + "\n" + result.toString()); } Document doc = getDocumentFromStrings(result.getOutput()); NodeList sessions = doc.getElementsByTagName(MIStrings.SESSION); if (sessions.getLength() != 1) { throw new ExecutionException(NLS.bind(Messages.TraceControl_MiInvalidNumberOfElementError, MIStrings.SESSION)); } Node rawSessionName = getFirstOf(sessions.item(0).getChildNodes(), MIStrings.NAME); if (rawSessionName == null) { throw new ExecutionException(Messages.TraceControl_MiMissingRequiredError); } if (!rawSessionName.getTextContent().equals(sessionName)) { throw new ExecutionException(NLS.bind(Messages.TraceControl_UnexpectedValueError, rawSessionName.getTextContent(), sessionName)); } }

Target:
public void destroySession(String sessionName, IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_DESTROY_SESSION, sessionName); ICommandResult result = executeCommand(command, monitor, false); List<String> errorOutput = result.getErrorOutput(); if (isError(result)) { if (ignoredPattern(errorOutput, LTTngControlServiceConstants.SESSION_NOT_FOUND_ERROR_PATTERN)) { return; } throw new ExecutionException(Messages.TraceControl_CommandError + " " + toCommandString(command) + "\n" + result.toString()); } Document doc = getDocumentFromStrings(result.getOutput()); NodeList sessions = doc.getElementsByTagName(MIStrings.SESSION); if (sessions.getLength() != 1) { throw new ExecutionException(NLS.bind(Messages.TraceControl_MiInvalidNumberOfElementError, MIStrings.SESSION)); } Node rawSessionName = getFirstOf(sessions.item(0).getChildNodes(), MIStrings.NAME); if (rawSessionName == null) { throw new ExecutionException(Messages.TraceControl_MiMissingRequiredError); } if (!rawSessionName.getTextContent().equals(sessionName)) { throw new ExecutionException(NLS.bind(Messages.TraceControl_UnexpectedValueError, rawSessionName.getTextContent(), sessionName)); } }
Source:
private void sleep() { try { Thread.sleep(this.delay); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } }

Target:
private void sleep() { try { TimeUnit.MILLISECONDS.sleep(this.delay); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException( "Unexpected interruption while retrying to process request", ex ); } }
Source:
public void testParseAndConstructUnifiedXmlFile(Path config) throws IOException { String[] parts = config.getFileName().toString().split("\\."); int major = Integer.parseInt(parts[0]); int minor = Integer.parseInt(parts[1]); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.fromXml(config.toString(), true, false, false)) { @Override public void call() { for(ParserVersionCheck check : ParserVersionCheck.values()) { if (check.isIncludedBy(major, minor)) { check.check(cm); } } } }); }

Target:
public void testParseAndConstructUnifiedXmlFile(Path config) throws IOException { String[] parts = config.getFileName().toString().split("\\."); int major = Integer.parseInt(parts[0]); int minor = Integer.parseInt(parts[1]); ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader(), false); try (InputStream is = FileLookupFactory.newInstance().lookupFileStrict(config.toString(), Thread.currentThread().getContextClassLoader())) { ConfigurationBuilderHolder holder = parserRegistry.parse(is); for(ParserVersionCheck check : ParserVersionCheck.values()) { if (check.isIncludedBy(major, minor)) { check.check(holder); } } } }
Source:
public static Iterable<Object[]> getParameters() { return Arrays.asList(new Object[][] { { 0, "0" }, { 3, "3" }, { 975, "975" }, { 1000, "1 k" }, { 4000, "4 k" }, { -4000, "-4 k" }, { 4000L, "4 k" }, { 4000.0, "4 k" }, { 12345678, "12.3 M" }, { Integer.MAX_VALUE, "2.1 G" }, { Integer.MIN_VALUE, "-2.1 G" }, { Long.MAX_VALUE, "9223.4 P" }, { 98765432.123456, "98.8 M" }, { -98765432.123456, "-98.8 M" }, { 555555555555L, "555.6 G" }, { 555555555555555L, "555.6 T" }, { 100100000, "100.1 M" }, { 0.1, "100 m" }, { 0.001, "1 m" }, { 0.000001, "1 µ" }, { 0.000000001, "1 n" }, { 0.000000000001, "1 p" }, { -0.04, "-40 m" }, { 0.002, "2 m" }, { 0.0555, "55.5 m" }, { 0.0004928373928, "492.8 µ" }, { 0.000000251, "251 n"}, { 0.000000000043, "43 p"}, { 0.000000045643, "45.6 n"}, { Double.MAX_VALUE, "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 P" }, { Double.POSITIVE_INFINITY, "∞" }, { Double.MIN_NORMAL, "0" }, { Double.NEGATIVE_INFINITY, "-∞" }, { Double.NaN, "�" }, { Double.MIN_NORMAL, "0" }, }); }

Target:
public static Iterable<Object[]> getParameters() { return Arrays.asList(new Object[][] { { 0, "0" }, { 3, "3" }, { 975, "975" }, { 1000, "1 k" }, { 4000, "4 k" }, { -4000, "-4 k" }, { 4000L, "4 k" }, { 4000.0, "4 k" }, { 12345678, "12.3 M" }, { Integer.MAX_VALUE, "2.1 G" }, { Integer.MIN_VALUE, "-2.1 G" }, { Long.MAX_VALUE, "9223.4 P" }, { 98765432.123456, "98.8 M" }, { -98765432.123456, "-98.8 M" }, { 555555555555L, "555.6 G" }, { 555555555555555L, "555.6 T" }, { 100100000, "100.1 M" }, { 0.1, "100 m" }, { 0.001, "1 m" }, { 0.000001, "1 µ" }, { 0.000000001, "1 n" }, { 0.000000000001, "1 p" }, { -0.04, "-40 m" }, { 0.002, "2 m" }, { 0.0555, "55.5 m" }, { 0.0004928373928, "492.8 µ" }, { 0.000000251, "251 n"}, { 0.000000000043, "43 p"}, { 0.000000045643, "45.6 n"}, { Double.MAX_VALUE, "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 P" }, { Double.POSITIVE_INFINITY, "∞" }, { Double.MIN_NORMAL, "0" }, { Double.NEGATIVE_INFINITY, "-∞" }, { Double.NaN, "�" }, }); }
Source:
public OvernightIndexRates overnightIndexRates(OvernightIndex index) { Curve curve = marketData.getValue(OvernightIndexCurveKey.of(index)); if (curve == null) { throw new IllegalArgumentException("Unable to find forward curve: " + index); } return OvernightIndexRates.of(index, getValuationDate(), curve, timeSeries(index)); }

Target:
public OvernightIndexRates overnightIndexRates(OvernightIndex index) { Curve curve = marketData.getValue(OvernightIndexCurveKey.of(index)); return OvernightIndexRates.of(index, getValuationDate(), curve, timeSeries(index)); }
Source:
public void onConfirmation(Serializable extra, int buttonClicked) { if (buttonClicked == DialogInterface.BUTTON_POSITIVE && extra.equals("upload")) runAsyncTask(); else if (buttonClicked == DialogInterface.BUTTON_POSITIVE && extra.equals("rerun")) reRunTest(); }

Target:
public void onConfirmation(Serializable extra, int buttonClicked) { if (buttonClicked == DialogInterface.BUTTON_POSITIVE && extra.equals(UPLOAD_KEY)) runAsyncTask(); else if (buttonClicked == DialogInterface.BUTTON_POSITIVE && extra.equals(RERUN_KEY)) reTestWebsites(); else if (buttonClicked == DialogInterface.BUTTON_NEUTRAL) startActivity(TextActivity.newIntent(this, TextActivity.TYPE_UPLOAD_LOG, (String)extra)); }
Source:
public Deferred<Void> initialize(Span span) { return super.initialize(span) .addCallback( arg -> { for (QueryNode node : (Collection<QueryNode>) this.downstream) { if (node instanceof TimeSeriesDataSource) { TimeSeriesDataSource timeSeriesDataSource = (TimeSeriesDataSource) node; TimeSeriesDataSourceConfig config = (TimeSeriesDataSourceConfig) timeSeriesDataSource.config(); List<QueryNodeConfig> pushDownNodes = config.getPushDownNodes(); for (QueryNodeConfig queryNodeConfig : pushDownNodes) { if(queryNodeConfig instanceof DownsampleConfig) { downsampleConfig = (DownsampleConfig) queryNodeConfig; break; } } break; } } return null; }); }

Target:
public Deferred<Void> initialize(Span span) { return super.initialize(span) .addCallback( arg -> { for (QueryNode node : (Collection<QueryNode>) this.downstream) { if (node instanceof TimeSeriesDataSource) { TimeSeriesDataSource timeSeriesDataSource = (TimeSeriesDataSource) node; TimeSeriesDataSourceConfig config = (TimeSeriesDataSourceConfig) timeSeriesDataSource.config(); List<QueryNodeConfig> pushDownNodes = config.getPushDownNodes(); for (QueryNodeConfig queryNodeConfig : pushDownNodes) { if(queryNodeConfig instanceof DownsampleConfig) { downsampleConfig = (DownsampleConfig) queryNodeConfig; break; } } break; } if(node instanceof Downsample){ Downsample downsample = (Downsample) node; downsampleConfig = (DownsampleConfig) downsample.config(); break; } } return null; }); }
Source:
protected void refreshVisuals() { boolean isHash = 0 == ((MultiplicityElement) getUMLElement()).getLower(); getPrimaryShape().setHashed(isHash); boolean stack = 1 < ((MultiplicityElement) getUMLElement()).getUpper(); getPrimaryShape().setStack(stack); getPrimaryShape().setLayerNumber(1); getPrimaryShape().setXOffSet(2); getPrimaryShape().setYOffSet(-2); getPrimaryShape().setPathPattern(PATTERN_PATH); super.refreshVisuals(); }

Target:
protected void refreshVisuals() { boolean isHash = 0 == ((MultiplicityElement) getUMLElement()).getLower(); getPrimaryShape().setHashed(isHash); boolean stack = 1 < ((MultiplicityElement) getUMLElement()).getUpper(); getPrimaryShape().setStack(stack); getPrimaryShape().setLayerNumber(LAYER_NUMBER); getPrimaryShape().setXOffSet(X_OFFSET); getPrimaryShape().setYOffSet(Y_OFFSET); getPrimaryShape().setPathPattern(PATTERN_PATH); getPrimaryShape().setLayerOpacity(LAYER_OPACITY); super.refreshVisuals(); }
Source:
public List<String> peerCapabilities() { final String capabilitiesList = prop.getProperty("peer.capabilities", DEFAULT_PROTOCOL_LIST); return Arrays.asList(capabilitiesList.split(",")); }

Target:
public List<String> peerCapabilities() { String capabilitiesList = prop.getProperty("peer.capabilities", DEFAULT_PROTOCOL_LIST); return Arrays.asList(capabilitiesList.split(",")); }
Source:
public static Iterable<ITmfEventAspect<?>> getEventAspects(ITmfTrace trace, Class<? extends ITmfEventAspect<?>> aspectClass) { return StreamSupport.stream(Iterables.concat(trace.getEventAspects(), EXTRA_ASPECTS).spliterator(), false) .filter(aspect -> aspectClass.isAssignableFrom(aspect.getClass())) .collect(Collectors.toList()); }

Target:
public static Iterable<ITmfEventAspect<?>> getEventAspects(ITmfTrace trace, Class<? extends ITmfEventAspect<?>> aspectClass) { return Iterables.filter(Iterables.concat(trace.getEventAspects(), EXTRA_ASPECTS), aspect -> aspectClass.isAssignableFrom(aspect.getClass())); }
Source:
protected void buildVmBootSequence() { if (managedDevices != null) { VmDeviceCommonUtils.updateVmDevicesBootOrder(vm.getStaticData(), managedDevices, vm.getboot_sequence(), VmDeviceCommonUtils.isOldClusterVersion(vm.getvds_group_compatibility_version())); for (VmDevice vmDevice : managedDevices) { for (int i = 0; i < devices.size(); i++) { XmlRpcStruct struct = (XmlRpcStruct) devices.get(i); Object o = struct.getItem(VdsProperties.SpecParams); if (o instanceof Map<?, ?>) { if (StringUtils.map2String((Map<String, String>) o).indexOf(vmDevice.getDeviceId().toString()) > 0) { struct.add(VdsProperties.BootOrder, String.valueOf(vmDevice.getBootOrder())); break; } } } } } }

Target:
protected void buildVmBootSequence() { if (managedDevices != null) { VmDeviceCommonUtils.updateVmDevicesBootOrder(vm.getStaticData(), managedDevices, vm.getboot_sequence(), VmDeviceCommonUtils.isOldClusterVersion(vm.getvds_group_compatibility_version())); for (VmDevice vmDevice : managedDevices) { for (int i = 0; i < devices.size(); i++) { XmlRpcStruct struct = (XmlRpcStruct) devices.get(i); Object o = struct.getItem(VdsProperties.SpecParams); if (o instanceof Map<?, ?>) { if (StringUtils.map2String((Map<String, String>) o).contains(vmDevice.getDeviceId().toString())) { struct.add(VdsProperties.BootOrder, String.valueOf(vmDevice.getBootOrder())); break; } } else { log.errorFormat("Improper value of spec_params for VM {0} : {1}", vm.getvm_name(), o.toString()); } } } } }
Source:
private static void updateOption(VdcOption option) { Map<String, Object> values = null; if ((values = _vdcOptionCache.get(option.getoption_name())) != null) { values.put(option.getversion(), GetValue(option)); } else { values = new HashMap<String, Object>(); values.put(option.getversion(), GetValue(option)); _vdcOptionCache.put(option.getoption_name(), values); } }

Target:
private static void updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); if (values != null) { values.put(option.getversion(), GetValue(option)); } else { values = new HashMap<String, Object>(); values.put(option.getversion(), GetValue(option)); _vdcOptionCache.put(option.getoption_name(), values); } }
Source:
public Set<Connection> getConnections() { Set<Connection> conns = new HashSet<>(); for (VoltNetwork vn : m_networks) { Set<Connection> connsForNetwork; try { connsForNetwork = vn.getConnections().get(); } catch (InterruptedException | ExecutionException e) { connsForNetwork = new HashSet<>(); } conns.addAll(connsForNetwork); } return conns; }

Target:
public Set<Connection> getConnections() { List<Future<Set<Connection>>> futures = new ArrayList<>(m_networks.length); for (VoltNetwork vn : m_networks) { futures.add(vn.getConnections()); } Set<Connection> conns = new HashSet<>(); for (Future<Set<Connection>> fut : futures) { Set<Connection> connsForNetwork; try { connsForNetwork = fut.get(); } catch (InterruptedException | ExecutionException e) { connsForNetwork = new HashSet<>(); } conns.addAll(connsForNetwork); } return conns; }
Source:
private static Object getValue(Type type, Object value) { if (type.equals(BIGINT)) { return value; } else if (type.equals(INTEGER)) { return ((Number) value).intValue(); } else if (type.equals(DOUBLE)) { return value; } else if (type.equals(VARCHAR)) { return ((Slice) value).toStringUtf8(); } else if (type.equals(BOOLEAN)) { return value; } throw new UnsupportedOperationException("Query Builder can't handle type: " + type); }

Target:
private static Object getValue(Type type, Object value) { if (type.equals(BIGINT)) { return value; } if (type.equals(INTEGER)) { return ((Number) value).intValue(); } if (type.equals(DOUBLE)) { return value; } if (type.equals(VARCHAR)) { return ((Slice) value).toStringUtf8(); } if (type.equals(BOOLEAN)) { return value; } throw new IllegalArgumentException("Unhandled type: " + type); }
Source:
public void testParallelWait() throws InterruptedException { final ExecutorAllCompletionService service = createService(2); for (int i = 0; i < 300; ++i) { service.submit(new WaitRunnable(10), null); } List<Thread> threads = new ArrayList<>(10); for (int i = 0; i < 10; ++i) { Thread t = new Thread(() -> { service.waitUntilAllCompleted(); assert service.isAllCompleted(); assert !service.isExceptionThrown(); }); threads.add(t); t.start(); } for (Thread t : threads) { t.join(); } assert service.isAllCompleted(); assert !service.isExceptionThrown(); }

Target:
public void testParallelWait() throws InterruptedException { final ExecutorAllCompletionService service = createService(2); for (int i = 0; i < 300; ++i) { service.submit(new WaitRunnable(10), null); } List<Thread> threads = new ArrayList<>(10); for (int i = 0; i < 10; ++i) { Thread t = new Thread(() -> { service.waitUntilAllCompleted(); assertTrue(service.isAllCompleted()); assertFalse(service.isExceptionThrown()); }); threads.add(t); t.start(); } for (Thread t : threads) { t.join(); } assertTrue(service.isAllCompleted()); assertFalse(service.isExceptionThrown()); }
Source:
public String getPeerUserAgent() { Set<String> clientCapabilities = currentRequest == null ? null : currentRequest.getClientCapabilities(); return UserAgent.getAgent(clientCapabilities, userAgent); }

Target:
public String getPeerUserAgent() { Set<String> clientCapabilities = currentRequest == null ? null : currentRequest.getClientCapabilities(); if (currentRequest == null) { return userAgent; } return UserAgent.getAgent(clientCapabilities, userAgent); }
Source:
private FanoutBucket asFanout(InMemoryNoteBucket bucket) { if (bucket == null) return EMPTY_FANOUT; if (bucket instanceof FanoutBucket) return (FanoutBucket) bucket; FanoutBucket fanoutBucket = ((LeafBucket) bucket).split(); return fanoutBucket; }

Target:
private FanoutBucket asFanout(InMemoryNoteBucket bucket) { if (bucket == null) return EMPTY_FANOUT; if (bucket instanceof FanoutBucket) return (FanoutBucket) bucket; return ((LeafBucket) bucket).split(); }
Source:
private void processSystemFunctions(ArtifactReadable functionsFolder, ISheetWriter writer) throws IOException { writer.startSheet("report", columnHeadings.length); writer.writeRow((Object[]) columnHeadings); for (ArtifactReadable systemFunction : functionsFolder.getDescendants()) { if (systemFunction.isOfType(CoreArtifactTypes.SystemFunction)) { writer.writeCell(systemFunction.getName()); accumulator.reset(systemFunction); accumulator.buildSubsystemsRequirementsMap(systemFunction); String criticality; if (systemFunction.getAttributes(CoreAttributeTypes.SafetyCriticality).size() != 1) { System.out.println(String.format("found too many attributes on %s", systemFunction.toString())); criticality = systemFunction.getAttributes(CoreAttributeTypes.SafetyCriticality).iterator().next().getDisplayableString(); } else { criticality = systemFunction.getSoleAttributeAsString(CoreAttributeTypes.SafetyCriticality); } writer.writeCell(criticality); writer.writeCell(getSFHAHazards(systemFunction)); for (ArtifactReadable systemRequirement : systemFunction.getRelated(CoreRelationTypes.Design__Requirement)) { writer.writeCell(systemRequirement.getSoleAttributeAsString(CoreAttributeTypes.ParagraphNumber, ""), SYSTEM_REQUIREMENT_INDEX); writer.writeCell(systemRequirement.getName()); accumulator.output(); } writer.endRow(); } } writer.endSheet(); }

Target:
private void processSystemFunctions(ArtifactReadable functionsFolder, ISheetWriter writer) throws IOException { writer.startSheet("report", columnHeadings.length); writer.writeRow((Object[]) columnHeadings); for (ArtifactReadable systemFunction : functionsFolder.getDescendants()) { if (systemFunction.isOfType(CoreArtifactTypes.SystemFunction)) { writer.writeCell(systemFunction.getName()); accumulator.reset(systemFunction); accumulator.buildSubsystemsRequirementsMap(systemFunction); String criticality; if (systemFunction.getAttributes(CoreAttributeTypes.SafetyCriticality).size() != 1) { logger.debug("found too many attributes on %s", systemFunction.toString()); criticality = systemFunction.getAttributes(CoreAttributeTypes.SafetyCriticality).iterator().next().getDisplayableString(); } else { criticality = systemFunction.getSoleAttributeAsString(CoreAttributeTypes.SafetyCriticality); } writer.writeCell(criticality); writer.writeCell(getSFHAHazards(systemFunction)); for (ArtifactReadable systemRequirement : systemFunction.getRelated(CoreRelationTypes.Design__Requirement)) { writer.writeCell(systemRequirement.getSoleAttributeAsString(CoreAttributeTypes.ParagraphNumber, ""), SYSTEM_REQUIREMENT_INDEX); writer.writeCell(systemRequirement.getName()); accumulator.output(); } writer.endRow(); } } writer.endSheet(); }
Source:
private Object getNextDiff(TreeItem start) { return getNextDataWhichSatisfies(start, new Predicate<EObject>() { public boolean apply(EObject input) { return input instanceof Diff; } }); }

Target:
private Object getNextDiff(TreeItem start) { return getNextData(start, Predicates.alwaysTrue()); }
Source:
private void addServerOfflineWatcher() { Runnable serverOfflineWatcher = new Runnable() { @Override public void run() { long units = 10l; TimeUnit unit = TimeUnit.MINUTES; try { while (true) { HostState state = getStateSafe(); if (state == null || HostState.OFFLINE.equals(state)) { startShutDownCountdown(units, unit); } unit.sleep(units); } }catch (Exception e){ LOG.error("Watcher thread encountered an error - thread will stop for safety", e); } } public HostState getStateSafe() { HostState state; try { state = host.getState(); } catch (IOException e) { LOG.error("Offline watcher failed to get state, counting as OFFLINE. Exception: ", e); state = HostState.OFFLINE; } return state; } private void startShutDownCountdown(long units, TimeUnit unit) { try { unit.sleep(units); HostState state = getStateSafe(); if (state == null || HostState.OFFLINE.equals(state)) { LOG.info("Partition Server was OFFLINE for " + units + " " + unit.toString()); stopSynchronized(); } } catch (InterruptedException e) { LOG.error("Interrupted while performing shutdown countdown", e); } } }; offlineWatcherThread = new Thread(serverOfflineWatcher, "Server Offline Watcher"); offlineWatcherThread.start(); }

Target:
private void addServerOfflineWatcher() { Runnable serverOfflineWatcher = new Runnable() { @Override public void run() { long units = 10l; TimeUnit unit = TimeUnit.MINUTES; try { while (true) { HostState state = getStateSafe(); if (state == null || HostState.OFFLINE.equals(state)) { startShutDownCountdown(units, unit); } unit.sleep(units); } }catch (Exception e){ LOG.error("Watcher thread encountered an error - thread will stop for safety", e); } } public HostState getStateSafe() { HostState state; try { state = host.getState(); } catch (IOException e) { LOG.error("Offline watcher failed to get state, counting as OFFLINE. Exception: ", e); state = HostState.OFFLINE; } return state; } private void startShutDownCountdown(long units, TimeUnit unit) { try { unit.sleep(units); HostState state = getStateSafe(); if (state == null || HostState.OFFLINE.equals(state)) { LOG.info("Partition Server was OFFLINE for " + units + " " + unit.toString()); LOG.error("Would have shutdown"); } } catch (InterruptedException e) { LOG.error("Interrupted while performing shutdown countdown", e); } } }; offlineWatcherThread = new Thread(serverOfflineWatcher, "Server Offline Watcher"); offlineWatcherThread.setDaemon(true); offlineWatcherThread.start(); }
Source:
private long doForceInsertNewDocumentWithHistory(BasicDocumentRevision rev, List<String> revHistory) { logger.entering(this.getClass().getCanonicalName(), "doForceInsertNewDocumentWithHistory()", new Object[]{rev, revHistory}); assert !this.containsDocument(rev.getId()); long docNumericID = insertDocumentID(rev.getId()); long parentSequence = 0L; for (int i = 0; i < revHistory.size() - 1; i++) { parentSequence = insertStubRevision(docNumericID, revHistory.get(i), parentSequence); } InsertRevisionOptions options = new InsertRevisionOptions(); options.docNumericId = docNumericID; options.revId = revHistory.get(revHistory.size() - 1); options.parentSequence = parentSequence; options.deleted = rev.isDeleted(); options.current = true; options.data = rev.getBody().asBytes(); options.available = true; options.copyAttachments = false; long sequence = insertRevision(options); return sequence; }

Target:
private long doForceInsertNewDocumentWithHistory(BasicDocumentRevision rev, List<String> revHistory) { logger.entering("BasicDocumentRevision", "doForceInsertNewDocumentWithHistory()", new Object[]{rev, revHistory}); assert !this.containsDocument(rev.getId()); long docNumericID = insertDocumentID(rev.getId()); long parentSequence = 0L; for (int i = 0; i < revHistory.size() - 1; i++) { parentSequence = insertStubRevision(docNumericID, revHistory.get(i), parentSequence); } InsertRevisionOptions options = new InsertRevisionOptions(); options.docNumericId = docNumericID; options.revId = revHistory.get(revHistory.size() - 1); options.parentSequence = parentSequence; options.deleted = rev.isDeleted(); options.current = true; options.data = rev.getBody().asBytes(); options.available = true; options.copyAttachments = false; long sequence = insertRevision(options); return sequence; }
Source:
protected Configuration createConfiguration() { Configuration conf = super.createConfiguration(); maybeEnableS3Guard(conf); try { URI bucketURI = new URI(checkNotNull(conf.get("fs.contract.test.fs.s3a"))); S3ATestUtils.removeBucketOverrides(bucketURI.getHost(), conf, READAHEAD_RANGE, INPUT_FADVISE); } catch (URISyntaxException e) { throw new RuntimeException(e); } S3ATestUtils.disableFilesystemCaching(conf); conf.setInt(READAHEAD_RANGE, READAHEAD); conf.set(INPUT_FADVISE, seekPolicy); conf.set(INPUT_FADVISE, seekPolicy); return conf; }

Target:
protected Configuration createConfiguration() { Configuration conf = super.createConfiguration(); maybeEnableS3Guard(conf); try { URI bucketURI = new URI(checkNotNull(conf.get("fs.contract.test.fs.s3a"))); S3ATestUtils.removeBucketOverrides(bucketURI.getHost(), conf, READAHEAD_RANGE, INPUT_FADVISE); } catch (URISyntaxException e) { throw new RuntimeException(e); } S3ATestUtils.disableFilesystemCaching(conf); conf.setInt(READAHEAD_RANGE, READAHEAD); conf.set(INPUT_FADVISE, seekPolicy); return conf; }
Source:
private static ChunkerModel trainModel(ModelType type, ChunkerFactory factory) throws IOException { TrainingParameters params = TrainingParameters.defaultParams(); params.put("PrintMessages", false); return ChunkerME.train("eng", createSampleStream(), params, factory); }

Target:
private static ChunkerModel trainModel(ModelType type, ChunkerFactory factory) throws IOException { TrainingParameters params = TrainingParameters.defaultParams(); params.put(AbstractTrainer.VERBOSE_PARAM, false); return ChunkerME.train("eng", createSampleStream(), params, factory); }
Source:
public static synchronized boolean sendSPAppsQueryFeedsIntent(@Nullable Context context) { assert context != null : "context = null"; final Context appContext = context.getApplicationContext(); if (appContext == null) { Log.wtf(TAG, "Unable to get application context"); return false; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext); if (!prefs.getBoolean(PREF_HAS_QUERIED_SP_APPS, false)) { appContext.sendBroadcast(new Intent(SPAReceiver.ACTION_SP_APPS_QUERY_FEEDS)); if (BuildConfig.DEBUG) Log.d(TAG, "Sending SP_APPS_QUERY_FEEDS intent"); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(PREF_HAS_QUERIED_SP_APPS, true); editor.commit(); return true; } else { return false; } }

Target:
public static synchronized boolean sendSPAppsQueryFeedsIntent(@Nullable Context context) { if (context == null) throw new IllegalArgumentException("context = null"); final Context appContext = context.getApplicationContext(); if (appContext == null) { Log.wtf(TAG, "Unable to get application context"); return false; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext); if (!prefs.getBoolean(PREF_HAS_QUERIED_SP_APPS, false)) { appContext.sendBroadcast(new Intent(SPAReceiver.ACTION_SP_APPS_QUERY_FEEDS)); if (BuildConfig.DEBUG) Log.d(TAG, "Sending SP_APPS_QUERY_FEEDS intent"); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(PREF_HAS_QUERIED_SP_APPS, true); editor.commit(); return true; } else { return false; } }
Source:
static void populateConfigFromManifest(@NonNull Configuration config, @NonNull Bundle data) { config.setBuildUUID(data.getString(MF_BUILD_UUID)); config.setAppVersion(data.getString(MF_APP_VERSION)); config.setReleaseStage(data.getString(MF_RELEASE_STAGE)); if (data.containsKey(MF_ENDPOINT)) { String endpoint = data.getString(MF_ENDPOINT); String sessionEndpoint = data.getString(MF_SESSIONS_ENDPOINT); config.setEndpoints(endpoint, sessionEndpoint); } config.setSendThreads(data.getBoolean(MF_SEND_THREADS, true)); config.setPersistUserBetweenSessions( data.getBoolean(MF_PERSIST_USER_BETWEEN_SESSIONS, false)); config.setDetectNdkCrashes(data.getBoolean(MF_DETECT_NDK_CRASHES, false)); config.setDetectAnrs(data.getBoolean(MF_DETECT_ANRS, false)); if (data.containsKey(MF_AUTO_CAPTURE_SESSIONS)) { config.setAutoCaptureSessions(data.getBoolean(MF_AUTO_CAPTURE_SESSIONS)); } config.setEnableExceptionHandler( data.getBoolean(MF_ENABLE_EXCEPTION_HANDLER, true)); }

Target:
static void populateConfigFromManifest(@NonNull Configuration config, @NonNull Bundle data) { config.setBuildUUID(data.getString(MF_BUILD_UUID)); config.setAppVersion(data.getString(MF_APP_VERSION)); config.setReleaseStage(data.getString(MF_RELEASE_STAGE)); if (data.containsKey(MF_ENDPOINT)) { String endpoint = data.getString(MF_ENDPOINT); String sessionEndpoint = data.getString(MF_SESSIONS_ENDPOINT); config.setEndpoints(endpoint, sessionEndpoint); } config.setSendThreads(data.getBoolean(MF_SEND_THREADS, true)); config.setPersistUserBetweenSessions( data.getBoolean(MF_PERSIST_USER_BETWEEN_SESSIONS, false)); if (data.containsKey(MF_DETECT_NDK_CRASHES)) { config.setDetectNdkCrashes(data.getBoolean(MF_DETECT_NDK_CRASHES)); } if (data.containsKey(MF_DETECT_ANRS)) { config.setDetectAnrs(data.getBoolean(MF_DETECT_ANRS)); } if (data.containsKey(MF_AUTO_CAPTURE_SESSIONS)) { config.setAutoCaptureSessions(data.getBoolean(MF_AUTO_CAPTURE_SESSIONS)); } config.setEnableExceptionHandler( data.getBoolean(MF_ENABLE_EXCEPTION_HANDLER, true)); }
Source:
private void validateEntrypointSelector(Component component, List<HasMetadata> filteredObjects) throws DevfileException { if (component.getEntrypoints() == null || component.getEntrypoints().isEmpty()) { return; } for (Entrypoint ep : component.getEntrypoints()) { ContainerSearch search = new ContainerSearch(ep.getParentName(), ep.getParentSelector(), ep.getContainerName()); List<Container> cs = search.search(filteredObjects); if (cs.isEmpty()) { throw new DevfileFormatException( format( "Component '%s' of type '%s' contains an entry point that doesn't match any" + " container:\n%s", getIdentifiableComponentName(component), component.getType(), toYAML(ep))); } } }

Target:
private void validateEntrypointSelector(Component component, List<HasMetadata> filteredObjects) throws DevfileException { if (component.getEntrypoints() == null || component.getEntrypoints().isEmpty()) { return; } for (Entrypoint ep : component.getEntrypoints()) { ContainerSearch search = new ContainerSearch(ep.getParentName(), ep.getParentSelector(), ep.getContainerName()); List<Container> cs = search.search(filteredObjects); if (cs.isEmpty()) { throw new DevfileFormatException( format( "Component '%s' of type '%s' contains an entry point that doesn't match any" + " container.", getIdentifiableComponentName(component), component.getType())); } } }
Source:
public static <T> Constructor<T> findConstructor(@Nonnull final Class<T> klass, @Nonnull final Class<?>... parameterTypes) { Preconditions.checkNotNull(klass, "class"); Preconditions.checkNotNull(parameterTypes, "parameter types"); final Constructor<T> constructor; try { constructor = klass.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); } catch (final NoSuchMethodException e) { final StringBuilder desc = new StringBuilder(); desc.append(klass.getSimpleName()).append('('); for (int i = 0, length = parameterTypes.length; i < length; i++) { desc.append(parameterTypes[i].getName()); if (i < length - 1) { desc.append(',').append(' '); } } desc.append(')'); throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + klass); } return constructor; }

Target:
public static <T> Constructor<T> findConstructor(@Nonnull final Class<T> klass, @Nonnull final Class<?>... parameterTypes) { Preconditions.checkNotNull(klass, "class"); Preconditions.checkNotNull(parameterTypes, "parameter types"); try { Constructor<T> constructor = klass.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; } catch (final NoSuchMethodException e) { final StringBuilder desc = new StringBuilder(); desc.append(klass.getSimpleName()); StringJoiner joiner = new StringJoiner(", ", "(", ")"); for (Class<?> type : parameterTypes) { joiner.add(type.getSimpleName()); } desc.append(joiner); throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + klass); } }
Source:
public ActivationKeyDTO createActivationKey(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "activation_key", required = true) ActivationKeyDTO dto) { Owner owner = findOwner(ownerKey); OwnerDTO ownerDTO = translator.translate(owner, OwnerDTO.class); dto.setOwner(ownerDTO); ActivationKey key = new ActivationKey(); this.populateEntity(key, dto); if (StringUtils.isBlank(key.getName())) { throw new BadRequestException(i18n.tr("Must provide a name for activation key.")); } String testName = key.getName().replace("-", "0").replace("_", "0"); if (!testName.matches("[a-zA-Z0-9]*")) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' must be alphanumeric or " + "include the characters ''-'' or ''_''", key.getName())); } if (activationKeyCurator.lookupForOwner(key.getName(), owner) != null) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' is already in use for owner {1}", key.getName(), ownerKey)); } if (key.getContentOverrides() != null) { contentOverrideValidator.validate(key.getContentOverrides()); } serviceLevelValidator.validate(owner, key.getServiceLevel()); ActivationKey newKey = activationKeyCurator.create(key); sink.emitActivationKeyCreated(newKey); return translator.translate(newKey, ActivationKeyDTO.class); }

Target:
public ActivationKeyDTO createActivationKey(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "activation_key", required = true) ActivationKeyDTO dto) { Owner owner = findOwner(ownerKey); if (StringUtils.isBlank(dto.getName())) { throw new BadRequestException(i18n.tr("Must provide a name for activation key.")); } String testName = dto.getName().replace("-", "0").replace("_", "0"); if (!testName.matches("[a-zA-Z0-9]*")) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' must be alphanumeric or " + "include the characters ''-'' or ''_''", dto.getName())); } if (activationKeyCurator.lookupForOwner(dto.getName(), owner) != null) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' is already in use for owner {1}", dto.getName(), ownerKey)); } serviceLevelValidator.validate(owner, dto.getServiceLevel()); OwnerDTO ownerDTO = translator.translate(owner, OwnerDTO.class); dto.setOwner(ownerDTO); ActivationKey key = new ActivationKey(); this.populateEntity(key, dto); if (key.getContentOverrides() != null) { contentOverrideValidator.validate(key.getContentOverrides()); } ActivationKey newKey = activationKeyCurator.create(key); sink.emitActivationKeyCreated(newKey); return translator.translate(newKey, ActivationKeyDTO.class); }