auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean hasFinishedBuild(String id) throws RestServiceException { ClientResponse response = null; try { LOGGER.info("Calling getById VCPENetworkManager service"); String url = getURL("vcpenetwork/hasFinishedBuild/" + id); Client client = Client.create(); WebResource webResource = client.resource(url); response = webResource.accept(MediaType.APPLICATION_XML).get(ClientResponse.class); LOGGER.info("VCPENetwork recovered"); } catch (ClientHandlerException e) { LOGGER.error(e.getMessage()); throw e; } String result; result = (checkResponse(response) ? response.getEntity(String.class) : null); return Boolean.parseBoolean(result); }

Target:
public boolean hasFinishedBuild(String id) throws RestServiceException { String result; ClientResponse response = null; try { LOGGER.info("Calling getById VCPENetworkManager service"); String url = getURL("vcpenetwork/hasFinishedBuild/" + id); Client client = Client.create(); WebResource webResource = client.resource(url); response = webResource.accept(MediaType.APPLICATION_XML).get(ClientResponse.class); LOGGER.info("VCPENetwork recovered"); } catch (ClientHandlerException e) { LOGGER.error(e.getMessage()); throw e; } result = (checkResponse(response) ? response.getEntity(String.class) : null); return Boolean.parseBoolean(result); }
Source:
Telemetry(final String tags, final StatsDProcessor processor) { this.tags = tags; this.tags = tags; this.processor = processor; this.timer = null; }

Target:
Telemetry(final String tags, final StatsDProcessor processor) { this.tags = tags; this.processor = processor; this.timer = null; }
Source:
public static Collection<Object[]> data() { Object[][] data = new Object[][] { { "endpoint-7.2.xml", 16, "schema/jboss-infinispan-endpoint_7_2.xsd" }, { "endpoint-8.0.xml", 16, "schema/jboss-infinispan-endpoint_8_0.xsd" }, { "endpoint-9.0.xml", 38, null }, }; return Arrays.asList(data); }

Target:
public static Collection<Object[]> data() { Object[][] data = new Object[][] { { "endpoint-7.2.xml", 16, "schema/jboss-infinispan-endpoint_7_2.xsd" }, { "endpoint-8.0.xml", 16, "schema/jboss-infinispan-endpoint_8_0.xsd" }, { "endpoint-9.0.xml", 38, "schema/jboss-infinispan-endpoint_9_0.xsd" }, }; return Arrays.asList(data); }
Source:
public boolean labels( String[] labels ) { checkClear(); for ( String label : labels ) { this.labels.add( label ); } return delegate.labels( labels ); }

Target:
public boolean labels( String[] labels ) { checkClear(); Collections.addAll( this.labels, labels ); return delegate.labels( labels ); }
Source:
public OptimizerAssert on(Function<PlanBuilder, PlanNode> planProvider) { checkArgument(plan == null, "plan has already been set"); PlanBuilder builder = new PlanBuilder(idAllocator, metadata); plan = planProvider.apply(builder); types = builder.getTypes(); return this; }

Target:
public OptimizerAssert on(Function<PlanBuilder, PlanNode> planProvider) { checkState(plan == null, "plan has already been set"); PlanBuilder builder = new PlanBuilder(idAllocator, metadata); plan = planProvider.apply(builder); types = builder.getTypes(); return this; }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { M_log.debug("doFilter: Called"); HttpServletRequest useRequest = (HttpServletRequest) request; HttpServletResponse useResponse=(HttpServletResponse)response; if ( BASIC_LTI_LAUNCH_REQUEST.equals(request.getParameter(LTI_MESSAGE_TYPE))) { M_log.debug("new launch so invalidate any existing session"); if (useRequest.getSession() != null) { M_log.debug("session id to invalidate: " + useRequest.getSession().getId()); useRequest.getSession().invalidate(); } } HttpSession session= useRequest.getSession(true); M_log.debug("session id: "+session.getId()); if(!checkForAuthorization(useRequest)) { useResponse.sendError(403); return; } chain.doFilter(useRequest, response); }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { M_log.debug("doFilter: Called"); HttpServletRequest useRequest = (HttpServletRequest) request; HttpServletResponse useResponse=(HttpServletResponse)response; if ( BASIC_LTI_LAUNCH_REQUEST.equals(request.getParameter(LTI_MESSAGE_TYPE))) { M_log.debug("new launch so invalidate any existing session"); if (useRequest.getSession() != null) { M_log.info("session id to invalidate: " + useRequest.getSession().getId()); useRequest.getSession().invalidate(); } } HttpSession session= useRequest.getSession(true); M_log.debug("session id: "+session.getId()); if(!checkForAuthorization(useRequest)) { useResponse.sendError(403); return; } chain.doFilter(useRequest, response); }
Source:
public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { URI redirectUri; try { redirectUri = new URI(String.format("http://localhost:%s", port)); } catch (URISyntaxException e) { return Mono.error(logger.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters parameters = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .build(); Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parameters))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); }

Target:
public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { URI redirectUri; try { redirectUri = new URI(HTTP_LOCALHOST + ":" + port); } catch (URISyntaxException e) { return Mono.error(logger.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters parameters = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .build(); Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parameters))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.content_tours, null); ButterKnife.inject(this, view); mitapiClient = new MITAPIClient(getActivity().getApplicationContext()); mitapiClient.get(Constants.TOURS, Constants.Tours.TOUR_PATH, null, null, new Callback<List<MITTourWrapper>>() { @Override public void success(List<MITTourWrapper> mitTourWrappers, Response response) { MITTourWrapper mitTourWrapper = mitTourWrappers.get(0); setTourInfoView(mitTourWrapper); } @Override public void failure(RetrofitError error) { } }); selfGuidedTourView.setBackground(getResources().getDrawable(R.drawable.tours_cover_image)); moreGuidedToursTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openWebsiteDialog(); } }); sendFeedbackView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendFeedback(); } }); mitInfoCenterView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openOutsideWebsite(getResources().getString(R.string.mit_about_guided_tour_url)); } }); mitAdmissionsView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openOutsideWebsite(getResources().getString(R.string.mit_admissions_url)); } }); return view; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.content_tours, null); ButterKnife.inject(this, view); mitApiClient = new MITAPIClient(getActivity().getApplicationContext()); mitApiClient.get(Constants.TOURS, Constants.Tours.TOUR_PATH, null, null, new Callback<List<MITTourWrapper>>() { @Override public void success(List<MITTourWrapper> mitTourWrappers, Response response) { MITTourWrapper mitTourWrapper = mitTourWrappers.get(0); setTourInfoView(mitTourWrapper); } @Override public void failure(RetrofitError error) { } }); selfGuidedTourView.setBackground(getResources().getDrawable(R.drawable.tours_cover_image)); return view; }
Source:
protected void decorateRequired() { if (decoration == null) { decoration = new ControlDecoration(getLabelControl(), SWT.TOP | SWT.RIGHT); decoration.setDescriptionText(Messages.AbstractAttributeEditor_AttributeIsRequired); decoration.setMarginWidth(0); Image image = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR) .getImage(); decoration.setImage(image); getLabelControl().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (decoration != null) { decoration.dispose(); decoration = null; } } }); } }

