auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
Future<?> triggerGC(final boolean force, final boolean suspendMajor, final boolean suspendMinor) { return gcExecutor.submit(() -> { try { runWithFlags(force, suspendMajor, suspendMinor); } catch (Exception e) { LOG.warn("Failed to complete gc {}", e.getMessage(), e); } }); }

Target:
Future<?> triggerGC(final boolean force, final boolean suspendMajor, final boolean suspendMinor) { return gcExecutor.submit(() -> { runWithFlags(force, suspendMajor, suspendMinor); }); }
Source:
protected void endSuccessfully() { endCommandActions(); getVmStaticDAO().incrementDbGeneration(getVmTemplate().getId()); }

Target:
protected void endSuccessfully() { endCommandActions(); incrementDbGenerationForRelatedEntities(); }
Source:
public static String fromPassword(StringWrapper unencryptedPasswordString) { try { return CryptUtil.encryptPassword(AppConfig.getInstance(), unencryptedPasswordString.value); } catch (Exception e) { android.util.Log.e(TAG, "Error encrypting password", e); return null; } }

Target:
public static String fromPassword(StringWrapper unencryptedPasswordString) { try { return CryptUtil.encryptPassword(AppConfig.getInstance(), unencryptedPasswordString.value); } catch (Exception e) { android.util.Log.e(TAG, "Error encrypting password", e); return unencryptedPasswordString.value; } }
Source:
public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile profile) { NicProfile managementNic = null; NicProfile controlNic = null; for (NicProfile nic : profile.getNics()) { if (nic.getTrafficType() == TrafficType.Management) { managementNic = nic; } else if (nic.getTrafficType() == TrafficType.Control && nic.getIp4Address() != null) { controlNic = nic; } } if (controlNic == null) { if (managementNic == null) { s_logger.error("Management network doesn't exist for the console proxy vm " + profile.getVirtualMachine()); return false; } controlNic = managementNic; } if(profile.getHypervisorType() == HypervisorType.Hyperv) { controlNic = managementNic; } CheckSshCommand check = new CheckSshCommand(profile.getInstanceName(), controlNic.getIp4Address(), 3922); cmds.addCommand("checkSsh", check); try { File uiFiles = new File("systemvm/js"); if (!uiFiles.exists()) { uiFiles = new File("/usr/share/cloudstack-common/systemvm/js"); } if (uiFiles.exists() && uiFiles.isDirectory()) { CopyFileInVmCommand copyFile = new CopyFileInVmCommand(uiFiles.getCanonicalPath(), "/usr/local/cloud/systemvm/js", controlNic.getIp4Address()); cmds.addCommand("copyFile", copyFile); } else { s_logger.error("Couldn't locate localization files for console proxy"); return false; } } catch (IOException e) { s_logger.error("Failed to copy localization files for console proxy: " + e.getMessage()); } return true; }

Target:
public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile profile) { NicProfile managementNic = null; NicProfile controlNic = null; for (NicProfile nic : profile.getNics()) { if (nic.getTrafficType() == TrafficType.Management) { managementNic = nic; } else if (nic.getTrafficType() == TrafficType.Control && nic.getIPv4Address() != null) { controlNic = nic; } } if (controlNic == null) { if (managementNic == null) { s_logger.error("Management network doesn't exist for the console proxy vm " + profile.getVirtualMachine()); return false; } controlNic = managementNic; } if(profile.getHypervisorType() == HypervisorType.Hyperv) { controlNic = managementNic; } CheckSshCommand check = new CheckSshCommand(profile.getInstanceName(), controlNic.getIPv4Address(), 3922); cmds.addCommand("checkSsh", check); try { File uiFiles = new File("systemvm/js"); if (!uiFiles.exists()) { uiFiles = new File("/usr/share/cloudstack-common/systemvm/js"); } if (uiFiles.exists() && uiFiles.isDirectory()) { CopyFileInVmCommand copyFile = new CopyFileInVmCommand(uiFiles.getCanonicalPath(), "/usr/local/cloud/systemvm/js", controlNic.getIPv4Address()); cmds.addCommand("copyFile", copyFile); } else { s_logger.error("Couldn't locate localization files for console proxy"); return false; } } catch (IOException e) { s_logger.error("Failed to copy localization files for console proxy: " + e.getMessage()); } return true; }
Source:
public void shouldRaiseAlertIfRequestParamAppearAsMetaCharsetValue() throws Exception { HttpMessage msg = createMessage(); msg.getRequestHeader().setURI(new URI("<LINK_0>", false)); msg.setResponseBody("<html><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></html>"); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), equalTo(1)); }

Target:
public void shouldRaiseAlertIfRequestParamAppearAsMetaCharsetValue() throws Exception { HttpMessage msg = createMessage(); msg.getRequestHeader().setURI(new URI("<LINK_0>", false)); msg.setResponseBody("<html><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></html>"); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), equalTo(1)); assertThat(alertsRaised.get(0).getParam(), equalTo("cs")); }
Source:
public static Function getFunction(String name) { Supplier<Function> supplier = func.get(name.toLowerCase()); if (supplier == null) { throw new IllegalArgumentException("Invalid function name '" + name + "'"); } return supplier.get(); }

Target:
public static Function getFunction(String name) { Supplier<Function> supplier = func.get(name.toLowerCase()); if (supplier == null) { throw new IAE("Invalid function name '%s'", name); } return supplier.get(); }
Source:
private void tryStartNewShipper(String walGroupId, PriorityBlockingQueue<Path> queue) { workerThreads.compute(walGroupId, (key, value) -> { if (value != null) { if (LOG.isDebugEnabled()) { LOG.debug( "{} Someone has beat us to start a worker thread for wal group {}", logPeerId(), key); } return value; } else { if (LOG.isDebugEnabled()) { LOG.debug("{} Starting up worker for wal group {}", logPeerId(), key); } ReplicationSourceShipper worker = createNewShipper(walGroupId, queue); ReplicationSourceWALReader walReader = createNewWALReader(walGroupId, queue, worker.getStartPosition()); Threads.setDaemonThreadRunning( walReader, Thread.currentThread().getName() + ".replicationSource.wal-reader." + walGroupId + "," + queueId, (t,e) -> { this.uncaughtException(t,e); while (true) { try { LOG.info("Refreshing replication sources now due " + "to previous error on reader thread."); this.manager.refreshSources(this.getPeerId()); break; } catch (IOException e1) { LOG.error("Replication sources refresh failed.", e1); sleepForRetries("Sleeping before try refreshing sources again", maxRetriesMultiplier); } } }); worker.setWALReader(walReader); worker.startup(this::uncaughtException); return worker; } }); }

