Search in sources :

Example 61 with Action

use of com.opensymphony.xwork2.Action in project bamboobsc by billchen198318.

the class JasperReportsResult method doExecute.

protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    // Will throw a runtime exception if no "datasource" property. TODO Best place for that is...?
    initializeProperties(invocation);
    LOG.debug("Creating JasperReport for dataSource = {}, format = {}", dataSource, format);
    HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
    HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(ServletActionContext.HTTP_RESPONSE);
    // TODO Set content type to config settings?
    if ("contype".equals(request.getHeader("User-Agent"))) {
        try (OutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/pdf");
            response.setContentLength(0);
        } catch (IOException e) {
            LOG.error("Error writing report output", e);
            throw new ServletException(e.getMessage(), e);
        }
        return;
    }
    // Construct the data source for the report.
    ValueStack stack = invocation.getStack();
    ValueStackDataSource stackDataSource = null;
    Connection conn = (Connection) stack.findValue(connection);
    if (conn == null)
        stackDataSource = new ValueStackDataSource(stack, dataSource, wrapField);
    if ("https".equalsIgnoreCase(request.getScheme())) {
        // set the the HTTP Header to work around IE SSL weirdness
        response.setHeader("CACHE-CONTROL", "PRIVATE");
        response.setHeader("Cache-Control", "maxage=3600");
        response.setHeader("Pragma", "public");
        response.setHeader("Accept-Ranges", "none");
    }
    // Determine the directory that the report file is in and set the reportDirectory parameter
    // For WW 2.1.7:
    //  ServletContext servletContext = ((ServletConfig) invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONFIG)).getServletContext();
    ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONTEXT);
    String systemId = servletContext.getRealPath(finalLocation);
    // TODO 更改 systemId 的位址
    if (Constants.JASPER_REPORTS_RESULT_LOCATION_REPLACE_MODE) {
        systemId = finalLocation;
    }
    Map parameters = new ValueStackShadowMap(stack);
    File directory = new File(systemId.substring(0, systemId.lastIndexOf(File.separator)));
    parameters.put("reportDirectory", directory);
    parameters.put(JRParameter.REPORT_LOCALE, invocation.getInvocationContext().getLocale());
    // put timezone in jasper report parameter
    if (timeZone != null) {
        timeZone = conditionalParse(timeZone, invocation);
        final TimeZone tz = TimeZone.getTimeZone(timeZone);
        if (tz != null) {
            // put the report time zone
            parameters.put(JRParameter.REPORT_TIME_ZONE, tz);
        }
    }
    // Add any report parameters from action to param map.
    Map reportParams = (Map) stack.findValue(reportParameters);
    if (reportParams != null) {
        LOG.debug("Found report parameters; adding to parameters...");
        parameters.putAll(reportParams);
    }
    ByteArrayOutputStream output;
    JasperPrint jasperPrint;
    // Fill the report and produce a print object
    try {
        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(new File(systemId));
        if (conn == null) {
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource);
        } else {
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
        }
    } catch (JRException e) {
        LOG.error("Error building report for uri {}", systemId, e);
        throw new ServletException(e.getMessage(), e);
    }
    // Export the print object to the desired output format
    try {
        if (contentDisposition != null || documentName != null) {
            final StringBuffer tmp = new StringBuffer();
            tmp.append((contentDisposition == null) ? "inline" : contentDisposition);
            if (documentName != null) {
                tmp.append("; filename=");
                tmp.append(documentName);
                tmp.append(".");
                tmp.append(format.toLowerCase());
            }
            response.setHeader("Content-disposition", tmp.toString());
        }
        JRExporter exporter;
        if (format.equals(FORMAT_PDF)) {
            response.setContentType("application/pdf");
            exporter = new JRPdfExporter();
        } else if (format.equals(FORMAT_CSV)) {
            response.setContentType("text/csv");
            exporter = new JRCsvExporter();
        } else if (format.equals(FORMAT_HTML)) {
            response.setContentType("text/html");
            // IMAGES_MAPS seems to be only supported as "backward compatible" from JasperReports 1.1.0
            Map imagesMap = new HashMap();
            request.getSession(true).setAttribute("IMAGES_MAP", imagesMap);
            exporter = new JRHtmlExporter();
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap);
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + imageServletUrl);
            // Needed to support chart images:
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint);
        } else if (format.equals(FORMAT_XLS)) {
            response.setContentType("application/vnd.ms-excel");
            exporter = new JRXlsExporter();
        } else if (format.equals(FORMAT_XML)) {
            response.setContentType("text/xml");
            exporter = new JRXmlExporter();
        } else if (format.equals(FORMAT_RTF)) {
            response.setContentType("application/rtf");
            exporter = new JRRtfExporter();
        } else {
            throw new ServletException("Unknown report format: " + format);
        }
        Map exportParams = (Map) stack.findValue(exportParameters);
        if (exportParams != null) {
            LOG.debug("Found export parameters; adding to exporter parameters...");
            exporter.getParameters().putAll(exportParams);
        }
        output = exportReportToBytes(jasperPrint, exporter);
    } catch (JRException e) {
        LOG.error("Error producing {} report for uri {}", format, systemId, e);
        throw new ServletException(e.getMessage(), e);
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
            LOG.warn("Could not close db connection properly", e);
        }
    }
    response.setContentLength(output.size());
    // Will throw ServletException on IOException.
    writeReport(response, output);
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletContext(javax.servlet.ServletContext) Connection(java.sql.Connection) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) TimeZone(java.util.TimeZone) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File)

