Search in sources :

Example 6 with GenericRuntimeException

use of com.openmeap.util.GenericRuntimeException in project OpenMEAP by OpenMEAP.

the class UpdateHandler method handleUpdate.

/**
	 * Handles processing an update requested by the application management
	 * service
	 * 
	 * @param updateHeader
	 */
public void handleUpdate(final UpdateHeader updateHeader, final StatusChangeHandler eventHandler) {
    final UpdateStatus update = new UpdateStatus(updateHeader, 0, false);
    if (eventHandler != null) {
        Thread activeUpdateThread = new Thread(new Runnable() {

            public void run() {
                try {
                    _handleUpdate(update, eventHandler);
                } catch (Exception e) {
                    UpdateException ue = null;
                    if (e instanceof UpdateException) {
                        ue = (UpdateException) e;
                    } else {
                        ue = new UpdateException(UpdateResult.UNDEFINED, e.getMessage(), e);
                    }
                    config.setLastUpdateResult(ue.getUpdateResult().toString());
                    update.setError(ue);
                    eventHandler.onStatusChange(update);
                }
            }
        });
        activeUpdateThread.start();
    } else {
        try {
            _handleUpdate(update, eventHandler);
        } catch (Exception e) {
            UpdateException ue = null;
            if (e instanceof UpdateException) {
                ue = (UpdateException) e;
            } else {
                ue = new UpdateException(UpdateResult.UNDEFINED, e.getMessage(), e);
            }
            config.setLastUpdateResult(ue.getUpdateResult().toString());
            throw new GenericRuntimeException(ue.getMessage(), ue);
        }
    }
}
Also used : GenericRuntimeException(com.openmeap.util.GenericRuntimeException) LocalStorageException(com.openmeap.thinclient.LocalStorageException) WebServiceException(com.openmeap.protocol.WebServiceException) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) IOException(java.io.IOException) HttpRequestException(com.openmeap.http.HttpRequestException)

Example 7 with GenericRuntimeException

use of com.openmeap.util.GenericRuntimeException in project OpenMEAP by OpenMEAP.

the class AbstractDigestInputStream method digest.

public byte[] digest() throws DigestException {
    InputStream is = null;
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance(getHashAlgorithm());
        is = new java.security.DigestInputStream(inputStream, md);
        byte[] bytes = new byte[1024];
        while (is.read(bytes) == 1024) ;
    } catch (Exception ioe) {
        throw new DigestException(ioe);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new GenericRuntimeException(e);
            }
        }
    }
    return md.digest();
}
Also used : InputStream(java.io.InputStream) IOException(java.io.IOException) MessageDigest(java.security.MessageDigest) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) IOException(java.io.IOException)

Example 8 with GenericRuntimeException

use of com.openmeap.util.GenericRuntimeException in project OpenMEAP by OpenMEAP.

the class ApplicationManagementServlet method handleArchiveDownload.