Target:
protected void decorateRequired() { if (decoration == null) { decoration = new ControlDecoration(getLabelControl(), SWT.TOP | SWT.RIGHT); decoration.setDescriptionText(Messages.AbstractAttributeEditor_AttributeIsRequired); decoration.setMarginWidth(0); Image image = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR) .getImage(); decoration.setImage(image); getLabelControl().addDisposeListener(disposeDecorationListener); } }
Source:
public SelectIterator(final Iterator<E> itr, final Condition<E> cond) { this.condition = cond; this.iterator = itr; if (this.iterator.hasNext()) { this.current.add(this.iterator.next()); } }

Target:
public SelectIterator(final Iterator<E> itr, final Condition<E> cond) { this.condition = cond; this.iterator = itr; }
Source:
public GrammarAST(int type, Token t, String text) { this(new CommonToken(type, text)); if ( t instanceof CommonToken ) { ((CommonToken) token).setStartIndex(((CommonToken) t).getStartIndex()); ((CommonToken) token).setStopIndex(((CommonToken) t).getStopIndex()); } token.setInputStream(t.getInputStream()); token.setLine(t.getLine()); token.setCharPositionInLine(t.getCharPositionInLine()); token.setTokenIndex(t.getTokenIndex()); }

Target:
public GrammarAST(int type, Token t, String text) { this(new CommonToken(t)); token.setType(type); token.setText(text); }
Source:
public int filter(Page page, int[] positions, int positionCount, RuntimeException[] errors) { checkArgument(positionCount <= positions.length); checkArgument(positionCount <= errors.length); if (inputChannels.length == 1 && page.getBlock(0) instanceof DictionaryBlock && deterministic) { return filterWithDictionary(page, positions, positionCount, errors); } int outputCount = 0; for (int i = 0; i < positionCount; i++) { int position = positions[i]; try { if (predicate.evaluate(session, page, position)) { positions[outputCount] = position; errors[outputCount] = errors[i]; outputCount++; } } catch (RuntimeException e) { positions[outputCount] = position; errors[outputCount] = e; outputCount++; } } return outputCount; }

Target:
public int filter(Page page, int[] positions, int positionCount, RuntimeException[] errors) { checkArgument(positionCount <= positions.length); checkArgument(positionCount <= errors.length); if (deterministic && inputChannels.length == 1 && page.getBlock(0) instanceof DictionaryBlock) { return filterWithDictionary(page, positions, positionCount, errors); } int outputCount = 0; for (int i = 0; i < positionCount; i++) { int position = positions[i]; try { if (predicate.evaluate(session, page, position)) { positions[outputCount] = position; errors[outputCount] = errors[i]; outputCount++; } } catch (RuntimeException e) { positions[outputCount] = position; errors[outputCount] = e; outputCount++; } } return outputCount; }
Source:
public void testCreateViewFromNonExistentTable() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute( "CREATE TABLE IF NOT EXISTS S.T1 (A INTEGER PRIMARY KEY, B INTEGER)"); try { conn.createStatement().execute( "CREATE VIEW IF NOT EXISTS V1(C INTEGER) AS SELECT * FROM T2"); } catch (TableNotFoundException e) { assertEquals("T2", e.getTableName()); assertEquals("", e.getSchemaName()); assertEquals("ERROR 1012 (42M03): Table undefined. tableName=T2", e.getMessage()); } conn.createStatement().execute( "CREATE VIEW IF NOT EXISTS V1(C INTEGER) AS SELECT * FROM S.T1"); try { conn.createStatement().execute( "CREATE VIEW IF NOT EXISTS V2(C INTEGER) AS SELECT * FROM S.T2"); } catch (TableNotFoundException e) { assertEquals("T2", e.getTableName()); assertEquals("S", e.getSchemaName()); assertEquals("ERROR 1012 (42M03): Table undefined. tableName=S.T2", e.getMessage()); } } }

Target:
public void testCreateViewFromNonExistentTable() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute( "CREATE TABLE IF NOT EXISTS S.T1 (A INTEGER PRIMARY KEY, B INTEGER)"); try { conn.createStatement().execute( "CREATE VIEW IF NOT EXISTS V1(C INTEGER) AS SELECT * FROM T2"); fail("Creating view on non-existent table should have failed"); } catch (TableNotFoundException e) { assertEquals("T2", e.getTableName()); assertEquals("", e.getSchemaName()); assertEquals("ERROR 1012 (42M03): Table undefined. tableName=T2", e.getMessage()); } conn.createStatement().execute( "CREATE VIEW IF NOT EXISTS V1(C INTEGER) AS SELECT * FROM S.T1"); try { conn.createStatement().execute( "CREATE VIEW IF NOT EXISTS V2(C INTEGER) AS SELECT * FROM S.T2"); fail("Creating view on non-existent table should have failed"); } catch (TableNotFoundException e) { assertEquals("T2", e.getTableName()); assertEquals("S", e.getSchemaName()); assertEquals("ERROR 1012 (42M03): Table undefined. tableName=S.T2", e.getMessage()); } } }
Source:
public void testFillArrayANDNOT() { LongBuffer data1 = LongBuffer.wrap(new long[]{1, 2, 4, 8, 16}); LongBuffer data2 = LongBuffer.wrap(new long[]{2, 1, 3, 7, 15}); LongBuffer data3 = LongBuffer.wrap(new long[]{2, 1, 3, 7}); short[] content = new short[5]; short[] content2 = new short[5]; short[] result = {0, 65, 130, 195, 260}; BufferUtil.fillArrayANDNOT(content, data1, data2); Assert.assertTrue(Arrays.equals(content, result)); BufferUtil.fillArrayANDNOT(content2, data1, data3); }