Target:
private void tryStartNewShipper(String walGroupId, PriorityBlockingQueue<Path> queue) { workerThreads.compute(walGroupId, (key, value) -> { if (value != null) { if (LOG.isDebugEnabled()) { LOG.debug( "{} Someone has beat us to start a worker thread for wal group {}", logPeerId(), key); } return value; } else { if (LOG.isDebugEnabled()) { LOG.debug("{} Starting up worker for wal group {}", logPeerId(), key); } ReplicationSourceShipper worker = createNewShipper(walGroupId, queue); ReplicationSourceWALReader walReader = createNewWALReader(walGroupId, queue, worker.getStartPosition()); Threads.setDaemonThreadRunning( walReader, Thread.currentThread().getName() + ".replicationSource.wal-reader." + walGroupId + "," + queueId, (t,e) -> this.uncaughtException(t, e, this.manager, this.getPeerId())); worker.setWALReader(walReader); worker.startup((t,e) -> this.uncaughtException(t, e, this.manager, this.getPeerId())); return worker; } }); }
Source:
public static void main(String[] args) { if (args.length < 5) { System.out.println("Please specify your access key and call id and leg id and recording id example :" + " java -jar <this jar file> test_accesskey e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Getting a recording"); final String callId = args[1]; final String legId = args[2]; final String recordingId = args[3]; final String basePath = args[4]; final String filePath = messageBirdClient.downloadRecording(callId, legId, recordingId, basePath); if (filePath != null) { System.out.println("Record file is downloaded to "+filePath); } } catch (GeneralException | NotFoundException | UnauthorizedException exception) { exception.printStackTrace(); } }