Example 62 with Action

use of com.opensymphony.xwork2.Action in project atlasmap by atlasmap.

the class DefaultAtlasFieldActionsServiceTest method testProcessActionWithActionActionDetailObjectAtlasExceptionNoMethod.

@Test(expected = AtlasException.class)
public void testProcessActionWithActionActionDetailObjectAtlasExceptionNoMethod() throws AtlasException {
    Action action = new AbsoluteValue();
    Object sourceObject = new Integer("1");
    ActionDetail actionDetail = new ActionDetail();
    actionDetail.setClassName("io.atlasmap.actions.NumberFieldActions");
    actionDetail.setSourceType(FieldType.NUMBER);
    // actionDetail.setMethod("absolute");
    fieldActionsService.processAction(action, actionDetail, sourceObject);
}
Also used : Action(io.atlasmap.v2.Action) AbsoluteValue(io.atlasmap.v2.AbsoluteValue) ActionDetail(io.atlasmap.v2.ActionDetail) Test(org.junit.Test)

Example 63 with Action

use of com.opensymphony.xwork2.Action in project atlasmap by atlasmap.

the class DefaultAtlasFieldActionsServiceTest method testProcessActionWithActionActionDetailObjectAtlasException.

@Test(expected = AtlasException.class)
public void testProcessActionWithActionActionDetailObjectAtlasException() throws AtlasException {
    Action action = new AbsoluteValue();
    Object sourceObject = new Integer("1");
    ActionDetail actionDetail = new ActionDetail();
    actionDetail.setClassName("io.atlasmap.actions.NumberFieldActions");
    actionDetail.setSourceType(FieldType.INTEGER);
    actionDetail.setMethod("absoluteValue");
    fieldActionsService.processAction(action, actionDetail, sourceObject);
}
Also used : Action(io.atlasmap.v2.Action) AbsoluteValue(io.atlasmap.v2.AbsoluteValue) ActionDetail(io.atlasmap.v2.ActionDetail) Test(org.junit.Test)

Example 64 with Action

use of com.opensymphony.xwork2.Action in project atlasmap by atlasmap.

the class DefaultAtlasFieldActionService method processAction.

