Search in sources :

Example 96 with JDOMException

use of org.jdom.JDOMException in project oozie by apache.

the class BundleStartXCommand method insertBundleActions.

/**
 * Insert bundle actions
 *
 * @throws CommandException thrown if failed to create bundle actions
 */
@SuppressWarnings("unchecked")
private void insertBundleActions() throws CommandException {
    if (bundleJob != null) {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        try {
            Element bAppXml = XmlUtils.parseXml(bundleJob.getJobXml());
            List<Element> coordElems = bAppXml.getChildren("coordinator", bAppXml.getNamespace());
            for (Element elem : coordElems) {
                Attribute name = elem.getAttribute("name");
                Attribute critical = elem.getAttribute("critical");
                if (name != null) {
                    if (map.containsKey(name.getValue())) {
                        throw new CommandException(ErrorCode.E1304, name);
                    }
                    Configuration coordConf = mergeConfig(elem);
                    // skip coord job if it is not enabled
                    if (!isEnabled(elem, coordConf)) {
                        continue;
                    }
                    boolean isCritical = false;
                    if (critical != null && Boolean.parseBoolean(critical.getValue())) {
                        isCritical = true;
                    }
                    map.put(name.getValue(), isCritical);
                } else {
                    throw new CommandException(ErrorCode.E1305);
                }
            }
        } catch (JDOMException jex) {
            throw new CommandException(ErrorCode.E1301, jex.getMessage(), jex);
        }
        // if there is no coordinator for this bundle, failed it.
        if (map.isEmpty()) {
            bundleJob.setStatus(Job.Status.FAILED);
            bundleJob.resetPending();
            try {
                BundleJobQueryExecutor.getInstance().executeUpdate(BundleJobQuery.UPDATE_BUNDLE_JOB_STATUS_PENDING, bundleJob);
            } catch (JPAExecutorException jex) {
                throw new CommandException(jex);
            }
            LOG.debug("No coord jobs for the bundle=[{0}], failed it!!", jobId);
            throw new CommandException(ErrorCode.E1318, jobId);
        }
        for (Entry<String, Boolean> coordName : map.entrySet()) {
            BundleActionBean action = createBundleAction(jobId, coordName.getKey(), coordName.getValue());
            insertList.add(action);
        }
    } else {
        throw new CommandException(ErrorCode.E0604, jobId);
    }
}
Also used : XConfiguration(org.apache.oozie.util.XConfiguration) Configuration(org.apache.hadoop.conf.Configuration) HashMap(java.util.HashMap) Attribute(org.jdom.Attribute) Element(org.jdom.Element) CommandException(org.apache.oozie.command.CommandException) JDOMException(org.jdom.JDOMException) JPAExecutorException(org.apache.oozie.executor.jpa.JPAExecutorException) BundleActionBean(org.apache.oozie.BundleActionBean)

Example 97 with JDOMException

use of org.jdom.JDOMException in project oozie by apache.

the class CoordELFunctions method ph3_coord_dataIn.

/**
 * Used to specify a list of URI's that are used as input dir to the workflow job. <p> Look for two evaluator-level
 * variables <p> A) .datain.&lt;DATAIN_NAME&gt; B) .datain.&lt;DATAIN_NAME&gt;.unresolved <p> A defines the current list of
 * URI. <p> B defines whether there are any unresolved EL-function (i.e latest) <p> If there are something
 * unresolved, this function will echo back the original function <p> otherwise it sends the uris.
 *
 * @param dataInName : Datain name
 * @return the list of URI's separated by INSTANCE_SEPARATOR <p> if there are unresolved EL function (i.e. latest)
 *         , echo back <p> the function without resolving the function.
 */