Target:
public static void main(String[] args) { if (args.length < 4) { System.out.println("Please specify your access key and call id and leg id and recording id and base path(optional) example :" + " java -jar <this jar file> test_accesskey e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938 /users/{user}/test"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Getting a recording"); final String callId = args[1]; final String legId = args[2]; final String recordingId = args[3]; String basePath = null; if (args.length > 4) { basePath = args[4]; } final String filePath = messageBirdClient.downloadRecording(callId, legId, recordingId, basePath); if (filePath != null) { System.out.println("Record file is downloaded to "+filePath); } } catch (GeneralException | NotFoundException | UnauthorizedException exception) { exception.printStackTrace(); } }
Source:
private static Collection<@NonNull TmfAbstractAnalysisRequirement> getSubRequirements() { Set<@NonNull String> requiredEventsFields = Collections.singleton( ITraceEventConstants.DURATION); TmfAnalysisEventFieldRequirement entryReq = new TmfAnalysisEventFieldRequirement( StringUtils.EMPTY, requiredEventsFields); return Collections.singleton(entryReq); }

Target:
private static Collection<@NonNull TmfAbstractAnalysisRequirement> getSubRequirements() { TmfAnalysisEventFieldRequirement entryReq = new TmfAnalysisEventFieldRequirement( StringUtils.EMPTY, Collections.singleton(ITraceEventConstants.DURATION)); return Collections.singleton(entryReq); }
Source:
public ReadContext init(InitContext context) { Configuration configuration = context.getConfiguration(); String readerSchemaString = configuration.get(AVRO_READ_SCHEMA); boolean checkSchemaCompatibility = configuration.getBoolean(AVRO_SCHEMA_COMPATIBILITY_CHECK, false); if (readerSchemaString != null && checkSchemaCompatibility) { Schema.Parser parser = new Schema.Parser(); Schema readerSchema = parser.parse(readerSchemaString); return init(configuration, mergeKeyValueMetadata(context, readerSchema), context.getFileSchema()); } else { return init(configuration, context.getMergedKeyValueMetaData(), context.getFileSchema()); } }

Target:
public ReadContext init(InitContext context) { MessageType fileSchema = context.getFileSchema(); MessageType schema = fileSchema; Map<String, String> metadata = getMergedKeyValueMetadata(context); Configuration configuration = context.getConfiguration(); String readerSchemaString = configuration.get(AVRO_READ_SCHEMA); if (readerSchemaString != null) { metadata.put(AVRO_READ_SCHEMA_METADATA_KEY, readerSchemaString); } String requestedProjectionString = configuration.get(AVRO_REQUESTED_PROJECTION); if (requestedProjectionString != null) { Schema avroRequestedProjection = new Schema.Parser().parse(requestedProjectionString); schema = new AvroSchemaConverter().convert(avroRequestedProjection); } String avroReadSchema = configuration.get(AVRO_READ_SCHEMA); if (avroReadSchema != null) { metadata = new LinkedHashMap<String, String>(); metadata.put(AVRO_READ_SCHEMA_METADATA_KEY, avroReadSchema); } return new ReadContext(getSchemaForRead(fileSchema, schema), metadata); }
Source:
public static SWTBotRootMenu contextMenu(final Control control, final int x, final int y) throws WidgetNotFoundException { ContextMenuHelper.notifyMenuDetect(control, control); WaitForObjectCondition<Menu> waitForMenu = waitForNatTablePopupMenu(control, x, y); new SWTBot().waitUntil(waitForMenu); return new SWTBotRootMenu(waitForMenu.get(0)); }

Target:
public static SWTBotRootMenu contextMenu(final Control control, final int x, final int y) throws WidgetNotFoundException { UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { control.notifyListeners(SWT.MouseDown, createMouseEvent(control, x, y, 3, SWT.NONE, 1)); } }); notifyMenuDetect(control, x, y); WaitForObjectCondition<Menu> waitForMenu = waitForNatTablePopupMenu(control, x, y); new SWTBot().waitUntil(waitForMenu); return new SWTBotRootMenu(waitForMenu.get(0)); }
Source:
public void testAllChildrenNoMatchExpectFalse() { fFilter.setNot(false); assertFalse(fFilter.matches(fEvent)); }

Target:
public void testAllChildrenNoMatchExpectFalse() { fFilter.setNot(false); ITmfFilterTreeNode child = fFilterNode.clone(); assertEquals("addChild()", 0, fFilterNode.addChild(child)); assertFalse(fFilter.matches(fEvent)); }
Source:
public static boolean isMatch(AttributeDescriptor a, AttributeDescriptor b, boolean strict) { if (a == b) { return true; } if (b == null) { return false; } if (a == null) { return false; } if (a.equals(b)) { return true; } if (strict) { if (a.getLocalName().equals(b.getLocalName()) && a.getType().getBinding().equals(b.getType().getBinding())) { return true; } } else { if (a.getLocalName().equals(b.getLocalName()) && a.getClass().equals(b.getClass())) { return true; } } return false; }

Target:
public static boolean isMatch(AttributeDescriptor a, AttributeDescriptor b, boolean strict) { if (a == b) { return true; } if (b == null) { return false; } if (a == null) { return false; } if (a.equals(b)) { return true; } if (strict) { if (a.getLocalName().equals(b.getLocalName()) && a.getType().getBinding().equals(b.getType().getBinding())) { return true; } } else { if (a.getLocalName().equals(b.getLocalName())) { return true; } } return false; }
Source:
private void initializeLanguageDialog(PreferenceScreen screen) { ListPreference languageSelection = (ListPreference) screen.findPreference(LANGUAGE); if (languageSelection != null) { Map<String, List<String>> items = new TreeMap<>(); for (String localeCode : LanguageUtil.APP_LANGUAGES) { Locale loc = LanguageUtil.getLocale(localeCode); items.put(loc.getDisplayName(loc).toLowerCase(), Arrays.asList(loc.getDisplayName(loc), loc.toString())); } CharSequence[] languageDialogLabels = new CharSequence[items.size() + 1]; CharSequence[] languageDialogValues = new CharSequence[items.size() + 1]; languageDialogLabels[0] = getResources().getString(R.string.language_system); languageDialogValues[0] = ""; int i = 1; for (Map.Entry<String, List<String>> e : items.entrySet()) { languageDialogLabels[i] = e.getValue().get(0); languageDialogValues[i] = e.getValue().get(1); i++; } languageSelection.setEntries(languageDialogLabels); languageSelection.setEntryValues(languageDialogValues); } }

Target:
private void initializeLanguageDialog(PreferenceScreen screen) { ListPreference languageSelection = (ListPreference) screen.findPreference(LANGUAGE); if (languageSelection != null) { Map<String, String> items = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (String localeCode : LanguageUtil.APP_LANGUAGES) { Locale loc = LanguageUtil.getLocale(localeCode); items.put(loc.getDisplayName(loc), loc.toString()); } CharSequence[] languageDialogLabels = new CharSequence[items.size() + 1]; CharSequence[] languageDialogValues = new CharSequence[items.size() + 1]; languageDialogLabels[0] = getResources().getString(R.string.language_system); languageDialogValues[0] = ""; int i = 1; for (Map.Entry<String, String> e : items.entrySet()) { languageDialogLabels[i] = e.getKey(); languageDialogValues[i] = e.getValue(); i++; } languageSelection.setEntries(languageDialogLabels); languageSelection.setEntryValues(languageDialogValues); } }
Source:
protected void compute() { try { final int parallelTaskCount = computeNumTasks(); if (sequences.size() < 4 || parallelTaskCount < 2) { LOG.info( "Input sequence count (%s) or available parallel merge task count (%s) too small to perform parallel" + " merge-combine, performing serially with a single merge-combine task", sequences.size(), parallelTaskCount ); QueuePusher<ResultBatch<T>> resultsPusher = new QueuePusher<>(out, hasTimeout, timeoutAt); List<BatchedResultsCursor<T>> sequenceCursors = new ArrayList<>(sequences.size()); for (Sequence<T> s : sequences) { sequenceCursors.add(new YielderBatchedResultsCursor<>(new SequenceBatcher<>(s, batchSize), orderingFn)); } PrepareMergeCombineInputsAction<T> blockForInputsAction = new PrepareMergeCombineInputsAction<>( sequenceCursors, resultsPusher, orderingFn, combineFn, yieldAfter, batchSize, cancellationGizmo ); getPool().execute(blockForInputsAction); } else { LOG.info("Spawning %s parallel merge-combine tasks for %s sequences", parallelTaskCount, sequences.size()); spawnParallelTasks(parallelTaskCount); } } catch (Exception ex) { cancellationGizmo.cancel(ex); out.offer(new ResultBatch<>()); } }

Target:
protected void compute() { try { final int parallelTaskCount = computeNumTasks(); if (parallelTaskCount < 2) { LOG.debug( "Input sequence count (%s) or available parallel merge task count (%s) too small to perform parallel" + " merge-combine, performing serially with a single merge-combine task", sequences.size(), parallelTaskCount ); QueuePusher<ResultBatch<T>> resultsPusher = new QueuePusher<>(out, hasTimeout, timeoutAt); List<BatchedResultsCursor<T>> sequenceCursors = new ArrayList<>(sequences.size()); for (Sequence<T> s : sequences) { sequenceCursors.add(new YielderBatchedResultsCursor<>(new SequenceBatcher<>(s, batchSize), orderingFn)); } PrepareMergeCombineInputsAction<T> blockForInputsAction = new PrepareMergeCombineInputsAction<>( sequenceCursors, resultsPusher, orderingFn, combineFn, yieldAfter, batchSize, targetTimeNanos, cancellationGizmo ); getPool().execute(blockForInputsAction); } else { LOG.debug("Spawning %s parallel merge-combine tasks for %s sequences", parallelTaskCount, sequences.size()); spawnParallelTasks(parallelTaskCount); } } catch (Exception ex) { cancellationGizmo.cancel(ex); out.offer(ResultBatch.TERMINAL); } }
Source:
public ImportInfoImpl accept(WorkspaceFilter wspFilter, Node parent, String name, ArtifactSetImpl artifacts) throws RepositoryException, IOException { Artifact dir = artifacts.getDirectory(); if (dir == null || artifacts.size() != 1) { return null; } ImportInfoImpl info = new ImportInfoImpl(); if (dir.getRelativePath().length() == 0) { return info; } if (!parent.hasNode(dir.getRelativePath())) { Node node = parent.addNode(dir.getRelativePath(), nodeType); info.onCreated(node.getPath()); } else { Set<String> hints = new HashSet<String>(); String rootPath = parent.getPath(); if (!rootPath.equals("/")) { rootPath += "/"; } for (Artifact a: artifacts.values(ArtifactType.HINT)) { hints.add(rootPath + a.getRelativePath()); } Node node = parent.getNode(dir.getRelativePath()); if (wspFilter.contains(node.getPath()) && !node.getPrimaryNodeType().isNodeType(nodeType)) { node = modifyPrimaryType(node, info); } NodeIterator iter = node.getNodes(); while (iter.hasNext()) { Node child = iter.nextNode(); String path = child.getPath(); if (wspFilter.contains(path)) { if (wspFilter.getImportMode(path) == ImportMode.REPLACE) { if (!hints.contains(path)) { if (getAclManagement().isACLNode(child)) { if (acHandling == AccessControlHandling.OVERWRITE || acHandling == AccessControlHandling.CLEAR) { info.onDeleted(path); getAclManagement().clearACL(node); } } else { info.onDeleted(path); child.remove(); } } else if (acHandling == AccessControlHandling.CLEAR && getAclManagement().isACLNode(child)) { info.onDeleted(path); getAclManagement().clearACL(node); } } } } } return info; }

Target:
public ImportInfoImpl accept(WorkspaceFilter wspFilter, Node parent, String name, ArtifactSetImpl artifacts) throws RepositoryException, IOException { Artifact dir = artifacts.getDirectory(); if (dir == null || artifacts.size() != 1) { return null; } ImportInfoImpl info = new ImportInfoImpl(); if (dir.getRelativePath().length() == 0) { return info; } if (!parent.hasNode(dir.getRelativePath())) { Node node = parent.addNode(dir.getRelativePath(), nodeType); info.onCreated(node.getPath()); } else { Set<String> hints = new HashSet<String>(); String rootPath = parent.getPath(); if (!rootPath.equals("/")) { rootPath += "/"; } for (Artifact a: artifacts.values(ArtifactType.HINT)) { hints.add(rootPath + a.getRelativePath()); } Node node = parent.getNode(dir.getRelativePath()); if (wspFilter.contains(node.getPath()) && !nodeType.equals(node.getPrimaryNodeType().getName())) { node = modifyPrimaryType(node, info); } NodeIterator iter = node.getNodes(); while (iter.hasNext()) { Node child = iter.nextNode(); String path = child.getPath(); if (wspFilter.contains(path)) { if (wspFilter.getImportMode(path) == ImportMode.REPLACE) { if (!hints.contains(path)) { if (getAclManagement().isACLNode(child)) { if (acHandling == AccessControlHandling.OVERWRITE || acHandling == AccessControlHandling.CLEAR) { info.onDeleted(path); getAclManagement().clearACL(node); } } else { info.onDeleted(path); child.remove(); } } else if (acHandling == AccessControlHandling.CLEAR && getAclManagement().isACLNode(child)) { info.onDeleted(path); getAclManagement().clearACL(node); } } } } } return info; }
Source:
protected void handleCreate(DebugEvent event) { if (isMissingRequiredThreadGroup(event)) { return; } fLastCreatedThread = (IThread) event.getSource(); super.handleCreate(event); fLastCreatedThread = null; }

Target:
protected void handleCreate(DebugEvent event) { if (isMissingRequiredThreadGroup(event)) { return; } super.handleCreate(event); }
Source:
public byte[] encode(final Identity identity) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final GZIPOutputStream gzip = new GZIPOutputStream(out); try { gzip.write(this.origin.encode(identity)); } finally { gzip.close(); out.close(); } return out.toByteArray(); }

