Search in sources :

Example 6 with StatusCodes

use of org.codehaus.enunciate.jaxrs.StatusCodes in project pentaho-platform by pentaho.

the class Log4jResource method updateLogLevel.

@PUT
@Path("/update")
@StatusCodes({ @ResponseCode(code = 200, condition = "Successfully update log level."), @ResponseCode(code = 304, condition = "Log level is not modified.") })
@Produces({ MediaType.TEXT_PLAIN })
public Response updateLogLevel(@FormParam("level") String targetLevel, @FormParam("category") String category) throws Exception {
    LOGGER.setLevel(Level.INFO);
    if (StringUtils.isBlank(targetLevel) && StringUtils.isBlank(category)) {
        return Response.notModified("No parameter provided, log level not modified.").build();
    }
    Logger root = LogManager.getRootLogger();
    if (StringUtils.isNotBlank(targetLevel)) {
        LOGGER.info("Request to set log level: " + targetLevel);
        if (StringUtils.isNotBlank(category)) {
            LOGGER.info("Request to set log level for package: " + category);
            Logger catLog = LogManager.exists(category);
            if (catLog != null) {
                catLog.setLevel(Level.toLevel(targetLevel, root.getLevel()));
                return Response.ok("Setting log level for: '" + catLog.getName() + "' to be: " + catLog.getLevel()).build();
            }
            return Response.notModified("Category: '" + Encode.forHtml(category) + "' not found, log level not modified.").build();
        }
        root.setLevel(Level.toLevel(targetLevel, root.getLevel()));
        LOGGER.info("Root logger level set to: " + root.getLevel());
        Enumeration e = LogManager.getCurrentLoggers();
        while (e.hasMoreElements()) {
            Logger logger = (Logger) e.nextElement();
            logger.setLevel(Level.toLevel(targetLevel, root.getLevel()));
        }
    }
    return Response.ok("Log level updated.").build();
}
Also used : Enumeration(java.util.Enumeration) Logger(org.apache.log4j.Logger) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) StatusCodes(org.codehaus.enunciate.jaxrs.StatusCodes) PUT(javax.ws.rs.PUT)

Example 7 with StatusCodes

use of org.codehaus.enunciate.jaxrs.StatusCodes in project data-access by pentaho.

the class AnalysisResource method putSchema.

