_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q9700
OjbMemberTagsHandler.forAllMemberTags
train
public void forAllMemberTags(String template, Properties attributes) throws XDocletException { if (getCurrentField() != null) { forAllMemberTags(template, attributes, FOR_FIELD, XDocletTagshandlerMessages.ONLY_CALL_FIELD_NOT_NULL, new String[]{"forAllMemberTags"}); } else if (getCurrentMethod() != null) { forAllMemberTags(template, attributes, FOR_METHOD, XDocletTagshandlerMessages.ONLY_CALL_METHOD_NOT_NULL, new String[]{"forAllMemberTags"}); } }
java
{ "resource": "" }
q9701
OjbMemberTagsHandler.forAllMemberTagTokens
train
public void forAllMemberTagTokens(String template, Properties attributes) throws XDocletException { if (getCurrentField() != null) { forAllMemberTagTokens(template, attributes, FOR_FIELD); } else if (getCurrentMethod() != null) { forAllMemberTagTokens(template, attributes, FOR_METHOD); } }
java
{ "resource": "" }
q9702
OjbMemberTagsHandler.ifDoesntHaveMemberTag
train
public void ifDoesntHaveMemberTag(String template, Properties attributes) throws XDocletException { boolean result = false; if (getCurrentField() != null) { if (!hasTag(attributes, FOR_FIELD)) { result = true; generate(template); } } else if (getCurrentMethod() != null) { if (!hasTag(attributes, FOR_METHOD)) { result = true; generate(template); } } if (!result) { String error = attributes.getProperty("error"); if (error != null) { getEngine().print(error); } } }
java
{ "resource": "" }
q9703
OjbMemberTagsHandler.ifHasMemberWithTag
train
public void ifHasMemberWithTag(String template, Properties attributes) throws XDocletException { ArrayList allMemberNames = new ArrayList(); HashMap allMembers = new HashMap(); boolean hasTag = false; addMembers(allMemberNames, allMembers, getCurrentClass(), null, null, null); for (Iterator it = allMemberNames.iterator(); it.hasNext(); ) { XMember member = (XMember) allMembers.get(it.next()); if (member instanceof XField) { setCurrentField((XField)member); if (hasTag(attributes, FOR_FIELD)) { hasTag = true; } setCurrentField(null); } else if (member instanceof XMethod) { setCurrentMethod((XMethod)member); if (hasTag(attributes, FOR_METHOD)) { hasTag = true; } setCurrentMethod(null); } if (hasTag) { generate(template); break; } } }
java
{ "resource": "" }
q9704
OjbMemberTagsHandler.ifMemberTagValueEquals
train
public void ifMemberTagValueEquals(String template, Properties attributes) throws XDocletException { if (getCurrentField() != null) { if (isTagValueEqual(attributes, FOR_FIELD)) { generate(template); } } else if (getCurrentMethod() != null) { if (isTagValueEqual(attributes, FOR_METHOD)) { generate(template); } } }
java
{ "resource": "" }
q9705
OjbMemberTagsHandler.addMembersInclSupertypes
train
private void addMembersInclSupertypes(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException { addMembers(memberNames, members, type, tagName, paramName, paramValue); if (type.getInterfaces() != null) { for (Iterator it = type.getInterfaces().iterator(); it.hasNext(); ) { addMembersInclSupertypes(memberNames, members, (XClass)it.next(), tagName, paramName, paramValue); } } if (!type.isInterface() && (type.getSuperclass() != null)) { addMembersInclSupertypes(memberNames, members, type.getSuperclass(), tagName, paramName, paramValue); } }
java
{ "resource": "" }
q9706
OjbMemberTagsHandler.addMembers
train
private void addMembers(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException { if (!type.isInterface() && (type.getFields() != null)) { XField field; for (Iterator it = type.getFields().iterator(); it.hasNext(); ) { field = (XField)it.next(); if (!field.isFinal() && !field.isStatic() && !field.isTransient()) { if (checkTagAndParam(field.getDoc(), tagName, paramName, paramValue)) { // already processed ? if (!members.containsKey(field.getName())) { memberNames.add(field.getName()); members.put(field.getName(), field); } } } } } if (type.getMethods() != null) { XMethod method; String propertyName; for (Iterator it = type.getMethods().iterator(); it.hasNext(); ) { method = (XMethod)it.next(); if (!method.isConstructor() && !method.isNative() && !method.isStatic()) { if (checkTagAndParam(method.getDoc(), tagName, paramName, paramValue)) { if (MethodTagsHandler.isGetterMethod(method) || MethodTagsHandler.isSetterMethod(method)) { propertyName = MethodTagsHandler.getPropertyNameFor(method); if (!members.containsKey(propertyName)) { memberNames.add(propertyName); members.put(propertyName, method); } } } } } } }
java
{ "resource": "" }
q9707
OjbMemberTagsHandler.checkTagAndParam
train
private boolean checkTagAndParam(XDoc doc, String tagName, String paramName, String paramValue) { if (tagName == null) { return true; } if (!doc.hasTag(tagName)) { return false; } if (paramName == null) { return true; } if (!doc.getTag(tagName).getAttributeNames().contains(paramName)) { return false; } return (paramValue == null) || paramValue.equals(doc.getTagAttributeValue(tagName, paramName)); }
java
{ "resource": "" }
q9708
LogFileCompressor.waitForSizeQueue
train
final void waitForSizeQueue(final int queueSize) { synchronized (this.queue) { while (this.queue.size() > queueSize) { try { this.queue.wait(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } try { Thread.sleep(500L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.queue.notifyAll(); } }
java
{ "resource": "" }
q9709
LogFileCompressor.begin
train
final void begin() { if (LogFileCompressionStrategy.existsFor(this.properties)) { final Thread thread = new Thread(this, "Log4J File Compressor"); thread.setDaemon(true); thread.start(); this.threadRef = thread; } }
java
{ "resource": "" }
q9710
LogFileCompressor.end
train
final void end() { final Thread thread = this.threadRef; this.keepRunning.set(false); if (thread != null) { // thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } this.threadRef = null; }
java
{ "resource": "" }
q9711
CreateMASCaseManager.addStory
train
public static void addStory(File caseManager, String storyName, String testPath, String user, String feature, String benefit) throws BeastException { FileWriter caseManagerWriter; String storyClass = SystemReader.createClassName(storyName); try { BufferedReader reader = new BufferedReader(new FileReader( caseManager)); String targetLine1 = " public void " + MASReader.createFirstLowCaseName(storyName) + "() {"; String targetLine2 = " Result result = JUnitCore.runClasses(" + testPath + "." + storyClass + ".class);"; String in; while ((in = reader.readLine()) != null) { if (in.equals(targetLine1)) { while ((in = reader.readLine()) != null) { if (in.equals(targetLine2)) { reader.close(); // This test is already written in the case manager. return; } } reader.close(); throw new BeastException("Two different stories with the same name (same method name) are being created in the same CaseManager file. That is not possible. Please, change the name of the story: " + testPath + "." + storyClass + ".java"); } } reader.close(); caseManagerWriter = new FileWriter(caseManager, true); caseManagerWriter.write(" /**\n"); caseManagerWriter.write(" * This is the story: " + storyName + "\n"); caseManagerWriter.write(" * requested by: " + user + "\n"); caseManagerWriter.write(" * providing the feature: " + feature + "\n"); caseManagerWriter.write(" * so the user gets the benefit: " + benefit + "\n"); caseManagerWriter.write(" */\n"); caseManagerWriter.write(" @Test\n"); caseManagerWriter.write(" public void " + MASReader.createFirstLowCaseName(storyName) + "() {\n"); caseManagerWriter.write(" Result result = JUnitCore.runClasses(" + testPath + "." + storyClass + ".class);\n"); caseManagerWriter.write(" Assert.assertTrue(result.wasSuccessful());\n"); caseManagerWriter.write(" }\n"); caseManagerWriter.write("\n"); caseManagerWriter.flush(); caseManagerWriter.close(); } catch (IOException e) { Logger logger = Logger.getLogger("CreateMASCaseManager.createTest"); logger.info("ERROR writing the file"); } }
java
{ "resource": "" }
q9712
CreateMASCaseManager.closeMASCaseManager
train
public static void closeMASCaseManager(File caseManager) { FileWriter caseManagerWriter; try { caseManagerWriter = new FileWriter(caseManager, true); caseManagerWriter.write("}\n"); caseManagerWriter.flush(); caseManagerWriter.close(); } catch (IOException e) { Logger logger = Logger .getLogger("CreateMASCaseManager.closeMASCaseManager"); logger.info("ERROR: There is a mistake closing caseManager file.\n"); } }
java
{ "resource": "" }
q9713
TiledFeatureService.fillTile
train
public void fillTile(InternalTile tile, Envelope maxTileExtent) throws GeomajasException { List<InternalFeature> origFeatures = tile.getFeatures(); tile.setFeatures(new ArrayList<InternalFeature>()); for (InternalFeature feature : origFeatures) { if (!addTileCode(tile, maxTileExtent, feature.getGeometry())) { log.debug("add feature"); tile.addFeature(feature); } } }
java
{ "resource": "" }
q9714
TiledFeatureService.clipTile
train
public void clipTile(InternalTile tile, double scale, Coordinate panOrigin) throws GeomajasException { log.debug("clipTile before {}", tile); List<InternalFeature> orgFeatures = tile.getFeatures(); tile.setFeatures(new ArrayList<InternalFeature>()); Geometry maxScreenBbox = null; // The tile's maximum bounds in screen space. Used for clipping. for (InternalFeature feature : orgFeatures) { // clip feature if necessary if (exceedsScreenDimensions(feature, scale)) { log.debug("feature {} exceeds screen dimensions", feature); InternalFeatureImpl vectorFeature = (InternalFeatureImpl) feature.clone(); tile.setClipped(true); vectorFeature.setClipped(true); if (null == maxScreenBbox) { maxScreenBbox = JTS.toGeometry(getMaxScreenEnvelope(tile, panOrigin)); } Geometry clipped = maxScreenBbox.intersection(feature.getGeometry()); vectorFeature.setClippedGeometry(clipped); tile.addFeature(vectorFeature); } else { tile.addFeature(feature); } } log.debug("clipTile after {}", tile); }
java
{ "resource": "" }
q9715
TiledFeatureService.exceedsScreenDimensions
train
private boolean exceedsScreenDimensions(InternalFeature f, double scale) { Envelope env = f.getBounds(); return (env.getWidth() * scale > MAXIMUM_TILE_COORDINATE) || (env.getHeight() * scale > MAXIMUM_TILE_COORDINATE); }
java
{ "resource": "" }
q9716
TiledFeatureService.getMaxScreenEnvelope
train
private Envelope getMaxScreenEnvelope(InternalTile tile, Coordinate panOrigin) { int nrOfTilesX = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenWidth()); int nrOfTilesY = Math.max(1, MAXIMUM_TILE_COORDINATE / tile.getScreenHeight()); double x1 = panOrigin.x - nrOfTilesX * tile.getTileWidth(); // double x2 = x1 + (nrOfTilesX * tileWidth * 2); double x2 = panOrigin.x + nrOfTilesX * tile.getTileWidth(); double y1 = panOrigin.y - nrOfTilesY * tile.getTileHeight(); // double y2 = y1 + (nrOfTilesY * tileHeight * 2); double y2 = panOrigin.y + nrOfTilesY * tile.getTileHeight(); return new Envelope(x1, x2, y1, y2); }
java
{ "resource": "" }
q9717
GrapesClient.getClient
train
private Client getClient(){ final ClientConfig cfg = new DefaultClientConfig(); cfg.getClasses().add(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider.class); cfg.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, timeout); return Client.create(cfg); }
java
{ "resource": "" }
q9718
GrapesClient.isServerAvailable
train
public boolean isServerAvailable(){ final Client client = getClient(); final ClientResponse response = client.resource(serverURL).get(ClientResponse.class); if(ClientResponse.Status.OK.getStatusCode() == response.getStatus()){ return true; } if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, "Failed to reach the targeted Grapes server", response.getStatus())); } client.destroy(); return false; }
java
{ "resource": "" }
q9719
GrapesClient.postBuildInfo
train
public void postBuildInfo(final String moduleName, final String moduleVersion, final Map<String, String> buildInfo, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.getBuildInfoPath(moduleName, moduleVersion)); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, buildInfo); client.destroy(); if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){ final String message = "Failed to POST buildInfo"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9720
GrapesClient.postModule
train
public void postModule(final Module module, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.moduleResourcePath()); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, module); client.destroy(); if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){ final String message = "Failed to POST module"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9721
GrapesClient.deleteModule
train
public void deleteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{ final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version)); final ClientResponse response = resource.delete(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = String.format(FAILED_TO_GET_MODULE, "to delete module", name, version); if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9722
GrapesClient.getModule
train
public Module getModule(final String name, final String version) throws GrapesCommunicationException { final Client client = getClient(); final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version)); final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = String.format(FAILED_TO_GET_MODULE, "get module details", name, version); if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(Module.class); }
java
{ "resource": "" }
q9723
GrapesClient.getModules
train
public List<Module> getModules(final Map<String, String> filters) throws GrapesCommunicationException { final Client client = getClient(); WebResource resource = client.resource(serverURL).path(RequestUtils.getAllModulesPath()); for(final Map.Entry<String,String> queryParam: filters.entrySet()){ resource = resource.queryParam(queryParam.getKey(), queryParam.getValue()); } final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = "Failed to get filtered modules."; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(new GenericType<List<Module>>(){}); }
java
{ "resource": "" }
q9724
GrapesClient.promoteModule
train
public void promoteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{ final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.promoteModulePath(name, version)); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = String.format(FAILED_TO_GET_MODULE, "promote module", name, version); if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9725
GrapesClient.getModulePromotionReport
train
public PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException { return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class); }
java
{ "resource": "" }
q9726
GrapesClient.postArtifact
train
public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath()); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact); client.destroy(); if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){ final String message = "Failed to POST artifact"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9727
GrapesClient.deleteArtifact
train
public void deleteArtifact(final String gavc, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{ final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactPath(gavc)); final ClientResponse response = resource.delete(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = "Failed to DELETE artifact " + gavc; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9728
GrapesClient.getArtifacts
train
public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException { final Client client = getClient(); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath()); final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString()) .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = "Failed to get artifacts"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(ArtifactList.class); }
java
{ "resource": "" }
q9729
GrapesClient.postDoNotUseArtifact
train
public void postDoNotUseArtifact(final String gavc, final Boolean doNotUse, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.getDoNotUseArtifact(gavc)); final ClientResponse response = resource.queryParam(ServerAPI.DO_NOT_USE, doNotUse.toString()) .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = "Failed to post do not use artifact"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9730
GrapesClient.getArtifactVersions
train
public List<String> getArtifactVersions(final String gavc) throws GrapesCommunicationException { final Client client = getClient(); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactVersions(gavc)); final ClientResponse response = resource .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = FAILED_TO_GET_CORPORATE_FILTERS; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(new GenericType<List<String>>(){}); }
java
{ "resource": "" }
q9731
GrapesClient.postLicense
train
public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath()); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license); client.destroy(); if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){ final String message = "Failed to POST license"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9732
GrapesClient.getModuleAncestors
train
public List<Dependency> getModuleAncestors(final String moduleName, final String moduleVersion) throws GrapesCommunicationException { final Client client = getClient(); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactAncestors(moduleName, moduleVersion)); final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, "true") .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, "true") .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, "true") .queryParam(ServerAPI.SCOPE_TEST_PARAM, "true") .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = String.format(FAILED_TO_GET_MODULE, "get module ancestors", moduleName, moduleVersion); if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(new GenericType<List<Dependency>>(){}); }
java
{ "resource": "" }
q9733
GrapesClient.getModuleDependencies
train
public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException { final Client client = getClient(); final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion)); final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, "true") .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, "true") .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, "true") .queryParam(ServerAPI.SCOPE_TEST_PARAM, "true") .queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString()) .queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString()) .queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString()) .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = String.format(FAILED_TO_GET_MODULE, "get module ancestors ", moduleName, moduleVersion); if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(new GenericType<List<Dependency>>(){}); }
java
{ "resource": "" }
q9734
GrapesClient.getModuleOrganization
train
public Organization getModuleOrganization(final String moduleName, final String moduleVersion) throws GrapesCommunicationException { final Client client = getClient(); final WebResource resource = client.resource(serverURL).path(RequestUtils.getModuleOrganizationPath(moduleName, moduleVersion)); final ClientResponse response = resource .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = "Failed to get module's organization"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } return response.getEntity(Organization.class); }
java
{ "resource": "" }
q9735
GrapesClient.createProductDelivery
train
public void createProductDelivery(final String productLogicalName, final Delivery delivery, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.getProductDelivery(productLogicalName)); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, delivery); client.destroy(); if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){ final String message = "Failed to create a delivery"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
{ "resource": "" }
q9736
ObjectEnvelope.refreshIdentity
train
public Identity refreshIdentity() { Identity oldOid = getIdentity(); this.oid = getBroker().serviceIdentity().buildIdentity(myObj); return oldOid; }
java
{ "resource": "" }
q9737
ObjectEnvelope.prepareInitialState
train
private void prepareInitialState(boolean isNewObject) { // determine appropriate modification state ModificationState initialState; if(isNewObject) { // if object is not already persistent it must be marked as new // it must be marked as dirty because it must be stored even if it will not modified during tx initialState = StateNewDirty.getInstance(); } else if(isDeleted(oid)) { // if object is already persistent it will be marked as old. // it is marked as dirty as it has been deleted during tx and now it is inserted again, // possibly with new field values. initialState = StateOldDirty.getInstance(); } else { // if object is already persistent it will be marked as old. // it is marked as clean as it has not been modified during tx already initialState = StateOldClean.getInstance(); } // remember it: modificationState = initialState; }
java
{ "resource": "" }
q9738
ObjectEnvelope.isDeleted
train
public boolean isDeleted(Identity id) { ObjectEnvelope envelope = buffer.getByIdentity(id); return (envelope != null && envelope.needsDelete()); }
java
{ "resource": "" }
q9739
ObjectEnvelope.setModificationState
train
public void setModificationState(ModificationState newModificationState) { if(newModificationState != modificationState) { if(log.isDebugEnabled()) { log.debug("object state transition for object " + this.oid + " (" + modificationState + " --> " + newModificationState + ")"); // try{throw new Exception();}catch(Exception e) // { // e.printStackTrace(); // } } modificationState = newModificationState; } }
java
{ "resource": "" }
q9740
ObjectEnvelope.markReferenceElements
train
void markReferenceElements(PersistenceBroker broker) { // these cases will be handled by ObjectEnvelopeTable#cascadingDependents() // if(getModificationState().needsInsert() || getModificationState().needsDelete()) return; Map oldImage = getBeforeImage(); Map newImage = getCurrentImage(); Iterator iter = newImage.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); // we only interested in references if(key instanceof ObjectReferenceDescriptor) { Image oldRefImage = (Image) oldImage.get(key); Image newRefImage = (Image) entry.getValue(); newRefImage.performReferenceDetection(oldRefImage); } } }
java
{ "resource": "" }
q9741
JadeConnector.createContainer
train
public void createContainer(String container) { ContainerController controller = this.platformContainers.get(container); if (controller == null) { // TODO make this configurable Profile p = new ProfileImpl(); p.setParameter(Profile.PLATFORM_ID, PLATFORM_ID); p.setParameter(Profile.MAIN_HOST, MAIN_HOST); p.setParameter(Profile.MAIN_PORT, MAIN_PORT); p.setParameter(Profile.LOCAL_HOST, MAIN_HOST); int port = Integer.parseInt(MAIN_PORT); port = port + 1 + this.platformContainers.size(); p.setParameter(Profile.LOCAL_PORT, Integer.toString(port)); p.setParameter(Profile.CONTAINER_NAME, container); logger.fine("Creating container " + container + "..."); ContainerController agentContainer = this.runtime .createAgentContainer(p); this.platformContainers.put(container, agentContainer); logger.fine("Container " + container + " created successfully."); } else { logger.fine("Container " + container + " is already created."); } }
java
{ "resource": "" }
q9742
QueryCustomizerDefaultImpl.customizeQuery
train
public Query customizeQuery(Object anObject, PersistenceBroker aBroker, CollectionDescriptor aCod, QueryByCriteria aQuery) { return aQuery; }
java
{ "resource": "" }
q9743
BeanLayer.getElements
train
public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException { if (null == filter) { filter = Filter.INCLUDE; } List<Object> filteredList = new ArrayList<Object>(); try { synchronized (featuresById) { for (Object feature : featuresById.values()) { if (filter.evaluate(feature)) { filteredList.add(feature); } } } } catch (Exception e) { // NOSONAR throw new LayerException(e, ExceptionCode.FILTER_EVALUATION_PROBLEM, filter, getId()); } // Sorting of elements. if (comparator != null) { Collections.sort(filteredList, comparator); } if (maxResultSize > 0) { int fromIndex = Math.max(0, offset); int toIndex = Math.min(offset + maxResultSize, filteredList.size()); toIndex = Math.max(fromIndex, toIndex); return filteredList.subList(fromIndex, toIndex).iterator(); } else { return filteredList.iterator(); } }
java
{ "resource": "" }
q9744
TiledRasterLayerServiceState.setTileUrls
train
public void setTileUrls(List<String> tileUrls) { this.tileUrls = tileUrls; if (null != urlStrategy) { urlStrategy.setUrls(tileUrls); } }
java
{ "resource": "" }
q9745
TiledRasterLayerServiceState.postConstruct
train
public void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException { if (null == layerInfo) { layerInfo = new RasterLayerInfo(); } layerInfo.setCrs(TiledRasterLayerService.MERCATOR); crs = geoService.getCrs2(TiledRasterLayerService.MERCATOR); layerInfo.setTileWidth(tileSize); layerInfo.setTileHeight(tileSize); Bbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, -TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS); layerInfo.setMaxExtent(bbox); maxBounds = converterService.toInternal(bbox); resolutions = new double[maxZoomLevel + 1]; double powerOfTwo = 1; for (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) { double resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo); resolutions[zoomLevel] = resolution; powerOfTwo *= 2; } }
java
{ "resource": "" }
q9746
AbstractIndirectionHandler.addListener
train
public synchronized void addListener(MaterializationListener listener) { if (_listeners == null) { _listeners = new ArrayList(); } // add listener only once if (!_listeners.contains(listener)) { _listeners.add(listener); } }
java
{ "resource": "" }
q9747
AbstractIndirectionHandler.beforeMaterialization
train
protected void beforeMaterialization() { if (_listeners != null) { MaterializationListener listener; for (int idx = _listeners.size() - 1; idx >= 0; idx--) { listener = (MaterializationListener) _listeners.get(idx); listener.beforeMaterialization(this, _id); } } }
java
{ "resource": "" }
q9748
AbstractIndirectionHandler.afterMaterialization
train
protected void afterMaterialization() { if (_listeners != null) { MaterializationListener listener; // listeners may remove themselves during the afterMaterialization // callback. // thus we must iterate through the listeners vector from back to // front // to avoid index problems. for (int idx = _listeners.size() - 1; idx >= 0; idx--) { listener = (MaterializationListener) _listeners.get(idx); listener.afterMaterialization(this, _realSubject); } } }
java
{ "resource": "" }
q9749
AbstractIndirectionHandler.getBroker
train
protected TemporaryBrokerWrapper getBroker() throws PBFactoryException { PersistenceBrokerInternal broker; boolean needsClose = false; if (getBrokerKey() == null) { /* arminw: if no PBKey is set we throw an exception, because we don't know which PB (connection) should be used. */ throw new OJBRuntimeException("Can't find associated PBKey. Need PBKey to obtain a valid" + "PersistenceBroker instance from intern resources."); } // first try to use the current threaded broker to avoid blocking broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey()); // current broker not found, create a intern new one if ((broker == null) || broker.isClosed()) { broker = (PersistenceBrokerInternal) PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey()); /** Specifies whether we obtained a fresh broker which we have to close after we used it */ needsClose = true; } return new TemporaryBrokerWrapper(broker, needsClose); }
java
{ "resource": "" }
q9750
AbstractIndirectionHandler.getRealSubject
train
public Object getRealSubject() throws PersistenceBrokerException { if (_realSubject == null) { beforeMaterialization(); _realSubject = materializeSubject(); afterMaterialization(); } return _realSubject; }
java
{ "resource": "" }
q9751
AbstractIndirectionHandler.materializeSubject
train
protected synchronized Object materializeSubject() throws PersistenceBrokerException { TemporaryBrokerWrapper tmp = getBroker(); try { Object realSubject = tmp.broker.getObjectByIdentity(_id); if (realSubject == null) { LoggerFactory.getLogger(IndirectionHandler.class).warn( "Can not materialize object for Identity " + _id + " - using PBKey " + getBrokerKey()); } return realSubject; } catch (Exception ex) { throw new PersistenceBrokerException(ex); } finally { tmp.close(); } }
java
{ "resource": "" }
q9752
DSetImpl.ojbAdd
train
public void ojbAdd(Object anObject) { DSetEntry entry = prepareEntry(anObject); entry.setPosition(elements.size()); elements.add(entry); }
java
{ "resource": "" }
q9753
FoundationLoggingThrowableInformationPatternConverter.generateAbbreviatedExceptionMessage
train
private String generateAbbreviatedExceptionMessage(final Throwable throwable) { final StringBuilder builder = new StringBuilder(); builder.append(": "); builder.append(throwable.getClass().getCanonicalName()); builder.append(": "); builder.append(throwable.getMessage()); Throwable cause = throwable.getCause(); while (cause != null) { builder.append('\n'); builder.append("Caused by: "); builder.append(cause.getClass().getCanonicalName()); builder.append(": "); builder.append(cause.getMessage()); // make sure the exception cause is not itself to prevent infinite // looping assert (cause != cause.getCause()); cause = (cause == cause.getCause() ? null : cause.getCause()); } return builder.toString(); }
java
{ "resource": "" }
q9754
GeoServiceImpl.postConstruct
train
@PostConstruct protected void postConstruct() throws GeomajasException { if (null != crsDefinitions) { for (CrsInfo crsInfo : crsDefinitions.values()) { try { CoordinateReferenceSystem crs = CRS.parseWKT(crsInfo.getCrsWkt()); String code = crsInfo.getKey(); crsCache.put(code, CrsFactory.getCrs(code, crs)); } catch (FactoryException e) { throw new GeomajasException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crsInfo.getKey()); } } } if (null != crsTransformDefinitions) { for (CrsTransformInfo crsTransformInfo : crsTransformDefinitions.values()) { String key = getTransformKey(crsTransformInfo); transformCache.put(key, getCrsTransform(key, crsTransformInfo)); } } GeometryFactory factory = new GeometryFactory(); EMPTY_GEOMETRIES.put(Point.class, factory.createPoint((Coordinate) null)); EMPTY_GEOMETRIES.put(LineString.class, factory.createLineString((Coordinate[]) null)); EMPTY_GEOMETRIES.put(Polygon.class, factory.createPolygon(null, null)); EMPTY_GEOMETRIES.put(MultiPoint.class, factory.createMultiPoint((Coordinate[]) null)); EMPTY_GEOMETRIES.put(MultiLineString.class, factory.createMultiLineString((LineString[]) null)); // cast needed! EMPTY_GEOMETRIES.put(MultiPolygon.class, factory.createMultiPolygon((Polygon[]) null)); // cast needed! EMPTY_GEOMETRIES.put(Geometry.class, factory.createGeometryCollection(null)); }
java
{ "resource": "" }
q9755
GeoServiceImpl.getSridFromCrs
train
public int getSridFromCrs(String crs) { int crsInt; if (crs.indexOf(':') != -1) { crsInt = Integer.parseInt(crs.substring(crs.indexOf(':') + 1)); } else { try { crsInt = Integer.parseInt(crs); } catch (NumberFormatException e) { crsInt = 0; } } return crsInt; }
java
{ "resource": "" }
q9756
PBPoolInfo.configure
train
public void configure(Configuration pConfig) throws ConfigurationException { if (pConfig instanceof PBPoolConfiguration) { PBPoolConfiguration conf = (PBPoolConfiguration) pConfig; this.setMaxActive(conf.getMaxActive()); this.setMaxIdle(conf.getMaxIdle()); this.setMaxWait(conf.getMaxWaitMillis()); this.setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis()); this.setTimeBetweenEvictionRunsMillis(conf.getTimeBetweenEvictionRunsMilli()); this.setWhenExhaustedAction(conf.getWhenExhaustedAction()); } else { LoggerFactory.getDefaultLogger().error(this.getClass().getName() + " cannot read configuration properties, use default."); } }
java
{ "resource": "" }
q9757
OTMKit.acquireConnection
train
public OTMConnection acquireConnection(PBKey pbKey) { TransactionFactory txFactory = getTransactionFactory(); return txFactory.acquireConnection(pbKey); }
java
{ "resource": "" }
q9758
JadexMessenger.sendMessageToAgents
train
public void sendMessageToAgents(String[] agent_name, String msgtype, Object message_content, Connector connector) { HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("performative", msgtype); hm.put(SFipa.CONTENT, message_content); IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length]; for (int i = 0; i < agent_name.length; i++) { ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]); } ((IMessageService) connector.getMessageService()).deliverMessage(hm, "fipa", ici); }
java
{ "resource": "" }
q9759
JadexMessenger.sendMessageToAgentsWithExtraProperties
train
public void sendMessageToAgentsWithExtraProperties(String[] agent_name, String msgtype, Object message_content, ArrayList<Object> properties, Connector connector) { HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("performative", msgtype); hm.put(SFipa.CONTENT, message_content); for (Object property : properties) { // Logger logger = Logger.getLogger("JadexMessenger"); // logger.info("Sending message with extra property: "+property.get(0)+", with value "+property.get(1)); hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1)); } IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length]; for (int i = 0; i < agent_name.length; i++) { ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]); } ((IMessageService) connector.getMessageService()).deliverMessage(hm, "fipa", ici); }
java
{ "resource": "" }
q9760
TransactionImpl.lock
train
public void lock(Object obj, int lockMode) throws LockNotGrantedException { if (log.isDebugEnabled()) log.debug("lock object was called on tx " + this + ", object is " + obj.toString()); checkOpen(); RuntimeObject rtObject = new RuntimeObject(obj, this); lockAndRegister(rtObject, lockMode, isImplicitLocking(), getRegistrationList()); // if(isImplicitLocking()) moveToLastInOrderList(rtObject.getIdentity()); }
java
{ "resource": "" }
q9761
TransactionImpl.doWriteObjects
train
protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException { /* arminw: if broker isn't in PB-tx, start tx */ if (!getBroker().isInTransaction()) { if (log.isDebugEnabled()) log.debug("call beginTransaction() on PB instance"); broker.beginTransaction(); } // Notify objects of impending commits. performTransactionAwareBeforeCommit(); // Now perfom the real work objectEnvelopeTable.writeObjects(isFlush); // now we have to perform the named objects namedRootsMap.performDeletion(); namedRootsMap.performInsert(); namedRootsMap.afterWriteCleanup(); }
java
{ "resource": "" }
q9762
TransactionImpl.doClose
train
protected synchronized void doClose() { try { LockManager lm = getImplementation().getLockManager(); Enumeration en = objectEnvelopeTable.elements(); while (en.hasMoreElements()) { ObjectEnvelope oe = (ObjectEnvelope) en.nextElement(); lm.releaseLock(this, oe.getIdentity(), oe.getObject()); } //remove locks for objects which haven't been materialized yet for (Iterator it = unmaterializedLocks.iterator(); it.hasNext();) { lm.releaseLock(this, it.next()); } // this tx is no longer interested in materialization callbacks unRegisterFromAllIndirectionHandlers(); unRegisterFromAllCollectionProxies(); } finally { /** * MBAIRD: Be nice and close the table to release all refs */ if (log.isDebugEnabled()) log.debug("Close Transaction and release current PB " + broker + " on tx " + this); // remove current thread from LocalTxManager // to avoid problems for succeeding calls of the same thread implementation.getTxManager().deregisterTx(this); // now cleanup and prepare for reuse refresh(); } }
java
{ "resource": "" }
q9763
TransactionImpl.refresh
train
protected void refresh() { if (log.isDebugEnabled()) log.debug("Refresh this transaction for reuse: " + this); try { // we reuse ObjectEnvelopeTable instance objectEnvelopeTable.refresh(); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("error closing object envelope table : " + e.getMessage()); e.printStackTrace(); } } cleanupBroker(); // clear the temporary used named roots map // we should do that, because same tx instance // could be used several times broker = null; clearRegistrationList(); unmaterializedLocks.clear(); txStatus = Status.STATUS_NO_TRANSACTION; }
java
{ "resource": "" }
q9764
TransactionImpl.abort
train
public void abort() { /* do nothing if already rolledback */ if (txStatus == Status.STATUS_NO_TRANSACTION || txStatus == Status.STATUS_UNKNOWN || txStatus == Status.STATUS_ROLLEDBACK) { log.info("Nothing to abort, tx is not active - status is " + TxUtil.getStatusString(txStatus)); return; } // check status of tx if (txStatus != Status.STATUS_ACTIVE && txStatus != Status.STATUS_PREPARED && txStatus != Status.STATUS_MARKED_ROLLBACK) { throw new IllegalStateException("Illegal state for abort call, state was '" + TxUtil.getStatusString(txStatus) + "'"); } if(log.isEnabledFor(Logger.INFO)) { log.info("Abort transaction was called on tx " + this); } try { try { doAbort(); } catch(Exception e) { log.error("Error while abort transaction, will be skipped", e); } // used in managed environments, ignored in non-managed this.implementation.getTxManager().abortExternalTx(this); try { if(hasBroker() && getBroker().isInTransaction()) { getBroker().abortTransaction(); } } catch(Exception e) { log.error("Error while do abort used broker instance, will be skipped", e); } } finally { txStatus = Status.STATUS_ROLLEDBACK; // cleanup things, e.g. release all locks doClose(); } }
java
{ "resource": "" }
q9765
TransactionImpl.getObjectByIdentity
train
public Object getObjectByIdentity(Identity id) throws PersistenceBrokerException { checkOpen(); ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(id); if (envelope != null) { return (envelope.needsDelete() ? null : envelope.getObject()); } else { return getBroker().getObjectByIdentity(id); } }
java
{ "resource": "" }
q9766
TransactionImpl.lockAndRegisterReferences
train
private void lockAndRegisterReferences(ClassDescriptor cld, Object sourceObject, int lockMode, List registeredObjects) throws LockNotGrantedException { if (implicitLocking) { Iterator i = cld.getObjectReferenceDescriptors(true).iterator(); while (i.hasNext()) { ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) i.next(); Object refObj = rds.getPersistentField().get(sourceObject); if (refObj != null) { boolean isProxy = ProxyHelper.isProxy(refObj); RuntimeObject rt = isProxy ? new RuntimeObject(refObj, this, false) : new RuntimeObject(refObj, this); if (!registrationList.contains(rt.getIdentity())) { lockAndRegister(rt, lockMode, registeredObjects); } } } } }
java
{ "resource": "" }
q9767
TransactionImpl.afterMaterialization
train
public void afterMaterialization(IndirectionHandler handler, Object materializedObject) { try { Identity oid = handler.getIdentity(); if (log.isDebugEnabled()) log.debug("deferred registration: " + oid); if(!isOpen()) { log.error("Proxy object materialization outside of a running tx, obj=" + oid); try{throw new Exception("Proxy object materialization outside of a running tx, obj=" + oid);}catch(Exception e) { e.printStackTrace(); } } ClassDescriptor cld = getBroker().getClassDescriptor(materializedObject.getClass()); RuntimeObject rt = new RuntimeObject(materializedObject, oid, cld, false, false); lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList()); } catch (Throwable t) { log.error("Register materialized object with this tx failed", t); throw new LockNotGrantedException(t.getMessage()); } unregisterFromIndirectionHandler(handler); }
java
{ "resource": "" }
q9768
TransactionImpl.afterLoading
train
public void afterLoading(CollectionProxyDefaultImpl colProxy) { if (log.isDebugEnabled()) log.debug("loading a proxied collection a collection: " + colProxy); Collection data = colProxy.getData(); for (Iterator iterator = data.iterator(); iterator.hasNext();) { Object o = iterator.next(); if(!isOpen()) { log.error("Collection proxy materialization outside of a running tx, obj=" + o); try{throw new Exception("Collection proxy materialization outside of a running tx, obj=" + o);} catch(Exception e) {e.printStackTrace();} } else { Identity oid = getBroker().serviceIdentity().buildIdentity(o); ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o)); RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o)); lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList()); } } unregisterFromCollectionProxy(colProxy); }
java
{ "resource": "" }
q9769
TransactionImpl.isTransient
train
protected boolean isTransient(ClassDescriptor cld, Object obj, Identity oid) { // if the Identity is transient we assume a non-persistent object boolean isNew = oid != null && oid.isTransient(); /* detection of new objects is costly (select of ID in DB to check if object already exists) we do: a. check if the object has nullified PK field b. check if the object is already registered c. lookup from cache and if not found, last option select on DB */ if(!isNew) { final PersistenceBroker pb = getBroker(); if(cld == null) { cld = pb.getClassDescriptor(obj.getClass()); } isNew = pb.serviceBrokerHelper().hasNullPKField(cld, obj); if(!isNew) { if(oid == null) { oid = pb.serviceIdentity().buildIdentity(cld, obj); } final ObjectEnvelope mod = objectEnvelopeTable.getByIdentity(oid); if(mod != null) { // already registered object, use current state isNew = mod.needsInsert(); } else { // if object was found cache, assume it's old // else make costly check against the DB isNew = pb.serviceObjectCache().lookup(oid) == null && !pb.serviceBrokerHelper().doesExist(cld, oid, obj); } } } return isNew; }
java
{ "resource": "" }
q9770
DependencyListView.getLicense
train
private License getLicense(final String licenseId) { License result = null; final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId); if (matchingLicenses.isEmpty()) { result = DataModelFactory.createLicense("#" + licenseId + "# (to be identified)", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET); result.setUnknown(true); } else { if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) { LOG.warn(String.format("%s matches multiple licenses %s. " + "Please run the report showing multiple matching on licenses", licenseId, matchingLicenses.toString())); } result = mapper.getLicense(matchingLicenses.iterator().next()); } return result; }
java
{ "resource": "" }
q9771
DependencyListView.getHeaders
train
private String[] getHeaders() { final List<String> headers = new ArrayList<>(); if(decorator.getShowSources()){ headers.add(SOURCE_FIELD); } if(decorator.getShowSourcesVersion()){ headers.add(SOURCE_VERSION_FIELD); } if(decorator.getShowTargets()){ headers.add(TARGET_FIELD); } if(decorator.getShowTargetsDownloadUrl()){ headers.add(DOWNLOAD_URL_FIELD); } if(decorator.getShowTargetsSize()){ headers.add(SIZE_FIELD); } if(decorator.getShowScopes()){ headers.add(SCOPE_FIELD); } if(decorator.getShowLicenses()){ headers.add(LICENSE_FIELD); } if(decorator.getShowLicensesLongName()){ headers.add(LICENSE_LONG_NAME_FIELD); } if(decorator.getShowLicensesUrl()){ headers.add(LICENSE_URL_FIELD); } if(decorator.getShowLicensesComment()){ headers.add(LICENSE_COMMENT_FIELD); } return headers.toArray(new String[headers.size()]); }
java
{ "resource": "" }
q9772
CachingLayerHttpService.getStream
train
public InputStream getStream(String url, RasterLayer layer) throws IOException { if (layer instanceof ProxyLayerSupport) { ProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer; if (proxyLayer.isUseCache() && null != cacheManagerService) { Object cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url); if (null != cachedObject) { testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE); return new ByteArrayInputStream((byte[]) cachedObject); } else { testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE); InputStream stream = super.getStream(url, proxyLayer); ByteArrayOutputStream os = new ByteArrayOutputStream(); int b; while ((b = stream.read()) >= 0) { os.write(b); } cacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(), getLayerEnvelope(proxyLayer)); return new ByteArrayInputStream((byte[]) os.toByteArray()); } } } return super.getStream(url, layer); }
java
{ "resource": "" }
q9773
CachingLayerHttpService.getLayerEnvelope
train
private Envelope getLayerEnvelope(ProxyLayerSupport layer) { Bbox bounds = layer.getLayerInfo().getMaxExtent(); return new Envelope(bounds.getX(), bounds.getMaxX(), bounds.getY(), bounds.getMaxY()); }
java
{ "resource": "" }
q9774
PromotionReportTranslator.buildErrorMsg
train
private static String buildErrorMsg(List<String> dependencies, String message) { final StringBuilder buffer = new StringBuilder(); boolean isFirstElement = true; for (String dependency : dependencies) { if (!isFirstElement) { buffer.append(", "); } // check if it is an instance of Artifact - add the gavc else append the object buffer.append(dependency); isFirstElement = false; } return String.format(message, buffer.toString()); }
java
{ "resource": "" }
q9775
CollectionPrefetcher.buildPrefetchQuery
train
protected Query buildPrefetchQuery(Collection ids) { CollectionDescriptor cds = getCollectionDescriptor(); QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor())); // check if collection must be ordered if (!cds.getOrderBy().isEmpty()) { Iterator iter = cds.getOrderBy().iterator(); while (iter.hasNext()) { query.addOrderBy((FieldHelper) iter.next()); } } return query; }
java
{ "resource": "" }
q9776
CollectionPrefetcher.associateBatched
train
protected void associateBatched(Collection owners, Collection children) { CollectionDescriptor cds = getCollectionDescriptor(); PersistentField field = cds.getPersistentField(); PersistenceBroker pb = getBroker(); Class ownerTopLevelClass = pb.getTopLevelClass(getOwnerClassDescriptor().getClassOfObject()); Class collectionClass = cds.getCollectionClass(); // this collection type will be used: HashMap ownerIdsToLists = new HashMap(owners.size()); IdentityFactory identityFactory = pb.serviceIdentity(); // initialize the owner list map for (Iterator it = owners.iterator(); it.hasNext();) { Object owner = it.next(); ownerIdsToLists.put(identityFactory.buildIdentity(getOwnerClassDescriptor(), owner), new ArrayList()); } // build the children lists for the owners for (Iterator it = children.iterator(); it.hasNext();) { Object child = it.next(); // BRJ: use cld for real class, relatedObject could be Proxy ClassDescriptor cld = getDescriptorRepository().getDescriptorFor(ProxyHelper.getRealClass(child)); Object[] fkValues = cds.getForeignKeyValues(child, cld); Identity ownerId = identityFactory.buildIdentity(null, ownerTopLevelClass, fkValues); List list = (List) ownerIdsToLists.get(ownerId); if (list != null) { list.add(child); } } // connect children list to owners for (Iterator it = owners.iterator(); it.hasNext();) { Object result; Object owner = it.next(); Identity ownerId = identityFactory.buildIdentity(owner); List list = (List) ownerIdsToLists.get(ownerId); if ((collectionClass == null) && field.getType().isArray()) { int length = list.size(); Class itemtype = field.getType().getComponentType(); result = Array.newInstance(itemtype, length); for (int j = 0; j < length; j++) { Array.set(result, j, list.get(j)); } } else { ManageableCollection col = createCollection(cds, collectionClass); for (Iterator it2 = list.iterator(); it2.hasNext();) { col.ojbAdd(it2.next()); } result = col; } Object value = field.get(owner); if ((value instanceof CollectionProxyDefaultImpl) && (result instanceof Collection)) { ((CollectionProxyDefaultImpl) value).setData((Collection) result); } else { field.set(owner, result); } } }
java
{ "resource": "" }
q9777
CollectionPrefetcher.createCollection
train
protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass) { Class fieldType = desc.getPersistentField().getType(); ManageableCollection col; if (collectionClass == null) { if (ManageableCollection.class.isAssignableFrom(fieldType)) { try { col = (ManageableCollection)fieldType.newInstance(); } catch (Exception e) { throw new OJBRuntimeException("Cannot instantiate the default collection type "+fieldType.getName()+" of collection "+desc.getAttributeName()+" in type "+desc.getClassDescriptor().getClassNameOfObject()); } } else if (fieldType.isAssignableFrom(RemovalAwareCollection.class)) { col = new RemovalAwareCollection(); } else if (fieldType.isAssignableFrom(RemovalAwareList.class)) { col = new RemovalAwareList(); } else if (fieldType.isAssignableFrom(RemovalAwareSet.class)) { col = new RemovalAwareSet(); } else { throw new MetadataException("Cannot determine a default collection type for collection "+desc.getAttributeName()+" in type "+desc.getClassDescriptor().getClassNameOfObject()); } } else { try { col = (ManageableCollection)collectionClass.newInstance(); } catch (Exception e) { throw new OJBRuntimeException("Cannot instantiate the collection class "+collectionClass.getName()+" of collection "+desc.getAttributeName()+" in type "+desc.getClassDescriptor().getClassNameOfObject()); } } return col; }
java
{ "resource": "" }
q9778
HibernateLayer.setFeatureModel
train
@Api public void setFeatureModel(FeatureModel featureModel) throws LayerException { this.featureModel = featureModel; if (null != getLayerInfo()) { featureModel.setLayerInfo(getLayerInfo()); } filterService.registerFeatureModel(featureModel); }
java
{ "resource": "" }
q9779
HibernateLayer.update
train
public void update(Object feature) throws LayerException { Session session = getSessionFactory().getCurrentSession(); session.update(feature); }
java
{ "resource": "" }
q9780
HibernateLayer.enforceSrid
train
private void enforceSrid(Object feature) throws LayerException { Geometry geom = getFeatureModel().getGeometry(feature); if (null != geom) { geom.setSRID(srid); getFeatureModel().setGeometry(feature, geom); } }
java
{ "resource": "" }
q9781
HibernateLayer.getBoundsLocal
train
private Envelope getBoundsLocal(Filter filter) throws LayerException { try { Session session = getSessionFactory().getCurrentSession(); Criteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName()); CriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat); Criterion c = (Criterion) filter.accept(visitor, criteria); if (c != null) { criteria.add(c); } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List<?> features = criteria.list(); Envelope bounds = new Envelope(); for (Object f : features) { Envelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal(); if (!geomBounds.isNull()) { bounds.expandToInclude(geomBounds); } } return bounds; } catch (HibernateException he) { throw new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo() .getDataSourceName(), filter.toString()); } }
java
{ "resource": "" }
q9782
ThreadScopeContext.getBean
train
public Object getBean(String name) { Bean bean = beans.get(name); if (null == bean) { return null; } return bean.object; }
java
{ "resource": "" }
q9783
ThreadScopeContext.setBean
train
public void setBean(String name, Object object) { Bean bean = beans.get(name); if (null == bean) { bean = new Bean(); beans.put(name, bean); } bean.object = object; }
java
{ "resource": "" }
q9784
ThreadScopeContext.remove
train
public Object remove(String name) { Bean bean = beans.get(name); if (null != bean) { beans.remove(name); bean.destructionCallback.run(); return bean.object; } return null; }
java
{ "resource": "" }
q9785
ThreadScopeContext.registerDestructionCallback
train
public void registerDestructionCallback(String name, Runnable callback) { Bean bean = beans.get(name); if (null == bean) { bean = new Bean(); beans.put(name, bean); } bean.destructionCallback = callback; }
java
{ "resource": "" }
q9786
ThreadScopeContext.clear
train
public void clear() { for (Bean bean : beans.values()) { if (null != bean.destructionCallback) { bean.destructionCallback.run(); } } beans.clear(); }
java
{ "resource": "" }
q9787
WmsProxyController.parseLayerId
train
private String parseLayerId(HttpServletRequest request) { StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/"); String token = ""; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); } return token; }
java
{ "resource": "" }
q9788
WmsProxyController.getLayer
train
private WmsLayer getLayer(String layerId) { RasterLayer layer = configurationService.getRasterLayer(layerId); if (layer instanceof WmsLayer) { return (WmsLayer) layer; } return null; }
java
{ "resource": "" }
q9789
WmsProxyController.createErrorImage
train
private byte[] createErrorImage(int width, int height, Exception e) throws IOException { String error = e.getMessage(); if (null == error) { Writer result = new StringWriter(); PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); error = result.toString(); } BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g = (Graphics2D) image.getGraphics(); g.setColor(Color.RED); g.drawString(error, ERROR_MESSAGE_X, height / 2); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", out); out.flush(); byte[] result = out.toByteArray(); out.close(); return result; }
java
{ "resource": "" }
q9790
LoggingHelper.formatConnectionEstablishmentMessage
train
public static String formatConnectionEstablishmentMessage(final String connectionName, final String host, final String connectionReason) { return CON_ESTABLISHMENT_FORMAT.format(new Object[] { connectionName, host, connectionReason }); }
java
{ "resource": "" }
q9791
LoggingHelper.formatConnectionTerminationMessage
train
public static String formatConnectionTerminationMessage(final String connectionName, final String host, final String connectionReason, final String terminationReason) { return CON_TERMINATION_FORMAT.format(new Object[] { connectionName, host, connectionReason, terminationReason }); }
java
{ "resource": "" }
q9792
JdbcMetadataUtils.findPlatformFor
train
public String findPlatformFor(String jdbcSubProtocol, String jdbcDriver) { String platform = (String)jdbcSubProtocolToPlatform.get(jdbcSubProtocol); if (platform == null) { platform = (String)jdbcDriverToPlatform.get(jdbcDriver); } return platform; }
java
{ "resource": "" }
q9793
DataValidator.validate
train
public static void validate(final License license) { // A license should have a name if(license.getName() == null || license.getName().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("License name should not be empty!") .build()); } // A license should have a long name if(license.getLongName() == null || license.getLongName().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("License long name should not be empty!") .build()); } // If there is a regexp, it should compile if(license.getRegexp() != null && !license.getRegexp().isEmpty()){ try{ Pattern.compile(license.getRegexp()); } catch (PatternSyntaxException e){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("License regexp does not compile!").build()); } Pattern regex = Pattern.compile("[&%//]"); if(regex.matcher(license.getRegexp()).find()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("License regexp does not compile!").build()); } } }
java
{ "resource": "" }
q9794
DataValidator.validate
train
public static void validate(final Module module) { if (null == module) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Module cannot be null!") .build()); } if(module.getName() == null || module.getName().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Module name cannot be null or empty!") .build()); } if(module.getVersion()== null || module.getVersion().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Module version cannot be null or empty!") .build()); } // Check artifacts for(final Artifact artifact: DataUtils.getAllArtifacts(module)){ validate(artifact); } // Check dependencies for(final Dependency dependency: DataUtils.getAllDependencies(module)){ validate(dependency.getTarget()); } }
java
{ "resource": "" }
q9795
DataValidator.validate
train
public static void validate(final Organization organization) { if(organization.getName() == null || organization.getName().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Organization name cannot be null or empty!") .build()); } }
java
{ "resource": "" }
q9796
DataValidator.validate
train
public static void validate(final ArtifactQuery artifactQuery) { final Pattern invalidChars = Pattern.compile("[^A-Fa-f0-9]"); if(artifactQuery.getUser() == null || artifactQuery.getUser().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Mandatory field [user] missing") .build()); } if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Invalid [stage] value (supported 0 | 1)") .build()); } if(artifactQuery.getName() == null || artifactQuery.getName().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Mandatory field [name] missing, it should be the file name") .build()); } if(artifactQuery.getSha256() == null || artifactQuery.getSha256().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Mandatory field [sha256] missing") .build()); } if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Invalid file checksum value") .build()); } if(artifactQuery.getType() == null || artifactQuery.getType().isEmpty()){ throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Mandatory field [type] missing") .build()); } }
java
{ "resource": "" }
q9797
SequenceManagerNextValImpl.getUniqueLong
train
protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException { long result; // lookup sequence name String sequenceName = calculateSequenceName(field); try { result = buildNextSequence(field.getClassDescriptor(), sequenceName); } catch (Throwable e) { // maybe the sequence was not created try { log.info("Create DB sequence key '"+sequenceName+"'"); createSequence(field.getClassDescriptor(), sequenceName); } catch (Exception e1) { throw new SequenceManagerException( SystemUtils.LINE_SEPARATOR + "Could not grab next id, failed with " + SystemUtils.LINE_SEPARATOR + e.getMessage() + SystemUtils.LINE_SEPARATOR + "Creation of new sequence failed with " + SystemUtils.LINE_SEPARATOR + e1.getMessage() + SystemUtils.LINE_SEPARATOR , e1); } try { result = buildNextSequence(field.getClassDescriptor(), sequenceName); } catch (Throwable e1) { throw new SequenceManagerException("Could not grab next id, sequence seems to exist", e); } } return result; }
java
{ "resource": "" }
q9798
OjbExtent.provideStateManagers
train
protected Collection provideStateManagers(Collection pojos) { PersistenceCapable pc; int [] fieldNums; Iterator iter = pojos.iterator(); Collection result = new ArrayList(); while (iter.hasNext()) { // obtain a StateManager pc = (PersistenceCapable) iter.next(); Identity oid = new Identity(pc, broker); StateManagerInternal smi = pmi.getStateManager(oid, pc.getClass()); // fetch attributes into StateManager JDOClass jdoClass = Helper.getJDOClass(pc.getClass()); fieldNums = jdoClass.getManagedFieldNumbers(); FieldManager fm = new OjbFieldManager(pc, broker); smi.replaceFields(fieldNums, fm); smi.retrieve(); // get JDO PersistencecCapable instance from SM and add it to result collection Object instance = smi.getObject(); result.add(instance); } return result; }
java
{ "resource": "" }
q9799
ReflectiveObjectCopyStrategy.copy
train
public final Object copy(final Object toCopy, PersistenceBroker broker) { return clone(toCopy, IdentityMapFactory.getIdentityMap(), new HashMap()); }
java
{ "resource": "" }