Target:
public void testFillArrayANDNOT() { LongBuffer data1 = LongBuffer.wrap(new long[]{1, 2, 4, 8, 16}); LongBuffer data2 = LongBuffer.wrap(new long[]{2, 1, 3, 7, 15}); short[] content = new short[5]; short[] result = {0, 65, 130, 195, 260}; BufferUtil.fillArrayANDNOT(content, data1, data2); Assert.assertTrue(Arrays.equals(content, result)); }
Source:
public static BlockVector2 at(int x, int z) { return new BlockVector2(x, z); }

Target:
public static BlockVector2 at(int x, int z) { switch (x) { case 0: if (z == 0) { return ZERO; } break; case 1: if (z == 1) { return ONE; } break; } return new BlockVector2(x, z); }
Source:
public static DnDTransferItem getTransferItem(@NonNull Transferable transferable, boolean allowPlaceholder) { DnDTransferItem item = null; try { if (transferable.isDataFlavorSupported(ItemTransferable.DESIGNER_FLAVOR)) { item = (DnDTransferItem)transferable.getTransferData(ItemTransferable.DESIGNER_FLAVOR); } else if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) { String xml = (String)transferable.getTransferData(DataFlavor.stringFlavor); if (!StringUtil.isEmpty(xml)) { item = new DnDTransferItem(new DnDTransferComponent("", xml, 200, 100)); } } } catch (InvalidDnDOperationException ex) { if (!allowPlaceholder) { return null; } String defaultXml = "<placeholder xmlns:android=\"<LINK_1>\"/>"; item = new DnDTransferItem(new DnDTransferComponent("", defaultXml, 200, 100)); } catch (IOException ex) { } catch (UnsupportedFlavorException ex) { } return item; }

Target:
public static DnDTransferItem getTransferItem(@NonNull Transferable transferable, boolean allowPlaceholder) { DnDTransferItem item = null; try { if (transferable.isDataFlavorSupported(ItemTransferable.DESIGNER_FLAVOR)) { item = (DnDTransferItem)transferable.getTransferData(ItemTransferable.DESIGNER_FLAVOR); } else if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) { String xml = (String)transferable.getTransferData(DataFlavor.stringFlavor); if (!StringUtil.isEmpty(xml)) { item = new DnDTransferItem(new DnDTransferComponent("", xml, 200, 100)); } } } catch (InvalidDnDOperationException ex) { if (!allowPlaceholder) { return null; } String defaultXml = "<placeholder xmlns:android=\"<LINK_1>\"/>"; item = new DnDTransferItem(new DnDTransferComponent("", defaultXml, 200, 100)); } catch (IOException ex) { LOG.warn(ex); } catch (UnsupportedFlavorException ex) { LOG.warn(ex); } return item; }
Source:
public Parser getParser() { return inputStream -> { String response = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining(OS.NEWLINE)); List<BibEntry> entries = new ArrayList<>(); Document doc = Jsoup.parse(response); List<Element> elements = doc.body().getElementsByClass("cite-this-item"); for (Element element : elements) { BibtexParser parser = new BibtexParser(importFormatPreferences, new DummyFileUpdateMonitor()); String id = element.attr("href").replace("citation/info/", ""); try { String data = IOUtils.toString(new URL(CITE_HOST + id), Charsets.UTF_8); entries.addAll(parser.parseEntries(data)); } catch (IOException e) { throw new ParseException("could not download data from jstor.org", e); } } return entries; }; }

Target:
public Parser getParser() { return inputStream -> { List<BibEntry> entries; try { Document doc = Jsoup.parse(inputStream, null, HOST); List<Element> elements = doc.body().getElementsByClass("cite-this-item"); StringBuilder stringBuilder = new StringBuilder(); for (Element element : elements) { String id = element.attr("href").replace("citation/info/", ""); String data = new URLDownload(CITE_HOST + id).asString(); stringBuilder.append(data); } BibtexParser parser = new BibtexParser(importFormatPreferences, new DummyFileUpdateMonitor()); entries = new ArrayList<>(parser.parseEntries(stringBuilder.toString())); } catch (IOException e) { throw new ParseException("Could not download data from jstor.org", e); } return entries; }; }
Source:
public WorkspaceCompilationInfo(Path prjPath, Properties bannedEnvVars) { this.prjPath = prjPath; }

Target:
public WorkspaceCompilationInfo(Path prjPath, Properties bannedEnvVars) { this.prjPath = prjPath; this.bannedEnvVars = bannedEnvVars; }
Source:
public void initialize(BatchRuntimeContext context) throws Exception { super.initialize(context); if (!Strings.isNullOrEmpty(config.drop)) { for (String dropField : Splitter.on(CopybookSourceConfig.fieldDelimiter).split(config.drop)) { fieldsToDrop.add(dropField); } } if (config.maxSplitSize == null) { config.maxSplitSize = DEFAULT_MAX_SPLIT_SIZE_IN_MB * CONVERT_TO_BYTES; } else { config.maxSplitSize = config.maxSplitSize * CONVERT_TO_BYTES; } outputSchema = getOutputSchema(); }

Target:
public void initialize(BatchRuntimeContext context) throws Exception { super.initialize(context); if (!Strings.isNullOrEmpty(config.drop)) { for (String dropField : Splitter.on(",").trimResults().split(config.drop)) { fieldsToDrop.add(dropField); } } if (config.maxSplitSize == null) { config.maxSplitSize = DEFAULT_MAX_SPLIT_SIZE_IN_MB * CONVERT_TO_BYTES; } else { config.maxSplitSize = config.maxSplitSize * CONVERT_TO_BYTES; } outputSchema = getOutputSchema(); }
Source:
private void scheduleRepairLogTruncateMsg() { SiteTaskerRunnable r = new SiteTaskerRunnable() { @Override void run() { synchronized (m_lock) { if (m_lastSentTruncationHandle < m_repairLogTruncationHandle) { m_lastSentTruncationHandle = m_repairLogTruncationHandle; m_repairLog.notifyTxnCommitInterests(m_lastSentTruncationHandle); if (m_sendToHSIds.length == 0) { return; } final RepairLogTruncationMessage truncMsg = new RepairLogTruncationMessage(m_repairLogTruncationHandle); m_mailbox.deliver(truncMsg); m_mailbox.send(m_sendToHSIds, truncMsg); } } } }; if (hostLog.isDebugEnabled()) { r.taskInfo = "Repair Log Truncate Message Handle:" + m_repairLogTruncationHandle; } m_tasks.offer(r); }