/**
 * Import Analysis Schema.
 *
 * <p><b>Example Request:</b><br />
 *    PUT pentaho/plugin/data-access/api/datasource/analysis/catalog/SampleSchema
 * <br /><b>PUT data:</b>
 *  <pre function="syntax.xml">
 *      ------WebKitFormBoundaryNLNb246RTFIn1elY
 *      Content-Disposition: form-data; name=&quot;uploadAnalysis&quot;; filename=&quot;SampleData2.mondrian.xml&quot;
 *      Content-Type: text/xml
 *
 *      &lt;?xml version=&quot;1.0&quot;?&gt;
 *      &lt;Schema name=&quot;SampleData2&quot;&gt;
 *      &lt;!-- Shared dimensions --&gt;
 *
 *      &lt;Dimension name=&quot;Region&quot;&gt;
 *      &lt;Hierarchy hasAll=&quot;true&quot; allMemberName=&quot;All Regions&quot;&gt;
 *      &lt;Table name=&quot;QUADRANT_ACTUALS&quot;/&gt;
 *      &lt;Level name=&quot;Region&quot; column=&quot;REGION&quot; uniqueMembers=&quot;true&quot;/&gt;
 *      &lt;/Hierarchy&gt;
 *      &lt;/Dimension&gt;
 *      &lt;Dimension name=&quot;Department&quot;&gt;
 *      &lt;Hierarchy hasAll=&quot;true&quot; allMemberName=&quot;All Departments&quot;&gt;
 *      &lt;Table name=&quot;QUADRANT_ACTUALS&quot;/&gt;
 *      &lt;Level name=&quot;Department&quot; column=&quot;DEPARTMENT&quot; uniqueMembers=&quot;true&quot;/&gt;
 *      &lt;/Hierarchy&gt;
 *      &lt;/Dimension&gt;
 *
 *      &lt;Dimension name=&quot;Positions&quot;&gt;
 *      &lt;Hierarchy hasAll=&quot;true&quot; allMemberName=&quot;All Positions&quot;&gt;
 *      &lt;Table name=&quot;QUADRANT_ACTUALS&quot;/&gt;
 *      &lt;Level name=&quot;Positions&quot; column=&quot;POSITIONTITLE&quot; uniqueMembers=&quot;true&quot;/&gt;
 *      &lt;/Hierarchy&gt;
 *      &lt;/Dimension&gt;
 *
 *      &lt;Cube name=&quot;Quadrant Analysis&quot;&gt;
 *      &lt;Table name=&quot;QUADRANT_ACTUALS&quot;/&gt;
 *      &lt;DimensionUsage name=&quot;Region&quot; source=&quot;Region&quot;/&gt;
 *      &lt;DimensionUsage name=&quot;Department&quot; source=&quot;Department&quot; /&gt;
 *      &lt;DimensionUsage name=&quot;Positions&quot; source=&quot;Positions&quot; /&gt;
 *      &lt;Measure name=&quot;Actual&quot; column=&quot;ACTUAL&quot; aggregator=&quot;sum&quot; formatString=&quot;#,###.00&quot;/&gt;
 *      &lt;Measure name=&quot;Budget&quot; column=&quot;BUDGET&quot; aggregator=&quot;sum&quot; formatString=&quot;#,###.00&quot;/&gt;
 *      &lt;Measure name=&quot;Variance&quot; column=&quot;VARIANCE&quot; aggregator=&quot;sum&quot; formatString=&quot;#,###.00&quot;/&gt;
 *      &lt;!--    &lt;CalculatedMember name=&quot;Variance Percent&quot; dimension=&quot;Measures&quot; formula=&quot;([Measures].[Variance]/[Measures].[Budget])*100&quot; /&gt; --&gt;
 *      &lt;/Cube&gt;
 *
 *      &lt;/Schema&gt;
 *
 *      ------WebKitFormBoundaryNLNb246RTFIn1elY
 *      Content-Disposition: form-data; name=&quot;parameters&quot;
 *
 *      DataSource=SampleData2;overwrite=true
 *      ------WebKitFormBoundaryNLNb246RTFIn1elY
 *      Content-Disposition: form-data; name=&quot;schemaFileInfo&quot;
 *
 *      test.xml
 *      ------WebKitFormBoundaryNLNb246RTFIn1elY
 *      Content-Disposition: form-data; name=&quot;catalogName&quot;
 *
 *      Catalog Name
 *      ------WebKitFormBoundaryNLNb246RTFIn1elY
 *      Content-Disposition: form-data; name=&quot;xmlaEnabledFlag&quot;
 *
 *      true
 *      ------WebKitFormBoundaryNLNb246RTFIn1elY--
 *  </pre>
 * </p>
 *
 * @param catalog         (optional) The catalog name.
 * @param uploadAnalysis  A Mondrian schema XML file.
 * @param schemaFileInfo  User selected name for the file.
 * @param origCatalogName (optional) The original catalog name.
 * @param datasourceName  (optional) The datasource  name.
 * @param overwrite       Flag for overwriting existing version of the file.
 * @param xmlaEnabledFlag Is XMLA enabled or not.
 * @param parameters      Import parameters.
 * @param acl             acl information for the data source. This parameter is optional.
 *
 * @return Response containing the success of the method.
 *
 * <p><b>Example Response:</b></p>
 * <pre function="syntax.xml">
 *   200
 * </pre>
 */