protected Object processAction(Action action, ActionDetail actionDetail, Object sourceObject) throws AtlasException {
    Object targetObject = null;
    if (actionDetail != null) {
        Object actionObject = null;
        try {
            Class<?> actionClazz = Class.forName(actionDetail.getClassName());
            actionObject = actionClazz.newInstance();
            Method method = null;
            if (actionDetail.getSourceType() != null) {
                switch(actionDetail.getSourceType()) {
                    case ANY:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Object.class);
                        break;
                    case BIG_INTEGER:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, BigInteger.class);
                        break;
                    case BOOLEAN:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Boolean.class);
                        break;
                    case BYTE:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Byte.class);
                        break;
                    case BYTE_ARRAY:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Byte[].class);
                        break;
                    case CHAR:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Character.class);
                        break;
                    case DATE:
                    case DATE_TIME:
                    case DATE_TZ:
                    case TIME_TZ:
                    case DATE_TIME_TZ:
                    case ANY_DATE:
                        if (sourceObject instanceof Calendar) {
                            sourceObject = DateTimeHelper.toZonedDateTime((Calendar) sourceObject);
                        } else if (sourceObject instanceof Date) {
                            sourceObject = DateTimeHelper.toZonedDateTime((Date) sourceObject, null);
                        } else if (sourceObject instanceof LocalDate) {
                            sourceObject = DateTimeHelper.toZonedDateTime((LocalDate) sourceObject, null);
                        } else if (sourceObject instanceof LocalTime) {
                            sourceObject = DateTimeHelper.toZonedDateTime((LocalTime) sourceObject, null);
                        } else if (sourceObject instanceof LocalDateTime) {
                            sourceObject = DateTimeHelper.toZonedDateTime((LocalDateTime) sourceObject, null);
                        } else if (!(sourceObject instanceof ZonedDateTime)) {
                            LOG.warn(String.format("Unsupported sourceObject type=%s in actionClass=%s", sourceObject.getClass(), actionDetail.getClassName()));
                            break;
                        }
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, ZonedDateTime.class);
                        break;
                    case DECIMAL:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, BigDecimal.class);
                        break;
                    case DOUBLE:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Double.class);
                        break;
                    case FLOAT:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Float.class);
                        break;
                    case INTEGER:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Integer.class);
                        break;
                    case LONG:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Long.class);
                        break;
                    case NUMBER:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Number.class);
                        break;
                    case SHORT:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, Short.class);
                        break;
                    case STRING:
                        method = actionClazz.getMethod(actionDetail.getMethod(), Action.class, String.class);
                        break;
                    default:
                        LOG.warn(String.format("Unsupported sourceType=%s in actionClass=%s", actionDetail.getSourceType().value(), actionDetail.getClassName()));
                        break;
                }
            }
            if (method == null) {
                throw new AtlasException(String.format("Unable to locate field action className=%s method=%s sourceType=%s", actionDetail.getClassName(), actionDetail.getMethod(), actionDetail.getSourceType()));
            }
            if (Modifier.isStatic(method.getModifiers())) {
                targetObject = method.invoke(null, action, sourceObject);
            } else {
                targetObject = method.invoke(actionObject, action, sourceObject);
            }
        } catch (Throwable e) {
            throw new AtlasException(String.format("Error processing action %s", actionDetail.getName()), e);
        }
        return targetObject;
    }
    return sourceObject;
}
Also used : LocalDateTime(java.time.LocalDateTime) AtlasFieldAction(io.atlasmap.api.AtlasFieldAction) Action(io.atlasmap.v2.Action) LocalTime(java.time.LocalTime) Calendar(java.util.Calendar) Method(java.lang.reflect.Method) AtlasException(io.atlasmap.api.AtlasException) LocalDate(java.time.LocalDate) Date(java.util.Date) LocalDate(java.time.LocalDate) BigDecimal(java.math.BigDecimal) BigInteger(java.math.BigInteger) ZonedDateTime(java.time.ZonedDateTime) BigInteger(java.math.BigInteger)

Example 65 with Action

use of com.opensymphony.xwork2.Action in project java-docs-samples by GoogleCloudPlatform.

the class Inspect method inspectGcsFile.

// [END dlp_inspect_file]
// [START dlp_inspect_gcs]
/**
 * Inspect GCS file for Info types and wait on job completion using Google Cloud Pub/Sub
 * notification
 *
 * @param bucketName The name of the bucket where the file resides.
 * @param fileName The path to the file within the bucket to inspect (can include wildcards, eg.
 *     my-image.*)
 * @param minLikelihood The minimum likelihood required before returning a match
 * @param infoTypes The infoTypes of information to match
 * @param maxFindings The maximum number of findings to report (0 = server maximum)
 * @param topicId Google Cloud Pub/Sub topic Id to notify of job status
 * @param subscriptionId Google Cloud Subscription to above topic to listen for job status updates
 * @param projectId Google Cloud project ID
 */