Target:
private void scheduleRepairLogTruncateMsg() { if (m_sendToHSIds.length == 0 && m_repairLog.hasNoTxnCommitInterests()) { return; } SiteTaskerRunnable r = new SiteTaskerRunnable() { @Override void run() { synchronized (m_lock) { if (m_lastSentTruncationHandle < m_repairLogTruncationHandle) { m_lastSentTruncationHandle = m_repairLogTruncationHandle; m_repairLog.notifyTxnCommitInterests(m_lastSentTruncationHandle); if (m_sendToHSIds.length == 0) { return; } final RepairLogTruncationMessage truncMsg = new RepairLogTruncationMessage(m_repairLogTruncationHandle); m_mailbox.deliver(truncMsg); m_mailbox.send(m_sendToHSIds, truncMsg); } } } }; if (hostLog.isDebugEnabled()) { r.taskInfo = "Repair Log Truncate Message Handle:" + m_repairLogTruncationHandle; } m_tasks.offer(r); }
Source:
public static TaskletType fromClassName(String className) { TaskletType type = UNKNOWN; if(className != null) { String name = className.trim(); for (TaskletType curType : values()) { if(curType.className.equals(name)) { type = curType; break; } } } return type; }

Target:
public static TaskletType fromClassName(String className) { TaskletType type = UNKNOWN; if(StringUtils.hasText(className)) { String name = className.trim(); for (TaskletType curType : values()) { if(curType.className.equals(name)) { type = curType; break; } } } return type; }
Source:
protected boolean isProcessed(ChronicleLogOffsetTracker tracker, long offset) { long last = tracker.readLastCommittedOffset(); return (last > 0) && (last >= offset); }

Target:
protected boolean isProcessed(ChronicleLogOffsetTracker tracker, long offset) { long last = tracker.readLastCommittedOffset(); return last > 0 && last >= offset; }
Source:
private boolean isFinalizeDeclaration(MethodTree tree) { return hasSemantic() && isMethodNamedFinalize(tree) && isOverriding(tree) && hasNoParameters(tree); }

Target:
private boolean isFinalizeDeclaration(MethodTree tree) { return hasSemantic() && isMethodNamedFinalize(tree) && hasNoParameters(tree); }
Source:
void initializeIndexGauges(String storeId, final PersistentIndex index, final long capacityInBytes) { String prefix = storeId + "."; Gauge<Long> currentCapacityUsed = index::getLogUsedCapacity; registry.register(MetricRegistry.name(Log.class, prefix + "CurrentCapacityUsed"), currentCapacityUsed); Gauge<Double> percentageUsedCapacity = () -> ((double) index.getLogUsedCapacity() / capacityInBytes) * 100; registry.register(MetricRegistry.name(Log.class, prefix + "PercentageUsedCapacity"), percentageUsedCapacity); Gauge<Long> currentSegmentCount = index::getLogSegmentCount; registry.register(MetricRegistry.name(Log.class, prefix + "CurrentSegmentCount"), currentSegmentCount); }

Target:
void initializeIndexGauges(String storeId, final PersistentIndex index, final long capacityInBytes) { String prefix = storeId + SEPERATOR; Gauge<Long> currentCapacityUsed = index::getLogUsedCapacity; registry.register(MetricRegistry.name(Log.class, prefix + "CurrentCapacityUsed"), currentCapacityUsed); Gauge<Double> percentageUsedCapacity = () -> ((double) index.getLogUsedCapacity() / capacityInBytes) * 100; registry.register(MetricRegistry.name(Log.class, prefix + "PercentageUsedCapacity"), percentageUsedCapacity); Gauge<Long> currentSegmentCount = index::getLogSegmentCount; registry.register(MetricRegistry.name(Log.class, prefix + "CurrentSegmentCount"), currentSegmentCount); }
Source:
private void addPutEntries(List<Long> offsets, long lastEntrySize, IndexSegment segment, NavigableMap<MockId, IndexValue> referenceIndex) throws StoreException { for (int i = 0; i < offsets.size(); i++) { MockId id; do { id = new MockId(UtilsTest.getRandomString(CUSTOM_ID_SIZE)); } while (referenceIndex.containsKey(id)); long offset = offsets.get(i); long size = i == offsets.size() - 1 ? lastEntrySize : offsets.get(i + 1) - offset; IndexValue value = IndexValueUtils.getIndexValue(size, new Offset(segment.getLogSegmentName(), offset), time.seconds(), version); segment.addEntry(new IndexEntry(id, value), new Offset(segment.getLogSegmentName(), offset + size)); if (resetKey == null) { resetKey = new Pair<StoreKey, PersistentIndex.IndexEntryType>(id, (value.isFlagSet(IndexValue.Flags.Delete_Index)) ? PersistentIndex.IndexEntryType.DELETE : PersistentIndex.IndexEntryType.PUT); } referenceIndex.put(id, value); } }

Target:
private List<IndexEntry> addPutEntries(List<Long> offsets, long lastEntrySize, IndexSegment segment, NavigableMap<MockId, IndexValue> referenceIndex) throws StoreException { List<IndexEntry> addedEntries = new ArrayList<>(); for (int i = 0; i < offsets.size(); i++) { MockId id; do { id = new MockId(UtilsTest.getRandomString(CUSTOM_ID_SIZE)); } while (referenceIndex.containsKey(id)); long offset = offsets.get(i); long size = i == offsets.size() - 1 ? lastEntrySize : offsets.get(i + 1) - offset; IndexValue value = IndexValueTest.getIndexValue(size, new Offset(segment.getLogSegmentName(), offset), time.milliseconds(), version); IndexEntry entry = new IndexEntry(id, value); segment.addEntry(entry, new Offset(segment.getLogSegmentName(), offset + size)); addedEntries.add(entry); referenceIndex.put(id, value); } return addedEntries; }
Source:
public synchronized boolean stopAndRemoveSupervisor(String id) { Preconditions.checkNotNull(id, "id"); return possiblyStopAndRemoveSupervisorInternal(id, true); }