@PUT
@Path("/catalog/{catalogId : .+}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
@StatusCodes({ @ResponseCode(code = 409, condition = "Content already exists (use overwrite flag to force)"), @ResponseCode(code = 401, condition = "Import failed because publish is prohibited"), @ResponseCode(code = 500, condition = "Unspecified general error has occurred"), @ResponseCode(code = 412, condition = "Analysis datasource import failed.  Error code or message included in response entity"), @ResponseCode(code = 403, condition = "Access Control Forbidden"), @ResponseCode(code = 201, condition = "Indicates successful import") })
public Response putSchema(// Optional
@PathParam(CATALOG_ID) String catalog, @FormDataParam(UPLOAD_ANALYSIS) InputStream uploadAnalysis, @FormDataParam(UPLOAD_ANALYSIS) FormDataContentDisposition schemaFileInfo, // Optional
@FormDataParam(ORIG_CATALOG_NAME) String origCatalogName, // Optional
@FormDataParam(DATASOURCE_NAME) String datasourceName, @FormDataParam(OVERWRITE_IN_REPOS) Boolean overwrite, @FormDataParam(XMLA_ENABLED_FLAG) Boolean xmlaEnabledFlag, @FormDataParam(PARAMETERS) String parameters, @FormDataParam(DATASOURCE_ACL) RepositoryFileAclDto acl) throws PentahoAccessControlException {
    try {
        service.putMondrianSchema(uploadAnalysis, schemaFileInfo, catalog, origCatalogName, datasourceName, overwrite, xmlaEnabledFlag, parameters, acl);
        Response response = Response.status(Response.Status.CREATED).build();
        logger.debug("putMondrianSchema Response " + response);
        return response;
    } catch (PentahoAccessControlException pac) {
        int statusCode = PlatformImportException.PUBLISH_USERNAME_PASSWORD_FAIL;
        logger.error("Error putMondrianSchema " + pac.getMessage() + " status = " + statusCode);
        throw new ResourceUtil.AccessControlException(pac.getMessage());
    } catch (PlatformImportException pe) {
        if (pe.getErrorStatus() == PlatformImportException.PUBLISH_PROHIBITED_SYMBOLS_ERROR) {
            throw new ResourceUtil.PublishProhibitedException(pe.getMessage());
        } else {
            String msg = pe.getMessage();
            logger.error("Error import analysis: " + msg + " status = " + pe.getErrorStatus());
            Throwable throwable = pe.getCause();
            if (throwable != null) {
                msg = throwable.getMessage();
                logger.error("Root cause: " + msg);
            }
            int status = pe.getErrorStatus();
            if (status == 8) {
                throw new ResourceUtil.ContentAlreadyExistsException(msg);
            } else {
                throw new ResourceUtil.ImportFailedException(msg);
            }
        }
    } catch (Exception e) {
        int statusCode = PlatformImportException.PUBLISH_GENERAL_ERROR;
        logger.error("Error putMondrianSchema " + e.getMessage() + " status = " + statusCode);
        throw new ResourceUtil.UnspecifiedErrorException(e.getMessage());
    }
}
Also used : Response(javax.ws.rs.core.Response) PlatformImportException(org.pentaho.platform.plugin.services.importer.PlatformImportException) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) FileNotFoundException(java.io.FileNotFoundException) RepositoryException(org.pentaho.platform.api.repository.RepositoryException) PlatformImportException(org.pentaho.platform.plugin.services.importer.PlatformImportException) WebApplicationException(javax.ws.rs.WebApplicationException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) StatusCodes(org.codehaus.enunciate.jaxrs.StatusCodes) PUT(javax.ws.rs.PUT)

Example 8 with StatusCodes

use of org.codehaus.enunciate.jaxrs.StatusCodes in project data-access by pentaho.

the class JDBCDatasourceResource method getConnectionIDs.

