Java Code Examples for org.ofbiz.base.util.Debug.logError()

The following are Jave code examples for showing how to use logError() of the org.ofbiz.base.util.Debug class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: scipio-erp   File: TechDataServices.java   View Source Code Vote up 6 votes
/** Used to request the remaining capacity available for dateFrom in a TechDataCalenda,
 * If the dateFrom (param in) is not  in an available TechDataCalendar period, the return value is zero.
 *
 * @param techDataCalendar        The TechDataCalendar cover
 * @param dateFrom                        the date
 * @return  long capacityRemaining
 */
public static long capacityRemainingBackward(GenericValue techDataCalendar,  Timestamp  dateFrom) {
    GenericValue techDataCalendarWeek = null;
    // TODO read TechDataCalendarExcWeek to manage exception week (maybe it's needed to refactor the entity definition
    try {
        techDataCalendarWeek = techDataCalendar.getRelatedOne("TechDataCalendarWeek", true);
    } catch (GenericEntityException e) {
        Debug.logError("Pb reading Calendar Week associated with calendar"+e.getMessage(), module);
        return 0;
    }
    // TODO read TechDataCalendarExcDay to manage execption day
    Calendar cDateTrav =  Calendar.getInstance();
    cDateTrav.setTime(dateFrom);
    Map<String, Object> position = dayEndCapacityAvailable(techDataCalendarWeek, cDateTrav.get(Calendar.DAY_OF_WEEK));
    int moveDay = ((Integer) position.get("moveDay")).intValue();
    if (moveDay != 0) return 0;
    Time startTime = (Time) position.get("startTime");
    Double capacity = (Double) position.get("capacity");
    Timestamp startAvailablePeriod = new Timestamp(UtilDateTime.getDayStart(dateFrom).getTime() + startTime.getTime() + cDateTrav.get(Calendar.ZONE_OFFSET) + cDateTrav.get(Calendar.DST_OFFSET));
    if (dateFrom.before(startAvailablePeriod)) return 0;
    Timestamp endAvailablePeriod = new Timestamp(startAvailablePeriod.getTime()+capacity.longValue());
    if (dateFrom.after(endAvailablePeriod)) return 0;
    return  dateFrom.getTime() - startAvailablePeriod.getTime();
}
 
Example 2
Project: scipio-erp   File: EntityCacheServices.java   View Source Code Vote up 6 votes
public void distributedClearCacheLineByCondition(String entityName, EntityCondition condition) {
    // Debug.logInfo("running distributedClearCacheLineByCondition for (name, condition): " + entityName + ", " + condition + ")", module);
    if (this.dispatcher == null) {
        Debug.logWarning("No dispatcher is available, somehow the setDelegator (which also creates a dispatcher) was not called, not running distributed cache clear", module);
        return;
    }

    GenericValue userLogin = getAuthUserLogin();
    if (userLogin == null) {
        Debug.logWarning("The userLogin for distributed cache clear was not found with userLoginId [" + userLoginId + "], not clearing remote caches.", module);
        return;
    }

    try {
        this.dispatcher.runAsync("distributedClearCacheLineByCondition", UtilMisc.toMap("entityName", entityName, "condition", condition, "userLogin", userLogin), false);
    } catch (GenericServiceException e) {
        Debug.logError(e, "Error running the distributedClearCacheLineByCondition service", module);
    }
}
 