Target:
public boolean stopAndRemoveSupervisor(String id) { Preconditions.checkState(started, "SupervisorManager not started"); Preconditions.checkNotNull(id, "id"); synchronized (lock) { Preconditions.checkState(started, "SupervisorManager not started"); return possiblyStopAndRemoveSupervisorInternal(id, true); } }
Source:
private GraphicsDevice getGraphicsDevOfType(GraphicsType type) { for (GraphicsDevice dev : getGraphicsDevices()) { if (dev.getGraphicsType() == type) { return dev; } } return null; }

Target:
private GraphicsDevice getGraphicsDevOfType(GraphicsType type) { return getGraphicsDevices().stream().filter(dev -> dev.getGraphicsType() == type).findFirst().orElse(null); }
Source:
public MethodOutcome createFHIRPatient(@ResourceParam Patient patient) { patient = patientResource.createFHIRPatient(patient); MethodOutcome retVal = new MethodOutcome(); retVal.setId(new IdDt(FHIRConstants.PATIENT, patient.getId().getIdPart())); OperationOutcome outcome = new OperationOutcome(); outcome.addIssue().setDetails("Patient is successfully created with " + patient.getId().getIdPart()); retVal.setOperationOutcome(outcome); return retVal; }

Target:
public MethodOutcome createFHIRPatient(@ResourceParam Patient patient) { patient = patientResource.createFHIRPatient(patient); MethodOutcome retVal = new MethodOutcome(); retVal.setId(new IdDt(FHIRConstants.PATIENT, patient.getId().getIdPart())); OperationOutcome outcome = new OperationOutcome(); outcome.addIssue().setDetails("Patient is successfully created with"); retVal.setOperationOutcome(outcome); return retVal; }
Source:
public int getSize() { int size = 0; DexReader reader = dexFile.readerAt(startOffset); reader.readLargeUleb128(); reader.readSmallUleb128(); size += reader.getOffset() - startOffset; Set<? extends DexBackedAnnotation> annotations = getAnnotations(); if (!annotations.isEmpty()){ size += 2 * 4; size += 4; for (DexBackedAnnotation dexBackedAnnotation : annotations) { size += 4; } } if (initialValueOffset > 0){ reader.setOffset(initialValueOffset); if (initialValue != null) { DexBackedEncodedValue.skipFrom(reader); size += reader.getOffset() - initialValueOffset; } } DexBackedFieldReference fieldRef = new DexBackedFieldReference(dexFile, fieldIndex); size += fieldRef.getSize(); return size; }

Target:
public int getSize() { int size = 0; DexReader reader = dexFile.readerAt(startOffset); reader.readLargeUleb128(); reader.readSmallUleb128(); size += reader.getOffset() - startOffset; Set<? extends DexBackedAnnotation> annotations = getAnnotations(); if (!annotations.isEmpty()) { size += 2 * 4; } if (initialValueOffset > 0) { reader.setOffset(initialValueOffset); if (initialValue != null) { DexBackedEncodedValue.skipFrom(reader); size += reader.getOffset() - initialValueOffset; } } DexBackedFieldReference fieldRef = new DexBackedFieldReference(dexFile, fieldIndex); size += fieldRef.getSize(); return size; }
Source:
public boolean removeVertex(final V v) { final Map<V, I> edges = adjacent.remove(v); if (edges != null) { inDegrees.remove(v); for (final Map.Entry<V, I> edge : edges.entrySet()) { final V neighbor = edge.getKey(); final int inDegree = inDegrees.get(neighbor) - 1; inDegrees.put(neighbor, inDegree); if (inDegree == 0) { rootVertices.add(neighbor); } } rootVertices.remove(v); for (Map.Entry<V, ConcurrentMap<V, I>> entry : adjacent.entrySet()) { entry.getValue().remove(v); } return true; } else { LOG.log(Level.WARNING, "The vertex {0} does exists", new Object[]{v}); return false; } }

Target:
public boolean removeVertex(final V v) { final Map<V, I> edges = adjacent.remove(v); if (edges != null) { numVertices -= 1; final int inDegreeEdges = inDegrees.remove(v); numEdges -= inDegreeEdges; numEdges -= edges.size(); for (final Map.Entry<V, I> edge : edges.entrySet()) { final V neighbor = edge.getKey(); final int inDegree = inDegrees.get(neighbor) - 1; inDegrees.put(neighbor, inDegree); } for (Map.Entry<V, Map<V, I>> entry : adjacent.entrySet()) { entry.getValue().remove(v); } return true; } else { LOG.log(Level.WARNING, "The vertex {0} does exists", new Object[]{v}); return false; } }
Source:
protected void doStart() throws Exception { super.doStart(); if (this.taskExecutor == null) { this.taskExecutor = new SimpleAsyncTaskExecutor( (getBeanName() == null ? "container" : getBeanName()) + "-"); } Long idleEventInterval = getIdleEventInterval(); if (idleEventInterval != null) { if (this.taskScheduler != null) { afterPropertiesSet(); } this.idleTask = this.taskScheduler.scheduleAtFixedRate(() -> { long now = System.currentTimeMillis(); if (now - getLastReceive() > idleEventInterval && now - this.lastAlertAt > idleEventInterval) { publishIdleContainerEvent(now - getLastReceive()); this.lastAlertAt = now; } }, this.getIdleEventInterval() / 2); } AtomicBoolean initialized = new AtomicBoolean(); this.taskExecutor.execute(() -> { synchronized (this.consumersMonitor) { while (!initialized.get() && isRunning()) { this.cancellationLock.reset(); try { for (String queue : getQueueNames()) { consumeFromQueue(queue); } } catch (Exception e) { this.logger.error("Error creating consumer; retrying in " + DirectMessageListenerContainer.this.recoveryInterval, e); doShutdown(); try { Thread.sleep(DirectMessageListenerContainer.this.recoveryInterval); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } continue; } initialized.set(true); } } }); if (logger.isInfoEnabled()) { this.logger.info("Container initialized for queues: " + Arrays.asList(getQueueNames())); } }