/**
 * Get a list of JDBC datasource IDs.
 *
 * <p><b>Example Request:</b><br />
 *    GET pentaho/plugin/data-access/api/datasource/jdbc/connection
 * </p>
 *
 * @return A list of JDBC datasource IDs.
 *
 * <p><b>Example Response:</b></p>
 *    <pre function="syntax.xml">
 *      {
 *        "Item": [
 *          {
 *            "@type": "xs:string",
 *            "$": "AgileBI"
 *          },
 *          {
 *            "@type": "xs:string",
 *            "$": "Audit"
 *          },
 *          {
 *            "@type": "xs:string",
 *            "$": "SampleData"
 *          },
 *          {
 *            "@type": "xs:string",
 *            "$": "TestDataSourceResource"
 *          },
 *          {
 *            "@type": "xs:string",
 *            "$": "baseball connection"
 *          },
 *          {
 *            "@type": "xs:string",
 *            "$": "baseball connection"
 *          },
 *          {
 *            "@type": "xs:string",
 *            "$": "live_logging_info"
 *          },
 *          {
 *            "@type": "xs:string",
 *            "$": "pentaho_operations_mart"
 *          }
 *        ]
 *      }
 *    </pre>
 */
@GET
@Path("/")
@Produces({ APPLICATION_JSON, APPLICATION_XML })
@StatusCodes({ @ResponseCode(code = 200, condition = "Successfully retrieved the list of JDBC datasource IDs"), @ResponseCode(code = 500, condition = "Internal error retrieving JDBC datasource IDs") })
public JaxbList<String> getConnectionIDs() {
    List<String> connStrList = new ArrayList<String>();
    try {
        List<IDatabaseConnection> conns = service.getConnections();
        for (IDatabaseConnection conn : conns) {
            conn.setPassword(null);
            connStrList.add(conn.getName());
        }
    } catch (ConnectionServiceException e) {
        logger.error("Error " + e.getMessage());
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
    JaxbList<String> connections = new JaxbList<String>(connStrList);
    return connections;
}
Also used : ConnectionServiceException(org.pentaho.platform.dataaccess.datasource.wizard.service.ConnectionServiceException) WebApplicationException(javax.ws.rs.WebApplicationException) ArrayList(java.util.ArrayList) IDatabaseConnection(org.pentaho.database.model.IDatabaseConnection) JaxbList(org.pentaho.platform.web.http.api.resources.JaxbList) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) StatusCodes(org.codehaus.enunciate.jaxrs.StatusCodes)

Example 9 with StatusCodes

use of org.codehaus.enunciate.jaxrs.StatusCodes in project pentaho-metaverse by pentaho.

the class MetaverseService method download.

/**
 * Download a zip file of all known lineage related artifacts created between (inclusive) two dates.
 *
 * <p><b>Example Request:</b><br />
 *    GET pentaho-di/osgi/cxf/lineage/api/download/all/20150101/20151231
 * </p>
 *
 * @param startingDate a date string in the format YYYYMMDD
 * @param endingDate   a date string in the format YYYYMMDD
 *
 * @return A zip file containing lineage artifacts
 */
@GET
@Path("/download/all/{startingDate}/{endingDate}")
@Produces({ "application/zip" })
@StatusCodes({ @ResponseCode(code = OK, condition = "Successfully created and returned the zip file."), @ResponseCode(code = BAD_REQUEST, condition = "Bad request, invalid starting and/or ending date provided."), @ResponseCode(code = SERVER_ERROR, condition = "Server Error.") })
public Response download(@PathParam("startingDate") final String startingDate, @PathParam("endingDate") String endingDate) {
    if (lineageCollector == null) {
        return Response.serverError().entity(Messages.getString("ERROR.LineageCollector.IsNull")).build();
    }
    String filename = "pentaho-lineage";
    if (startingDate != null) {
        filename += "_" + startingDate;
    }
    if (endingDate != null) {
        filename += "-" + endingDate;
    }
    filename += ".zip";
    try {
        final List<String> artifacts = lineageCollector.listArtifacts(startingDate, endingDate);
        StreamingOutput stream = new LineageStreamingOutput(artifacts, lineageCollector);
        return Response.ok(stream).header("Content-Type", "application/zip").header("Content-Disposition", "inline; filename=" + filename).build();
    } catch (IllegalArgumentException e) {
        // illegal date format, return an error to the caller
        throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity("Invalid date string provided. All dates must be valid and conform to this format " + DATE_FORMAT).build());
    }
}
Also used : BadRequestException(javax.ws.rs.BadRequestException) StreamingOutput(javax.ws.rs.core.StreamingOutput) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) StatusCodes(org.codehaus.enunciate.jaxrs.StatusCodes)