private Result handleArchiveDownload(HttpServletRequest request, HttpServletResponse response) {
    Result res = new Result();
    Error err = new Error();
    res.setError(err);
    GlobalSettings settings = modelManager.getGlobalSettings();
    Map properties = this.getServicesWebProperties();
    String nodeKey = (String) properties.get("clusterNodeUrlPrefix");
    ClusterNode clusterNode = settings.getClusterNode(nodeKey);
    if (nodeKey == null || clusterNode == null) {
        // TODO: create a configuration error code
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error("For each node in the cluster, the property or environment variable OPENMEAP_CLUSTER_NODE_URL_PREFIX must match the \"Service Url Prefix\" value configured in the administrative interface.  This value is currently " + nodeKey + ".");
        return res;
    }
    String pathValidation = clusterNode.validateFileSystemStoragePathPrefix();
    if (pathValidation != null) {
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error("There is an issue with the location at \"File-system Storage Prefix\".  " + pathValidation);
        return res;
    }
    String hash = request.getParameter(UrlParamConstants.APPARCH_HASH);
    String hashAlg = request.getParameter(UrlParamConstants.APPARCH_HASH_ALG);
    String fileName = null;
    if (hash == null || hashAlg == null) {
        // look in the apps directory for the archive specified
        String appName = request.getParameter(UrlParamConstants.APP_NAME);
        String versionId = request.getParameter(UrlParamConstants.APP_VERSION);
        ApplicationVersion appVersion = modelManager.getModelService().findAppVersionByNameAndId(appName, versionId);
        if (appVersion == null) {
            String mesg = "The application version " + versionId + " was not found for application " + appName;
            err.setCode(ErrorCode.APPLICATION_VERSION_NOTFOUND);
            err.setMessage(mesg);
            logger.warn(mesg);
            return res;
        }
        String auth = request.getParameter(UrlParamConstants.AUTH_TOKEN);
        com.openmeap.model.dto.Application app = appVersion.getApplication();
        try {
            if (auth == null || !AuthTokenProvider.validateAuthToken(app.getProxyAuthSalt(), auth)) {
                err.setCode(ErrorCode.AUTHENTICATION_FAILURE);
                err.setMessage("The \"auth\" token presented is not recognized, missing, or empty.");
                return res;
            }
        } catch (DigestException e) {
            throw new GenericRuntimeException(e);
        }
        hash = appVersion.getArchive().getHash();
        hashAlg = appVersion.getArchive().getHashAlgorithm();
        fileName = app.getName() + " - " + appVersion.getIdentifier();
    } else {
        fileName = hashAlg + "-" + hash;
    }
    File file = ApplicationArchive.getFile(clusterNode.getFileSystemStoragePathPrefix(), hashAlg, hash);
    if (!file.exists()) {
        String mesg = "The application archive with " + hashAlg + " hash " + hash + " was not found.";
        // TODO: create an enumeration for this error
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage(mesg);
        logger.warn(mesg);
        return res;
    }
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(file.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(file.length()).intValue());
        URLCodec codec = new URLCodec();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".zip\";");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        //if(outputStream!=null) {outputStream.close();}
        }
        response.flushBuffer();
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
    }
    return null;
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) ApplicationVersion(com.openmeap.model.dto.ApplicationVersion) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) Error(com.openmeap.protocol.dto.Error) GlobalSettings(com.openmeap.model.dto.GlobalSettings) IOException(java.io.IOException) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) FileNameMap(java.net.FileNameMap) FileInputStream(java.io.FileInputStream) Result(com.openmeap.protocol.dto.Result) URLCodec(org.apache.commons.codec.net.URLCodec) BufferedInputStream(java.io.BufferedInputStream) DigestException(com.openmeap.digest.DigestException) FileNameMap(java.net.FileNameMap) Map(java.util.Map) File(java.io.File)

Example 9 with GenericRuntimeException

use of com.openmeap.util.GenericRuntimeException in project OpenMEAP by OpenMEAP.

the class ServiceManagementServlet method authenticates.

/**
	 * Validates that the auth in a request passes validation
	 * @param arg0
	 * @return
	 */
private Boolean authenticates(HttpServletRequest arg0) {
    String authSalt = getAuthSalt();
    String auth = (String) arg0.getParameter(UrlParamConstants.AUTH_TOKEN);
    Boolean isGood;
    try {
        isGood = AuthTokenProvider.validateAuthToken(authSalt, auth);
    } catch (DigestException e) {
        throw new GenericRuntimeException(e);
    }
    logger.debug("Authentication of token \"{}\" with salt \"{}\" returned {}", new Object[] { authSalt, auth, isGood });
    return (auth != null && isGood);
}
Also used : DigestException(com.openmeap.digest.DigestException) GenericRuntimeException(com.openmeap.util.GenericRuntimeException)

Example 10 with GenericRuntimeException

use of com.openmeap.util.GenericRuntimeException in project OpenMEAP by OpenMEAP.

the class ApplicationManagementServiceImpl method connectionOpen.