Target:
protected void doStart() throws Exception { super.doStart(); if (this.taskExecutor == null) { this.taskExecutor = new SimpleAsyncTaskExecutor( (getBeanName() == null ? "container" : getBeanName()) + "-"); } long idleEventInterval = getIdleEventInterval(); if (idleEventInterval > 0) { if (this.taskScheduler != null) { afterPropertiesSet(); } this.idleTask = this.taskScheduler.scheduleAtFixedRate(() -> { long now = System.currentTimeMillis(); if (now - getLastReceive() > idleEventInterval && now - this.lastAlertAt > idleEventInterval) { publishIdleContainerEvent(now - getLastReceive()); this.lastAlertAt = now; } }, idleEventInterval / 2); } AtomicBoolean initialized = new AtomicBoolean(); this.taskExecutor.execute(() -> { synchronized (this.consumersMonitor) { while (!initialized.get() && isRunning()) { this.cancellationLock.reset(); try { for (String queue : getQueueNames()) { consumeFromQueue(queue); } } catch (Exception e) { this.logger.error("Error creating consumer; retrying in " + DirectMessageListenerContainer.this.recoveryInterval, e); doShutdown(); try { Thread.sleep(DirectMessageListenerContainer.this.recoveryInterval); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } continue; } initialized.set(true); } } }); if (logger.isInfoEnabled()) { this.logger.info("Container initialized for queues: " + Arrays.asList(getQueueNames())); } }
Source:
private void writeVmCustomMetadata() { writer.writeStartElement(OVIRT_VM_URI, "custom"); Map<String, String> vmCutomProperties = VmPropertiesUtils.getInstance().getVMProperties( vm.getCompatibilityVersion(), vm.getStaticData()); vmCutomProperties.entrySet().forEach( property -> writer.writeElement(OVIRT_VM_URI, property.getKey(), property.getValue())); writer.writeEndElement(); }

Target:
private void writeVmCustomMetadata() { writer.writeStartElement(OVIRT_VM_URI, "custom"); Map<String, String> vmCustomProperties = VmPropertiesUtils.getInstance().getVMProperties( vm.getCompatibilityVersion(), vm.getStaticData()); vmCustomProperties.entrySet().forEach( property -> writer.writeElement(OVIRT_VM_URI, property.getKey(), property.getValue())); writer.writeEndElement(); }
Source:
public void forceLedger(final BookieSocketAddress addr, final long ledgerId, final ForceLedgerCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.forceLedgerComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, addr, null); return; } client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, safeRun(() -> { cb.forceLedgerComplete(rc, ledgerId, addr, ctx); })); } catch (RejectedExecutionException re) { cb.forceLedgerComplete(getRc(BKException.Code.InterruptedException), ledgerId, addr, ctx); } } else { pcbc.forceLedger(ledgerId, cb, ctx); } }, ledgerId); }

Target:
public void forceLedger(final BookieSocketAddress addr, final long ledgerId, final ForceLedgerCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.forceLedgerComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, addr, ctx); return; } client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, safeRun(() -> { cb.forceLedgerComplete(rc, ledgerId, addr, ctx); })); } catch (RejectedExecutionException re) { cb.forceLedgerComplete(getRc(BKException.Code.InterruptedException), ledgerId, addr, ctx); } } else { pcbc.forceLedger(ledgerId, cb, ctx); } }, ledgerId); }
Source:
public static void setUpClass() throws Exception { repository = new TestRepository(); repository.create( HistoryGuru.class.getResourceAsStream("repositories.zip")); RuntimeEnvironment env = RuntimeEnvironment.getInstance(); env.setHistoryEnabled(true); env.setRepositories(repository.getSourceRoot()); }

Target:
public static void setUpClass() throws Exception { repository = new TestRepository(); repository.create( HistoryGuru.class.getResourceAsStream("repositories.zip")); RuntimeEnvironment env = RuntimeEnvironment.getInstance(); env.setRepositories(repository.getSourceRoot()); env.setHistoryEnabled(true); }
Source:
public void setUp() throws Exception { storeEntity(EntityType.CLUSTER, "corp", CLUSTER_XML); storeEntity(EntityType.FEED, "clicks", FEED_XML); storeEntity(EntityType.FEED, "impressions", FEED_XML); storeEntity(EntityType.FEED, "clicksummary", FEED_XML); storeEntity(EntityType.PROCESS, "clicksummary", PROCESS_XML); storeEntity(EntityType.PROCESS, "pig-process", PIG_PROCESS_XML); storeEntity(EntityType.PROCESS, "post-process", POST_PROCEES_XML); ConfigurationStore store = ConfigurationStore.get(); cluster = store.get(EntityType.CLUSTER, "corp"); org.apache.falcon.entity.v0.cluster.Property property = new org.apache.falcon.entity.v0.cluster.Property(); property.setName(SecurityUtil.HIVE_METASTORE_KERBEROS_PRINCIPAL); property.setValue("hive/_HOST"); cluster.getProperties().getProperties().add(property); ClusterHelper.getInterface(cluster, Interfacetype.WRITE).setEndpoint(hdfsUrl); ClusterHelper.getInterface(cluster, Interfacetype.REGISTRY).setEndpoint("thrift://localhost:49083"); fs = new Path(hdfsUrl).getFileSystem(EmbeddedCluster.newConfiguration()); fs.create(new Path(ClusterHelper.getLocation(cluster, ClusterLocationType.WORKING).getPath(), "libext/PROCESS/ext.jar")).close(); Process process = store.get(EntityType.PROCESS, "clicksummary"); Path wfpath = new Path(process.getWorkflow().getPath()); assert new Path(hdfsUrl).getFileSystem(EmbeddedCluster.newConfiguration()).mkdirs(wfpath); }