Example 10 with StatusCodes

use of org.codehaus.enunciate.jaxrs.StatusCodes in project pentaho-metaverse by pentaho.

the class MetaverseService method downloadFile.

/**
 * Download a zip file of all known lineage related artifacts for a specified file
 * created between two dates (inclusive)
 *
 * <p><b>Example Request:</b><br />
 *    POST pentaho-di/osgi/cxf/lineage/api/download/file/20150101/20151231
 * <br /><b>POST data:</b>
 *  <pre function="syntax.xml">
 *    { "path": "/home/suzy/test.ktr" }
 *  </pre>
 * </p>
 *
 * @param request      {@link LineageRequest} containing the path to the file of interest
 * @param startingDate a date string in the format YYYYMMDD
 * @param endingDate   a date string in the format YYYYMMDD
 *
 * @return A zip file containing lineage artifacts
 */
@POST
@Path("/download/file/{startingDate}/{endingDate}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({ "application/zip" })
@StatusCodes({ @ResponseCode(code = OK, condition = "Successfully created and returned the zip file."), @ResponseCode(code = BAD_REQUEST, condition = "Bad request, invalid starting and/or ending date provided."), @ResponseCode(code = SERVER_ERROR, condition = "Server Error.") })
public Response downloadFile(LineageRequest request, @PathParam("startingDate") String startingDate, @PathParam("endingDate") String endingDate) {
    if (lineageCollector == null) {
        return Response.serverError().entity(Messages.getString("ERROR.LineageCollector.IsNull")).build();
    }
    if (request == null || request.getPath() == null) {
        return Response.serverError().entity(Messages.getString("ERROR.NoPathFound")).build();
    }
    try {
        final List<String> artifacts = lineageCollector.listArtifactsForFile(request.getPath(), startingDate, endingDate);
        File f = new File(request.getPath());
        String filename = f.getName() + "_lineage";
        if (startingDate != null) {
            filename += "_" + startingDate;
        }
        if (endingDate != null) {
            filename += "-" + endingDate;
        }
        filename += ".zip";
        StreamingOutput stream = new LineageStreamingOutput(artifacts, lineageCollector);
        return Response.ok(stream).header("Content-Type", "application/zip").header("Content-Disposition", "inline; filename=" + filename).build();
    } catch (IllegalArgumentException e) {
        // illegal date format, return an error to the caller
        throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity("Invalid date string provided. All dates must be valid and conform to this format " + DATE_FORMAT).build());
    }
}
Also used : BadRequestException(javax.ws.rs.BadRequestException) StreamingOutput(javax.ws.rs.core.StreamingOutput) File(java.io.File) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) StatusCodes(org.codehaus.enunciate.jaxrs.StatusCodes)

Aggregations

Path (javax.ws.rs.Path)17 StatusCodes (org.codehaus.enunciate.jaxrs.StatusCodes)17 Produces (javax.ws.rs.Produces)15 Consumes (javax.ws.rs.Consumes)8 GET (javax.ws.rs.GET)8 ArrayList (java.util.ArrayList)5 POST (javax.ws.rs.POST)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 PUT (javax.ws.rs.PUT)4 Facet (org.codehaus.enunciate.Facet)4 PentahoAccessControlException (org.pentaho.platform.api.engine.PentahoAccessControlException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 List (java.util.List)2 Properties (java.util.Properties)2 BadRequestException (javax.ws.rs.BadRequestException)2 StreamingOutput (javax.ws.rs.core.StreamingOutput)2 IDatabaseConnection (org.pentaho.database.model.IDatabaseConnection)2