private static void inspectGcsFile(String bucketName, String fileName, Likelihood minLikelihood, List<InfoType> infoTypes, int maxFindings, String topicId, String subscriptionId, String projectId) throws Exception {
    // Instantiates a client
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
        CloudStorageOptions cloudStorageOptions = CloudStorageOptions.newBuilder().setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl("gs://" + bucketName + "/" + fileName)).build();
        StorageConfig storageConfig = StorageConfig.newBuilder().setCloudStorageOptions(cloudStorageOptions).build();
        FindingLimits findingLimits = FindingLimits.newBuilder().setMaxFindingsPerRequest(maxFindings).build();
        InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes).setMinLikelihood(minLikelihood).setLimits(findingLimits).build();
        String pubSubTopic = String.format("projects/%s/topics/%s", projectId, topicId);
        Action.PublishToPubSub publishToPubSub = Action.PublishToPubSub.newBuilder().setTopic(pubSubTopic).build();
        Action action = Action.newBuilder().setPubSub(publishToPubSub).build();
        InspectJobConfig inspectJobConfig = InspectJobConfig.newBuilder().setStorageConfig(storageConfig).setInspectConfig(inspectConfig).addActions(action).build();
        // Semi-synchronously submit an inspect job, and wait on results
        CreateDlpJobRequest createDlpJobRequest = CreateDlpJobRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setInspectJob(inspectJobConfig).build();
        DlpJob dlpJob = dlpServiceClient.createDlpJob(createDlpJobRequest);
        System.out.println("Job created with ID:" + dlpJob.getName());
        final SettableApiFuture<Boolean> done = SettableApiFuture.create();
        // Set up a Pub/Sub subscriber to listen on the job completion status
        Subscriber subscriber = Subscriber.newBuilder(ProjectSubscriptionName.of(projectId, subscriptionId), (pubsubMessage, ackReplyConsumer) -> {
            if (pubsubMessage.getAttributesCount() > 0 && pubsubMessage.getAttributesMap().get("DlpJobName").equals(dlpJob.getName())) {
                // notify job completion
                done.set(true);
                ackReplyConsumer.ack();
            }
        }).build();
        subscriber.startAsync();
        // For long jobs, consider using a truly asynchronous execution model such as Cloud Functions
        try {
            done.get(1, TimeUnit.MINUTES);
            // Wait for the job to become available
            Thread.sleep(500);
        } catch (Exception e) {
            System.out.println("Unable to verify job completion.");
        }
        DlpJob completedJob = dlpServiceClient.getDlpJob(GetDlpJobRequest.newBuilder().setName(dlpJob.getName()).build());
        System.out.println("Job status: " + completedJob.getState());
        InspectDataSourceDetails inspectDataSourceDetails = completedJob.getInspectDetails();
        InspectDataSourceDetails.Result result = inspectDataSourceDetails.getResult();
        if (result.getInfoTypeStatsCount() > 0) {
            System.out.println("Findings: ");
            for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
                System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
                System.out.println("\tCount: " + infoTypeStat.getCount());
            }
        } else {
            System.out.println("No findings.");
        }
    }
}
Also used : ByteContentItem(com.google.privacy.dlp.v2.ByteContentItem) InspectResult(com.google.privacy.dlp.v2.InspectResult) KindExpression(com.google.privacy.dlp.v2.KindExpression) Options(org.apache.commons.cli.Options) Likelihood(com.google.privacy.dlp.v2.Likelihood) Subscriber(com.google.cloud.pubsub.v1.Subscriber) BigQueryOptions(com.google.privacy.dlp.v2.BigQueryOptions) HelpFormatter(org.apache.commons.cli.HelpFormatter) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) CloudStorageOptions(com.google.privacy.dlp.v2.CloudStorageOptions) ArrayList(java.util.ArrayList) DefaultParser(org.apache.commons.cli.DefaultParser) InspectDataSourceDetails(com.google.privacy.dlp.v2.InspectDataSourceDetails) FindingLimits(com.google.privacy.dlp.v2.InspectConfig.FindingLimits) InspectContentResponse(com.google.privacy.dlp.v2.InspectContentResponse) ServiceOptions(com.google.cloud.ServiceOptions) URLConnection(java.net.URLConnection) StorageConfig(com.google.privacy.dlp.v2.StorageConfig) CommandLine(org.apache.commons.cli.CommandLine) PartitionId(com.google.privacy.dlp.v2.PartitionId) Action(com.google.privacy.dlp.v2.Action) DatastoreOptions(com.google.privacy.dlp.v2.DatastoreOptions) ProjectTopicName(com.google.pubsub.v1.ProjectTopicName) Option(org.apache.commons.cli.Option) InspectJobConfig(com.google.privacy.dlp.v2.InspectJobConfig) DlpServiceClient(com.google.cloud.dlp.v2.DlpServiceClient) Finding(com.google.privacy.dlp.v2.Finding) CreateDlpJobRequest(com.google.privacy.dlp.v2.CreateDlpJobRequest) Files(java.nio.file.Files) CommandLineParser(org.apache.commons.cli.CommandLineParser) ContentItem(com.google.privacy.dlp.v2.ContentItem) InfoType(com.google.privacy.dlp.v2.InfoType) InfoTypeStats(com.google.privacy.dlp.v2.InfoTypeStats) SettableApiFuture(com.google.api.core.SettableApiFuture) ByteString(com.google.protobuf.ByteString) TimeUnit(java.util.concurrent.TimeUnit) InspectConfig(com.google.privacy.dlp.v2.InspectConfig) List(java.util.List) ProjectName(com.google.privacy.dlp.v2.ProjectName) GetDlpJobRequest(com.google.privacy.dlp.v2.GetDlpJobRequest) Paths(java.nio.file.Paths) ParseException(org.apache.commons.cli.ParseException) BigQueryTable(com.google.privacy.dlp.v2.BigQueryTable) ProjectSubscriptionName(com.google.pubsub.v1.ProjectSubscriptionName) OptionGroup(org.apache.commons.cli.OptionGroup) DlpJob(com.google.privacy.dlp.v2.DlpJob) InspectContentRequest(com.google.privacy.dlp.v2.InspectContentRequest) Collections(java.util.Collections) Action(com.google.privacy.dlp.v2.Action) FindingLimits(com.google.privacy.dlp.v2.InspectConfig.FindingLimits) StorageConfig(com.google.privacy.dlp.v2.StorageConfig) InspectDataSourceDetails(com.google.privacy.dlp.v2.InspectDataSourceDetails) ByteString(com.google.protobuf.ByteString) InspectConfig(com.google.privacy.dlp.v2.InspectConfig) CreateDlpJobRequest(com.google.privacy.dlp.v2.CreateDlpJobRequest) ParseException(org.apache.commons.cli.ParseException) InfoTypeStats(com.google.privacy.dlp.v2.InfoTypeStats) Subscriber(com.google.cloud.pubsub.v1.Subscriber) DlpServiceClient(com.google.cloud.dlp.v2.DlpServiceClient) CloudStorageOptions(com.google.privacy.dlp.v2.CloudStorageOptions) DlpJob(com.google.privacy.dlp.v2.DlpJob) InspectJobConfig(com.google.privacy.dlp.v2.InspectJobConfig)

Aggregations

ActionSupport (com.opensymphony.xwork2.ActionSupport)61 List (java.util.List)40 Action (io.atlasmap.v2.Action)35 ArrayList (java.util.ArrayList)23 Test (org.junit.jupiter.api.Test)16 Content (com.agiletec.plugins.jacms.aps.system.services.content.model.Content)14 SimpleField (io.atlasmap.v2.SimpleField)13 Field (io.atlasmap.v2.Field)12 Mapping (io.atlasmap.v2.Mapping)11 ActionContext (com.opensymphony.xwork2.ActionContext)9 AtlasMapping (io.atlasmap.v2.AtlasMapping)9 Collections (java.util.Collections)9 HashMap (java.util.HashMap)9 SettableApiFuture (com.google.api.core.SettableApiFuture)8 ServiceOptions (com.google.cloud.ServiceOptions)8 DlpServiceClient (com.google.cloud.dlp.v2.DlpServiceClient)8 Subscriber (com.google.cloud.pubsub.v1.Subscriber)8 Action (com.google.privacy.dlp.v2.Action)8 BigQueryTable (com.google.privacy.dlp.v2.BigQueryTable)8 CreateDlpJobRequest (com.google.privacy.dlp.v2.CreateDlpJobRequest)8