public static String ph3_coord_dataIn(String dataInName) {
    String uris = "";
    ELEvaluator eval = ELEvaluator.getCurrent();
    if (eval.getVariable(".datain." + dataInName) == null && (eval.getVariable(".actionInputLogic") != null && !StringUtils.isEmpty(eval.getVariable(".actionInputLogic").toString()))) {
        try {
            return new CoordInputLogicEvaluatorUtil().getInputDependencies(dataInName, (SyncCoordAction) eval.getVariable(COORD_ACTION));
        } catch (JDOMException e) {
            XLog.getLog(CoordELFunctions.class).error(e);
            throw new RuntimeException(e.getMessage());
        }
    }
    uris = (String) eval.getVariable(".datain." + dataInName);
    Object unResolvedObj = eval.getVariable(".datain." + dataInName + ".unresolved");
    if (unResolvedObj == null) {
        return uris;
    }
    Boolean unresolved = Boolean.parseBoolean(unResolvedObj.toString());
    if (unresolved != null && unresolved.booleanValue() == true) {
        return "${coord:dataIn('" + dataInName + "')}";
    }
    return uris;
}
Also used : CoordInputLogicEvaluatorUtil(org.apache.oozie.coord.input.logic.CoordInputLogicEvaluatorUtil) ELEvaluator(org.apache.oozie.util.ELEvaluator) JDOMException(org.jdom.JDOMException)

Example 98 with JDOMException

use of org.jdom.JDOMException in project oozie by apache.

the class LiteWorkflowStoreService method liteExecute.

/**
 * Delegation method used by the Action and Decision {@link NodeHandler} on start. <p> This method provides the
 * necessary information to create ActionExecutors.
 *
 * @param context NodeHandler context.
 * @param actionType the action type.
 * @throws WorkflowException thrown if there was an error parsing the action configuration.
 */
@SuppressWarnings("unchecked")
protected static void liteExecute(NodeHandler.Context context, String actionType) throws WorkflowException {
    XLog log = XLog.getLog(LiteWorkflowStoreService.class);
    String jobId = context.getProcessInstance().getId();
    String nodeName = context.getNodeDef().getName();
    String skipVar = context.getProcessInstance().getVar(context.getNodeDef().getName() + WorkflowInstance.NODE_VAR_SEPARATOR + ReRunXCommand.TO_SKIP);
    boolean skipAction = false;
    if (skipVar != null) {
        skipAction = skipVar.equals("true");
    }
    WorkflowActionBean action = new WorkflowActionBean();
    String actionId = Services.get().get(UUIDService.class).generateChildId(jobId, nodeName);
    if (!skipAction) {
        String nodeConf = context.getNodeDef().getConf();
        if (actionType == null) {
            try {
                Element element = XmlUtils.parseXml(nodeConf);
                actionType = element.getName();
                nodeConf = XmlUtils.prettyPrint(element).toString();
            } catch (JDOMException ex) {
                throw new WorkflowException(ErrorCode.E0700, ex.getMessage(), ex);
            }
        }
        log.debug(" Creating action for node [{0}]", nodeName);
        action.setType(actionType);
        action.setConf(nodeConf);
        action.setLogToken(((WorkflowJobBean) context.getTransientVar(WORKFLOW_BEAN)).getLogToken());
        action.setStatus(WorkflowAction.Status.PREP);
        action.setJobId(jobId);
    }
    String executionPath = context.getExecutionPath();
    action.setExecutionPath(executionPath);
    action.setCred(context.getNodeDef().getCred());
    log.debug("Setting action for cred: '" + context.getNodeDef().getCred() + "', name: '" + context.getNodeDef().getName() + "'");
    action.setUserRetryCount(0);
    int userRetryMax = getUserRetryMax(context);
    int userRetryInterval = getUserRetryInterval(context);
    action.setUserRetryMax(userRetryMax);
    action.setUserRetryInterval(userRetryInterval);
    log.debug("Setting action for userRetryMax: '" + userRetryMax + "', userRetryInterval: '" + userRetryInterval + "', name: '" + context.getNodeDef().getName() + "'");
    action.setName(nodeName);
    action.setId(actionId);
    context.setVar(nodeName + WorkflowInstance.NODE_VAR_SEPARATOR + ACTION_ID, actionId);
    List list = (List) context.getTransientVar(ACTIONS_TO_START);
    if (list == null) {
        list = new ArrayList();
        context.setTransientVar(ACTIONS_TO_START, list);
    }
    list.add(action);
}
Also used : XLog(org.apache.oozie.util.XLog) Element(org.jdom.Element) WorkflowException(org.apache.oozie.workflow.WorkflowException) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) JDOMException(org.jdom.JDOMException) WorkflowActionBean(org.apache.oozie.WorkflowActionBean)

Example 99 with JDOMException