Target:
public void setUp() throws Exception { storeEntity(EntityType.CLUSTER, "corp", CLUSTER_XML); storeEntity(EntityType.FEED, "clicks", FEED_XML); storeEntity(EntityType.FEED, "impressions", FEED_XML); storeEntity(EntityType.FEED, "clicksummary", FEED_XML); storeEntity(EntityType.PROCESS, "clicksummary", PROCESS_XML); storeEntity(EntityType.PROCESS, "pig-process", PIG_PROCESS_XML); ConfigurationStore store = ConfigurationStore.get(); cluster = store.get(EntityType.CLUSTER, "corp"); org.apache.falcon.entity.v0.cluster.Property property = new org.apache.falcon.entity.v0.cluster.Property(); property.setName(SecurityUtil.HIVE_METASTORE_KERBEROS_PRINCIPAL); property.setValue("hive/_HOST"); cluster.getProperties().getProperties().add(property); ClusterHelper.getInterface(cluster, Interfacetype.WRITE).setEndpoint(hdfsUrl); ClusterHelper.getInterface(cluster, Interfacetype.REGISTRY).setEndpoint("thrift://localhost:49083"); fs = new Path(hdfsUrl).getFileSystem(EmbeddedCluster.newConfiguration()); fs.create(new Path(ClusterHelper.getLocation(cluster, ClusterLocationType.WORKING).getPath(), "libext/PROCESS/ext.jar")).close(); Process process = store.get(EntityType.PROCESS, "clicksummary"); Path wfpath = new Path(process.getWorkflow().getPath()); assert new Path(hdfsUrl).getFileSystem(EmbeddedCluster.newConfiguration()).mkdirs(wfpath); }
Source:
public void saveQuestionAndAdjustQuestionNumbers(FeedbackQuestionAttributes question, boolean isUpdating, int oldQuestionNumber) throws InvalidParametersException, EntityDoesNotExistException, EntityAlreadyExistsException { FeedbackQuestionAttributes fqaSaved = oldQuestionsDb.saveQuestionAndAdjustQuestionNumbers(question, isUpdating, oldQuestionNumber); newQuestionsDb.saveQuestionAndAdjustQuestionNumbers(fqaSaved, isUpdating, oldQuestionNumber); }

Target:
public void saveQuestionAndAdjustQuestionNumbers( FeedbackQuestionAttributes question, boolean isUpdating, int oldQuestionNumber) throws InvalidParametersException, EntityDoesNotExistException, EntityAlreadyExistsException { FeedbackQuestionAttributes fqaSaved = oldQuestionsDb.saveQuestionAndAdjustQuestionNumbers(question, isUpdating, oldQuestionNumber); try { newQuestionsDb.saveQuestionAndAdjustQuestionNumbers(fqaSaved, isUpdating, oldQuestionNumber); } catch (EntityDoesNotExistException e) { } }
Source:
void handleXaTxnRollbackOnly(final MessageInputStream message, final int invId) throws IOException { int param; int len; SimpleXid xid = null; int secContext = 0; boolean hasSecContext = false; while ((param = message.read()) != - 1) { len = StreamUtils.readPackedUnsignedInt32(message); switch (param) { case P_XID: { xid = readXid(message, len); break; } case P_SEC_CONTEXT: { secContext = readIntParam(message, len); hasSecContext = true; break; } default: { readIntParam(message, len); } } } if (xid == null) { writeParamError(invId); return; } SecurityIdentity securityIdentity = getSecurityIdentity(M_RESP_XA_RB_ONLY, invId, secContext, hasSecContext); if (securityIdentity == null) { return; } securityIdentity.runAsObjIntConsumer((x, i) -> { try { final ImportResult<LocalTransaction> importResult = localTransactionContext.findOrImportTransaction(x, 0, true); if (importResult != null) { importResult.getControl().end(XAResource.TMFAIL); return; } else { Log.log.noAssociatedTransactionsDuringRollbackOnly(x); } writeSimpleResponse(M_RESP_XA_RB_ONLY, i); } catch (XAException e) { writeExceptionResponse(M_RESP_XA_RB_ONLY, i, e); return; } }, xid, invId); }

Target:
void handleXaTxnRollbackOnly(final MessageInputStream message, final int invId) throws IOException { int param; int len; SimpleXid xid = null; int secContext = 0; boolean hasSecContext = false; while ((param = message.read()) != - 1) { len = StreamUtils.readPackedUnsignedInt32(message); switch (param) { case P_XID: { xid = readXid(message, len); break; } case P_SEC_CONTEXT: { secContext = readIntParam(message, len); hasSecContext = true; break; } default: { readIntParam(message, len); } } } if (xid == null) { writeParamError(invId); return; } SecurityIdentity securityIdentity = getSecurityIdentity(M_RESP_XA_RB_ONLY, invId, secContext, hasSecContext); if (securityIdentity == null) { return; } securityIdentity.runAsObjIntConsumer((x, i) -> { try { final ImportResult<LocalTransaction> importResult = localTransactionContext.findOrImportTransaction(x, 0, true); if (importResult != null) { importResult.getControl().end(XAResource.TMFAIL); } else { Log.log.debugf("No transaction associated with xid %s during setRollbackOnly execution", x); } writeSimpleResponse(M_RESP_XA_RB_ONLY, i); } catch (XAException e) { writeExceptionResponse(M_RESP_XA_RB_ONLY, i, e); return; } }, xid, invId); }
Source:
private ITimeGraphState createTimeGraphState(ITmfStateInterval interval, ITmfStateSystem ss) throws StateSystemDisposedException { long startTime = interval.getStartTime(); long endTime = interval.getEndTime(); long duration = endTime - startTime + 1; Object statusObj = interval.getValue(); Type type = fEntryModelTypes.get(interval.getAttribute()); if (statusObj instanceof Integer) { int status = (int) statusObj; if (type == Type.CPU) { if (status == StateValues.CPU_STATUS_RUN_USERMODE || status == StateValues.CPU_STATUS_RUN_SYSCALL) { return fTimeEventNames.getUnchecked(interval); } } else if (type == Type.CURRENT_THREAD) { Object processName = null; if (fExecNamesCache.containsEntry(status, interval)) { processName = fExecNamesCache.get(status).first().getValue(); } else { int quark = ss.optQuarkAbsolute(Attributes.THREADS, Integer.toString(status), Attributes.EXEC_NAME); if (quark != ITmfStateSystem.INVALID_ATTRIBUTE) { ITmfStateInterval namedInterval = ss.querySingleState(endTime, quark); fExecNamesCache.put(status, namedInterval); processName = namedInterval.getValue(); } } if (processName instanceof String) { return new TimeGraphState(startTime, duration, status, (String) processName); } } return new TimeGraphState(startTime, duration, status); } return new TimeGraphState(startTime, duration, Integer.MIN_VALUE); }

