List of usage examples for javax.xml.ws Holder Holder
public Holder(T value)
From source file:fr.xebia.demo.ws.employee.EmployeeServiceIntegrationTest.java
@Test public void testPutEmployee() throws Exception { int id = random.nextInt(); Employee employee = new Employee(); employee.setId(null);//from w w w .j ava2 s. com employee.setLastName("Doe-" + id); employee.setFirstName("John"); employee.setGender(Gender.MALE); employee.setBirthdate(new Date(new GregorianCalendar(1976, 01, 05).getTimeInMillis())); employeeService.putEmployee(new Holder<Employee>(employee)); System.out.println(ToStringBuilder.reflectionToString(employee)); }
From source file:fr.xebia.demo.ws.employee.EmployeeServiceIntegrationTest.java
@Test(expected = SOAPFaultException.class) public void testPutEmployeeFirstNameMissing() throws Exception { int id = random.nextInt(); Employee employee = new Employee(); employee.setId(id);//from ww w .ja v a2s . c om employee.setLastName("Doe-" + id); employee.setFirstName(null); employee.setGender(Gender.MALE); employee.setBirthdate(new Date(new GregorianCalendar(1976, 01, 05).getTimeInMillis())); try { employeeService.putEmployee(new Holder<Employee>(employee)); } catch (SOAPFaultException e) { e.printStackTrace(); throw e; } /* * throws javax.xml.ws.soap.SOAPFaultException: Marshalling Error: cvc-complex-type.2.4.b: The content of element 'employee' is not * complete. One of '{"http://demo.xebia.fr/xml/employee":firstName}' is expected. */ }
From source file:fr.xebia.demo.ws.employee.EmployeeServiceIntegrationTest.java
@Test(expected = SOAPFaultException.class) public void testPutEmployeeFirstNameTooLong() throws Exception { int id = random.nextInt(); Employee employee = new Employee(); employee.setId(id);// w ww . j av a 2 s .co m employee.setLastName("Doe-" + id); String firstName = StringUtils.repeat("John ", 100); Assert.assertTrue("firstName must be longer than 256 chars to exceed Schema constraint", firstName.length() > 256); employee.setFirstName(firstName); employee.setGender(Gender.MALE); employee.setBirthdate(new Date(new GregorianCalendar(1976, 01, 05).getTimeInMillis())); try { employeeService.putEmployee(new Holder<Employee>(employee)); } catch (SOAPFaultException e) { e.printStackTrace(); throw e; } /* * throws javax.xml.ws.soap.SOAPFaultException: Marshalling Error: cvc-maxLength-valid: Value '...' with length = '500' is not * facet-valid with respect to maxLength '256' for type '#AnonType_firstNameEmployee'. */ }
From source file:com.cisco.dvbu.ps.deploytool.dao.wsapi.ResourceCacheWSDAOImpl.java
public void takeResourceCacheAction(String actionName, String resourceCachePath, String resourceCacheType, CacheConfig resourceCacheConfig, String serverId, String pathToServersXML, Boolean validateResourceExists) throws CompositeException { // For debugging if (logger.isDebugEnabled()) { logger.debug(// w w w.ja v a 2s. com "ResourceCacheWSDAOImpl.takeResourceCacheAction(actionName, resourceCachePath, resourceCacheType, resourceCacheConfig, serverId, pathToServersXML, validateResourceExists)." + " actionName=" + actionName + " resourceCachePath=" + resourceCachePath + " resourceCacheType=" + resourceCacheType + " resourceCacheConfig:" + " serverId=" + serverId + " pathToServersXML=" + pathToServersXML + " validateResourceExists=" + validateResourceExists); } String command = null; // read target server properties from xml and build target server object based on target server name CompositeServer targetServer = WsApiHelperObjects.getServerLogger(serverId, pathToServersXML, "ResourceCacheWSDAOImpl.takeResourceCacheAction(" + actionName + ")", logger); // Ping the Server to make sure it is alive and the values are correct. WsApiHelperObjects.pingServer(targetServer, true); // Construct the resource port based on target server name ResourcePortType port = CisApiFactory.getResourcePort(targetServer); try { if (actionName.equalsIgnoreCase(ResourceCacheDAO.action.UPDATE.name())) { if (validateResourceExists) { // Make sure the resource exists before executing any actions if (!DeployManagerUtil.getDeployManager().resourceExists(serverId, resourceCachePath, resourceCacheType, pathToServersXML)) { //.doResourceExist(serverId, resourceCachePath, pathToServersXML) throw new ApplicationException("The resource " + resourceCachePath + " does not exist."); } } Holder<CacheConfig> cacheConfig = new Holder<CacheConfig>(resourceCacheConfig); if (logger.isDebugEnabled()) { String clearRule = null; String refreshMode = null; String expirationPeriod = null; int scheduleCount = 0; String scheduleInterval = null; String scheduleRecurringDay = null; String scheduleEndTimeInADay = null; String scheduleFromTimeInADay = null; String scheduleMode = null; String schedulePeriod = null; String scheduleStartTime = null; String storagePath = null; String storageMode = null; int storageTargetEntrySize = 0; String cacheConfigText = ""; if (resourceCacheConfig != null) { if (resourceCacheConfig.getExpirationPeriod() != null) expirationPeriod = resourceCacheConfig.getExpirationPeriod().toString(); if (resourceCacheConfig.getClearRule() != null) clearRule = resourceCacheConfig.getClearRule().toString(); // Check the refresh entry if (resourceCacheConfig.getRefresh() != null) { if (resourceCacheConfig.getRefresh().getMode() != null) refreshMode = resourceCacheConfig.getRefresh().getMode().toString(); if (resourceCacheConfig.getRefresh().getSchedule() != null) { if (resourceCacheConfig.getRefresh().getSchedule().getCount() != null) scheduleCount = resourceCacheConfig.getRefresh().getSchedule().getCount(); if (resourceCacheConfig.getRefresh().getSchedule().getInterval() != null) scheduleInterval = resourceCacheConfig.getRefresh().getSchedule().getInterval() .toString(); if (resourceCacheConfig.getRefresh().getSchedule().getRecurringDay() != null) scheduleRecurringDay = resourceCacheConfig.getRefresh().getSchedule() .getRecurringDay().toString(); if (resourceCacheConfig.getRefresh().getSchedule().getEndTimeInADay() != null) scheduleEndTimeInADay = resourceCacheConfig.getRefresh().getSchedule() .getEndTimeInADay().toString(); if (resourceCacheConfig.getRefresh().getSchedule().getFromTimeInADay() != null) scheduleFromTimeInADay = resourceCacheConfig.getRefresh().getSchedule() .getFromTimeInADay().toString(); if (resourceCacheConfig.getRefresh().getSchedule().getMode() != null) scheduleMode = resourceCacheConfig.getRefresh().getSchedule().getMode() .toString(); if (resourceCacheConfig.getRefresh().getSchedule().getPeriod() != null) schedulePeriod = resourceCacheConfig.getRefresh().getSchedule().getPeriod() .toString(); if (resourceCacheConfig.getRefresh().getSchedule().getStartTime() != null) scheduleStartTime = resourceCacheConfig.getRefresh().getSchedule() .getStartTime().toString(); } } // Check the storage entry if (resourceCacheConfig.getStorage() != null) { if (resourceCacheConfig.getStorage().getStorageDataSourcePath() != null) storagePath = resourceCacheConfig.getStorage().getStorageDataSourcePath(); if (resourceCacheConfig.getStorage().getMode() != null) storageMode = resourceCacheConfig.getStorage().getMode().toString(); if (resourceCacheConfig.getStorage().getStorageTargets() != null && resourceCacheConfig.getStorage().getStorageTargets().getEntry() != null) storageTargetEntrySize = resourceCacheConfig.getStorage().getStorageTargets() .getEntry().size(); } cacheConfigText = cacheConfigText + "\n expirationPeriod=" + expirationPeriod; cacheConfigText = cacheConfigText + "\n clearRule=" + clearRule; cacheConfigText = cacheConfigText + "\n RefreshMode=" + refreshMode; cacheConfigText = cacheConfigText + "\n RefreshSchedule:"; cacheConfigText = cacheConfigText + "\n Count=" + scheduleCount; cacheConfigText = cacheConfigText + "\n Interval=" + scheduleInterval; cacheConfigText = cacheConfigText + "\n RecurringDaynt=" + scheduleRecurringDay; cacheConfigText = cacheConfigText + "\n EndTimeInADay=" + scheduleEndTimeInADay; cacheConfigText = cacheConfigText + "\n FromTimeInADay=" + scheduleFromTimeInADay; cacheConfigText = cacheConfigText + "\n Mode=" + scheduleMode; cacheConfigText = cacheConfigText + "\n Period=" + schedulePeriod; cacheConfigText = cacheConfigText + "\n StartTime=" + scheduleStartTime; cacheConfigText = cacheConfigText + "\n Storage:"; cacheConfigText = cacheConfigText + "\n DataSourcePath=" + storagePath; cacheConfigText = cacheConfigText + "\n Mode=" + storageMode; cacheConfigText = cacheConfigText + "\n TargetsEntrySize=" + storageTargetEntrySize; } logger.debug("ResourceCacheWSDAOImpl.takeResourceCacheAction(" + actionName + "). Invoking port.updateResourceCacheConfig(" + "\n path=\"" + resourceCachePath + "\"," + "\n type=\"" + resourceCacheType + "\"," + "\n detailLevel=\"FULL\"," + "\n cacheConfig:" + cacheConfigText + ")."); } command = "updateResourceCacheConfig"; // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { port.updateResourceCacheConfig(resourceCachePath, ResourceType.valueOf(resourceCacheType), DetailLevel.FULL, cacheConfig); if (logger.isDebugEnabled()) { logger.debug("ResourceCacheWSDAOImpl.takeResourceCacheAction(" + actionName + "). Success: port.updateResourceCacheConfig()."); } } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } /* Update the cache configuration for a resource. Request Elements: path: The path of a cacheable resource. type: The type of a cached resource may be "TABLE" or "PROCEDURE". detail: The level of detail of resources in the response. May be "NONE", "SIMPLE", or "FULL". cacheConfig: The cache configuration of the given resource. configured (optional): "true" if caching should be configured for the given resource; otherwise "false". If not provided, the configured setting will be left unaltered. If configured is "false" all other elements will be ignored. enabled (optional): "true" if the cache is enabled; otherwise "false". If not provided, the enable setting will be left unaltered. storage (optional): How the cached is stored. If not provided, the storage settings will be left unaltered. mode: Storage type used for the cache. May be either "AUTOMATIC" or "DATA_SOURCE" storageDataSourcePath (optional): If the mode is "DATA_SOURCE", this identifies the path to the data source being used to store cache data. storageTargets (optional): If the mode is "DATA_SOURCE", this identifies the tables used for storing cache data entry: targetName: For a TABLE resource this is always "result". For a PROCEDURE resource, this is the name of a cursor parameter, or an empty string for the scalar output parameters. path: The path to the table used for storing this data. type: Always "TABLE" refresh (optional): How the cache should be refreshed. If not provided, the refresh settings will be left unaltered. mode: How the cache should be refreshed. May be "MANUAL" or "SCHEDULED". schedule (optional): If the mode is "SCHEDULED", this element will exist with the following child elements: mode: Always "INTERVAL". startTime: When the first refresh should occur. interval: The number of seconds between refreshes. expirationPeriod: The amount of time in milliseconds that the cache will be cleared after it is refreshed. If less than zero, the period will be set to zero. If zero then the cache will never expire. If not provided, the enable setting will be left unaltered. clearRule: One of "NONE", "ON_LOAD", or "ON_FAILURE". Normally old cache data is cleared on expiration and when a cache refresh successfully completes. In the latter case the old cache data is replaced by the new cached data. If "NONE", then the normal behavior will be used. If "ON_LOAD", in addition to the normal behavior the old cache data will be cleared when a refresh is started. If "ON_FAILURE", in addition to the normal behavior the old cache data will be cleared when a refresh fails. If not provided, the enable setting will be left unaltered. Response Elements: cacheConfig (optional): The cache configuration of the given resource. This element is only present in the response if the detail level is not "NONE". Faults: IllegalArgument: If the path is malformed or an illegal type is provided. IllegalState: If the resource type does not support caching. NotFound: If the resource or any portion of the path to the resource does not exist. Security: The user must have READ access on all items in the path. Security: If the user does not have WRITE access on the last item in the path. Security: If the user does not have the ACCESS_TOOLS right. */ } else if (actionName.equalsIgnoreCase(ResourceCacheDAO.action.REFRESH.name())) { command = "refreshResourceCache"; if (isCacheEnabled(resourceCachePath, resourceCacheType, serverId, pathToServersXML)) { if (logger.isDebugEnabled()) { logger.debug("ResourceCacheWSDAOImpl.takeResourceCacheAction(" + actionName + "). Invoking port.refreshResourceCache(\"" + resourceCachePath + "\", \"" + resourceCacheType + "\")."); } // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { port.refreshResourceCache(resourceCachePath, ResourceType.valueOf(resourceCacheType)); if (logger.isDebugEnabled()) { logger.debug("ResourceCacheWSDAOImpl.takeResourceCacheAction(" + actionName + "). Success: port.refreshResourceCache()."); } } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } } /* Refreshes the cache on a resource. Also see "updateResourceCacheConfig" for enabling and disabling caching. Request Elements: path: The path of the resource with caching enabled. type: The type of the resource may be either "TABLE" or "PROCEDURE". Response Elements: N/A Faults: IllegalArgument: If the path is malformed or an illegal type is provided. IllegalState: If the cache is disabled or the resource type does not support caching. NotFound: If the resource or any portion of the path to the resource does not exist. Security: If the user does not have READ access on all items in the path other than the last one. Security: If the user does not have WRITE access to the last item in the path. Security: If the user does not have the ACCESS_TOOLS right. ServerError: If any problems with connecting to or retrieving data from the data source when refreshing. */ } else if (actionName.equalsIgnoreCase(ResourceCacheDAO.action.CLEAR.name())) { command = "clearResourceCache"; if (isCacheEnabled(resourceCachePath, resourceCacheType, serverId, pathToServersXML)) { if (logger.isDebugEnabled()) { logger.debug("ResourceCacheWSDAOImpl.takeResourceCacheAction(" + actionName + "). Invoking port.clearResourceCache(\"" + resourceCachePath + "\", \"" + resourceCacheType + "\")."); } // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { port.clearResourceCache(resourceCachePath, ResourceType.valueOf(resourceCacheType)); if (logger.isDebugEnabled()) { logger.debug("ResourceCacheWSDAOImpl.takeResourceCacheAction(" + actionName + "). Success: port.clearResourceCache()."); } } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } } /* Clears an existing resource cache. Only purposefully configured resources of type TABLE and PROCEDURE support caching in this release. Procedure variants are cleared from the cache along with any cached results. Use the refreshResourceCache procedure to initiate an immediate refresh of a table or cached view, or allow the cache to get refreshed on next use of the resource. Request Elements: path: The path of the resource configured to use caching. type: The type of the resource. Valid values are "TABLE" and "PROCEDURE". Response Elements: N/A Faults: IllegalArgument: If the path is malformed or an illegal type is provided. IllegalState: If the cache is disabled. NotAllowed: The resource type must support caching. Only TABLE and PROCEDURE resources support caching in this release. NotFound: If the resource or any portion of the path to the resource does not exist. Security: If the user does not have READ access on all items in the path other than the last one. Security: If the user does not have WRITE access to the last item in the path. Security: If the user does not have the ACCESS_TOOLS right. */ } if (logger.isInfoEnabled()) { logger.debug("ResourceCacheWSDAOImpl.takeResourceCacheAction::success for action=" + actionName); } } catch (UpdateResourceCacheConfigSoapFault e) { CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), ResourceCacheDAO.action.UPDATE.name(), "ResourceCache", resourceCachePath, targetServer), e.getFaultInfo()); throw new ApplicationException(e.getMessage(), e); } catch (RefreshResourceCacheSoapFault e) { CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), ResourceCacheDAO.action.REFRESH.name(), "ResourceCache", resourceCachePath, targetServer), e.getFaultInfo()); throw new ApplicationException(e.getMessage(), e); } catch (ClearResourceCacheSoapFault e) { CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), ResourceCacheDAO.action.CLEAR.name(), "ResourceCache", resourceCachePath, targetServer), e.getFaultInfo()); throw new ApplicationException(e.getMessage(), e); } }
From source file:se.vgregion.usdservice.USDServiceImpl.java
@Override public String createRequest(Properties requestParameters, String userId, Collection<Attachment> attachments) { int sessionID = 0; try {/* w ww. j a va2s . com*/ sessionID = getUSDWebService().login(wsUser, wsPassword); String contactHandle = lookupContactHandle(userId, sessionID); if (contactHandle == null) { // Use the wsUser as fallback if the user is unknown contactHandle = lookupContactHandle(wsUser, sessionID); } requestParameters.setProperty("customer", contactHandle); List<String> lAttributes = new ArrayList<String>(); List<String> lAttributeValues = new ArrayList<String>(); for (Enumeration<Object> e = requestParameters.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); lAttributes.add(key); lAttributeValues.add(key); lAttributeValues.add(requestParameters.getProperty(key)); } List<String> properties = Collections.<String>emptyList(); Holder<String> reqHandle = new Holder<String>(""); Holder<String> reqNumber = new Holder<String>(""); String template = ""; Holder<String> result = new Holder<String>(); getUSDWebService().createRequest(sessionID, contactHandle, toArrayOfString(lAttributeValues), toArrayOfString(properties), template, toArrayOfString(lAttributes), reqHandle, reqNumber, result); String handle = null; try { handle = extractHandle(result.toString()); } catch (Exception e) { throw new RuntimeException("Error parsing handle to USD incident from xml response...\n" + result, e); } if (!StringUtils.isEmpty(handle)) { for (Attachment attachment : attachments) { int i = 0; try { createAttachment(sessionID, wsAttachmentRepHandle, handle, "Attachment " + i, attachment); } catch (Exception e) { log.error("Failed to create attachment in USD [" + attachment.getFilename() + "]"); } i++; } } return result.toString(); } finally { getUSDWebService().logout(sessionID); } }
From source file:egovframework.rte.itl.webservice.service.impl.EgovWebServiceClientImpl.java
@SuppressWarnings("unchecked") public EgovIntegrationMessage service(EgovIntegrationMessage requestMessage) { LOG.debug("EgovWebServiceClient service (requestMesage = " + requestMessage + ")"); synchronized (initializedLock) { if (initialized == false) { LOG.debug("Initialize Client"); // ServiceEndpointInterface Impl ? ? try { service = Service.create(wsdlURL, serviceName); client = service.getPort(portName, serviceEndpointInterfaceClass); initialized = true;/* w w w. j a va 2 s.c o m*/ } catch (Throwable e) { LOG.error("Cannot create web service port", e); initialized = false; // return new EgovWebServiceMessage(new EgovWebServiceMessageHeader(requestMessage.getHeader()) { { setResultCode(ResultCode.FAIL_IN_INITIALIZING); } }); } } } LOG.debug("Create Request Message"); // get request params List<Object> params = new ArrayList<Object>(); // requestMessage? Body value object . boolean succeed = false; try { Map<String, Object> requestBody = requestMessage.getBody(); for (ServiceParamInfo paramInfo : serviceEndpointInterfaceInfo.getParamInfos()) { if (paramInfo.getMode().equals(Mode.IN) || paramInfo.getMode().equals(Mode.INOUT)) { Object valueObject = null; if (paramInfo.getType() == EgovWebServiceMessageHeader.TYPE) { LOG.debug("Insert Message Header"); LOG.debug("value = " + requestMessage.getHeader()); valueObject = requestMessage.getHeader(); } else { LOG.debug("Insert Param \"" + paramInfo.getName() + "\""); Object typedObject = requestBody.get(paramInfo.getName()); valueObject = messageConverter.convertToValueObject(typedObject, paramInfo.getType()); LOG.debug("value = " + valueObject); } if (paramInfo.getMode().equals(Mode.INOUT)) { LOG.debug("Wrapping Holder"); valueObject = new Holder(valueObject); } params.add(valueObject); } else { params.add(new Holder()); } } succeed = true; } catch (Throwable e) { LOG.error("Cannot Create Request Message", e); } if (succeed == false) { // ? return new EgovWebServiceMessage(new EgovWebServiceMessageHeader(requestMessage.getHeader()) { { setResultCode(ResultCode.FAIL_IN_CREATING_REQUEST_MESSAGE); } }); } // call method LOG.debug("Invoke method"); Object[] paramArray = params.toArray(); succeed = false; try { method.invoke(client, paramArray); succeed = true; } catch (Throwable e) { LOG.error("Fail to invoke method", e); } if (succeed == false) { // return new EgovWebServiceMessage(new EgovWebServiceMessageHeader(requestMessage.getHeader()) { { setResultCode(ResultCode.FAIL_IN_SENDING_REQUEST); } }); } // responseValueObject typed object . LOG.debug("Parse Response Message"); EgovIntegrationMessageHeader responseHeader = null; succeed = true; // response parsing? ? . Map<String, Object> responseBody = new HashMap<String, Object>(); int i = 0; for (ServiceParamInfo paramInfo : serviceEndpointInterfaceInfo.getParamInfos()) { if (paramInfo.getMode().equals(Mode.OUT) || paramInfo.getMode().equals(Mode.INOUT)) { Object valueObject = ((Holder) paramArray[i]).value; if (paramInfo.getType() == EgovWebServiceMessageHeader.TYPE) { responseHeader = (EgovWebServiceMessageHeader) valueObject; } else { try { Object typedObject = messageConverter.convertToTypedObject(valueObject, paramInfo.getType()); responseBody.put(paramInfo.getName(), typedObject); } catch (Throwable e) { LOG.error("Cannot parse response message", e); succeed = false; } } } i++; } if (succeed) { // ? ? , requestHeader ? ? if (responseHeader == null) { responseHeader = new EgovWebServiceMessageHeader(requestMessage.getHeader()); } return new EgovWebServiceMessage(responseHeader, responseBody); } else { // ? parsing if (responseHeader == null) { responseHeader = new EgovWebServiceMessageHeader(requestMessage.getHeader()); } responseHeader.setResultCode(ResultCode.FAIL_IN_PARSING_RESPONSE_MESSAGE); return new EgovWebServiceMessage(responseHeader, responseBody); } }
From source file:org.taverna.server.master.DirectoryREST.java
@Override @CallCounted//w ww . j a va 2 s . c o m @PerfLogged @RolesAllowed({ USER, SELF }) public Response setFileContents(List<PathSegment> filePath, InputStream contents, UriInfo ui) throws NoDirectoryEntryException, NoUpdateException, FilesystemAccessException { Holder<Boolean> isNew = new Holder<>(true); support.copyStreamToFile(contents, getFileForWrite(filePath, isNew)); if (isNew.value) return created(ui.getAbsolutePath()).build(); else return noContent().build(); }
From source file:org.taverna.server.master.DirectoryREST.java
@Override @CallCounted/*from ww w. j a va 2 s . c om*/ @PerfLogged @RolesAllowed(USER) public Response setFileContentsFromURL(List<PathSegment> filePath, List<URI> referenceList, UriInfo ui) throws NoDirectoryEntryException, NoUpdateException, FilesystemAccessException { support.permitUpdate(run); if (referenceList.isEmpty() || referenceList.size() > 1) return status(422).entity("URI list must have single URI in it").build(); URI uri = referenceList.get(0); try { uri.toURL(); } catch (MalformedURLException e) { return status(422).entity("URI list must have value URL in it").build(); } Holder<Boolean> isNew = new Holder<>(true); File f = getFileForWrite(filePath, isNew); try { support.copyDataToFile(uri, f); } catch (MalformedURLException ex) { // Should not happen; called uri.toURL() successfully above throw new NoUpdateException("failed to parse URI", ex); } catch (IOException ex) { throw new FilesystemAccessException("failed to transfer data from URI", ex); } if (isNew.value) return created(ui.getAbsolutePath()).build(); else return noContent().build(); }
From source file:cz.cas.lib.proarc.desa.SIP2DESATransporter.java
/** * Upload one SIP file from the input folder. First call the DESA API method * asyncSubmitPackageStart, then copy the zip file to the mapped DESA target * folder and finally call the DESA API method asyncSubmitPackageEnd. Add * the corresponding entry into the results file JAXB representation. * * @param file/*ww w . jav a2 s .c o m*/ * @param sipType * @param writeResults */ private void uploadFile(File file, SipType sipType, boolean writeResults) { Holder<String> sipId = new Holder<String>(getSipId(file)); Holder<String> idSipVersion = new Holder<String>(); String checksum = getMD5Checksum(file); log.info("Transporting file: " + file.getName()); if (useRest) { idSipVersion.value = desaClient.submitPackage(file, operatorName, producerCode, sipId.value, FileHashAlg.MD_5, checksum, "cs"); log.info("Received idSipVersion:" + idSipVersion.value); if (idSipVersion.value == null || "".equals(idSipVersion.value)) { throw new RuntimeException("DESA REST call did not return idSipVersion for file " + file.getName()); } } else { try { desaPort.asyncSubmitPackageStart(0, producerCode, operatorName, sipId, (int) file.length(), checksum, FileHashAlg.MD_5, idSipVersion); } catch (SIPSubmissionFault sipSubmissionFault) { throw new RuntimeException(sipSubmissionFault); } if (idSipVersion.value == null || "".equals(idSipVersion.value)) { throw new RuntimeException("DESA SOAP call did not return idSipVersion for file " + file.getName()); } File target = new File(getDesaFolder(), idSipVersion.value + ".sip"); try { FileUtils.copyFile(file, target); } catch (IOException e) { throw new RuntimeException(e); } log.info("Received idSipVersion:" + idSipVersion.value); try { desaPort.asyncSubmitPackageEnd(0, producerCode, operatorName, idSipVersion.value); } catch (SIPSubmissionFault sipSubmissionFault) { throw new RuntimeException(sipSubmissionFault); } } if (writeResults) { XMLGregorianCalendar currentDate = desaClient.getXmlTypes() .newXMLGregorianCalendar(new GregorianCalendar()); PSPSIP.SIP entry = resultsFactory.createPSPSIPSIP(); entry.setIdentifier(sipId.value); entry.setIdSIPVersion(idSipVersion.value); entry.setResultTime(currentDate); entry.setResultCode(ResultType.PROGRESS); entry.setType(sipType); results.getSIP().add(entry); } }
From source file:cz.cas.lib.proarc.desa.SIP2DESATransporter.java
/** * Check the status of the SIP of one entry in the results file and update * the entry in the JAXB object.// w ww . ja v a2s . com * * @param sip * @return */ private boolean checkSIP(PSPSIP.SIP sip) { Holder<String> sipId = new Holder<String>(sip.getIdentifier()); Holder<String> idSipVersion = new Holder<String>(sip.getIdSIPVersion()); Holder<String> packageStateCode = new Holder<String>(); Holder<String> packageStateText = new Holder<String>(); Holder<String> errorCode = new Holder<String>(); log.info("Checking file: " + sipId.value); /* * if(config.getBoolean("desa.rest")){ try { URLConnection connection = * new * URL(config.getString("desa.restapi")+"/packagestatus"+"?userName=" * +config.getString("desa.user") * +"&producerCode="+config.getString("desa.producer" * )+"&producerSipId="+ * sipId.value+"&idSIPVersion="+idSipVersion.value).openConnection(); * packageStateCode * .value=connection.getHeaderField("X-DEA-packageStateCode"); * packageStateText * .value=connection.getHeaderField("X-DEA-packageStateText"); * errorCode.value=connection.getHeaderField("X-DEA-errorCode"); } catch * (Exception e) { throw new RuntimeException(e); } }else{ */ try { desaPort.getPackageStatus(0, producerCode, operatorName, idSipVersion, sipId, packageStateCode, packageStateText, errorCode); } catch (SIPSubmissionFault sipSubmissionFault) { throw new RuntimeException(sipSubmissionFault); } catch (Exception e1) { log.log(Level.SEVERE, "DESA exception", e1); throw new IllegalStateException("DESA exception", e1); } /* } */ log.info("Status: " + packageStateCode.value + " (" + packageStateText.value + ")" + (errorCode.value != null ? (", errorCode:" + errorCode.value) : "")); XMLGregorianCalendar currentDate = desaClient.getXmlTypes() .newXMLGregorianCalendar(new GregorianCalendar()); ; boolean retval = false; sip.setResultTime(currentDate); if ("AI_ACC_OK".equalsIgnoreCase(packageStateCode.value)) { sip.setResultCode(ResultType.FINISHED); retval = true; } else if ("AI_ERROR".equalsIgnoreCase(packageStateCode.value) || "AI_INVALID".equalsIgnoreCase(packageStateCode.value) || "AI_REJECT".equalsIgnoreCase(packageStateCode.value) || "AI_INFECTED".equalsIgnoreCase(packageStateCode.value) || "AI_QA_ERR".equalsIgnoreCase(packageStateCode.value)) { sip.setResultCode(ResultType.ERROR); } else { sip.setResultCode(ResultType.PROGRESS); } return retval; }