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);
}
}
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.<DATAIN_NAME> B) .datain.<DATAIN_NAME>.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;
}
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);
}
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();
}
}
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();
}
Aggregations