Example 3
Project: scipio-erp   File: IdealEvents.java   View Source Code Vote up 6 votes
private static String getPaymentGatewayConfigValue(Delegator delegator, String paymentGatewayConfigId, String paymentGatewayConfigParameterName,
                                                   String resource, String parameterName) {
    String returnValue = "";
    if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) {
        try {
            GenericValue ideal = EntityQuery.use(delegator).from("PaymentGatewayiDEAL").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne();
            if (UtilValidate.isNotEmpty(ideal)) {
                Object idealField = ideal.get(paymentGatewayConfigParameterName);
                if (idealField != null) {
                    returnValue = idealField.toString().trim();
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    } else {
        String value = EntityUtilProperties.getPropertyValue(resource, parameterName, delegator);
        if (value != null) {
            returnValue = value.trim();
        }
    }
    return returnValue;
}
 
Example 4
Project: scipio-erp   File: CmsPageServices.java   View Source Code Vote up 6 votes
/**
 * Creates a new page version in the repository. The content is not live
 * until it is approved.
 */
public static Map<String, Object> addPageVersion(DispatchContext dctx, Map<String, ?> context) {
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Delegator delegator = dctx.getDelegator();
    try {
        CmsPage page = CmsPage.getWorker().findByIdAlways(delegator, (String) context.get("pageId"), false);
        CmsPageVersion version = page.addVersion((String) context.get("content"));
        String partyId = CmsServiceUtil.getUserPartyId(context);
        if (partyId != null) {
            version.setCreatedBy(partyId);
        }
        if (context.get("comment") != null) {
            version.setVersionComment((String) context.get("comment"));
        }
        version.store();
        result.put("versionId", version.getId());
    } catch (Exception e) {
        FormattedError err = errorFmt.format(e, "Error adding page version (pageId: " + context.get("pageId") + ")", context);
        Debug.logError(err.getEx(), err.getLogMsg(), module);
        return err.returnError();
    }
    return result;
}
 
Example 5
Project: scipio-erp   File: CmsControlDataServices.java   View Source Code Vote up 6 votes
public static Map<String, Object> createUpdateProcessViewMapping(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();

    String processViewMappingId = (String) context.get("processViewMappingId");
    String webSiteId = (String) context.get("webSiteId");

    try {
        CmsProcessViewMapping processViewMapping = CmsProcessViewMapping.getWorker()
                .createOrUpdateControlDataObject(delegator, webSiteId, processViewMappingId, context);
        processViewMappingId = processViewMapping.getId();
    } catch (Exception e) {
        FormattedError err = errorFmt.format(e, "Error creating or updating process view mapping", context);
        Debug.logError(err.getEx(), err.getLogMsg(), module);
        return err.returnError();
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("processViewMappingId", processViewMappingId);
    return result;
}
 
Example 6
Project: scipio-erp   File: FlexibleMapAccessor.java   View Source Code Vote up 6 votes
/** Given the name based information in this accessor, remove the value from the passed in Map.
 * @param base the Map to remove from
 * @return the object removed
 */
public T remove(Map<String, ? extends Object> base) {
    if (this.isEmpty) {
        return null;
    }
    T object = get(base);
    if (object == null) {
        return null;
    }
    try {
        Map<String, Object> writableMap = UtilGenerics.cast(base);
        UelUtil.removeValue(writableMap, getExpression(base));
    } catch (Exception e) {
        Debug.logError("UEL exception while removing value: " + e + ", original = " + this.original, module);
    }
    return object;
}
 
Example 7
Project: scipio-erp   File: CmsPageTemplateServices.java   View Source Code Vote up 6 votes
/**
 * Gets a page template version.
 */
public static Map<String, Object> getPageTemplateVersion(DispatchContext dctx, Map<String, ?> context) {
    Map<String, Object> result = ServiceUtil.returnSuccess();
    try {
        Delegator delegator = dctx.getDelegator();
        String pageTemplateId = (String) context.get("pageTemplateId");
        String versionId = (String) context.get("versionId");
        boolean minimalInfoOnly = EntityUtil.toBoolean((String) context.get("minimalInfoOnly"), false);
        
        CmsPageTemplateVersion tmpVer = CmsPageTemplate.getVerComTemplateWorker().findSpecificTemplateVersion(delegator, pageTemplateId, versionId);
        
        if (tmpVer != null) {
            Map<String, Object> version = new HashMap<>();
            tmpVer.putIntoMap(version, minimalInfoOnly, null);
            result.put("version", version);
        } else {
            result = ServiceUtil.returnFailure("Could not find page template version '" + versionId + "' for page template '" +
                    pageTemplateId + "'"); // TODO: Localize
        }
    } catch(Exception e) {
        FormattedError err = errorFmt.format(e, context);
        Debug.logError(err.getEx(), err.getLogMsg(), module);
        return err.returnFailure();
    }
    return result;
}
 
Example 8
Project: scipio-erp   File: InventoryWorker.java   View Source Code Vote up 6 votes
/**
 * Finds all outstanding Purchase orders for a productId.  The orders and the items cannot be completed, cancelled, or rejected
 * @param productId the product id
 * @param delegator the delegator
 * @return returns all outstanding Purchase orders for a productId
 */
public static List<GenericValue> getOutstandingPurchaseOrders(String productId, Delegator delegator) {
    try {
        List<EntityCondition> purchaseOrderConditions = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"),
                EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED"),
                EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"),
                EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED"),
                EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
                EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"));
        purchaseOrderConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER"));
        purchaseOrderConditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
        List<GenericValue> purchaseOrders = EntityQuery.use(delegator).from("OrderHeaderAndItems")
                .where(EntityCondition.makeCondition(purchaseOrderConditions, EntityOperator.AND))
                .orderBy("estimatedDeliveryDate DESC", "orderDate")
                .queryList();
        return purchaseOrders;
    } catch (GenericEntityException ex) {
        Debug.logError("Unable to find outstanding purchase orders for product [" + productId + "] due to " + ex.getMessage() + " - returning null", module);
        return null;
    }
}
 
Example 9
Project: scipio-erp   File: ProductServices.java   View Source Code Vote up 6 votes
/**
 * SCIPIO: getProductContentLocalizedSimpleTextViews.
 * Added 2017-10-27.
 */
public static Map<String, Object> getProductContentLocalizedSimpleTextViews(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    
    String productId = (String) context.get("productId");
    Collection<String> productContentTypeIdList = UtilGenerics.checkCollection(context.get("productContentTypeIdList"));
    boolean filterByDate = !Boolean.FALSE.equals(context.get("filterByDate"));
    boolean useCache = Boolean.TRUE.equals(context.get("useCache"));
    
    Map<String, List<GenericValue>> viewsByType = null; 
    try {
        viewsByType = ProductWorker.getProductContentLocalizedSimpleTextViews(delegator, dispatcher, 
                productId, productContentTypeIdList, filterByDate ? UtilDateTime.nowTimestamp() : null, useCache);
        Map<String, Object> result = ServiceUtil.returnSuccess();
        CategoryServices.postprocessProductCategoryContentLocalizedSimpleTextContentAssocViews(dctx, context, viewsByType, result);
        return result;
    } catch (Exception e) {
        PropertyMessage msgIntro = PropertyMessage.makeWithVars("ProductErrorUiLabels", 
                "productservices.error_reading_ProductContent_simple_texts_for_alternate_locale_for_product",
                "productId", productId);
        Debug.logError(e, PropertyMessageExUtil.makeLogMessage(msgIntro, e), module);
        return ServiceUtil.returnFailure(msgIntro, e, locale);
    }
}
 
Example 10
Project: scipio-erp   File: MimeMessageWrapper.java   View Source Code Vote up 5 votes
protected String getTextFromStream(InputStream stream) {
    StringBuilder builder = new StringBuilder();
    byte[] buffer = new byte[4096];
    try {
        for (int n; (n = stream.read(buffer)) != -1;) {
            builder.append(new String(buffer, 0, n));
        }
    } catch (IOException e) {
        Debug.logError(e, module);
        return null;
    }
    return builder.toString();
}
 
Example 11
Project: scipio-erp   File: SolrUtil.java   View Source Code Vote up 5 votes
public static GenericValue getSolrStatus(Delegator delegator) {
    GenericValue solrStatus;
    try {
        solrStatus = EntityQuery.use(delegator).from("SolrStatus")
                .where("solrId", "SOLR-MAIN").cache(false).queryOne();
        if (solrStatus == null) {
            Debug.logWarning("Could not get SolrStatus for SOLR-MAIN - seed data missing?", module);
        } else {
            return solrStatus;
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    return null;
}
 
Example 12
Project: scipio-erp   File: ProductUtilServices.java   View Source Code Vote up 5 votes
/** for all disc products, remove from category memberships */
public static Map<String, Object> removeCategoryMembersOfDiscProducts(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;

    try {
        EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList(
                EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.NOT_EQUAL, null),
                EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp)
               ), EntityOperator.AND);
        EntityListIterator eli = EntityQuery.use(delegator).from("Product").where(condition).queryIterator();
        GenericValue product = null;
        int numSoFar = 0;
        while ((product = eli.next()) != null) {
            String productId = product.getString("productId");
            List<GenericValue> productCategoryMemberList = EntityQuery.use(delegator).from("ProductCategoryMember").where("productId", productId).queryList();
            if (productCategoryMemberList.size() > 0) {
                for (GenericValue productCategoryMember: productCategoryMemberList) {
                    // coded this way rather than a removeByAnd so it can be easily changed...
                    productCategoryMember.remove();
                }
                numSoFar++;
                if (numSoFar % 500 == 0) {
                    Debug.logInfo("Removed category members for " + numSoFar + " sales discontinued products.", module);
                }
            }
        }
        eli.close();
        Debug.logInfo("Completed - Removed category members for " + numSoFar + " sales discontinued products.", module);
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resourceError,"productutilservices.entity_error_running_removeCategoryMembersOfDiscProducts", messageMap, locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    }

    return ServiceUtil.returnSuccess();
}
 
Example 13
Project: scipio-erp   File: CatalogWorker.java   View Source Code Vote up 5 votes
public static boolean getCatalogQuickaddUse(ServletRequest request, String prodCatalogId) {
    if (prodCatalogId == null || prodCatalogId.length() <= 0) return false;
    Delegator delegator = (Delegator) request.getAttribute("delegator");

    try {
        GenericValue prodCatalog = EntityQuery.use(delegator).from("ProdCatalog").where("prodCatalogId", prodCatalogId).cache().queryOne();

        if (prodCatalog != null) {
            return "Y".equals(prodCatalog.getString("useQuickAdd"));
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error looking up name for prodCatalog with id " + prodCatalogId, module);
    }
    return false;
}
 
Example 14
Project: scipio-erp   File: WidgetFactory.java   View Source Code Vote up 5 votes
/**
 * Returns a <code>ModelScreenWidget</code> instance that implements the specified
 * XML element.
 * 
 * @param modelScreen The containing screen for the widget
 * @param element The widget XML element
 * @return a <code>ModelScreenWidget</code> instance that implements the specified
 * XML element
 * @throws IllegalArgumentException
 */
public static ModelScreenWidget getModelScreenWidget(ModelScreen modelScreen, Element element) {
    Assert.notNull("modelScreen", modelScreen, "element", element);
    Constructor<? extends ModelScreenWidget> widgetConst = screenWidgets.get(element.getTagName());
    if (widgetConst == null) {
        throw new IllegalArgumentException("ModelScreenWidget class not found for element " + element.getTagName());
    }
    try {
        return widgetConst.newInstance(modelScreen, element);
    } catch (Exception e) {
        // log the original exception since the rethrown exception doesn't include much info about it and hides the cause
        Debug.logError(e, "Error getting widget for element " + element.getTagName(), module);
        throw new IllegalArgumentException(e.getMessage() + " for element " + element.getTagName());
    }
}
 
Example 15
Project: scipio-erp   File: OrderReadHelper.java   View Source Code Vote up 5 votes
public String getOrderAttribute(String attributeName) {
    String attributeValue = null;
    if (orderHeader != null) {
        try {
            GenericValue orderAttribute = EntityUtil
                    .getFirst(orderHeader.getRelated("OrderAttribute", UtilMisc.toMap("attrName", attributeName), null, false));
            if (orderAttribute != null) {
                attributeValue = orderAttribute.getString("attrValue");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    return attributeValue;
}
 
Example 16
Project: scipio-erp   File: HtmlMenuRendererImage.java   View Source Code Vote up 5 votes
public String buildDivStr(ModelMenuItem menuItem, Map<String, Object> context) throws IOException {

        StringBuilder imgStr = new StringBuilder("<img src=\"");
        String contentId = menuItem.getAssociatedContentId(context);
        Delegator delegator = (Delegator)request.getAttribute("delegator");
        GenericValue webSitePublishPoint = null;
                //Debug.logInfo("in HtmlMenuRendererImage, contentId:" + contentId,"");
        try {
            if (WidgetContentWorker.contentWorker != null) {
                webSitePublishPoint = WidgetContentWorker.contentWorker.getWebSitePublishPointExt(delegator, contentId, false);
            } else {
                Debug.logError("Not rendering image because can't get WebSitePublishPoint, not ContentWorker found.", module);
            }
        } catch (GenericEntityException e) {
                //Debug.logInfo("in HtmlMenuRendererImage, GEException:" + e.getMessage(),"");
            throw new RuntimeException(e.getMessage());
        }
        String medallionLogoStr = webSitePublishPoint.getString("medallionLogo");
        StringWriter buf = new StringWriter();
        appendContentUrl(buf, medallionLogoStr);
        imgStr.append(buf.toString());
                //Debug.logInfo("in HtmlMenuRendererImage, imgStr:" + imgStr,"");
        String cellWidth = menuItem.getCellWidth();
        imgStr.append("\"");
        if (UtilValidate.isNotEmpty(cellWidth))
            imgStr.append(" width=\"").append(cellWidth).append("\" ");

        imgStr.append(" border=\"0\" />");
        return imgStr.toString();
    }
 
Example 17
Project: scipio-erp   File: ProductServices.java   View Source Code Vote up 4 votes
/**
 * SCIPIO: replaceProductContentLocalizedSimpleTexts.
 * Added 2017-12-06.
 */
public static Map<String, Object> replaceProductContentLocalizedSimpleTexts(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    String productId = (String) context.get("productId");
    
    try {
        GenericValue product = delegator.findOne("Product", UtilMisc.toMap("productId", productId), false);
        if (product == null) {
            throw new IllegalArgumentException(UtilProperties.getMessage("ProductUiLabels", "ProductProductNotFound", locale) + ": " + productId);
        }
        
        Map<String, Object> contentFieldsUnparsed = UtilGenerics.checkMap(context.get("contentFields"));
        Map<String, List<Map<String, Object>>> contentFields = LocalizedContentWorker.parseLocalizedSimpleTextContentFieldParams(contentFieldsUnparsed, null, true);
    
        for(Map.Entry<String, List<Map<String, Object>>> entry : contentFields.entrySet()) {
            String productContentTypeId = entry.getKey();
            List<Map<String, Object>> entries = entry.getValue();
        
            List<GenericValue> productContentList = EntityQuery.use(delegator).from("ProductContent")
                    .where("productId", productId, "productContentTypeId", productContentTypeId).filterByDate()
                    .orderBy("-fromDate").queryList();
            GenericValue productContent = EntityUtil.getFirst(productContentList);
            if (productContentList.size() > 1) {
                Debug.logWarning("replaceProductContentLocalizedSimpleTexts: Multiple active ProductContent found for productContentTypeId '"
                        + productContentTypeId + "' for product '" + productId + "'; updating only latest (contentId: '" + productContent.getString("contentId") + "')", module);
            }
            
            String mainContentId = null;
            if (productContent != null) {
                mainContentId = productContent.getString("contentId");
            }

            Map<String, Object> servCtx = dctx.makeValidContext("replaceContentLocalizedSimpleTexts", ModelService.IN_PARAM, context);
            servCtx.put("mainContentId", mainContentId);
            servCtx.put("entries", entries);
            Map<String, Object> servResult = dispatcher.runSync("replaceContentLocalizedSimpleTexts", servCtx);
            if (!ServiceUtil.isSuccess(servResult)) {
                return ServiceUtil.returnError(getReplStcAltLocErrorPrefix(context, locale) + ": " + ServiceUtil.getErrorMessage(servResult));
            }
            if (mainContentId == null && servResult.get("mainContentId") != null) {
                // must create a new ProductContent record
                mainContentId = (String) servResult.get("mainContentId");
                
                productContent = delegator.makeValue("ProductContent");
                productContent.put("productId", productId);
                productContent.put("contentId", mainContentId);
                productContent.put("productContentTypeId", productContentTypeId);
                productContent.put("fromDate", UtilDateTime.nowTimestamp());
                productContent = delegator.create(productContent);
            } else if (servResult.get("mainContentId") != null && Boolean.TRUE.equals(servResult.get("allContentEmpty"))) {
                mainContentId = (String) servResult.get("mainContentId");
                if (Boolean.TRUE.equals(context.get("mainContentDelete"))) {
                    delegator.removeByAnd("ProductContent", UtilMisc.toMap("contentId", mainContentId));
                    LocalizedContentWorker.removeContentAndRelated(delegator, dispatcher, context, mainContentId);
                }
            }
        }
        return ServiceUtil.returnSuccess();
    } catch(Exception e) {
        Debug.logError(e, getReplStcAltLocErrorPrefix(context, Locale.ENGLISH) + ": " + e.getMessage(), module);
        return ServiceUtil.returnError(getReplStcAltLocErrorPrefix(context, locale) + ": " + e.getMessage());
    }
}
 
Example 18
Project: scipio-erp   File: OutputServices.java   View Source Code Vote up 4 votes
public static Map<String, Object> createFileFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
    Locale locale = (Locale) serviceContext.get("locale");
    Delegator delegator = dctx.getDelegator();
    String screenLocation = (String) serviceContext.remove("screenLocation");
    Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
    String contentType = (String) serviceContext.remove("contentType");
    String filePath = (String) serviceContext.remove("filePath");
    String fileName = (String) serviceContext.remove("fileName");

    if (UtilValidate.isEmpty(screenContext)) {
        screenContext = FastMap.newInstance();
    }
    screenContext.put("locale", locale);
    if (UtilValidate.isEmpty(contentType)) {
        contentType = "application/pdf";
    }

    try {
        MapStack<String> screenContextTmp = MapStack.create();
        screenContextTmp.put("locale", locale);

        Writer writer = new StringWriter();
        // substitute the freemarker variables...
        ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()),
                EntityUtilProperties.getPropertyValue("widget", "screenfop.screenrenderer", dctx.getDelegator()));
        ScreenRenderer screensAtt = ScreenRenderer.makeWithEnvAwareFetching(writer, screenContextTmp, foScreenStringRenderer);
        screensAtt.populateContextForService(dctx, screenContext);
        screenContextTmp.putAll(screenContext);
        screensAtt.getContext().put("formStringRenderer", foFormRenderer);
        screensAtt.render(screenLocation);

        // create the input stream for the generation
        StreamSource src = new StreamSource(new StringReader(writer.toString()));

        // create the output stream for the generation
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
        ApacheFopWorker.transform(src, null, fop);

        baos.flush();
        baos.close();

        fileName += UtilDateTime.nowAsString();
        if ("application/pdf".equals(contentType)) {
            fileName += ".pdf";
        } else if ("application/postscript".equals(contentType)) {
            fileName += ".ps";
        } else if ("text/plain".equals(contentType)) {
            fileName += ".txt";
        }
        if (UtilValidate.isEmpty(filePath)) {
            filePath = EntityUtilProperties.getPropertyValue("content.properties", "content.output.path", "/output", delegator);
        }
        File file = new File(filePath, fileName);

        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baos.toByteArray());
        fos.close();

    } catch (Exception e) {
        Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
    }

    return ServiceUtil.returnSuccess();
}
 
Example 19
Project: scipio-erp   File: ModelFormField.java   View Source Code Vote up 4 votes
@Override
public String getDescription(Map<String, Object> context) {
    Locale locale = UtilMisc.ensureLocale(context.get("locale"));

    // rather than using the context to expand the string, lookup the given entity and use it to expand the string
    GenericValue value = null;
    String fieldKey = this.keyFieldName;
    if (UtilValidate.isEmpty(fieldKey))
        fieldKey = getModelFormField().fieldName;

    Delegator delegator = WidgetWorker.getDelegator(context);
    // SCIPIO: only encode after the lookup
    //String fieldValue = getModelFormField().getEntry(context);
    String fieldValue = getModelFormField().getEntryRaw(context);
    try {
        value = delegator.findOne(this.entityName, this.cache, fieldKey, fieldValue);
    } catch (GenericEntityException e) {
        String errMsg = "Error getting value from the database for display of field [" + getModelFormField().getName()
                + "] on form [" + getModelFormField().modelForm.getName() + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new IllegalArgumentException(errMsg);
    }

    String retVal = null;
    if (value != null) {
        // expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity
        MapStack<String> localContext = MapStack.create(context);
        // Rendering code might try to modify the GenericEntity instance,
        // so we make a copy of it.
        Map<String, Object> genericEntityClone = UtilGenerics.cast(value.clone());
        localContext.push(genericEntityClone);

        // expand with the new localContext, which is locale aware
        retVal = this.getDescription().expandString(localContext, locale);
    }
    // try to get the entry for the field if description doesn't expand to anything
    if (UtilValidate.isEmpty(retVal)) {
        retVal = fieldValue;
    } 
    if (UtilValidate.isEmpty(retVal)) {
        retVal = "";
    } else if (this.getModelFormField().getEncodeOutput()) {
        retVal = WidgetWorker.getEarlyEncoder(context).encode(retVal); // SCIPIO: simplified
    }
    return retVal;
}
 
Example 20
Project: scipio-erp   File: ModelMenu.java   View Source Code Vote up 4 votes
Element loadIncludedMenu(String menuName, String resource, 
        Element currMenuElem, String currResource, 
        Map<String, Element> menuElemCache, boolean useCache, boolean cacheConsume) {
    Element inclMenuElem = null;
    Element inclRootElem = null;
    String targetResource;
    if (UtilValidate.isNotEmpty(resource)) {
        targetResource = resource;
    }
    else {
        targetResource = currResource;
    }
    
    String fullLocation = targetResource + "#" + menuName;
    if (useCache && menuElemCache.containsKey(fullLocation)) {
        inclMenuElem = menuElemCache.get(fullLocation);
        if (cacheConsume) {
            menuElemCache.remove(fullLocation);
        }
    }
    else {
        if (true) { // UtilValidate.isNotEmpty(resource)
            try {
                URL menuFileUrl = FlexibleLocation.resolveLocation(targetResource);
                Document menuFileDoc = UtilXml.readXmlDocument(menuFileUrl, true, true);
                // SCIPIO: New: Save original location as user data in Document
                if (menuFileDoc != null) {
                    WidgetDocumentInfo.retrieveAlways(menuFileDoc).setResourceLocation(targetResource);
                }
                inclRootElem = menuFileDoc.getDocumentElement();
            } catch (Exception e) {
                Debug.logError(e, "Failed to load include-menu-items resource: " + resource, module);
            }
        }
        //else {
            // SCIPIO: No! we must reload the orig doc always because the Elements get written to!
            // must have fresh versions.
            // try to find a menu definition in the same file
            //inclRootElem = currMenuElem.getOwnerDocument().getDocumentElement();
        //}
        
        if (inclRootElem != null) {
            List<? extends Element> menuElements = UtilXml.childElementList(inclRootElem, "menu");
            for (Element menuElementEntry : menuElements) {
                if (menuElementEntry.getAttribute("name").equals(menuName)) {
                    inclMenuElem = menuElementEntry;
                    break;
                }
            }
        }
        if (useCache && !cacheConsume) {
            menuElemCache.put(fullLocation, inclMenuElem);
        }
    }
    return inclMenuElem;
}