use of org.jdom.JDOMException in project oozie by apache.

the class XmlUtils method getRootAttribute.

/**
 * //TODO move this to action registry method Return the value of an attribute from the root element of an XML
 * document.
 *
 * @param filePath path of the XML document.
 * @param attributeName attribute to retrieve value for.
 * @return value of the specified attribute.
 */
public static String getRootAttribute(String filePath, String attributeName) {
    ParamChecker.notNull(filePath, "filePath");
    ParamChecker.notNull(attributeName, "attributeName");
    SAXBuilder saxBuilder = createSAXBuilder();
    try {
        Document doc = saxBuilder.build(Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath));
        return doc.getRootElement().getAttributeValue(attributeName);
    } catch (JDOMException e) {
        throw new RuntimeException();
    } catch (IOException e) {
        throw new RuntimeException();
    }
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) IOException(java.io.IOException) Document(org.jdom.Document) JDOMException(org.jdom.JDOMException)

Example 100 with JDOMException

use of org.jdom.JDOMException in project ofbiz-framework by apache.

the class ProductServices method addAdditionalViewForProduct.

public static Map<String, Object> addAdditionalViewForProduct(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    String productId = (String) context.get("productId");
    String productContentTypeId = (String) context.get("productContentTypeId");
    ByteBuffer imageData = (ByteBuffer) context.get("uploadedFile");
    Locale locale = (Locale) context.get("locale");
    if (UtilValidate.isNotEmpty(context.get("_uploadedFile_fileName"))) {
        Map<String, Object> imageContext = new HashMap<>();
        imageContext.putAll(context);
        imageContext.put("delegator", delegator);
        imageContext.put("tenantId", delegator.getDelegatorTenantId());
        String imageFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format", delegator);
        String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", delegator), imageContext);
        String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", delegator), imageContext);
        imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath;
        imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix;
        FlexibleStringExpander filenameExpander = FlexibleStringExpander.getInstance(imageFilenameFormat);
        String viewNumber = String.valueOf(productContentTypeId.charAt(productContentTypeId.length() - 1));
        String viewType = "additional" + viewNumber;
        String id = productId;
        if (imageFilenameFormat.endsWith("${id}")) {
            id = productId + "_View_" + viewNumber;
            viewType = "additional";
        }
        String fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", "original"));
        String filePathPrefix = "";
        String filenameToUse = fileLocation;
        if (fileLocation.lastIndexOf('/') != -1) {
            // adding 1 to include the trailing slash
            filePathPrefix = fileLocation.substring(0, fileLocation.lastIndexOf('/') + 1);
            filenameToUse = fileLocation.substring(fileLocation.lastIndexOf('/') + 1);
        }
        List<GenericValue> fileExtension;
        try {
            fileExtension = EntityQuery.use(delegator).from("FileExtension").where("mimeTypeId", (String) context.get("_uploadedFile_contentType")).queryList();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
        GenericValue extension = EntityUtil.getFirst(fileExtension);
        if (extension != null) {
            filenameToUse += "." + extension.getString("fileExtensionId");
        }
        /* Write the new image file */
        String targetDirectory = imageServerPath + "/" + filePathPrefix;
        try {
            File targetDir = new File(targetDirectory);
            // Create the new directory
            if (!targetDir.exists()) {
                boolean created = targetDir.mkdirs();
                if (!created) {
                    String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_create_target_directory", locale) + " - " + targetDirectory;
                    Debug.logFatal(errMsg, module);
                    return ServiceUtil.returnError(errMsg);
                }
            // Delete existing image files
            // Images are ordered by productId (${location}/${id}/${viewtype}/${sizetype})
            } else if (!filenameToUse.contains(productId)) {
                try {
                    File[] files = targetDir.listFiles();
                    for (File file : files) {
                        if (file.isFile()) {
                            if (!file.delete()) {
                                Debug.logError("File : " + file.getName() + ", couldn't be deleted", module);
                            }
                        }
                    }
                } catch (SecurityException e) {
                    Debug.logError(e, module);
                }
            // Images aren't ordered by productId (${location}/${viewtype}/${sizetype}/${id})
            } else {
                try {
                    File[] files = targetDir.listFiles();
                    for (File file : files) {
                        if (file.isFile() && file.getName().startsWith(productId + "_View_" + viewNumber)) {
                            if (!file.delete()) {
                                Debug.logError("File : " + file.getName() + ", couldn't be deleted", module);
                            }
                        }
                    }
                } catch (SecurityException e) {
                    Debug.logError(e, module);
                }
            }
        } catch (NullPointerException e) {
            Debug.logError(e, module);
        }
        // Write
        try {
            File file = new File(imageServerPath + "/" + fileLocation + "." + extension.getString("fileExtensionId"));
            try {
                RandomAccessFile out = new RandomAccessFile(file, "rw");
                out.write(imageData.array());
                out.close();
            } catch (FileNotFoundException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteFile", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
            } catch (IOException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteBinaryData", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
            }
        } catch (NullPointerException e) {
            Debug.logError(e, module);
        }
        /* scale Image in different sizes */
        Map<String, Object> resultResize = new HashMap<>();
        try {
            resultResize.putAll(ScaleImage.scaleImageInAllSize(imageContext, filenameToUse, "additional", viewNumber));
        } catch (IOException e) {
            Debug.logError(e, "Scale additional image in all different sizes is impossible : " + e.toString(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewScaleImpossible", UtilMisc.toMap("errorString", e.toString()), locale));
        } catch (JDOMException e) {
            Debug.logError(e, "Errors occur in parsing ImageProperties.xml : " + e.toString(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewParsingError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        String imageUrl = imageUrlPrefix + "/" + fileLocation + "." + extension.getString("fileExtensionId");
        /* store the imageUrl version of the image, for backwards compatibility with code that does not use scaled versions */
        Map<String, Object> result = addImageResource(dispatcher, delegator, context, imageUrl, productContentTypeId);
        if (ServiceUtil.isError(result)) {
            return result;
        }
        /* now store the image versions created by ScaleImage.scaleImageInAllSize */
        /* have to shrink length of productContentTypeId, as otherwise value is too long for database field */
        Map<String, String> imageUrlMap = UtilGenerics.checkMap(resultResize.get("imageUrlMap"));
        for (String sizeType : ScaleImage.sizeTypeList) {
            imageUrl = imageUrlMap.get(sizeType);
            if (UtilValidate.isNotEmpty(imageUrl)) {
                try {
                    GenericValue productContentType = EntityQuery.use(delegator).from("ProductContentType").where("productContentTypeId", "XTRA_IMG_" + viewNumber + "_" + sizeType.toUpperCase(Locale.getDefault())).cache().queryOne();
                    if (UtilValidate.isNotEmpty(productContentType)) {
                        result = addImageResource(dispatcher, delegator, context, imageUrl, "XTRA_IMG_" + viewNumber + "_" + sizeType.toUpperCase(Locale.getDefault()));
                        if (ServiceUtil.isError(result)) {
                            Debug.logError(ServiceUtil.getErrorMessage(result), module);
                            return result;
                        }
                    }
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                    return ServiceUtil.returnError(e.getMessage());
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) JDOMException(org.jdom.JDOMException) ByteBuffer(java.nio.ByteBuffer) Delegator(org.apache.ofbiz.entity.Delegator) RandomAccessFile(java.io.RandomAccessFile) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FlexibleStringExpander(org.apache.ofbiz.base.util.string.FlexibleStringExpander) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

JDOMException (org.jdom.JDOMException)137 IOException (java.io.IOException)103 Element (org.jdom.Element)82 Document (org.jdom.Document)49 SAXBuilder (org.jdom.input.SAXBuilder)45 File (java.io.File)22 StringReader (java.io.StringReader)19 VirtualFile (com.intellij.openapi.vfs.VirtualFile)13 ArrayList (java.util.ArrayList)11 Nullable (org.jetbrains.annotations.Nullable)11 NotNull (org.jetbrains.annotations.NotNull)10 List (java.util.List)9 CommandException (org.apache.oozie.command.CommandException)9 InputStream (java.io.InputStream)8 Namespace (org.jdom.Namespace)8 SAXException (org.xml.sax.SAXException)8 URL (java.net.URL)7 HashMap (java.util.HashMap)7 THashMap (gnu.trove.THashMap)6 InvalidDataException (com.intellij.openapi.util.InvalidDataException)5