code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
private static void loadFile(String filePath) { final Path path = FileSystems.getDefault().getPath(filePath); try { data.clear(); data.load(Files.newBufferedReader(path)); } catch(IOException e) { LOG.warn("Exception while loading " + path.toString(), e); } }
Loads the file content in the properties collection @param filePath The path of the file to be loaded
public static String getSerializedAttributes(final String prefix, final Properties attributeProperties) { final StringBuffer buf = new StringBuffer(); appendSerializedAttributes(buf, prefix, attributeProperties); return buf.toString(); }
Returns an XML-string with serialized configuration attributes. Used when serializing {@link org.apache.ojb.broker.metadata.AttributeContainer} attributes. @param prefix the line prefix (ie indent) or null for no prefix @param attributeProperties the properties object holding attributes to be serialized (null-safe) @return XML-string with serialized configuration attributes (never null)
public static void appendSerializedAttributes(final StringBuffer buf, final String prefix, final Properties attributeProperties) { if (attributeProperties != null) { final Enumeration keys = attributeProperties.keys(); while (keys.hasMoreElements()) { final String key = (String) keys.nextElement(); final String value = attributeProperties.getProperty( key ); if (prefix != null) { buf.append(prefix); } buf.append("<attribute attribute-name=\"").append(key); buf.append("\" attribute-value=\"" ).append(value); buf.append("\"/>"); buf.append(XML_EOL); } } }
Appends an XML-string with serialized configuration attributes to the specified buffer. Used when serializing {@link org.apache.ojb.broker.metadata.AttributeContainer} attributes. @param buf the string buffer to append to @param prefix the line prefix (ie indent) or null for no prefix @param attributeProperties the properties object holding attributes to be serialized (null-safe)
public void setValue(String fieldRefName, boolean returnedByProcedure) { this.fieldSource = SOURCE_FIELD; this.fieldRefName = fieldRefName; this.returnedByProcedure = returnedByProcedure; this.constantValue = null; // If the field reference is not valid, then disregard the value // of the returnedByProcedure argument. if (this.getFieldRef() == null) { this.returnedByProcedure = false; } // If the field reference is not valid, then disregard the value // of the returnedByProcedure argument. if (this.getFieldRef() == null) { this.returnedByProcedure = false; } }
Sets up this object to represent a value that is derived from a field in the corresponding class-descriptor. <p> If the value of <code>fieldRefName</code> is blank or refers to an invalid field reference, then the value of the corresponding argument will be set to null. In this case, {@link #getIsReturnedByProcedure} will be set to <code>false</code>, regardless of the value of the <code>returnedByProcedure</code> argument. @param fieldRefName the name of the field reference that provides the value of this argument. @param returnedByProcedure indicates that the value of the argument is returned by the procedure that is invoked.
public void setValue(String constantValue) { this.fieldSource = SOURCE_VALUE; this.fieldRefName = null; this.returnedByProcedure = false; this.constantValue = constantValue; }
Sets up this object to represent an argument that will be set to a constant value. @param constantValue the constant value.
public final int getJdbcType() { switch (this.fieldSource) { case SOURCE_FIELD : return this.getFieldRef().getJdbcType().getType(); case SOURCE_NULL : return java.sql.Types.NULL; case SOURCE_VALUE : return java.sql.Types.VARCHAR; default : return java.sql.Types.NULL; } }
Retrieve the jdbc type for the field descriptor that is related to this argument.
public String toXML() { String eol = System.getProperty("line.separator"); RepositoryTags tags = RepositoryTags.getInstance(); // The result String result = " "; switch (this.fieldSource) { case SOURCE_FIELD : result += " " + tags.getOpeningTagNonClosingById(RUNTIME_ARGUMENT); result += " " + tags.getAttribute(FIELD_REF, this.fieldRefName); result += " " + tags.getAttribute(RETURN, String.valueOf(this.returnedByProcedure)); result += "/>"; break; case SOURCE_VALUE : result += " " + tags.getOpeningTagNonClosingById(CONSTANT_ARGUMENT); result += " " + tags.getAttribute(VALUE, this.constantValue); result += "/>"; break; case SOURCE_NULL : result += " " + tags.getOpeningTagNonClosingById(RUNTIME_ARGUMENT); result += "/>"; break; default : break; } // Return the result. return (result + eol); }
/* @see XmlCapable#toXML()
private boolean isCacheable(PipelineContext context) throws GeomajasException { VectorLayer layer = context.get(PipelineCode.LAYER_KEY, VectorLayer.class); return !(layer instanceof VectorLayerLazyFeatureConversionSupport && ((VectorLayerLazyFeatureConversionSupport) layer).useLazyFeatureConversion()); }
Features are only cacheable when not converted lazily as lazy features are incomplete, it would put detached objects in the cache. @return true when features are not converted lazily
@Deprecated public List<Double> getResolutions() { List<Double> resolutions = new ArrayList<Double>(); for (ScaleInfo scale : getZoomLevels()) { resolutions.add(1. / scale.getPixelPerUnit()); } return resolutions; }
Get the list of supported resolutions for the layer. Each resolution is specified in map units per pixel. @return list of supported resolutions @deprecated use {@link #getZoomLevels()}
@Deprecated public void setResolutions(List<Double> resolutions) { getZoomLevels().clear(); for (Double resolution : resolutions) { getZoomLevels().add(new ScaleInfo(1. / resolution)); } }
Set the list of supported resolutions. Each resolution is specified in map units per pixel. @param resolutions resolutions @deprecated use {@link #setZoomLevels()}
public static void registerTinyTypes(Class<?> head, Class<?>... tail) { final Set<HeaderDelegateProvider> systemRegisteredHeaderProviders = stealAcquireRefToHeaderDelegateProviders(); register(head, systemRegisteredHeaderProviders); for (Class<?> tt : tail) { register(tt, systemRegisteredHeaderProviders); } }
Registers Jersey HeaderDelegateProviders for the specified TinyTypes. @param head a TinyType @param tail other TinyTypes @throws IllegalArgumentException when a non-TinyType is given
private void readSingleDataFile(Task task, DdlUtilsDataHandling handling, File dataFile, Writer output) { if (!dataFile.exists()) { task.log("Could not find data file "+dataFile.getAbsolutePath(), Project.MSG_ERR); } else if (!dataFile.isFile()) { task.log("Path "+dataFile.getAbsolutePath()+" does not denote a data file", Project.MSG_ERR); } else if (!dataFile.canRead()) { task.log("Could not read data file "+dataFile.getAbsolutePath(), Project.MSG_ERR); } else { try { FileReader reader = new FileReader(dataFile.getAbsolutePath()); handling.getInsertDataSql(reader, output); output.flush(); output.close(); task.log("Read data file "+dataFile.getAbsolutePath(), Project.MSG_INFO); } catch (Exception ex) { if (isFailOnError()) { throw new BuildException("Could not read data file "+dataFile.getAbsolutePath(), ex); } } } }
Reads a single data file. @param task The parent task @param reader The data reader @param schemaFile The schema file
@POST public Response postArtifact(@Auth final DbCredential credential, final Artifact artifact){ if(!credential.getRoles().contains(AvailableRoles.DATA_UPDATER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } LOG.info("Got a post Artifact request [" + artifact.getGavc() + "]"); // setting default origin to maven if(artifact.getOrigin() == null || artifact.getOrigin().isEmpty()){ artifact.setOrigin("maven"); } // Checks if the data is corrupted DataValidator.validatePostArtifact(artifact); // Store the Artifact final ArtifactHandler artifactHandler = getArtifactHandler(); // checking artifact with same SHA256 final DbArtifact artifactWithSameSHA = artifactHandler.getArtifactUsingSHA256(artifact.getSha256()); if(artifactWithSameSHA != null){ throw new WebApplicationException(Response.serverError().status(HttpStatus.CONFLICT_409) .entity("Artifact with same checksum already exists.").build()); } // checking artifact with same SHA256 DbArtifact artifactWithSameGAVC = null; try{ artifactWithSameGAVC = artifactHandler.getArtifact(artifact.getGavc()); }catch(WebApplicationException e){ LOG.info("Validating result for artifact GAVC: No matching artifact found " + e); } if(artifactWithSameGAVC != null){ throw new WebApplicationException(Response.serverError().status(HttpStatus.CONFLICT_409) .entity("Artifact with same GAVC already exists.").build()); } artifact.setCreatedDateTime(new Date()); final DbArtifact dbArtifact = getModelMapper().getDbArtifact(artifact); artifactHandler.store(dbArtifact); // Add the licenses for(final String license: artifact.getLicenses()){ artifactHandler.addLicense(dbArtifact.getGavc(), license); } return Response.ok().status(HttpStatus.CREATED_201).build(); }
Handle artifact posts when the server got a request POST <grapes_url>/artifact & MIME that contains the artifact. @param credential DbCredential @param artifact The artifact to add to Grapes database @return Response An acknowledgment:<br/>- 400 if the artifact is MIME is malformed<br/>- 500 if internal error<br/>- 201 if ok
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path(ServerAPI.GET_GAVCS) public Response getGavcs(@Context final UriInfo uriInfo){ LOG.info("Got a get GAVCs request"); final ListView view = new ListView("GAVCS view", "gavc"); final FiltersHolder filters = new FiltersHolder(); filters.init(uriInfo.getQueryParameters()); final List<String> gavcs = getArtifactHandler().getArtifactGavcs(filters); Collections.sort(gavcs); view.addAll(gavcs); return Response.ok(view).build(); }
Return a list of gavc, stored in Grapes, regarding the filters passed in the query parameters. This method is call via GET <grapes_url>/artifact/gavcs @return Response A list (in HTML or JSON) of gavc
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path(ServerAPI.GET_GROUPIDS) public Response getGroupIds(@Context final UriInfo uriInfo){ LOG.info("Got a get groupIds request [" + uriInfo.getPath() + "]"); final ListView view = new ListView("GroupIds view", "groupId"); final FiltersHolder filters = new FiltersHolder(); filters.init(uriInfo.getQueryParameters()); final List<String> groupIds = getArtifactHandler().getArtifactGroupIds(filters); Collections.sort(groupIds); view.addAll(groupIds); return Response.ok(view).build(); }
Return a list of groupIds, stored in Grapes. This method is call via GET <grapes_url>/artifact/groupids @return Response A list (in HTML or JSON) of gavc
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path("/{gavc}" + ServerAPI.GET_VERSIONS) public Response getVersions(@PathParam("gavc") final String gavc){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get artifact versions request [%s]", gavc)); } final ListView view = new ListView("Versions View", "version"); final List<String> versions = getArtifactHandler().getArtifactVersions(gavc); Collections.sort(versions); view.addAll(versions); return Response.ok(view).build(); }
Returns the list of available versions of an artifact This method is call via GET <grapes_url>/artifact/<gavc>/versions @param gavc String @return Response a list of versions in JSON or in HTML
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/{gavc}" + ServerAPI.GET_LAST_VERSION) public Response getLastVersion(@PathParam("gavc") final String gavc){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get artifact last version request. [%s]", gavc)); } final String lastVersion = getArtifactHandler().getArtifactLastVersion(gavc); return Response.ok(lastVersion).build(); }
Returns the list of available versions of an artifact This method is call via GET <grapes_url>/artifact/<gavc>/versions @param gavc String @return Response String version in JSON
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path("/{gavc}") public Response get(@PathParam("gavc") final String gavc){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get artifact request [%s]", gavc)); } final ArtifactView view = new ArtifactView(); final DbArtifact dbArtifact = getArtifactHandler().getArtifact(gavc); view.setShouldNotBeUse(dbArtifact.getDoNotUse()); final Artifact artifact = getModelMapper().getArtifact(dbArtifact); view.setArtifact(artifact); final DbOrganization dbOrganization = getArtifactHandler().getOrganization(dbArtifact); if(dbOrganization != null){ final Organization organization = getModelMapper().getOrganization(dbOrganization); view.setOrganization(organization); } DbComment dbComment = getCommentHandler().getLatestComment(gavc, DbArtifact.class.getSimpleName()); if(dbComment != null) { final Comment comment = getModelMapper().getComment(dbComment); view.setComment(comment); } return Response.ok(view).build(); }
Return an Artifact regarding its gavc. This method is call via GET <grapes_url>/artifact/<gavc> @param gavc String @return Response An artifact in HTML or JSON
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/isPromoted") public Response isPromoted(@QueryParam("user") final String user, @QueryParam("stage") final int stage, @QueryParam("name") final String filename, @QueryParam("sha256") final String sha256, @QueryParam("type") final String type, @QueryParam("location") final String location) { LOG.info("Got a get artifact promotion request"); // Validating request final ArtifactQuery query = new ArtifactQuery(user, stage, filename, sha256, type, location); DataValidator.validate(query); if(LOG.isInfoEnabled()) { LOG.info(String.format("Artifact validation request. Details [%s]", query.toString())); } // Validating type of request file final GrapesServerConfig cfg = getConfig(); final List<String> validatedTypes = cfg.getExternalValidatedTypes(); if(!validatedTypes.contains(type)) { return Response.ok(buildArtifactNotSupportedResponse(validatedTypes)).status(HttpStatus.UNPROCESSABLE_ENTITY_422).build(); } final DbArtifact dbArtifact = getArtifactHandler().getArtifactUsingSHA256(sha256); // // No such artifact was identified in the underlying data structure // if(dbArtifact == null) { final String jiraLink = buildArtifactNotificationJiraLink(query); sender.send(cfg.getArtifactNotificationRecipients(), buildArtifactValidationSubject(filename), buildArtifactValidationBody(query, "N/A")); // No Jenkins job if not artifact return Response.ok(buildArtifactNotKnown(query, jiraLink)).status(HttpStatus.NOT_FOUND_404).build(); } final ArtifactPromotionStatus promotionStatus = new ArtifactPromotionStatus(); promotionStatus.setPromoted(dbArtifact.isPromoted()); // If artifact is promoted if(dbArtifact.isPromoted()){ promotionStatus.setMessage(Messages.get(ARTIFACT_VALIDATION_IS_PROMOTED)); return Response.ok(promotionStatus).build(); } else { final String jenkinsJobInfo = getArtifactHandler().getModuleJenkinsJobInfo(dbArtifact); promotionStatus.setMessage(buildArtifactNotPromotedYetResponse(query, jenkinsJobInfo.isEmpty() ? "<i>(Link to Jenkins job not found)</i>" : jenkinsJobInfo)); // If someone just did not promote the artifact, don't spam the support with more emails } return Response.ok(promotionStatus).build(); }
Return promotion status of an Artifact regarding artifactQuery from third party. This method is call via POST <grapes_url>/artifact/isPromoted @param user The user name in the external system @param stage An integer value depending on the stage in the external system @param filename The name of the file needing validation @param sha256 The file checksum value @param type The type of the file as defined in the external system @param location The location of the binary file @return Response A response message in case the request is invalid or or an object containing the promotional status and additional message providing human readable information
@POST @Path("/{gavc}" + ServerAPI.GET_DOWNLOAD_URL) public Response updateDownloadUrl(@Auth final DbCredential credential, @PathParam("gavc") final String gavc, @QueryParam(ServerAPI.URL_PARAM) final String downLoadUrl){ if(!credential.getRoles().contains(AvailableRoles.DATA_UPDATER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } if(LOG.isInfoEnabled()) { LOG.info(String.format("Got an update downloadUrl request [%s] [%s]", gavc, downLoadUrl)); } if(gavc == null || downLoadUrl == null){ return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build(); } getArtifactHandler().updateDownLoadUrl(gavc, downLoadUrl); return Response.ok("done").build(); }
Update an artifact download url. This method is call via GET <grapes_url>/artifact/<gavc>/downloadurl?url=<targetUrl> @param credential DbCredential @param gavc String @param downLoadUrl String @return Response
@POST @Path("/{gavc}" + ServerAPI.GET_PROVIDER) public Response updateProvider(@Auth final DbCredential credential, @PathParam("gavc") final String gavc, @QueryParam(ServerAPI.PROVIDER_PARAM) final String provider){ if(!credential.getRoles().contains(AvailableRoles.DATA_UPDATER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } if(LOG.isInfoEnabled()) { LOG.info(String.format("Got an update downloadUrl request [%s] [%s]", gavc, provider)); } if(gavc == null || provider == null){ return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build(); } getArtifactHandler().updateProvider(gavc, provider); return Response.ok("done").build(); }
Update an artifact download url. This method is call via GET <grapes_url>/artifact/<gavc>/downloadurl?url=<targetUrl>
@DELETE @Path("/{gavc}") public Response delete(@Auth final DbCredential credential, @PathParam("gavc") final String gavc){ if(!credential.getRoles().contains(AvailableRoles.DATA_DELETER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a delete artifact request [%s]", gavc)); } getArtifactHandler().deleteArtifact(gavc); return Response.ok().build(); }
Delete an Artifact regarding its gavc. This method is call via DELETE <grapes_url>/artifact/<gavc> @param credential DbCredential @param gavc String @return Response
@POST @Path("/{gavc}" + ServerAPI.SET_DO_NOT_USE) public Response postDoNotUse(@Auth final DbCredential credential, @PathParam("gavc") final String gavc, @QueryParam(ServerAPI.DO_NOT_USE) final BooleanParam doNotUse, final String commentText){ if(!credential.getRoles().contains(AvailableRoles.ARTIFACT_CHECKER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a add \"DO_NOT_USE\" request [%s]", gavc)); } // Set comment for artifact if available getCommentHandler().store(gavc, doNotUse.get() ? "mark as DO_NOT_USE" : "cleared DO_NOT_USE flag", commentText, credential, DbArtifact.class.getSimpleName()); getArtifactHandler().updateDoNotUse(gavc, doNotUse.get()); return Response.ok("done").build(); }
Add "DO_NOT_USE" flag to an artifact @param credential DbCredential @param gavc String @param doNotUse boolean @return Response
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/{gavc}" + ServerAPI.SET_DO_NOT_USE) public Response getDoNotUse(@PathParam("gavc") final String gavc){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get doNotUse artifact request [%s]", gavc)); } final DbArtifact artifact = getArtifactHandler().getArtifact(gavc); return Response.ok(artifact.getDoNotUse()).build(); }
Return true if the targeted artifact is flagged with "DO_NOT_USE". This method is call via GET <grapes_url>/artifact/<gavc>/donotuse @param gavc String @return Response
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path("/{gavc}" + ServerAPI.GET_ANCESTORS) public Response getAncestors(@PathParam("gavc") final String gavc, @Context final UriInfo uriInfo){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get artifact request [%s]", gavc)); } final FiltersHolder filters = new FiltersHolder(); filters.getDecorator().setShowLicenses(false); filters.init(uriInfo.getQueryParameters()); final AncestorsView view = new AncestorsView("Ancestor List Of " + gavc, filters.getDecorator(), getLicenseHandler(), getModelMapper()); final List<DbModule> dbAncestors = getArtifactHandler().getAncestors(gavc, filters); final Artifact artifact = DataUtils.createArtifact(gavc); for(final DbModule dbAncestor : dbAncestors){ final Module ancestor = getModelMapper().getModule(dbAncestor); view.addAncestor(ancestor, artifact); } return Response.ok(view).build(); }
Return the list of ancestor of an artifact. This method is call via GET <grapes_url>/artifact/<gavc>/ancestors @param gavc String @param uriInfo UriInfo @return Response A list of ancestor in HTML or JSON
@GET @Produces({MediaType.APPLICATION_JSON}) @Path("/{gavc}" + ServerAPI.GET_LICENSES) public Response getLicenses(@PathParam("gavc") final String gavc, @Context final UriInfo uriInfo){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get artifact licenses request [%s]", gavc)); } final LicenseListView view = new LicenseListView("Licenses of " + gavc); final FiltersHolder filters = new FiltersHolder(); filters.init(uriInfo.getQueryParameters()); final List<DbLicense> dbLicenses = getArtifactHandler().getArtifactLicenses(gavc,filters); for(final DbLicense license: dbLicenses){ view.add(getModelMapper().getLicense(license)); } return Response.ok(view).build(); }
Returns the list of licenses used by an artifact. This method is call via GET <grapes_url>/artifact/{gavc}/licenses @param gavc The artifact gavc identification @return Response A list of dependencies in JSON
@POST @Path("/{gavc}" + ServerAPI.GET_LICENSES) public Response addLicense(@Auth final DbCredential credential, @PathParam("gavc") final String gavc, @QueryParam(ServerAPI.LICENSE_ID_PARAM) final String licenseId){ if(!credential.getRoles().contains(AvailableRoles.DATA_UPDATER) && !credential.getRoles().contains(AvailableRoles.LICENSE_SETTER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a add license request [%s]", gavc)); } if(licenseId == null){ return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build(); } getArtifactHandler().addLicenseToArtifact(gavc, licenseId); cacheUtils.clear(CacheName.PROMOTION_REPORTS); return Response.ok("done").build(); }
Add a license to an artifact @param credential DbCredential @param gavc String @param licenseId String @return Response
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path("/{gavc}" + ServerAPI.GET_MODULE) public Response getModule(@PathParam("gavc") final String gavc, @Context final UriInfo uriInfo){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get artifact's module request [%s]", gavc)); } final ArtifactHandler artifactHandler = getArtifactHandler(); final DbArtifact artifact = artifactHandler.getArtifact(gavc); final DbModule module = artifactHandler.getModule(artifact); if(module == null){ return Response.noContent().build(); } final ModuleView view = new ModuleView(); view.setModule(getModelMapper().getModule(module)); view.setOrganization(module.getOrganization()); return Response.ok(view).build(); }
Returns the Module of an artifact. This method is call via GET <grapes_url>/artifact/{gavc}/module @param gavc String @return Response a module in HTML or JSON
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path("/{gavc}" + ServerAPI.GET_ORGANIZATION) public Response getOrganization(@PathParam("gavc") final String gavc, @Context final UriInfo uriInfo){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get artifact's organization request [%s]", gavc)); } final ArtifactHandler artifactHandler = getArtifactHandler(); final DbArtifact artifact = artifactHandler.getArtifact(gavc); final DbModule module = artifactHandler.getModule(artifact); if(module == null || module.getOrganization().isEmpty()) { return Response.noContent().build(); } final DbOrganization organization = getOrganizationHandler().getOrganization(module.getOrganization()); final OrganizationView view = new OrganizationView(getModelMapper().getOrganization(organization)); return Response.ok(view).build(); }
Returns the Organization of an artifact. This method is call via GET <grapes_url>/artifact/{gavc}/module @param gavc String @return Response a module in HTML or JSON
@GET @Produces(MediaType.APPLICATION_JSON) @Path(ServerAPI.GET_ALL) public Response getAll(@Context final UriInfo uriInfo){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get all artifact request [%s]", uriInfo.getPath())); } final FiltersHolder filters = new FiltersHolder(); filters.init(uriInfo.getQueryParameters()); if(filters.getArtifactFieldsFilters().size() == 0) { LOG.warn("No artifact filtering criteria. Returning BAD_REQUEST"); throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Please provide at least one artifact filtering criteria").build()); } final List<Artifact> artifacts = new ArrayList<>(); final List<DbArtifact> dbArtifacts = getArtifactHandler().getArtifacts(filters); for(final DbArtifact dbArtifact: dbArtifacts){ artifacts.add(getModelMapper().getArtifact(dbArtifact)); } return Response.ok(artifacts).build(); }
Return all the artifacts that matches the filters. This method is call via GET <grapes_url>/artifact/<gavc> Following filters can be used: artifactId, classifier, groupId, hasLicense, licenseId, type, uriInfo, version @param uriInfo UriInfo @return Response An artifact in HTML or JSON
private String forceAscii(StringBuilder source) { int length = source.length(); StringBuilder res = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = source.charAt(i); if ((c >= SAFE_ASCII_LOWER && c <= SAFE_ASCII_UPPER) || Character.isSpaceChar(c)) { res.append(c); } else { res.append("\\u"); String scode = Integer.toHexString(i); while (scode.length() < 4) { scode = "0" + scode; } res.append(scode); } } return res.toString(); }
Convert StringBuilder output to a string while escaping characters. This prevents outputting control characters and unreadable characters. It seems both cause problems for certain editors. <p/> The ASCII characters (excluding controls characters) are copied to the result as is, other characters are escaped using \\uxxxx notation. Note that string comparisons on this result may be inaccurate as both (Java strings) "\\u1234" and "\u1234" will produce the same converted string! @param source StringBuilder to convert @return String representation using only ASCI characters
public void apply() { String in = readLineWithMessage("Edit Product with id:"); int id = Integer.parseInt(in); // We don't have a reference to the selected Product. // So first we have to lookup the object, // we do this by a query by example (QBE): // 1. build an example object with matching primary key values: Product example = new Product(); example.setId(id); // 2. build a QueryByIdentity from this sample instance: Query query = new QueryByIdentity(example); try { // 3. start broker transaction broker.beginTransaction(); // 4. lookup the product specified by the QBE Product toBeEdited = (Product) broker.getObjectByQuery(query); // 5. edit the existing entry System.out.println("please edit the product entry"); in = readLineWithMessage("enter name (was " + toBeEdited.getName() + "):"); toBeEdited.setName(in); in = readLineWithMessage("enter price (was " + toBeEdited.getPrice() + "):"); toBeEdited.setPrice(Double.parseDouble(in)); in = readLineWithMessage("enter available stock (was " + toBeEdited.getStock() + "):"); toBeEdited.setStock(Integer.parseInt(in)); // 6. now ask broker to store the edited object broker.store(toBeEdited); // 7. commit transaction broker.commitTransaction(); } catch (Throwable t) { // rollback in case of errors broker.abortTransaction(); t.printStackTrace(); } }
perform this use case
public static String generateQuery(final Map<String,Object> params){ final StringBuilder sb = new StringBuilder(); boolean newEntry = false; sb.append("{"); for(final Entry<String,Object> param: params.entrySet()){ if(newEntry){ sb.append(", "); } sb.append(param.getKey()); sb.append(": "); sb.append(getParam(param.getValue())); newEntry = true; } sb.append("}"); return sb.toString(); }
Generate a Jongo query regarding a set of parameters. @param params Map<queryKey, queryValue> of query parameters @return String
public static String generateQuery(final String key, final Object value) { final Map<String, Object> params = new HashMap<>(); params.put(key, value); return generateQuery(params); }
Generate a Jongo query with provided the parameter. @param key @param value @return String
private static Object getParam(final Object param) { final StringBuilder sb = new StringBuilder(); if(param instanceof String){ sb.append("'"); sb.append((String)param); sb.append("'"); } else if(param instanceof Boolean){ sb.append(String.valueOf((Boolean)param)); } else if(param instanceof Integer){ sb.append(String.valueOf((Integer)param)); } else if(param instanceof DBRegExp){ sb.append('/'); sb.append(((DBRegExp) param).toString()); sb.append('/'); } return sb.toString(); }
Handle the serialization of String, Integer and boolean parameters. @param param to serialize @return Object
protected ObjectCacheDescriptor searchInClassDescriptor(Class targetClass) { return targetClass != null ? broker.getClassDescriptor(targetClass).getObjectCacheDescriptor() : null; }
Try to lookup {@link ObjectCacheDescriptor} in {@link org.apache.ojb.broker.metadata.ClassDescriptor}. @param targetClass @return Returns the found {@link ObjectCacheDescriptor} or <code>null</code> if none was found.
public static PathInfo splitPath(String aPath) { String prefix = null; String suffix = null; String colName = aPath; if (aPath == null) { return new PathInfo(null, null, null, null); } // ignore leading ( and trailing ) ie: sum(avg(col1)) int braceBegin = aPath.lastIndexOf("("); int braceEnd = aPath.indexOf(")"); int opPos = StringUtils.indexOfAny(aPath, "+-/*"); if (braceBegin >= 0 && braceEnd >= 0 && braceEnd > braceBegin) { int colBegin; int colEnd; String betweenBraces; betweenBraces = aPath.substring(braceBegin + 1, braceEnd).trim(); // look for ie 'distinct name' colBegin = betweenBraces.indexOf(" "); // look for multiarg function like to_char(col,'format_mask') colEnd = betweenBraces.indexOf(","); colEnd = colEnd > 0 ? colEnd : betweenBraces.length(); prefix = aPath.substring(0, braceBegin + 1) + betweenBraces.substring(0, colBegin + 1); colName = betweenBraces.substring(colBegin + 1, colEnd); suffix = betweenBraces.substring(colEnd) + aPath.substring(braceEnd); } else if (opPos >= 0) { colName = aPath.substring(0, opPos).trim(); suffix = aPath.substring(opPos); } return new PathInfo(aPath, prefix, colName.trim(), suffix); }
Split a path into column , prefix and suffix, the prefix contains all info up to the column <br> ie: avg(amount) -> amount , avg( , )<br> ie: sum (accounts.amount) as theSum -> accounts.amount , sum( , ) as theSum <br> ie: count( distinct id ) as bla -> id , count(distinct , ) as bla <br> Supports simple expressions ie: price * 1.05 TODO: cannot resolve multiple attributes in expression ie: price - bonus @param aPath @return PathInfo
public static String getOjbClassName(ResultSet rs) { try { return rs.getString(OJB_CLASS_COLUMN); } catch (SQLException e) { return null; } }
Returns the name of the class to be instantiated. @param rs the Resultset @return null if the column is not available
public static LockStrategy getStrategyFor(Object obj) { int isolationLevel = getIsolationLevel(obj); switch (isolationLevel) { case IsolationLevels.IL_READ_UNCOMMITTED: return readUncommitedStrategy; case IsolationLevels.IL_READ_COMMITTED: return readCommitedStrategy; case IsolationLevels.IL_REPEATABLE_READ: return readRepeatableStrategy; case IsolationLevels.IL_SERIALIZABLE: return serializableStrategy; case IsolationLevels.IL_OPTIMISTIC: return noopStrategy; case IsolationLevels.IL_NONE: return noopStrategy; default: return readUncommitedStrategy; } }
obtains a LockStrategy for Object obj. The Strategy to be used is selected by evaluating the ClassDescriptor of obj.getClass(). @return LockStrategy
public static int getIsolationLevel(Object obj) { Class c = ProxyHelper.getRealClass(obj); int isolationLevel = IsolationLevels.IL_READ_UNCOMMITTED; try { ClassDescriptor cld = TxManagerFactory.instance().getCurrentTransaction().getBroker().getClassDescriptor(c); isolationLevel = cld.getIsolationLevel(); } catch (PersistenceBrokerException e) { LoggerFactory.getDefaultLogger().error("[LockStrategyFactory] Can't detect locking isolation level", e); } return isolationLevel; }
determines the isolationlevel of class c by evaluating the ClassDescriptor of obj.getClass(). @return int the isolationlevel
public void setOjbQuery(org.apache.ojb.broker.query.Query ojbQuery) { this.ojbQuery = ojbQuery; }
Sets the ojbQuery, needed only as long we don't support the soda constraint stuff. @param ojbQuery The ojbQuery to set
@POST public Response postOrganization(@Auth final DbCredential credential, final Organization organization){ if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } LOG.info("Got a post organization request."); // Checks if the data is corrupted DataValidator.validate(organization); final DbOrganization dbOrganization = getModelMapper().getDbOrganization(organization); getOrganizationHandler().store(dbOrganization); return Response.ok().status(HttpStatus.CREATED_201).build(); }
Handle organization posts when the server got a request POST <dm_url>/organization & MIME that contains an organization. @param organization The organization to add to Grapes database @return Response An acknowledgment:<br/>- 400 if the artifact is MIME is malformed<br/>- 500 if internal error<br/>- 201 if ok
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path(ServerAPI.GET_NAMES) public Response getNames(){ LOG.info("Got a get organization names request."); final ListView view = new ListView("Organization Ids list", "Organizations"); final List<String> names = getOrganizationHandler().getOrganizationNames(); view.addAll(names); return Response.ok(view).build(); }
Return the list of available organization name. This method is call via GET <dm_url>/organization/names @return Response A list of organization name in HTML or JSON
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path("/{name}") public Response get(@PathParam("name") final String name){ LOG.info("Got a get organization request."); final DbOrganization dbOrganization = getOrganizationHandler().getOrganization(name); final Organization organization = getModelMapper().getOrganization(dbOrganization); final OrganizationView view = new OrganizationView(organization); return Response.ok(view).build(); }
Returns an organization This method is call via GET <dm_url>/organization/<name> @param name String @return Response An Organization in HTML or JSON
@DELETE @Path("/{name}") public Response delete(@Auth final DbCredential credential, @PathParam("name") final String name){ if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_DELETER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } LOG.info("Got a delete organization request."); getOrganizationHandler().deleteOrganization(name); return Response.ok("done").build(); }
Delete an organization This method is call via DELETE <dm_url>/organization/<name> @param name String Organization name @return Response
@GET @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON}) @Path("/{name}" + ServerAPI.GET_CORPORATE_GROUPIDS) public Response getCorporateGroupIdPrefix(@PathParam("name") final String organizationId){ LOG.info("Got a get corporate groupId prefix request for organization " + organizationId +"."); final ListView view = new ListView("Organization " + organizationId, "Corporate GroupId Prefix"); final List<String> corporateGroupIds = getOrganizationHandler().getCorporateGroupIds(organizationId); view.addAll(corporateGroupIds); return Response.ok(view).build(); }
Return the list of corporate GroupId prefix configured for an organization. @param organizationId String Organization name @return Response A list of corporate groupId prefix in HTML or JSON
@POST @Path("/{name}" + ServerAPI.GET_CORPORATE_GROUPIDS) public Response addCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam("name") final String organizationId, final String corporateGroupId){ LOG.info("Got an add a corporate groupId prefix request for organization " + organizationId +"."); if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } if(corporateGroupId == null || corporateGroupId.isEmpty()){ LOG.error("No corporate GroupId to add!"); throw new WebApplicationException(Response.serverError().status(HttpStatus.BAD_REQUEST_400) .entity("CorporateGroupId to add should be in the query content.").build()); } getOrganizationHandler().addCorporateGroupId(organizationId, corporateGroupId); return Response.ok().status(HttpStatus.CREATED_201).build(); }
Add a new Corporate GroupId to an organization. @param credential DbCredential @param organizationId String Organization name @param corporateGroupId String @return Response
@DELETE @Path("/{name}" + ServerAPI.GET_CORPORATE_GROUPIDS) public Response removeCorporateGroupIdPrefix(@Auth final DbCredential credential, @PathParam("name") final String organizationId, final String corporateGroupId){ LOG.info("Got an remove a corporate groupId prefix request for organization " + organizationId +"."); if(!credential.getRoles().contains(DbCredential.AvailableRoles.DATA_UPDATER)){ throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } if(corporateGroupId == null || corporateGroupId.isEmpty()){ LOG.error("No corporate GroupId to remove!"); return Response.serverError().status(HttpStatus.BAD_REQUEST_400).build(); } getOrganizationHandler().removeCorporateGroupId(organizationId, corporateGroupId); return Response.ok("done").build(); }
Remove an existing Corporate GroupId from an organization. @return Response
protected Object getObjectFromResultSet() throws PersistenceBrokerException { Object[] result = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { try { int jdbcType = rsMetaData.getColumnType(i + 1); Object item = JdbcTypesHelper.getObjectFromColumn(getRsAndStmt().m_rs, new Integer(jdbcType), i + 1); result[i] = item; } catch (SQLException e) { throw new PersistenceBrokerException(e); } } return result; }
returns an Object[] representing the columns of the current ResultSet row. There is no OJB object materialization, Proxy generation etc. involved to maximize performance.
@SuppressWarnings("unchecked") public CommandResponse execute(String commandName, CommandRequest request, String userToken, String locale) { String id = Long.toString(++commandCount); // NOTE indicative, this is not (fully) thread safe or cluster aware log.info(id + MSG_START + commandName + " for user token " + userToken + " in locale " + locale); if (log.isTraceEnabled()) { log.trace(id + MSG_START + commandName + " request " + request); } long begin = System.currentTimeMillis(); CommandResponse response; String previousToken = securityContext.getToken(); // for null token we always need to *try* as otherwise login would never be possible boolean tokenIdentical = null != userToken && userToken.equals(previousToken); try { if (!tokenIdentical) { // need to change security context if (!securityManager.createSecurityContext(userToken)) { // not authorized response = new CommandResponse(); response.setId(id); response.getErrors().add( new GeomajasSecurityException(ExceptionCode.CREDENTIALS_MISSING_OR_INVALID, userToken)); serializeExceptions(response, "", locale, id); response.setExecutionTime(System.currentTimeMillis() - begin); return response; } } // check access rights for the command if (securityContext.isCommandAuthorized(commandName)) { Command command = null; try { command = applicationContext.getBean(commandName, Command.class); } catch (BeansException be) { log.debug(id + MSG_START + commandName + ", could not create command bean", be); } if (null != command) { response = command.getEmptyCommandResponse(); response.setId(id); try { command.execute(request, response); } catch (Throwable throwable) { //NOPMD log.debug(id + MSG_START + commandName + ", error executing command", throwable); response.getErrors().add(throwable); serializeExceptions(response, commandName, locale, id); } } else { response = new CommandResponse(); response.setId(id); response.getErrors().add(new GeomajasException(ExceptionCode.COMMAND_NOT_FOUND, commandName)); serializeExceptions(response, commandName, locale, id); } } else { // not authorized response = new CommandResponse(); response.setId(id); response.getErrors().add( new GeomajasSecurityException(ExceptionCode.COMMAND_ACCESS_DENIED, commandName, securityContext .getUserId())); serializeExceptions(response, commandName, locale, id); } long executionTime = System.currentTimeMillis() - begin; response.setExecutionTime(executionTime); if (log.isDebugEnabled()) { log.debug(id + MSG_START + commandName + " done in " + executionTime + "ms"); } if (log.isTraceEnabled()) { log.trace(id + MSG_START + commandName + " response " + response); } return response; } finally { if (!tokenIdentical) { // clear security context securityManager.clearSecurityContext(); } } }
General command execution function. <p/> The security context is built for the authentication token. The security context is cleared again at the end of processing if the security context was changed. @param commandName name of command to execute @param request {@link CommandRequest} object for the command (if any) @param userToken token to identify user @param locale which should be used for the error messages in the response @return {@link CommandResponse} command response
private String getErrorMessage(final Throwable throwable, final Locale locale) { String message; if (!(throwable instanceof GeomajasException)) { message = throwable.getMessage(); } else { message = ((GeomajasException) throwable).getMessage(locale); } if (null == message || 0 == message.length()) { message = throwable.getClass().getName(); } return message; }
Get localized error message for a {@link Throwable}. @param throwable throwable to get message for @param locale locale to use for message @return exception message
private InternalFeature convertFeature(Object feature, Geometry geometry, VectorLayer layer, CrsTransform transformation, List<StyleFilter> styles, LabelStyleInfo labelStyle, int featureIncludes) throws GeomajasException { FeatureModel featureModel = layer.getFeatureModel(); InternalFeature res = new InternalFeatureImpl(); res.setId(featureModel.getId(feature)); res.setLayer(layer); res.setGeometry(geometry); // in layer coordinate space for security checks res = attributeService.getAttributes(layer, res, feature); // includes security checks if (null != res) { // add and clear data according to the feature includes // unfortunately the data needs to be there for the security tests and can only be removed later if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_LABEL) != 0) { // value expression takes preference over attribute name String valueExpression = labelStyle.getLabelValueExpression(); if (valueExpression != null) { res.setLabel(featureExpressionService.evaluate(valueExpression, res).toString()); } else { // must have an attribute name ! String labelAttr = labelStyle.getLabelAttributeName(); if (LabelStyleInfo.ATTRIBUTE_NAME_ID.equalsIgnoreCase(labelAttr)) { res.setLabel(featureModel.getId(feature)); } else { Attribute<?> attribute = res.getAttributes().get(labelAttr); if (null != attribute && null != attribute.getValue()) { res.setLabel(attribute.getValue().toString()); } } } } // If allowed, add the geometry (transformed!) to the InternalFeature: if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_GEOMETRY) != 0) { Geometry transformed; if (null != transformation) { transformed = geoService.transform(geometry, transformation); } else { transformed = geometry; } res.setGeometry(transformed); } else { res.setGeometry(null); } // If allowed, add the style definition to the InternalFeature: if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_STYLE) != 0) { // We calculate the style on the (almost complete) internal feature to allow synthetic attributes. res.setStyleDefinition(findStyleFilter(res, styles).getStyleDefinition()); } // If allowed, add the attributes to the InternalFeature: if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES) == 0) { res.setAttributes(null); } } return res; }
Convert the generic feature object (as obtained from the layer model) into a {@link InternalFeature}, with requested data. Part may be lazy loaded. @param feature A feature object that comes directly from the {@link VectorLayer} @param geometry geometry of the feature, passed in as needed in surrounding code to calc bounding box @param layer vector layer for the feature @param transformation transformation to apply to the geometry @param styles style filters to apply @param labelStyle label style @param featureIncludes aspects to include in features @return actual feature @throws GeomajasException oops
private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) { for (StyleFilter styleFilter : styles) { if (styleFilter.getFilter().evaluate(feature)) { return styleFilter; } } return new StyleFilterImpl(); }
Find the style filter that must be applied to this feature. @param feature feature to find the style for @param styles style filters to select from @return a style filter
public final void fireFileRollEvent(final FileRollEvent fileRollEvent) { final Object[] listeners = this.fileRollEventListeners.toArray(); for (int i = 0; i < listeners.length; i++) { final FileRollEventListener listener = (FileRollEventListener) listeners[i]; listener.onFileRoll(fileRollEvent); } }
/* (non-Javadoc) @see org.apache.log4j.appender.FileRollEventSource#fireFileRollEvent(org.apache .log4j.appender.FileRollEvent)
final void roll(final long timeForSuffix) { final File backupFile = this.prepareBackupFile(timeForSuffix); // close filename this.getAppender().closeFile(); // rename filename on disk to filename+suffix(+number) this.doFileRoll(this.getAppender().getIoFile(), backupFile); // setup new file 'filename' this.getAppender().openFile(); this.fireFileRollEvent(new FileRollEvent(this, backupFile)); }
Invoked by subclasses; performs actual file roll. Tests to see whether roll is necessary have already been performed, so just do it.
private File prepareBackupFile(final long timeForSuffix) { final String timeSuffix = this.backupSuffixHelper .backupTimeAsString(timeForSuffix); final BackupFile backupFile = new BackupFile( this.getAppender().getIoFile(), timeSuffix); // read in a sorted list of log files (most recent first), filtered on // the suffix pattern final LogFileList logFileList = this.logFileListFilteredOn(backupFile); String backupCountSuffix = this.backupSuffixHelper .defaultBackupCountAsString(); if (!logFileList.isEmpty()) { // file list not empty: numbering to be added to suffix. final File lastLogFile = logFileList.lastFile(); // extract number appended to filename of last file in list backupCountSuffix = this.backupSuffixHelper.nextBackupCountAsString( lastLogFile.getName(), backupFile.getBaseFile()); } backupFile.setBackupCountSuffix(backupCountSuffix); return backupFile.getBackupFile(); }
Builds the file that the current log file will be renamed to, including the base log file name, plus time part, plus backup counter suffix, e.g.&nbsp;&quotbase.log.2007-01-01.1&quot;. @param timeForSuffix @return The file to be used when performing the actual file roll.
private void doFileRoll(final File from, final File to) { final FileHelper fileHelper = FileHelper.getInstance(); if (!fileHelper.deleteExisting(to)) { this.getAppender().getErrorHandler() .error("Unable to delete existing " + to + " for rename"); } final String original = from.toString(); if (fileHelper.rename(from, to)) { LogLog.debug("Renamed " + original + " to " + to); } else { this.getAppender().getErrorHandler() .error("Unable to rename " + original + " to " + to); } }
Renames the current base log file to the roll file name. @param from The current base log file. @param to The backup file.
public static spilloverpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{ spilloverpolicy_lbvserver_binding obj = new spilloverpolicy_lbvserver_binding(); obj.set_name(name); spilloverpolicy_lbvserver_binding response[] = (spilloverpolicy_lbvserver_binding[]) obj.get_resources(service); return response; }
Use this API to fetch spilloverpolicy_lbvserver_binding resources of given name .
public static appfwprofile_excluderescontenttype_binding[] get(nitro_service service, String name) throws Exception{ appfwprofile_excluderescontenttype_binding obj = new appfwprofile_excluderescontenttype_binding(); obj.set_name(name); appfwprofile_excluderescontenttype_binding response[] = (appfwprofile_excluderescontenttype_binding[]) obj.get_resources(service); return response; }
Use this API to fetch appfwprofile_excluderescontenttype_binding resources of given name .
public static base_response update(nitro_service client, sslparameter resource) throws Exception { sslparameter updateresource = new sslparameter(); updateresource.quantumsize = resource.quantumsize; updateresource.crlmemorysizemb = resource.crlmemorysizemb; updateresource.strictcachecks = resource.strictcachecks; updateresource.ssltriggertimeout = resource.ssltriggertimeout; updateresource.sendclosenotify = resource.sendclosenotify; updateresource.encrypttriggerpktcount = resource.encrypttriggerpktcount; updateresource.denysslreneg = resource.denysslreneg; updateresource.insertionencoding = resource.insertionencoding; updateresource.ocspcachesize = resource.ocspcachesize; updateresource.pushflag = resource.pushflag; updateresource.dropreqwithnohostheader = resource.dropreqwithnohostheader; updateresource.pushenctriggertimeout = resource.pushenctriggertimeout; updateresource.undefactioncontrol = resource.undefactioncontrol; updateresource.undefactiondata = resource.undefactiondata; return updateresource.update_resource(client); }
Use this API to update sslparameter.
public static base_response unset(nitro_service client, sslparameter resource, String[] args) throws Exception{ sslparameter unsetresource = new sslparameter(); return unsetresource.unset_resource(client,args); }
Use this API to unset the properties of sslparameter resource. Properties that need to be unset are specified in args array.
public static sslparameter get(nitro_service service) throws Exception{ sslparameter obj = new sslparameter(); sslparameter[] response = (sslparameter[])obj.get_resources(service); return response[0]; }
Use this API to fetch all the sslparameter resources that are configured on netscaler.
public static <T> Class<T[]> asArrayClass(Class<T> klass) { return (Class<T[]>) Array.newInstance(klass, 1).getClass(); }
This will return a class of the type T[] from a given class. When we read from the AG pipe, Java needs a reference to a generic array type. @param klass a class to turn into an array class @param <T> the type of the class. @return an array of klass with a length of 1
public static base_response add(nitro_service client, spilloverpolicy resource) throws Exception { spilloverpolicy addresource = new spilloverpolicy(); addresource.name = resource.name; addresource.rule = resource.rule; addresource.action = resource.action; addresource.comment = resource.comment; return addresource.add_resource(client); }
Use this API to add spilloverpolicy.
public static base_response update(nitro_service client, spilloverpolicy resource) throws Exception { spilloverpolicy updateresource = new spilloverpolicy(); updateresource.name = resource.name; updateresource.rule = resource.rule; updateresource.action = resource.action; updateresource.comment = resource.comment; return updateresource.update_resource(client); }
Use this API to update spilloverpolicy.
public static spilloverpolicy[] get(nitro_service service, options option) throws Exception{ spilloverpolicy obj = new spilloverpolicy(); spilloverpolicy[] response = (spilloverpolicy[])obj.get_resources(service,option); return response; }
Use this API to fetch all the spilloverpolicy resources that are configured on netscaler.
public static spilloverpolicy get(nitro_service service, String name) throws Exception{ spilloverpolicy obj = new spilloverpolicy(); obj.set_name(name); spilloverpolicy response = (spilloverpolicy) obj.get_resource(service); return response; }
Use this API to fetch spilloverpolicy resource of given name .
public static spilloverpolicy[] get_filtered(nitro_service service, String filter) throws Exception{ spilloverpolicy obj = new spilloverpolicy(); options option = new options(); option.set_filter(filter); spilloverpolicy[] response = (spilloverpolicy[]) obj.getfiltered(service, option); return response; }
Use this API to fetch filtered set of spilloverpolicy resources. filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
@Override public ParseResult parse(Reader reader, AttributeSource parent) throws IOException { ParseResult res = new ParseResult(); // get MtasUpdateRequestProcessorResult StringBuilder sb = new StringBuilder(); char[] buf = new char[128]; int cnt; while ((cnt = reader.read(buf)) > 0) { sb.append(buf, 0, cnt); } Iterator<MtasUpdateRequestProcessorResultItem> iterator; try ( MtasUpdateRequestProcessorResultReader result = new MtasUpdateRequestProcessorResultReader( sb.toString());) { iterator = result.getIterator(); if (iterator != null && iterator.hasNext()) { res.str = result.getStoredStringValue(); res.bin = result.getStoredBinValue(); } else { res.str = null; res.bin = null; result.close(); return res; } parent.clearAttributes(); while (iterator.hasNext()) { MtasUpdateRequestProcessorResultItem item = iterator.next(); if (item.tokenTerm != null) { CharTermAttribute catt = parent.addAttribute(CharTermAttribute.class); catt.append(item.tokenTerm); } if (item.tokenFlags != null) { FlagsAttribute flags = parent.addAttribute(FlagsAttribute.class); flags.setFlags(item.tokenFlags); } if (item.tokenPosIncr != null) { PositionIncrementAttribute patt = parent .addAttribute(PositionIncrementAttribute.class); patt.setPositionIncrement(item.tokenPosIncr); } if (item.tokenPayload != null) { PayloadAttribute p = parent.addAttribute(PayloadAttribute.class); p.setPayload(new BytesRef(item.tokenPayload)); } if (item.tokenOffsetStart != null && item.tokenOffsetEnd != null) { OffsetAttribute offset = parent.addAttribute(OffsetAttribute.class); offset.setOffset(item.tokenOffsetStart, item.tokenOffsetEnd); } // capture state and add to result State state = parent.captureState(); res.states.add(state.clone()); // reset for reuse parent.clearAttributes(); } } catch (IOException e) { // ignore log.debug(e); } return res; }
/* (non-Javadoc) @see org.apache.solr.schema.PreAnalyzedField.PreAnalyzedParser#parse(java.io. Reader, org.apache.lucene.util.AttributeSource)
@Override public String toFormattedString(Field f) throws IOException { return this.getClass().getName() + " " + f.name(); }
/* (non-Javadoc) @see org.apache.solr.schema.PreAnalyzedField.PreAnalyzedParser#toFormattedString (org.apache.lucene.document.Field)
public static <IN> PaddedList<IN> valueOf(List<IN> list, IN padding) { return new PaddedList<IN>(list, padding); }
A static method that provides an easy way to create a list of a certain parametric type. This static constructor works better with generics. @param list The list to pad @param padding The padding element (may be null) @return The padded list
@Override public int nextStartPosition() throws IOException { // no document if (docId == -1 || docId == NO_MORE_DOCS) { throw new IOException("no document"); // finished } else if (noMorePositions) { return NO_MORE_POSITIONS; // littleSpans already at start match, because of check for matching // document } else if (!calledNextStartPosition) { calledNextStartPosition = true; return spans1.spans.startPosition(); // compute next match } else { if (goToNextStartPosition()) { // match found return spans1.spans.startPosition(); } else { // no more matches: document finished return NO_MORE_POSITIONS; } } }
/* (non-Javadoc) @see org.apache.lucene.search.spans.Spans#nextStartPosition()
@Override public void collect(SpanCollector collector) throws IOException { spans1.spans.collect(collector); spans2.spans.collect(collector); }
/* (non-Javadoc) @see org.apache.lucene.search.spans.Spans#collect(org.apache.lucene.search.spans .SpanCollector)
@Override public int advance(int target) throws IOException { reset(); if (docId == NO_MORE_DOCS) { return docId; } else if (target < docId) { // should not happen docId = NO_MORE_DOCS; return docId; } else { // advance 1 int spans1DocId = spans1.spans.docID(); int newTarget = target; if (spans1DocId < newTarget) { spans1DocId = spans1.spans.advance(target); if (spans1DocId == NO_MORE_DOCS) { docId = NO_MORE_DOCS; return docId; } newTarget = Math.max(newTarget, spans1DocId); } int spans2DocId = spans2.spans.docID(); // advance 2 if (spans2DocId < newTarget) { spans2DocId = spans2.spans.advance(newTarget); if (spans2DocId == NO_MORE_DOCS) { docId = NO_MORE_DOCS; return docId; } } // check equal docId, otherwise next if (spans1DocId == spans2DocId) { docId = spans1DocId; // check match if (goToNextStartPosition()) { return docId; } else { return nextDoc(); } } else { return nextDoc(); } } }
/* (non-Javadoc) @see org.apache.lucene.search.DocIdSetIterator#advance(int)
private boolean goToNextStartPosition() throws IOException { int nextSpans1StartPosition; int nextSpans1EndPosition; int nextSpans2StartPosition; int nextSpans2EndPosition; // loop over span1 while ((nextSpans1StartPosition = spans1.spans .nextStartPosition()) != NO_MORE_POSITIONS) { nextSpans1EndPosition = spans1.spans.endPosition(); if (noMorePositionsSpan2 && nextSpans1StartPosition > lastSpans2StartPosition) { noMorePositions = true; return false; // check if start/en span1 matches start/end span2 from last or previous } else if ((nextSpans1StartPosition == lastSpans2StartPosition && nextSpans1EndPosition == lastSpans2EndPosition) || (nextSpans1StartPosition == previousSpans2StartPosition && previousSpans2EndPositions.contains(nextSpans1EndPosition))) { return true; } else { // try to find matching span2 while (!noMorePositionsSpan2 && nextSpans1StartPosition >= lastSpans2StartPosition) { // get new span2 nextSpans2StartPosition = spans2.spans.nextStartPosition(); // check for finished span2 if (nextSpans2StartPosition == NO_MORE_POSITIONS) { noMorePositionsSpan2 = true; } else { // get end for new span2 nextSpans2EndPosition = spans2.spans.endPosition(); // check for registering last span2 as previous if (nextSpans1StartPosition <= lastSpans2StartPosition) { if (previousSpans2StartPosition != lastSpans2StartPosition) { previousSpans2StartPosition = lastSpans2StartPosition; previousSpans2EndPositions.clear(); } previousSpans2EndPositions.add(lastSpans2EndPosition); } // register span2 as last lastSpans2StartPosition = nextSpans2StartPosition; lastSpans2EndPosition = nextSpans2EndPosition; // check for match if (nextSpans1StartPosition == nextSpans2StartPosition && nextSpans1EndPosition == nextSpans2EndPosition) { return true; } } } } } noMorePositions = true; return false; }
Go to next start position. @return true, if successful @throws IOException Signals that an I/O exception has occurred.
private void reset() { calledNextStartPosition = false; noMorePositions = false; noMorePositionsSpan2 = false; lastSpans2StartPosition = -1; lastSpans2EndPosition = -1; previousSpans2StartPosition = -1; previousSpans2EndPositions.clear(); }
Reset.
@Override public TwoPhaseIterator asTwoPhaseIterator() { if (spans1 == null || spans2 == null || !query.twoPhaseIteratorAllowed()) { return null; } else { // TODO return null; } }
/* (non-Javadoc) @see mtas.search.spans.util.MtasSpans#asTwoPhaseIterator()
public static base_response add(nitro_service client, locationfile resource) throws Exception { locationfile addresource = new locationfile(); addresource.Locationfile = resource.Locationfile; addresource.format = resource.format; return addresource.add_resource(client); }
Use this API to add locationfile.
public static base_response delete(nitro_service client) throws Exception { locationfile deleteresource = new locationfile(); return deleteresource.delete_resource(client); }
Use this API to delete locationfile.
public static locationfile get(nitro_service service) throws Exception{ locationfile obj = new locationfile(); locationfile[] response = (locationfile[])obj.get_resources(service); return response[0]; }
Use this API to fetch all the locationfile resources that are configured on netscaler.
public static sslcertkey_sslocspresponder_binding[] get(nitro_service service, String certkey) throws Exception{ sslcertkey_sslocspresponder_binding obj = new sslcertkey_sslocspresponder_binding(); obj.set_certkey(certkey); sslcertkey_sslocspresponder_binding response[] = (sslcertkey_sslocspresponder_binding[]) obj.get_resources(service); return response; }
Use this API to fetch sslcertkey_sslocspresponder_binding resources of given name .
public static sslcertkey_sslocspresponder_binding[] get_filtered(nitro_service service, String certkey, String filter) throws Exception{ sslcertkey_sslocspresponder_binding obj = new sslcertkey_sslocspresponder_binding(); obj.set_certkey(certkey); options option = new options(); option.set_filter(filter); sslcertkey_sslocspresponder_binding[] response = (sslcertkey_sslocspresponder_binding[]) obj.getfiltered(service, option); return response; }
Use this API to fetch filtered set of sslcertkey_sslocspresponder_binding resources. filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
public static appflowpolicy_appflowpolicylabel_binding[] get(nitro_service service, String name) throws Exception{ appflowpolicy_appflowpolicylabel_binding obj = new appflowpolicy_appflowpolicylabel_binding(); obj.set_name(name); appflowpolicy_appflowpolicylabel_binding response[] = (appflowpolicy_appflowpolicylabel_binding[]) obj.get_resources(service); return response; }
Use this API to fetch appflowpolicy_appflowpolicylabel_binding resources of given name .
public static authenticationvserver_authenticationnegotiatepolicy_binding[] get(nitro_service service, String name) throws Exception{ authenticationvserver_authenticationnegotiatepolicy_binding obj = new authenticationvserver_authenticationnegotiatepolicy_binding(); obj.set_name(name); authenticationvserver_authenticationnegotiatepolicy_binding response[] = (authenticationvserver_authenticationnegotiatepolicy_binding[]) obj.get_resources(service); return response; }
Use this API to fetch authenticationvserver_authenticationnegotiatepolicy_binding resources of given name .
public static base_response update(nitro_service client, rnatparam resource) throws Exception { rnatparam updateresource = new rnatparam(); updateresource.tcpproxy = resource.tcpproxy; return updateresource.update_resource(client); }
Use this API to update rnatparam.
public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{ rnatparam unsetresource = new rnatparam(); return unsetresource.unset_resource(client,args); }
Use this API to unset the properties of rnatparam resource. Properties that need to be unset are specified in args array.
public static rnatparam get(nitro_service service) throws Exception{ rnatparam obj = new rnatparam(); rnatparam[] response = (rnatparam[])obj.get_resources(service); return response[0]; }
Use this API to fetch all the rnatparam resources that are configured on netscaler.
public static base_response update(nitro_service client, nd6ravariables resource) throws Exception { nd6ravariables updateresource = new nd6ravariables(); updateresource.vlan = resource.vlan; updateresource.ceaserouteradv = resource.ceaserouteradv; updateresource.sendrouteradv = resource.sendrouteradv; updateresource.srclinklayeraddroption = resource.srclinklayeraddroption; updateresource.onlyunicastrtadvresponse = resource.onlyunicastrtadvresponse; updateresource.managedaddrconfig = resource.managedaddrconfig; updateresource.otheraddrconfig = resource.otheraddrconfig; updateresource.currhoplimit = resource.currhoplimit; updateresource.maxrtadvinterval = resource.maxrtadvinterval; updateresource.minrtadvinterval = resource.minrtadvinterval; updateresource.linkmtu = resource.linkmtu; updateresource.reachabletime = resource.reachabletime; updateresource.retranstime = resource.retranstime; updateresource.defaultlifetime = resource.defaultlifetime; return updateresource.update_resource(client); }
Use this API to update nd6ravariables.
public static base_responses update(nitro_service client, nd6ravariables resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { nd6ravariables updateresources[] = new nd6ravariables[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i] = new nd6ravariables(); updateresources[i].vlan = resources[i].vlan; updateresources[i].ceaserouteradv = resources[i].ceaserouteradv; updateresources[i].sendrouteradv = resources[i].sendrouteradv; updateresources[i].srclinklayeraddroption = resources[i].srclinklayeraddroption; updateresources[i].onlyunicastrtadvresponse = resources[i].onlyunicastrtadvresponse; updateresources[i].managedaddrconfig = resources[i].managedaddrconfig; updateresources[i].otheraddrconfig = resources[i].otheraddrconfig; updateresources[i].currhoplimit = resources[i].currhoplimit; updateresources[i].maxrtadvinterval = resources[i].maxrtadvinterval; updateresources[i].minrtadvinterval = resources[i].minrtadvinterval; updateresources[i].linkmtu = resources[i].linkmtu; updateresources[i].reachabletime = resources[i].reachabletime; updateresources[i].retranstime = resources[i].retranstime; updateresources[i].defaultlifetime = resources[i].defaultlifetime; } result = update_bulk_request(client, updateresources); } return result; }
Use this API to update nd6ravariables resources.
public static nd6ravariables[] get(nitro_service service, options option) throws Exception{ nd6ravariables obj = new nd6ravariables(); nd6ravariables[] response = (nd6ravariables[])obj.get_resources(service,option); return response; }
Use this API to fetch all the nd6ravariables resources that are configured on netscaler.
public static nd6ravariables get(nitro_service service, Long vlan) throws Exception{ nd6ravariables obj = new nd6ravariables(); obj.set_vlan(vlan); nd6ravariables response = (nd6ravariables) obj.get_resource(service); return response; }
Use this API to fetch nd6ravariables resource of given name .
public static nd6ravariables[] get(nitro_service service, Long vlan[]) throws Exception{ if (vlan !=null && vlan.length>0) { nd6ravariables response[] = new nd6ravariables[vlan.length]; nd6ravariables obj[] = new nd6ravariables[vlan.length]; for (int i=0;i<vlan.length;i++) { obj[i] = new nd6ravariables(); obj[i].set_vlan(vlan[i]); response[i] = (nd6ravariables) obj[i].get_resource(service); } return response; } return null; }
Use this API to fetch nd6ravariables resources of given names .
public static nd6ravariables[] get_filtered(nitro_service service, String filter) throws Exception{ nd6ravariables obj = new nd6ravariables(); options option = new options(); option.set_filter(filter); nd6ravariables[] response = (nd6ravariables[]) obj.getfiltered(service, option); return response; }
Use this API to fetch filtered set of nd6ravariables resources. filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
public static gslbrunningconfig get(nitro_service service) throws Exception{ gslbrunningconfig obj = new gslbrunningconfig(); gslbrunningconfig[] response = (gslbrunningconfig[])obj.get_resources(service); return response[0]; }
Use this API to fetch all the gslbrunningconfig resources that are configured on netscaler.
public String classifyValuedInstance(List<StringDoublePair> features) { List<scala.Tuple2<String,Double>> nfs = new ArrayList<scala.Tuple2<String,Double>>(); for (StringDoublePair el : features) { nfs.add(new scala.Tuple2<String,Double>(el.getString(), el.getDouble())); } return maxEnt.decodeValuedInstance(nfs); }
/* @param features - A list of string-double pairs representing the valued features for a classification instance @return label - A string representing the predicted label according to the decoder
public List<StringDoublePair> classifyInstanceDistribution(List<String> features) { List<scala.Tuple2<String,Double>> r = maxEnt.decodeInstanceAsDistribution(features); List<StringDoublePair> res = new ArrayList<StringDoublePair>(); for (scala.Tuple2<String,Double> el : r) { res.add(new StringDoublePair(el._1, el._2)); } return res; }
/* @param features - A list of strings representing the features for a classification instance @return labelposteriorpair list - A list of pairs that include each label and a posterior probability mass
public List<StringDoublePair> classifyValuedInstanceDistribution(List<StringDoublePair> features) { List<scala.Tuple2<String,Double>> nfs = new ArrayList<scala.Tuple2<String,Double>>(); for (StringDoublePair el : features) { nfs.add(new scala.Tuple2<String,Double>(el.getString(), el.getDouble())); } List<scala.Tuple2<String,Double>> r = maxEnt.decodeValuedInstanceAsDistribution(nfs); List<StringDoublePair> res = new ArrayList<StringDoublePair>(); for (scala.Tuple2<String,Double> el : r) { res.add(new StringDoublePair(el._1, el._2)); } return res; }
/* @param features - A list of string-double pairs representing the valued features for a classification instance @return string-double pair list - A list of pairs that include each label and a posterior probability mass
public static base_response update(nitro_service client, callhome resource) throws Exception { callhome updateresource = new callhome(); updateresource.emailaddress = resource.emailaddress; updateresource.proxymode = resource.proxymode; updateresource.ipaddress = resource.ipaddress; updateresource.port = resource.port; return updateresource.update_resource(client); }
Use this API to update callhome.
public static base_response unset(nitro_service client, callhome resource, String[] args) throws Exception{ callhome unsetresource = new callhome(); return unsetresource.unset_resource(client,args); }
Use this API to unset the properties of callhome resource. Properties that need to be unset are specified in args array.
public static callhome get(nitro_service service) throws Exception{ callhome obj = new callhome(); callhome[] response = (callhome[])obj.get_resources(service); return response[0]; }
Use this API to fetch all the callhome resources that are configured on netscaler.