Target:
public byte[] encode(final Identity identity) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final GZIPOutputStream gzip = new GZIPOutputStream(out); try { gzip.write(this.origin.encode(identity)); } finally { gzip.close(); } return out.toByteArray(); }
Source:
private Collection<CommandParameter> getDiagramTypesCreation() { final Collection<CommandParameter> result = new HashSet<CommandParameter>(); for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) { DiagramDescription sequenceDiagramDescription = diagramTypeDescriptor.getDiagramDescriptionProvider().createDiagramDescription(); sequenceDiagramDescription.setDefaultLayer(DescriptionFactory.eINSTANCE.createLayer()); final CommandParameter typeCommandParameter = new CommandParameter(null, DescriptionPackage.Literals.VIEWPOINT__OWNED_REPRESENTATIONS, sequenceDiagramDescription); result.add(typeCommandParameter); } return result; }

Target:
private Collection<CommandParameter> getDiagramTypesCreation() { final Collection<CommandParameter> result = new HashSet<CommandParameter>(); for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) { DiagramDescription specificDiagramDescription = diagramTypeDescriptor.getDiagramDescriptionProvider().createDiagramDescription(); if (specificDiagramDescription.getDefaultLayer() == null) { specificDiagramDescription.setDefaultLayer(DescriptionFactory.eINSTANCE.createLayer()); } final CommandParameter typeCommandParameter = new CommandParameter(null, DescriptionPackage.Literals.VIEWPOINT__OWNED_REPRESENTATIONS, specificDiagramDescription); result.add(typeCommandParameter); } return result; }
Source:
protected void testAccessControl() throws Exception { dataBundle = getTypicalDataBundle(); removeAndRestoreDataBundle(dataBundle); InstructorAttributes moderatedInstructor = dataBundle.instructors.get("instructor1OfCourse1"); String courseId = moderatedInstructor.courseId; String feedbackSessionName = ""; String moderatedInstructorEmail = "instructor1@course1.tmt"; String[] submissionParams; feedbackSessionName = "First feedback session"; submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName, Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON, moderatedInstructorEmail }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); verifyUnaccessibleWithoutModifyCoursePrivilege(submissionParams); }