public ConnectionOpenResponse connectionOpen(ConnectionOpenRequest request) throws WebServiceException {
    String reqAppArchHashVal = StringUtils.trimToNull(request.getApplication().getHashValue());
    String reqAppVerId = StringUtils.trimToNull(request.getApplication().getVersionId());
    String reqAppName = StringUtils.trimToNull(request.getApplication().getName());
    ConnectionOpenResponse response = new ConnectionOpenResponse();
    GlobalSettings settings = modelManager.getGlobalSettings();
    if (StringUtils.isBlank(settings.getExternalServiceUrlPrefix()) && logger.isWarnEnabled()) {
        logger.warn("The external service url prefix configured in the admin interface is blank.  " + "This will probably cause issues downloading application archives.");
    }
    Application application = getApplication(reqAppName, reqAppVerId);
    // Generate a new auth token for the device to present to the proxy
    String authToken;
    try {
        authToken = AuthTokenProvider.newAuthToken(application.getProxyAuthSalt());
    } catch (DigestException e) {
        throw new GenericRuntimeException(e);
    }
    response.setAuthToken(authToken);
    // If there is a deployment, 
    // and the version of that deployment differs in hash value or identifier
    // then return an update in the response
    Deployment lastDeployment = modelManager.getModelService().getLastDeployment(application);
    Boolean reqAppVerDiffers = lastDeployment != null && !lastDeployment.getVersionIdentifier().equals(reqAppVerId);
    Boolean reqAppArchHashValDiffers = lastDeployment != null && reqAppArchHashVal != null && !lastDeployment.getApplicationArchive().getHash().equals(reqAppArchHashVal);
    //   the app hash value is different than reported
    if (reqAppVerDiffers || reqAppArchHashValDiffers) {
        // TODO: I'm not happy with the discrepancies between the model and schema
        // ...besides, this update header should be encapsulated somewhere else
        ApplicationArchive currentVersionArchive = lastDeployment.getApplicationArchive();
        UpdateHeader uh = new UpdateHeader();
        uh.setVersionIdentifier(lastDeployment.getVersionIdentifier());
        uh.setInstallNeeds(Long.valueOf(currentVersionArchive.getBytesLength() + currentVersionArchive.getBytesLengthUncompressed()));
        uh.setStorageNeeds(Long.valueOf(currentVersionArchive.getBytesLengthUncompressed()));
        uh.setType(UpdateType.fromValue(lastDeployment.getType().toString()));
        uh.setUpdateUrl(currentVersionArchive.getDownloadUrl(settings));
        uh.setHash(new Hash());
        uh.getHash().setAlgorithm(HashAlgorithm.fromValue(currentVersionArchive.getHashAlgorithm()));
        uh.getHash().setValue(currentVersionArchive.getHash());
        response.setUpdate(uh);
    }
    return response;
}
Also used : DigestException(com.openmeap.digest.DigestException) Deployment(com.openmeap.model.dto.Deployment) UpdateHeader(com.openmeap.protocol.dto.UpdateHeader) GlobalSettings(com.openmeap.model.dto.GlobalSettings) ConnectionOpenResponse(com.openmeap.protocol.dto.ConnectionOpenResponse) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) Hash(com.openmeap.protocol.dto.Hash) Application(com.openmeap.model.dto.Application) ApplicationArchive(com.openmeap.model.dto.ApplicationArchive)

Aggregations

GenericRuntimeException (com.openmeap.util.GenericRuntimeException)12 DigestException (com.openmeap.digest.DigestException)5 IOException (java.io.IOException)5 GlobalSettings (com.openmeap.model.dto.GlobalSettings)3 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 InputStream (java.io.InputStream)3 OutputStream (java.io.OutputStream)3 Application (com.openmeap.model.dto.Application)2 ApplicationArchive (com.openmeap.model.dto.ApplicationArchive)2 UpdateHeader (com.openmeap.protocol.dto.UpdateHeader)2 LocalStorageException (com.openmeap.thinclient.LocalStorageException)2 UpdateException (com.openmeap.thinclient.update.UpdateException)2 JSONException (com.openmeap.thirdparty.org.json.me.JSONException)2 JSONObject (com.openmeap.thirdparty.org.json.me.JSONObject)2 BufferedInputStream (java.io.BufferedInputStream)2 FileInputStream (java.io.FileInputStream)2 FileNameMap (java.net.FileNameMap)2 HttpRequestException (com.openmeap.http.HttpRequestException)1 ModelManager (com.openmeap.model.ModelManager)1