Target:
private ITimeGraphState createTimeGraphState(ITmfStateInterval interval, ITmfStateSystem ss) throws StateSystemDisposedException { long startTime = interval.getStartTime(); long endTime = interval.getEndTime(); long duration = endTime - startTime + 1; Object statusObj = interval.getValue(); Type type = fEntryModelTypes.get(interval.getAttribute()); if (statusObj instanceof Integer) { int status = (int) statusObj; if (type == Type.CPU) { if (status == StateValues.CPU_STATUS_RUN_USERMODE || status == StateValues.CPU_STATUS_RUN_SYSCALL) { return fTimeEventNames.getUnchecked(interval); } } else if (type == Type.CURRENT_THREAD) { Object processName = null; if (fExecNamesCache.containsEntry(status, interval)) { NavigableSet<ITmfStateInterval> intervalSet = fExecNamesCache.get(status); for (ITmfStateInterval i: intervalSet) { if (CACHE_COMPARATOR.compare(i, interval) == 0) { processName = i.getValue(); break; } } } else { int quark = ss.optQuarkAbsolute(Attributes.THREADS, Integer.toString(status), Attributes.EXEC_NAME); if (quark != ITmfStateSystem.INVALID_ATTRIBUTE) { ITmfStateInterval namedInterval = ss.querySingleState(endTime, quark); fExecNamesCache.put(status, namedInterval); processName = namedInterval.getValue(); } } if (processName instanceof String) { return new TimeGraphState(startTime, duration, status, (String) processName); } } return new TimeGraphState(startTime, duration, status); } return new TimeGraphState(startTime, duration, Integer.MIN_VALUE); }
Source:
public static void register(ScalarFunctionModule module) { module.register(NAME, new BaseFunctionResolver(FUNCTION_PARAMS) { @Override public FunctionImplementation getForTypes(List<DataType> signatureTypes) throws IllegalArgumentException { DataType returnType = null; boolean paramHadTimezone = false; int timestampParamTypeId = signatureTypes.get(1).id(); switch (timestampParamTypeId) { case LongType.ID: case TimestampType.ID_WITHOUT_TZ: returnType = DataTypes.TIMESTAMPZ; break; case TimestampType.ID_WITH_TZ: returnType = DataTypes.TIMESTAMP; paramHadTimezone = true; break; default: throw new IllegalArgumentException(String.format( Locale.ENGLISH, "invalid argument to %s: expected second parameter" + " to be of either type [%s, %s, %s] but found %s", NAME, LongType.INSTANCE.getName(), TimestampType.INSTANCE_WITH_TZ.getName(), TimestampType.INSTANCE_WITHOUT_TZ.getName(), signatureTypes.get(1))); } return new TimezoneFunction(new FunctionInfo(new FunctionIdent(NAME, signatureTypes), returnType), paramHadTimezone); } }); }

Target:
public static void register(ScalarFunctionModule module) { module.register(NAME, new BaseFunctionResolver(FUNCTION_PARAMS) { @Override public FunctionImplementation getForTypes(List<DataType> signatureTypes) throws IllegalArgumentException { DataType returnType = signatureTypes.get(1).id() == TimestampType.ID_WITH_TZ ? DataTypes.TIMESTAMP : DataTypes.TIMESTAMPZ; return new TimezoneFunction(new FunctionInfo(new FunctionIdent(NAME, signatureTypes), returnType)); } }); }
Source:
private void prepareSqlDatabase() { String host = mainConfig.getString("sql.host", "localhost"); int port = mainConfig.getInt("sql.port", 3306); String db = mainConfig.getString("sql.database", "EchoPet"); String user = mainConfig.getString("sql.username", "none"); String pass = mainConfig.getString("sql.password", "none"); BoneCPConfig bcc = new BoneCPConfig(); bcc.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + db); bcc.setUsername(user); bcc.setPassword(pass); bcc.setPartitionCount(2); bcc.setMinConnectionsPerPartition(3); bcc.setMaxConnectionsPerPartition(7); bcc.setConnectionTestStatement("SELECT 1"); try { dbPool = new BoneCP(bcc); } catch (SQLException e) { Logger.log(Logger.LogLevel.SEVERE, "Failed to connect to MySQL! [MySQL DataBase: " + db + "].", e, true); } if (dbPool != null) { Connection connection = null; Statement statement = null; try { connection = dbPool.getConnection(); statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS EchoPet_version3 (" + "OwnerName varchar(255)," + "PetType varchar(255)," + "PetName varchar(255)," + "PetData INT," + "RiderPetType varchar(255)," + "RiderPetName varchar(255), " + "RiderPetData INT," + "PRIMARY KEY (OwnerName)" + ");"); TableMigrationUtil.migrateTables(); } catch (SQLException e) { Logger.log(Logger.LogLevel.SEVERE, "Table generation failed [MySQL DataBase: " + db + "].", e, true); } finally { try { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException ignored) { } } } }

Target:
private void prepareSqlDatabase() { String host = mainConfig.getString("sql.host", "localhost"); int port = mainConfig.getInt("sql.port", 3306); String db = mainConfig.getString("sql.database", "EchoPet"); String user = mainConfig.getString("sql.username", "none"); String pass = mainConfig.getString("sql.password", "none"); BoneCPConfig bcc = new BoneCPConfig(); bcc.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + db); bcc.setUsername(user); bcc.setPassword(pass); bcc.setPartitionCount(2); bcc.setMinConnectionsPerPartition(3); bcc.setMaxConnectionsPerPartition(7); bcc.setConnectionTestStatement("SELECT 1"); try { dbPool = new BoneCP(bcc); } catch (SQLException e) { Logger.log(Logger.LogLevel.SEVERE, "Failed to connect to MySQL! [MySQL DataBase: " + db + "].", e, true); } if (dbPool != null) { Connection connection = null; Statement statement = null; try { connection = dbPool.getConnection(); statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS EchoPet_version3 (" + "OwnerName varchar(36)," + "PetType varchar(255)," + "PetName varchar(255)," + "PetData BIGINT," + "RiderPetType varchar(255)," + "RiderPetName varchar(255), " + "RiderPetData BIGINT," + "PRIMARY KEY (OwnerName)" + ");"); TableMigrationUtil.migrateTables(); } catch (SQLException e) { Logger.log(Logger.LogLevel.SEVERE, "Table generation failed [MySQL DataBase: " + db + "].", e, true); } finally { try { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException ignored) { } } } }