Target:
protected void testAccessControl() throws Exception { InstructorAttributes moderatedInstructor = typicalBundle.instructors.get("helperOfCourse1"); String courseId = moderatedInstructor.courseId; String feedbackSessionName = "First feedback session"; String moderatedInstructorEmail = "helper@course1.tmt"; String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName, Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON, moderatedInstructorEmail }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); verifyUnaccessibleWithoutModifySessionPrivilege(submissionParams); }
Source:
private void courtier(Game game, MoveContext context, Player currentPlayer) { if (currentPlayer.getHand().size() == 0) return; Card card = currentPlayer.controlPlayer.courtier_cardToReveal(context); if (card == null) { Util.playerError(currentPlayer, "Courtier errror, reveal random card."); card = Util.randomCard(currentPlayer.hand); } int numTypes = card.getNumberOfTypes(currentPlayer); if (numTypes > 0) { CourtierOption[] options = currentPlayer.controlPlayer.courtier_chooseOptions(context, numTypes); if (options == null || options.length != numTypes ) { Util.playerError(currentPlayer, "Courtier Erro, Ignoring"); } else { for (CourtierOption option : options) { switch (option) { case AddAction: context.actions++; break; case AddBuy: context.buys++; break; case AddCoins: context.addCoins(3, this.controlCard); break; case GainGold: currentPlayer.gainNewCard(Cards.gold, this.controlCard, context); break; } } } } }

Target:
private void courtier(Game game, MoveContext context, Player currentPlayer) { if (currentPlayer.getHand().size() == 0) return; Card card = currentPlayer.controlPlayer.courtier_cardToReveal(context); if (card == null) { Util.playerError(currentPlayer, "Courtier errror, reveal random card."); card = Util.randomCard(currentPlayer.hand); } currentPlayer.reveal(card, this.controlCard, context); int numTypes = card.getNumberOfTypes(currentPlayer); if (numTypes > 0) { CourtierOption[] options = null; if (numTypes >= 4) { options = CourtierOption.values(); } else { options = currentPlayer.controlPlayer.courtier_chooseOptions(context, CourtierOption.values(), numTypes); } if (options == null || options.length != numTypes ) { Util.playerError(currentPlayer, "Courtier Erro, Ignoring"); } else { for (CourtierOption option : options) { switch (option) { case AddAction: context.actions++; break; case AddBuy: context.buys++; break; case AddCoins: context.addCoins(3, this.controlCard); break; case GainGold: currentPlayer.gainNewCard(Cards.gold, this.controlCard, context); break; } } } } }
Source:
public void startNextKeyspace() { final String keyspace = super.nextKeyspace(); if (keyspace == null) { return; } restoreFeature = executorService.submit(new Runnable() { @Override public void run() { try { LOGGER.info("Starting restore on keyspace {}", keyspace); keyspaceStarted(); final BackupManager backupManager = new BackupManager(checkNotNull(jmxConnect), backupDir); backupManager.restore(keyspace, truncateTables); keyspaceFinished("SUCCESS", keyspace); } catch (final Exception e) { LOGGER.error("Failed to restore keyspace " + keyspace, e); keyspaceFinished("FAILURE", keyspace); } finally { startNextKeyspace(); } } }); LOGGER.info("Submitted restore for keyspace {}", keyspace); }

Target:
public void startNextKeyspace() { final String keyspace = super.nextKeyspace(); if (keyspace == null) { return; } restoreFeature = executorService.submit(new Runnable() { @Override public void run() { try { LOGGER.info("Starting restore on keyspace {}", keyspace); keyspaceStarted(); final BackupManager backupManager = new BackupManager(checkNotNull(jmxConnect), backupDir); backupManager.restore(keyspace); keyspaceFinished(SUCCESS, keyspace); } catch (final Exception e) { LOGGER.error("Failed to restore keyspace " + keyspace, e); keyspaceFinished(FAILURE, keyspace); } finally { startNextKeyspace(); } } }); LOGGER.info("Submitted restore for keyspace {}", keyspace); }
Source:
private List<Tuple> tuplesResult(EntityKey[] keys, Object[] searchObjects, TupleContext tupleContext, DBCursor cursor) { List<Tuple> tuples = CollectionHelper.initializeSizedList( searchObjects.length, null ); for ( DBObject dbObject : cursor ) { for ( int i = 0; i < searchObjects.length; i++ ) { if ( dbObject.get( ID_FIELDNAME ).equals( searchObjects[i] ) ) { tuples.set( i, createTuple( keys[i], tupleContext, dbObject ) ); break; } } } return tuples; }

Target:
private List<Tuple> tuplesResult(EntityKey[] keys, Object[] searchObjects, TupleContext tupleContext, DBCursor cursor) { Tuple[] tuples = new Tuple[searchObjects.length]; for ( DBObject dbObject : cursor ) { for ( int i = 0; i < searchObjects.length; i++ ) { if ( dbObject.get( ID_FIELDNAME ).equals( searchObjects[i] ) ) { tuples[i] = createTuple( keys[i], tupleContext, dbObject ); break; } } } return Arrays.asList( tuples ); }
Source:
private void writeObject(ObjectOutputStream oos) throws IOException { if (buf == null) { buf = new byte[codec.sizeof(object)]; codec.encode(object, buf); } oos.defaultWriteObject(); }

Target:
private void writeObject(ObjectOutputStream oos) throws IOException { if (buf == null) { buf = new byte[codec.sizeof(object)]; codec.encode(object, buf); } oos.writeInt(hash); if (object == null) { oos.writeInt(buf.length); oos.write(buf); } else { oos.writeInt(codec.sizeof(object)); CodedOutputStream cos = CodedOutputStream.newInstance(oos); codec.encode(object, cos); cos.flush(); } }
Source:
public void reportsRequestResultWhenStopFails() throws Exception { final Repo repo = new MkGithub().randomRepo(); final Issue issue = repo.issues().create("Bug", "stop it please"); final Talk talk = ReportsTest.example(repo, issue); final Agent agent = new Reports(repo.github()); agent.execute(talk); MatcherAssert.assertThat( talk.read(), XhtmlMatchers.hasXPath(XPATH) ); MatcherAssert.assertThat( "Comment contains warning about stop request", repo.issues().get(1).comments().get(1).toString().contains( ReportsTest.PHRASES.getString("Reports.stop-fails").replace( "%s", "" ) ) ); }

Target:
public void reportsRequestResultWhenStopFails() throws Exception { final String user = "john"; final String stop = "stop it please"; final Repo repo = new MkGithub(user).randomRepo(); final Talk talk = ReportsTest.example( repo, repo.issues().create("Bug", stop) ); final Agent agent = new Reports(repo.github()); agent.execute(talk); MatcherAssert.assertThat( talk.read(), XhtmlMatchers.hasXPath(XPATH) ); MatcherAssert.assertThat( "Comment contains warning about stop request", repo.issues().get(1).comments().get(1).json().getString( "body" ).equals( String.format( "> %s\n\n@%s %s %s", stop, user, ReportsTest.PHRASES.getString("Reports.stop-fails"), Logger.format( ReportsTest.PHRASES.getString("Reports.success"), "<LINK_0>", DURATION ) ) ) ); }
Source:
private boolean isVmRunningInDatabaseOnMonitoredHost() { if (vdsManager.getVdsId().equals(dbVm.getRunOnVds())) { return true; } logVmDetectedOnUnexpectedHost(); if (dbVm.getStatus().equals(VMStatus.MigratingFrom)) { auditVmMigrationAbort(); } return false; }

Target:
private boolean isVmRunningInDatabaseOnMonitoredHost() { if (vdsManager.getVdsId().equals(dbVm.getRunOnVds())) { return true; } logVmDetectedOnUnexpectedHost(); return false; }
Source:
protected PoolingDriver instance() throws OseeCoreException { try { Class.forName(CONNECTION_POOL_DRIVER); } catch (Exception ex) { throw new OseeDataStoreException(ex, "Error loading connectino pool driver [%s]", CONNECTION_POOL_DRIVER); } PoolingDriver driver; try { driver = (PoolingDriver) DriverManager.getDriver(CONNECTION_POOL_ID); } catch (SQLException ex) { throw new OseeDataStoreException(ex, "Error finding connection pool driver with id [%s]", CONNECTION_POOL_ID); } return driver; }

Target:
protected PoolingDriver instance() throws OseeCoreException { try { Class.forName(CONNECTION_POOL_DRIVER); } catch (Exception ex) { throw new OseeDataStoreException(ex, "Error loading connection pool driver [%s]", CONNECTION_POOL_DRIVER); } PoolingDriver driver; try { driver = (PoolingDriver) DriverManager.getDriver(CONNECTION_POOL_ID); } catch (SQLException ex) { throw new OseeDataStoreException(ex, "Error finding connection pool driver with id [%s]", CONNECTION_POOL_ID); } return driver; }
Source:
public void testGenerateInitAmazonS3WithOptionalQueryParams() throws IOException, ParseException, TemplateModelException { final Map<String,Object> testMap = new HashMap<>(); final Request testRequest = RequestConverter.toRequest(new Ds3Request( "com.spectralogic.s3.server.handler.reqhandler.amazons3.CreateObjectRequestHandler", HttpVerb.PUT, Classification.amazons3, Requirement.REQUIRED, Requirement.REQUIRED, null, null, null, null, false, null, ImmutableList.of( new Ds3Param("Job", "java.util.UUID", true), new Ds3Param("Offset", "long", false)), ImmutableList.of()), new Ds3DocSpecImpl( ImmutableMap.of(), ImmutableMap.of())); testMap.put("requestEntry", testRequest); final CCodeGenerator codeGenerator = new CCodeGenerator(); final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); codeGenerator.processTemplate(testMap, "request-templates/InitRequest.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "ds3_request* ds3_init_create_object(const char* bucket_name, const char* object_name, const uint64_t length) {" + "\n" + " struct _ds3_request* request = _common_request_init(HTTP_PUT, _build_path(\"/\", bucket_name, object_name));" + "\n" + " request->length = length;" + "\n" + "\n" + " return (ds3_request*) request;" + "\n" + "}\n"; assertEquals(expectedOutput, output); }

Target:
public void testGenerateInitAmazonS3WithOptionalQueryParams() throws IOException, ParseException, TemplateModelException { final Map<String,Object> testMap = new HashMap<>(); final Request testRequest = RequestConverter.toRequest(new Ds3Request( "com.spectralogic.s3.server.handler.reqhandler.amazons3.CreateObjectRequestHandler", HttpVerb.PUT, Classification.amazons3, Requirement.REQUIRED, Requirement.REQUIRED, null, null, null, null, false, null, ImmutableList.of( new Ds3Param("Job", "java.util.UUID", true), new Ds3Param("Offset", "long", false)), ImmutableList.of()), new Ds3DocSpecEmptyImpl()); testMap.put("requestEntry", testRequest); final CCodeGenerator codeGenerator = new CCodeGenerator(); final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); codeGenerator.processTemplate(testMap, "request-templates/InitRequest.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "ds3_request* ds3_init_create_object(const char* bucket_name, const char* object_name, const uint64_t length) {" + "\n" + " struct _ds3_request* request = _common_request_init(HTTP_PUT, _build_path(\"/\", bucket_name, object_name));" + "\n" + " request->length = length;" + "\n" + "\n" + " return (ds3_request*) request;" + "\n" + "}\n"; assertEquals(expectedOutput, output); }
Source:
public void handleEvent(IResumedDMEvent event) { VisualizerModel model = fVisualizer.getModel(); if (model == null) { return; } IDMContext context = event.getDMContext(); if (context != null && isSessionAllStop(context.getSessionId()) ) { List<VisualizerThread> tList = model.getThreads(); for(VisualizerThread t : tList) { t.setState(VisualizerExecutionState.RUNNING); t.setLocationInfo((String) null); } fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); return; } if (context instanceof IContainerDMContext) { } else if (context instanceof IMIExecutionDMContext) { int tid; VisualizerThread thread = null; try { tid = Integer.parseInt(((IMIExecutionDMContext) context).getThreadId()); thread = model.getThread(tid); } catch (NumberFormatException e) { return; } if (thread != null) { assert thread.getState() == VisualizerExecutionState.SUSPENDED || thread.getState() == VisualizerExecutionState.CRASHED; thread.setState(VisualizerExecutionState.RUNNING); thread.setLocationInfo((String) null); fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); } } }

Target:
public void handleEvent(IResumedDMEvent event) { VisualizerModel model = fVisualizer.getModel(); if (model == null) { return; } IDMContext context = event.getDMContext(); if (context != null && isSessionAllStop(context.getSessionId()) ) { List<VisualizerThread> tList = model.getThreads(); for(VisualizerThread t : tList) { t.setState(VisualizerExecutionState.RUNNING); t.setLocationInfo((String) null); } fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); return; } if (context instanceof IContainerDMContext) { } else if (context instanceof IMIExecutionDMContext) { int tid; VisualizerThread thread = null; String strThreadId = ((IMIExecutionDMContext) context).getThreadId(); try { tid = Integer.parseInt(strThreadId); thread = model.getThread(tid); } catch (NumberFormatException e) { assert false : THE_THREAD_ID_DOES_NOT_CONVERT_TO_AN_INTEGER + strThreadId; return; } if (thread != null) { assert thread.getState() == VisualizerExecutionState.SUSPENDED || thread.getState() == VisualizerExecutionState.CRASHED; thread.setState(VisualizerExecutionState.RUNNING); thread.setLocationInfo((String) null); fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); } } }
Source:
public static String urlConstructor(String... urlChunks) { String url = canvasURL + CANVAS_API_VERSION; for (String chunk : urlChunks) { url += chunk; } return url; }

Target:
public static String urlConstructor(String... urlChunks) { StringBuffer url =new StringBuffer(); url.append(canvasURL); url.append(CANVAS_API_VERSION); for (String chunk : urlChunks) { url.append(chunk); } return url.toString(); }
Source:
public void multipleTags() throws Exception { if (!getVersion(dockerClient).isGreaterOrEqual(RemoteApiVersion.VERSION_1_21)) { throw new SkipException("API version should be >= 1.21"); } File baseDir = fileFromBuildTestResource("labels"); String imageId = dockerClient.buildImageCmd(baseDir).withNoCache(true) .withTag("docker-java-test:tag1").withTag("docker-java-test:tag2") .exec(new BuildImageResultCallback()) .awaitImageId(); InspectImageResponse inspectImageResponse = dockerClient.inspectImageCmd(imageId).exec(); assertThat(inspectImageResponse, not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); assertThat(inspectImageResponse.getRepoTags().size(), equalTo(2)); assertThat(inspectImageResponse.getRepoTags().contains("docker-java-test:tag1"), equalTo(true)); assertThat(inspectImageResponse.getRepoTags().contains("docker-java-test:tag2"), equalTo(true)); }

Target:
public void multipleTags() throws Exception { if (!getVersion(dockerClient).isGreaterOrEqual(RemoteApiVersion.VERSION_1_21)) { throw new SkipException("API version should be >= 1.21"); } File baseDir = fileFromBuildTestResource("labels"); String imageId = dockerClient.buildImageCmd(baseDir).withNoCache(true) .withTag("fallback-when-withTags-not-called") .withTags(new HashSet<>(Arrays.asList("docker-java-test:tag1", "docker-java-test:tag2"))) .exec(new BuildImageResultCallback()) .awaitImageId(); InspectImageResponse inspectImageResponse = dockerClient.inspectImageCmd(imageId).exec(); assertThat(inspectImageResponse, not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); assertThat(inspectImageResponse.getRepoTags().size(), equalTo(2)); assertThat(inspectImageResponse.getRepoTags(), containsInAnyOrder("docker-java-test:tag1", "docker-java-test:tag2")); }
Source:
public void start() { if (!ctx.game.loggedIn()){ ctx.controller.stop(); return; } System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); }

Target:
public void start() { System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); }
Source:
private static boolean isMatch(Method method, List<Object> args, Class<?>[] paramClasses, String lookupMethodName) { if (!method.getName().equals(lookupMethodName)) { return false; } Class<?> types[] = method.getParameterTypes(); if (types.length != args.size()) { return false; } for (int i = 0; i < types.length; i++) { Class<?> type = types[i]; Object arg = args.get(i); if (paramClasses != null && type != paramClasses[i]) { return false; } if (arg == null) { if (type.isPrimitive()) { throw new NullPointerException(String.format("The type of No.%d parameter is primitive(%s), " + "but the value passed is null.", i + 1, type.getName())); } continue; } if (ReflectUtils.isPrimitive(arg.getClass())) { if (arg instanceof String && type.isEnum()) { continue; } if (!ReflectUtils.isPrimitive(type)) { return false; } if (!ReflectUtils.isCompatible(type, arg)) { return false; } } else if (arg instanceof JSONObject) { try { ((JSONObject) arg).toJavaObject(type); } catch (Exception ex) { return false; } } else if (arg instanceof Collection) { if (!type.isArray() && !type.isAssignableFrom(arg.getClass())) { return false; } } else { if (!type.isAssignableFrom(arg.getClass())) { return false; } } } return true; }

Target:
private static boolean isMatch(Method method, List<Object> args, Class<?>[] paramClasses, String lookupMethodName) { if (!method.getName().equals(lookupMethodName)) { return false; } Class<?> types[] = method.getParameterTypes(); if (types.length != args.size()) { return false; } for (int i = 0; i < types.length; i++) { Class<?> type = types[i]; Object arg = args.get(i); if (paramClasses != null && type != paramClasses[i]) { return false; } if (arg == null) { if (type.isPrimitive()) { throw new NullPointerException(String.format("The type of No.%d parameter is primitive(%s), " + "but the value passed is null.", i + 1, type.getName())); } continue; } if (ReflectUtils.isPrimitive(arg.getClass())) { if (arg instanceof String && type.isEnum()) { continue; } if (!ReflectUtils.isPrimitive(type)) { return false; } if (!ReflectUtils.isCompatible(type, arg)) { return false; } } else if (arg instanceof Map) { String name = (String) ((Map<?, ?>) arg).get("class"); if (StringUtils.isNotEmpty(name)) { Class<?> cls = ReflectUtils.forName(name); if (!type.isAssignableFrom(cls)) { return false; } } else { if (arg instanceof JSONObject) { try { ((JSONObject) arg).toJavaObject(type); } catch (Exception ex) { return false; } } } } else if (arg instanceof Collection) { if (!type.isArray() && !type.isAssignableFrom(arg.getClass())) { return false; } } else { if (!type.isAssignableFrom(arg.getClass())) { return false; } } } return true; }
Source:
public String apply(@Nullable Object value) { if (Objects.isNull(value)) { return null; } if (asMillis && value instanceof String) { final Long theLong = GuavaUtils.tryParseLong((String) value); return theLong == null ? apply(new DateTime(value).getMillis()) : apply(theLong.longValue()); } else { return apply(new DateTime(value).getMillis()); } }

Target:
public String apply(@Nullable Object value) { if (value == null) { return null; } if (asMillis && value instanceof String) { final Long theLong = GuavaUtils.tryParseLong((String) value); return theLong == null ? apply(new DateTime(value).getMillis()) : apply(theLong.longValue()); } else { return apply(new DateTime(value).getMillis()); } }
Source:
void entityClass() { boundedContext.register(ProjectAggregate.class); }

Target:
void entityClass() { boundedContext.register(ProjectAggregate.class); assertRegisteredRepositoryOf(ProjectAggregate.class); }
Source:
public void testAccept() throws Exception { RejectionPolicy rejectionPolicy = new ServerTimeRejectionPolicyFactory().create( new Period("PT10M") ); Assert.assertTrue(rejectionPolicy.accept(new DateTime().getMillis())); Assert.assertFalse(rejectionPolicy.accept(new DateTime("2000").getMillis())); }

Target:
public void testAccept() throws Exception { Period period = new Period("PT10M"); RejectionPolicy rejectionPolicy = new ServerTimeRejectionPolicyFactory().create(period); DateTime now = new DateTime(); DateTime past = now.minus(period).minus(1); Assert.assertTrue(rejectionPolicy.accept(now.getMillis())); Assert.assertFalse(rejectionPolicy.accept(past.getMillis())); }
Source:
protected void wpLogin() { logoutIfNecessary(); new LoginFlow().loginSiteAddress( E2E_WP_COM_USER_SITE_ADDRESS, E2E_WP_COM_USER_USERNAME, E2E_WP_COM_USER_PASSWORD); }

Target:
protected void wpLogin() { logoutIfNecessary(); new LoginFlow().loginEmailPassword(); }
Source:
private void copyVmPermissions() { if (getVmId() == null || !getParameters().isCopyVmPermissions()) { return; } PermissionDAO dao = getDbFacade().getPermissionDao(); List<permissions> vmPermissions = dao.getAllForEntity(getVmId(), getCurrentUser().getUserId(), false); List<permissions> templatePermissions = new ArrayList<permissions>(); for (permissions vmPermission : vmPermissions) { templatePermissions.add(new permissions(getCurrentUser().getUserId(), vmPermission.getrole_id(), getParameters().getVmTemplateId(), VdcObjectType.VmTemplate)); } if (templatePermissions.size() > 0) { MultiLevelAdministrationHandler.addPermission(templatePermissions.toArray(new permissions[templatePermissions.size()])); } }

Target:
private void copyVmPermissions() { if (isVmInDb || !getParameters().isCopyVmPermissions()) { return; } PermissionDAO dao = getDbFacade().getPermissionDao(); List<permissions> vmPermissions = dao.getAllForEntity(getVmId(), getCurrentUser().getUserId(), false); List<permissions> templatePermissions = new ArrayList<permissions>(); for (permissions vmPermission : vmPermissions) { templatePermissions.add(new permissions(getCurrentUser().getUserId(), vmPermission.getrole_id(), getParameters().getVmTemplateId(), VdcObjectType.VmTemplate)); } if (templatePermissions.size() > 0) { MultiLevelAdministrationHandler.addPermission(templatePermissions.toArray(new permissions[templatePermissions.size()])); } }
Source:
private String getDefaultPrimitiveValue(TypeName type) { String valueString = null; try { Class<?> primitiveClass = Primitives.unwrap(Class.forName(type.box().toString())); if(primitiveClass != null) { Object defaultValue = Defaults.defaultValue(primitiveClass); if(defaultValue != null) { valueString = defaultValue.toString(); if (!Strings.isNullOrEmpty(valueString)) { switch (type.toString()) { case "double": valueString = valueString + "d"; break; case "float": valueString = valueString + "f"; break; case "long": valueString = valueString + "L"; } } } } } catch (Exception e) { } return valueString; }

Target:
private String getDefaultPrimitiveValue(TypeName type) { String valueString = null; try { Class<?> primitiveClass = Primitives.unwrap(Class.forName(type.box().toString())); if (primitiveClass != null) { Object defaultValue = Defaults.defaultValue(primitiveClass); if (defaultValue != null) { valueString = defaultValue.toString(); if (!Strings.isNullOrEmpty(valueString)) { switch (type.toString()) { case "double": valueString = valueString + "d"; break; case "float": valueString = valueString + "f"; break; case "long": valueString = valueString + "L"; break; } } } } } catch (ClassNotFoundException ignored) { } return valueString; }