Example usage for java.net MalformedURLException getCause

List of usage examples for java.net MalformedURLException getCause

Introduction

In this page you can find the example usage for java.net MalformedURLException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.iride.ayride.HomePageActivity.java

private void initializeMobileService() {
    try {/*from  w w  w .  ja  va  2s  . c o m*/
        MobileServiceClient mobileServiceClient = new MobileServiceClient(getString(R.string.azureApiUrl),
                getString(R.string.azureApiKey), this);
        this.vehicleMobileServiceTable = mobileServiceClient.getTable("vehicle_info", Vehicle.class);
        this.rideMobileServiceTable = mobileServiceClient.getTable("ride_info", Ride.class);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        Log.e(loggerTag, e.getCause().toString());
    }
}

From source file:com.newrelic.agent.transport.DataSenderImpl.java

private ReadResult send(String method, String encoding, String uri, JSONStreamAware params,
        int timeoutInMillis)/* 857:    */ throws Exception
/* 858:    */ {//from   ww w .  jav a 2s .  com
    /* 859:    */ try
    /* 860:    */ {
        /* 861:653 */ return connectAndSend(method, encoding, uri, params, timeoutInMillis);
        /* 862:    */ }
    /* 863:    */ catch (MalformedURLException e)
    /* 864:    */ {
        /* 865:655 */ Agent.LOG.log(Level.SEVERE,
                "You have requested a connection to New Relic via a protocol which is unavailable in your runtime: {0}",
                new Object[] { e.toString() });
        /* 866:    */
        /* 867:    */
        /* 868:    */
        /* 869:659 */ throw new ForceDisconnectException(e.toString());
        /* 870:    */ }
    /* 871:    */ catch (SocketException e)
    /* 872:    */ {
        /* 873:661 */ if ((e.getCause() instanceof NoSuchAlgorithmException))
        /* 874:    */ {
            /* 875:662 */ String msg = MessageFormat.format(
                    "You have requested a connection to New Relic via an algorithm which is unavailable in your runtime: {0}  This may also be indicative of a corrupted keystore or trust store on your server.",
                    new Object[] { e.getCause().toString() });
            /* 876:    */
            /* 877:    */
            /* 878:665 */ Agent.LOG.error(msg);
            /* 879:    */ }
        /* 880:    */ else
        /* 881:    */ {
            /* 882:668 */ Agent.LOG.log(Level.INFO,
                    "A socket exception was encountered while sending data to New Relic ({0}).  Please check your network / proxy settings.",
                    new Object[] { e.toString() });
            /* 883:672 */ if (Agent.LOG.isLoggable(Level.FINE)) {
                /* 884:673 */ Agent.LOG.log(Level.FINE, "Error sending JSON({0}): {1}",
                        new Object[] { method, DataSenderWriter.toJSONString(params) });
                /* 885:    */ }
            /* 886:676 */ Agent.LOG.log(Level.FINEST, e, e.toString(), new Object[0]);
            /* 887:    */ }
        /* 888:678 */ throw e;
        /* 889:    */ }
    /* 890:    */ catch (HttpError e)
    /* 891:    */ {
        /* 892:707 */ throw e;
        /* 893:    */ }
    /* 894:    */ catch (Exception e)
    /* 895:    */ {
        /* 896:709 */ Agent.LOG.log(Level.INFO, "Remote {0} call failed : {1}.",
                new Object[] { method, e.toString() });
        /* 897:710 */ if (Agent.LOG.isLoggable(Level.FINE)) {
            /* 898:711 */ Agent.LOG.log(Level.FINE, "Error sending JSON({0}): {1}",
                    new Object[] { method, DataSenderWriter.toJSONString(params) });
            /* 899:    */ }
        /* 900:713 */ Agent.LOG.log(Level.FINEST, e, e.toString(), new Object[0]);
        /* 901:714 */ throw e;
        /* 902:    */ }
    /* 903:    */ }

From source file:com.bdaum.zoom.gps.internal.operations.GeotagOperation.java

protected Waypoint getPlaceInfo(Meta meta, int i, double lat, double lon, IProgressMonitor aMonitor,
        IAdaptable info) throws UnknownHostException, EOFException {
    RasterCoordinate coord = new RasterCoordinate(lat, lon, 2);
    Waypoint place = coord.findClosestMatch(placeMap, 0.06d, 'K');
    if (place != null)
        return place;
    try {//  w w w  . ja  v a2  s .c o  m
        if (!lastAccessFailed && yieldWebservice(aMonitor))
            return null;
        lastAccessFailed = true;
        place = GpsUtilities.fetchPlaceInfo(lat, lon);
        if (place != null && !Double.isNaN(place.getLat()) && !Double.isNaN(place.getLon())) {
            double elevation = getElevation(place.getLat(), place.getLon(), aMonitor);
            if (!Double.isNaN(elevation))
                place.setElevation(elevation);
        }
        if (place != null) {
            placeMap.put(coord, place);
            lastAccessFailed = false;
            return place;
        }
    } catch (MalformedURLException e) {
        // should never happen
    } catch (SocketTimeoutException e) {
        addError(Messages.getString("GeotagOperation.connection_timed_out"), //$NON-NLS-1$
                null);
    } catch (HttpException e) {
        String message = e.getMessage();
        if (message.indexOf("(503)") >= 0) { //$NON-NLS-1$
            addError(Messages.getString("GeotagOperation.geonaming_aborted"), e); //$NON-NLS-1$
            if (aMonitor != null)
                aMonitor.setCanceled(true);
        } else
            addError(NLS.bind(Messages.getString("GeotagOperation.http_exception"), message), //$NON-NLS-1$
                    null);
    } catch (IOException e) {
        if (e instanceof UnknownHostException)
            throw (UnknownHostException) e;
        addError(Messages.getString("GeotagOperation.IO_Error_parsing_response"), //$NON-NLS-1$
                e);
    } catch (NumberFormatException e) {
        addError(Messages.getString("GeotagOperation.Number_format_parsing_response"), //$NON-NLS-1$
                e);
    } catch (WebServiceException e) {
        addWarning(Messages.getString("GeotagOperation.Geoname_signalled_exception"), e); //$NON-NLS-1$
        Throwable e2 = e.getCause();
        if (e2 instanceof WebServiceException && e2 != e) {
            try {
                int code = Integer.parseInt(e2.getMessage());
                if (code >= 18 && code <= 20) {
                    handleResume(meta, code, i, info);
                    throw new EOFException();
                }
            } catch (NumberFormatException e1) {
                // do nothing
            }
            addError(Messages.getString("GeotagOperation.geonaming_aborted"), e2); //$NON-NLS-1$
            if (aMonitor != null)
                aMonitor.setCanceled(true);
        }
    } catch (SAXException e) {
        addError(Messages.getString("GeotagOperation.XML_problem_parsing_response"), e); //$NON-NLS-1$
    } catch (ParserConfigurationException e) {
        addError(Messages.getString("GeotagOperation.internal_error_configuring_sax"), e); //$NON-NLS-1$
    }
    return null;
}

From source file:azkaban.webapp.AzkabanWebServer.java

private static void loadViewerPlugins(Context root, String pluginPath, VelocityEngine ve) {
    File viewerPluginPath = new File(pluginPath);
    if (!viewerPluginPath.exists()) {
        return;/*from   w  w w.java 2s .  c o  m*/
    }

    ClassLoader parentLoader = AzkabanWebServer.class.getClassLoader();
    File[] pluginDirs = viewerPluginPath.listFiles();
    ArrayList<String> jarPaths = new ArrayList<String>();
    for (File pluginDir : pluginDirs) {
        if (!pluginDir.exists()) {
            logger.error("Error viewer plugin path " + pluginDir.getPath() + " doesn't exist.");
            continue;
        }

        if (!pluginDir.isDirectory()) {
            logger.error("The plugin path " + pluginDir + " is not a directory.");
            continue;
        }

        // Load the conf directory
        File propertiesDir = new File(pluginDir, "conf");
        Props pluginProps = null;
        if (propertiesDir.exists() && propertiesDir.isDirectory()) {
            File propertiesFile = new File(propertiesDir, "plugin.properties");
            File propertiesOverrideFile = new File(propertiesDir, "override.properties");

            if (propertiesFile.exists()) {
                if (propertiesOverrideFile.exists()) {
                    pluginProps = PropsUtils.loadProps(null, propertiesFile, propertiesOverrideFile);
                } else {
                    pluginProps = PropsUtils.loadProps(null, propertiesFile);
                }
            } else {
                logger.error("Plugin conf file " + propertiesFile + " not found.");
                continue;
            }
        } else {
            logger.error("Plugin conf path " + propertiesDir + " not found.");
            continue;
        }

        String pluginName = pluginProps.getString("viewer.name");
        String pluginWebPath = pluginProps.getString("viewer.path");
        String pluginJobTypes = pluginProps.getString("viewer.jobtypes", null);
        int pluginOrder = pluginProps.getInt("viewer.order", 0);
        boolean pluginHidden = pluginProps.getBoolean("viewer.hidden", false);
        List<String> extLibClasspath = pluginProps.getStringList("viewer.external.classpaths",
                (List<String>) null);

        String pluginClass = pluginProps.getString("viewer.servlet.class");
        if (pluginClass == null) {
            logger.error("Viewer class is not set.");
        } else {
            logger.error("Plugin class " + pluginClass);
        }

        URLClassLoader urlClassLoader = null;
        File libDir = new File(pluginDir, "lib");
        if (libDir.exists() && libDir.isDirectory()) {
            File[] files = libDir.listFiles();

            ArrayList<URL> urls = new ArrayList<URL>();
            for (int i = 0; i < files.length; ++i) {
                try {
                    URL url = files[i].toURI().toURL();
                    urls.add(url);
                } catch (MalformedURLException e) {
                    logger.error(e);
                }
            }

            // Load any external libraries.
            if (extLibClasspath != null) {
                for (String extLib : extLibClasspath) {
                    File extLibFile = new File(pluginDir, extLib);
                    if (extLibFile.exists()) {
                        if (extLibFile.isDirectory()) {
                            // extLibFile is a directory; load all the files in the
                            // directory.
                            File[] extLibFiles = extLibFile.listFiles();
                            for (int i = 0; i < extLibFiles.length; ++i) {
                                try {
                                    URL url = extLibFiles[i].toURI().toURL();
                                    urls.add(url);
                                } catch (MalformedURLException e) {
                                    logger.error(e);
                                }
                            }
                        } else { // extLibFile is a file
                            try {
                                URL url = extLibFile.toURI().toURL();
                                urls.add(url);
                            } catch (MalformedURLException e) {
                                logger.error(e);
                            }
                        }
                    } else {
                        logger.error("External library path " + extLibFile.getAbsolutePath() + " not found.");
                        continue;
                    }
                }
            }

            urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), parentLoader);
        } else {
            logger.error("Library path " + libDir.getAbsolutePath() + " not found.");
            continue;
        }

        Class<?> viewerClass = null;
        try {
            viewerClass = urlClassLoader.loadClass(pluginClass);
        } catch (ClassNotFoundException e) {
            logger.error("Class " + pluginClass + " not found.");
            continue;
        }

        String source = FileIOUtils.getSourcePathFromClass(viewerClass);
        logger.info("Source jar " + source);
        jarPaths.add("jar:file:" + source);

        Constructor<?> constructor = null;
        try {
            constructor = viewerClass.getConstructor(Props.class);
        } catch (NoSuchMethodException e) {
            logger.error("Constructor not found in " + pluginClass);
            continue;
        }

        Object obj = null;
        try {
            obj = constructor.newInstance(pluginProps);
        } catch (Exception e) {
            logger.error(e);
            logger.error(e.getCause());
        }

        if (!(obj instanceof AbstractAzkabanServlet)) {
            logger.error("The object is not an AbstractAzkabanServlet");
            continue;
        }

        AbstractAzkabanServlet avServlet = (AbstractAzkabanServlet) obj;
        root.addServlet(new ServletHolder(avServlet), "/" + pluginWebPath + "/*");
        PluginRegistry.getRegistry().register(
                new ViewerPlugin(pluginName, pluginWebPath, pluginOrder, pluginHidden, pluginJobTypes));
    }

    // Velocity needs the jar resource paths to be set.
    String jarResourcePath = StringUtils.join(jarPaths, ", ");
    logger.info("Setting jar resource path " + jarResourcePath);
    ve.addProperty("jar.resource.loader.path", jarResourcePath);
}

From source file:ch.entwine.weblounge.kernel.fop.FopEndpoint.java

/**
 * Downloads both XML and XSL document and transforms them to PDF.
 * /*ww w.j av a  2  s  . c  om*/
 * @param xmlURL
 *          the URL to the XML document
 * @param xslURL
 *          the URL to the XSL document
 * @return the generated PDF
 * @throws WebApplicationException
 *           if the XML document cannot be downloaded
 * @throws WebApplicationException
 *           if the XSL document cannot be downloaded
 * @throws WebApplicationException
 *           if the PDF creation fails
 */
@POST
@Path("/pdf")
public Response transformToPdf(@FormParam("xml") String xmlURL, @FormParam("xsl") String xslURL,
        @FormParam("parameters") String params) {

    // Make sure we have a service
    if (fopService == null)
        throw new WebApplicationException(Status.SERVICE_UNAVAILABLE);

    final Document xml;
    final Document xsl;

    // Load the xml document
    InputStream xmlInputStream = null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xmlInputStream = new URL(xmlURL).openStream();
        xml = documentBuilder.parse(xmlInputStream);
    } catch (MalformedURLException e) {
        logger.warn("Error creating xml url from '{}'", xmlURL);
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (IOException e) {
        logger.warn("Error accessing xml document at '{}': {}", xmlURL, e.getMessage());
        throw new WebApplicationException(Status.NOT_FOUND);
    } catch (ParserConfigurationException e) {
        logger.warn("Error setting up xml parser: {}", e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (SAXException e) {
        logger.warn("Error parsing xml document from {}: {}", xmlURL, e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(xmlInputStream);
    }

    // Load the XLST stylesheet
    InputStream xslInputStream = null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xslInputStream = new URL(xslURL).openStream();
        xsl = documentBuilder.parse(xslInputStream);
    } catch (MalformedURLException e) {
        logger.warn("Error creating xsl url from '{}'", xslURL);
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (IOException e) {
        logger.warn("Error accessing xsl stylesheet at '{}': {}", xslURL, e.getMessage());
        throw new WebApplicationException(Status.NOT_FOUND);
    } catch (ParserConfigurationException e) {
        logger.warn("Error setting up xml parser: {}", e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (SAXException e) {
        logger.warn("Error parsing xml document from {}: {}", xslURL, e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(xslInputStream);
    }

    // Create the filename
    String name = FilenameUtils.getBaseName(xmlURL) + ".pdf";

    // Process the parameters
    final List<String[]> parameters = new ArrayList<String[]>();
    if (StringUtils.isNotBlank(params)) {
        for (String param : StringUtils.split(params, ";")) {
            String[] parameterValue = StringUtils.split(param, "=");
            if (parameterValue.length != 2) {
                logger.warn("Parameter for PDF generation is malformed: {}", param);
                throw new WebApplicationException(Status.BAD_REQUEST);
            }
            parameters.add(
                    new String[] { StringUtils.trim(parameterValue[0]), StringUtils.trim(parameterValue[1]) });
        }
    }

    // Write the file contents back
    ResponseBuilder response = Response.ok(new StreamingOutput() {
        public void write(OutputStream os) throws IOException, WebApplicationException {
            try {
                fopService.xml2pdf(xml, xsl, parameters.toArray(new String[parameters.size()][2]), os);
            } catch (IOException e) {
                Throwable cause = e.getCause();
                if (cause == null || !"Broken pipe".equals(cause.getMessage()))
                    logger.warn("Error writing file contents to response", e);
            } catch (TransformerConfigurationException e) {
                logger.error("Error setting up the XSL transfomer: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (FOPException e) {
                logger.error("Error creating PDF document: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (TransformerException e) {
                logger.error("Error transforming to PDF: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    });

    // Set response information
    response.type("application/pdf");
    response.header("Content-Disposition", "inline; filename=" + name);
    response.lastModified(new Date());

    return response.build();
}

From source file:de.unikassel.puma.openaccess.sword.SwordService.java

/**
 * collects all informations to send Documents with metadata to repository 
 * @throws SwordException /*from   w w  w.ja  v  a  2s. c o m*/
 */
public void submitDocument(PumaData<?> pumaData, User user) throws SwordException {
    log.info("starting sword");
    DepositResponse depositResponse = new DepositResponse(999);
    File swordZipFile = null;

    Post<?> post = pumaData.getPost();

    // -------------------------------------------------------------------------------
    /*
     * retrieve ZIP-FILE
     */
    if (post.getResource() instanceof BibTex) {

        // fileprefix
        String fileID = HashUtils.getMD5Hash(user.getName().getBytes()) + "_"
                + post.getResource().getIntraHash();

        // Destination directory 
        File destinationDirectory = new File(repositoryConfig.getDirTemp() + "/" + fileID);

        // zip-filename
        swordZipFile = new File(destinationDirectory.getAbsoluteFile() + "/" + fileID + ".zip");

        byte[] buffer = new byte[18024];

        log.info("getIntraHash = " + post.getResource().getIntraHash());

        /*
         * get documents
         */

        // At the moment, there are no Documents delivered by method parameter post.
        // retrieve list of documents from database - workaround

        // get documents for post and insert documents into post 
        ((BibTex) post.getResource())
                .setDocuments(retrieveDocumentsFromDatabase(user, post.getResource().getIntraHash()));

        if (((BibTex) post.getResource()).getDocuments().isEmpty()) {
            // Wenn kein PDF da, dann Fehlermeldung ausgeben!!
            log.info("throw SwordException: noPDFattached");
            throw new SwordException("error.sword.noPDFattached");
        }

        try {
            // create directory
            boolean mkdir_success = (new File(destinationDirectory.getAbsolutePath())).mkdir();
            if (mkdir_success) {
                log.info("Directory: " + destinationDirectory.getAbsolutePath() + " created");
            }

            // open zip archive to add files to
            log.info("zipFilename: " + swordZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(swordZipFile));

            ArrayList<String> fileList = new ArrayList<String>();

            for (final Document document : ((BibTex) post.getResource()).getDocuments()) {

                //getpostdetails
                // get file and store it in hard coded folder "/tmp/"
                //final Document document2 = logic.getDocument(user.getName(), post.getResource().getIntraHash(), document.getFileName());

                // move file to user folder with username_resource-hash as folder name

                // File (or directory) to be copied 
                //File fileToZip = new File(document.getFileHash());

                fileList.add(document.getFileName());

                // Move file to new directory 
                //boolean rename_success = fileToCopy.renameTo(new File(destinationDirectory, fileToMove.getName()));
                /*
                if (!rename_success) { 
                   // File was not successfully moved } 
                   log.info("File was not successfully moved: "+fileToMove.getName());
                }
                */
                ZipEntry zipEntry = new ZipEntry(document.getFileName());

                // Set the compression ratio
                zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

                String inputFilePath = projectDocumentPath + document.getFileHash().substring(0, 2) + "/"
                        + document.getFileHash();
                FileInputStream in = new FileInputStream(inputFilePath);

                // Add ZIP entry to output stream.
                zipOutputStream.putNextEntry(zipEntry);

                // Transfer bytes from the current file to the ZIP file
                //out.write(buffer, 0, in.read(buffer));

                int len;
                while ((len = in.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }

                zipOutputStream.closeEntry();

                // Close the current file input stream
                in.close();
            }

            // write meta data into zip archive
            ZipEntry zipEntry = new ZipEntry("mets.xml");
            zipOutputStream.putNextEntry(zipEntry);

            // create XML-Document
            // PrintWriter from a Servlet

            MetsBibTexMLGenerator metsBibTexMLGenerator = new MetsBibTexMLGenerator(urlRenderer);
            metsBibTexMLGenerator.setUser(user);
            metsBibTexMLGenerator.setFilenameList(fileList);
            //metsGenerator.setMetadata(metadataMap);
            metsBibTexMLGenerator.setMetadata((PumaData<BibTex>) pumaData);

            //            PumaPost additionalMetadata = new PumaPost();
            //            additionalMetadata.setExaminstitution(null);
            //            additionalMetadata.setAdditionaltitle(null);
            //            additionalMetadata.setExamreferee(null);
            //            additionalMetadata.setPhdoralexam(null);
            //            additionalMetadata.setSponsors(null);
            //            additionalMetadata.setAdditionaltitle(null);   

            //            metsBibTexMLGenerator.setMetadata((Post<BibTex>) post);

            //StreamResult streamResult = new StreamResult(zipOutputStream);

            zipOutputStream.write(metsBibTexMLGenerator.generateMets().getBytes("UTF-8"));

            zipOutputStream.closeEntry();

            // close zip archive  
            zipOutputStream.close();

            log.debug("saved to " + swordZipFile.getPath());

        } catch (MalformedURLException e) {
            // e.printStackTrace();
            log.info("MalformedURLException! " + e.getMessage());
        } catch (IOException e) {
            //e.printStackTrace();
            log.info("IOException! " + e.getMessage());

        } catch (ResourceNotFoundException e) {
            // e.printStackTrace();
            log.warn("ResourceNotFoundException! SwordService-retrievePost");
        }
    }
    /*
     * end of retrieve ZIP-FILE
     */
    //---------------------------------------------------

    /*
     * do the SWORD stuff
     */

    if (null != swordZipFile) {

        // get an instance of SWORD-Client
        Client swordClient = new Client();

        PostMessage swordMessage = new PostMessage();

        // create sword post message

        // message file
        // create directory in temp-folder
        // store post documents there
        // store meta data there in format http://purl.org/net/sword-types/METSDSpaceSIP
        // delete post document files and meta data file

        // add files to zip archive
        // -- send zip archive
        // -- delete zip archive

        swordClient.setServer(repositoryConfig.getHttpServer(), repositoryConfig.getHttpPort());
        swordClient.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordClient.setCredentials(repositoryConfig.getAuthUsername(), repositoryConfig.getAuthPassword());

        // message meta
        swordMessage.setNoOp(false);
        swordMessage.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordMessage.setFilepath(swordZipFile.getAbsolutePath());
        swordMessage.setFiletype("application/zip");
        swordMessage.setFormatNamespace("http://purl.org/net/sword-types/METSDSpaceSIP"); // sets packaging!
        swordMessage.setVerbose(false);

        try {
            // check depositurl against service document
            if (checkServicedokument(retrieveServicedocument(), repositoryConfig.getHttpServicedocumentUrl(),
                    SWORDFILETYPE, SWORDFORMAT)) {
                // transmit sword message (zip file with document metadata and document files
                swordMessage.setDestination(repositoryConfig.getHttpDepositUrl());

                depositResponse = swordClient.postFile(swordMessage);

                /*
                 * 200 OK Used in response to successful GET operations and
                 * to Media Resource Creation operations where X-No-Op is
                 * set to true and the server supports this header.
                 * 
                 * 201 Created
                 * 
                 * 202 Accepted - One of these MUST be used to indicate that
                 * a deposit was successful. 202 Accepted is used when
                 * processing of the data is not yet complete.
                 * 
                 * 
                 * 400 Bad Request - used to indicate that there is some
                 * problem with the request where there is no more
                 * appropriate 4xx code.
                 * 
                 * 401 Unauthorized - In addition to the usage described in
                 * HTTP, servers that support mediated deposit SHOULD use
                 * this status code when the server does not understand the
                 * value given in the X-Behalf-Of header. In this case a
                 * human-readable explanation MUST be provided.
                 * 
                 * 403 Forbidden - indicates that there was a problem making
                 * the deposit, it may be that the depositor is not
                 * authorised to deposit on behalf of the target owner, or
                 * the target owner does not have permission to deposit into
                 * the specified collection.
                 * 
                 * 412 Precondition failed - MUST be returned by server
                 * implementations if a calculated checksum does not match a
                 * value provided by the client in the Content-MD5 header.
                 * 
                 * 415 Unsupported Media Type - MUST be used to indicate
                 * that the format supplied in either a Content-Type header
                 * or in an X-Packaging header or the combination of the two
                 * is not accepted by the server.
                 */

                log.info("throw SwordException: errcode" + depositResponse.getHttpResponse());
                throw new SwordException("error.sword.errcode" + depositResponse.getHttpResponse());

            }

        } catch (SWORDClientException e) {
            log.warn("SWORDClientException: " + e.getMessage() + "\n" + e.getCause() + " / "
                    + swordMessage.getDestination());
            throw new SwordException("error.sword.urlnotaccessable");
        }

    }

}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportExecuteBL.java

/**
 * Serializes the data source into the response's output stream using a
 * ReportExporter//from w ww.j  a v  a  2 s .  c om
 *
 * @param templateID
 * @param datasource
 * @return
 */
static String prepareReportResponse(HttpServletResponse response, Integer templateID,
        Map<String, Object> contextMap, Map<String, Object> description, Object datasource,
        Map<String, Object> parameters, ServletContext servletContext, TPersonBean personBean, Locale locale) {
    URL baseURL = null;
    String logoFolder = null;
    URL completeURL = null;
    String baseFileName = null;
    if (templateID == null) {
        final String baseFolder = "/design/silver/";
        // direct pdf/xls from report overview
        try {
            // set the baseURL to take some standard icons from
            // "/design/silver/icons"
            // which ale already used by the report overview anyway
            baseURL = servletContext.getResource(baseFolder + "16x16");
            LOGGER.debug("baseURL: " + baseURL.toString());
        } catch (final MalformedURLException e) {
            LOGGER.error("Getting the baseURL for " + baseFolder + "16x16 failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        // set the baseURL to take some standard icons from
        // "/design/silver/icons"
        // which ale already used by the report overview anyway
        logoFolder = HandleHome.getTrackplus_Home() + File.separator + HandleHome.LOGOS_DIR + File.separator;
    } else {
        // template exists
        final File template = ReportBL.getDirTemplate(templateID);
        final ILabelBean templateBean = ReportFacade.getInstance().getByKey(templateID);
        if (templateBean != null) {
            baseFileName = templateBean.getLabel();
        }
        try {
            baseURL = template.toURL();
            LOGGER.debug("baseURL: " + baseURL.toString());
        } catch (final MalformedURLException e) {
            LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
            return null;
        }
        try {
            completeURL = new URL(baseURL.toExternalForm() /*
                                                           * +
                                                           * "/"File.separator
                                                           */
                    + description.get(IDescriptionAttributes.MASTERFILE));
            completeURL.openStream();
            LOGGER.debug("completeURL: " + completeURL.toString());
        } catch (final Exception me) {
            LOGGER.error(LocalizeUtil.getParametrizedString(
                    "report.reportExportManager.err.masterFileTemplateNotFound",
                    new String[] { me.getMessage() }, locale) + me);
            return null;
        }
    }
    if (parameters == null) {
        parameters = new HashMap<String, Object>();
    }
    parameters.put(JasperReportExporter.REPORT_PARAMETERS.BASE_URL, baseURL);
    if (logoFolder != null) {
        parameters.put(JasperReportExporter.REPORT_PARAMETERS.LOGO_FOLDER_URL, logoFolder);
    }
    if (completeURL != null) {
        parameters.put(JasperReportExporter.REPORT_PARAMETERS.COMPLETE_URL, completeURL);
    }
    if (baseFileName == null) {
        baseFileName = "TrackReport";
    }
    baseFileName += DateTimeUtils.getInstance().formatISODateTime(new Date());
    response.reset();
    final String format = (String) description.get(IDescriptionAttributes.FORMAT);
    if (ReportExporter.FORMAT_PDF.equals(format)) {
        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".pdf\"");
    } else if (ReportExporter.FORMAT_RTF.equals(format)) {
        response.setHeader("Content-Type", "application/rtf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".rtf\"");
    } else if (ReportExporter.FORMAT_XML.equals(format)) {
        response.setHeader("Content-Type", "text/xml");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xml\"");
    } else if (ReportExporter.FORMAT_HTML.equals(format)) {
        response.setHeader("Content-Type", "text/html");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".html\"");
    } else if (ReportExporter.FORMAT_ZIP.equals(format)) {
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".zip\"");
    } else if (ReportExporter.FORMAT_XLS.equals(format)) {
        response.setHeader("Content-Type", "application/xls");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xls\"");
    } else if (ReportExporter.FORMAT_CSV.equals(format)) {
        final String csvEncoding = personBean.getCsvEncoding();
        LOGGER.debug("csvEncoding is " + csvEncoding);
        if (csvEncoding != null) {
            response.setContentType("text/plain; " + csvEncoding);
        } else {
            response.setContentType("text/plain; charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".csv\"");
    } else if (ReportExporter.FORMAT_DOCX.equals(format)) {
        response.setHeader("Content-Type",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".docx\"");
    }
    DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response);
    OutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
    } catch (final IOException e) {
        LOGGER.error("Getting the output stream failed with " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    try {
        LOGGER.debug("Exporter type is " + description.get(IDescriptionAttributes.TYPE) + " exporter format is "
                + description.get(IDescriptionAttributes.FORMAT));
        final ReportExporter exporter = ReportExecuteBL
                .getExporter((String) description.get(IDescriptionAttributes.TYPE));
        exporter.exportReport((Document) datasource, personBean, locale, parameters, outputStream, contextMap,
                description);
        LOGGER.debug("Export done...");
    } catch (final ReportExportException e) {
        LOGGER.error("Exporting the report failed with " + e.getMessage());
        String actionMessage = "";
        if (e.getCause() != null) {
            actionMessage = LocalizeUtil.getParametrizedString(e.getMessage(),
                    new String[] { e.getCause().getMessage() }, locale);
        } else {
            actionMessage = LocalizeUtil.getLocalizedTextFromApplicationResources(e.getMessage(), locale);
        }
        LOGGER.error(actionMessage);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } catch (final Exception e) {
        LOGGER.error("Exporting the report failed with throwable " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return null;
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity.java

private void runTests() {

    MobileServiceClient client = null;/* w  ww.j  a v a 2 s.  c om*/

    try {
        client = createMobileServiceClient();
    } catch (MalformedURLException e) {
        createAndShowDialog(e, "Error");
    }

    // getMobileServiceRuntimeFeatures(client);

    final TestGroup group = (TestGroup) mTestGroupSpinner.getSelectedItem();
    logWithTimestamp(new Date(), "Tests for group \'" + group.getName() + "\'");

    logSeparator();

    final MobileServiceClient currentClient = client;

    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
            || Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // For android versions 4.0.x
        // Run a first Void AsyncTask on UI thread to enable the possibility
        // of running others on sub threads
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                return null;
            }
        }.execute();

    }

    Thread thread = new Thread() {

        @Override
        public void run() {
            group.runTests(currentClient, new TestExecutionCallback() {

                @Override
                public void onTestStart(TestCase test) {
                    final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }

                    });

                    log("TEST START", test.getName());
                }

                @Override
                public void onTestGroupComplete(TestGroup group, List<TestResult> results) {
                    log("TEST GROUP COMPLETED", group.getName() + " - " + group.getStatus().toString());
                    logSeparator();

                    if (group.getName().startsWith(TestGroup.AllTestsGroupName)) {

                        List<TestCase> tests = new ArrayList<TestCase>();

                        for (TestResult result : results) {
                            tests.add(result.getTestCase());
                        }

                        DaylightLogger logger = new DaylightLogger(getDaylightURL(), getDaylightProject(),
                                getDaylightClientId(), getDaylightClientSecret(), getDaylightRuntime(),
                                getDaylightRunId());
                        try {
                            logger.reportResultsToDaylight(group.getFailedTestCount(), group.getStartTime(),
                                    group.getEndTime(), tests, group.getSourceMap());
                        } catch (Throwable e) {
                            log(e.getMessage());
                        }
                    }

                    if (shouldRunUnattended()) {
                        // String logContent = mLog.toString();
                        // postLogs(logContent, true);

                        boolean passed = true;
                        for (TestResult result : results) {
                            if (result.getStatus() != TestStatus.Passed) {
                                passed = false;
                                break;
                            }
                        }

                        try {
                            String sdCard = Environment.getExternalStorageDirectory().getPath();
                            FileOutputStream fos = new FileOutputStream(sdCard + "/done_android_e2e.txt");
                            OutputStreamWriter osw = new OutputStreamWriter(fos);
                            BufferedWriter bw = new BufferedWriter(osw);
                            bw.write("Completed successfully.\n");
                            bw.write(passed ? "PASSED" : "FAILED");
                            bw.write("\n");
                            bw.close();
                            osw.close();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onTestComplete(TestCase test, TestResult result) {
                    Throwable e = result.getException();
                    if (e != null) {
                        StringBuilder sb = new StringBuilder();
                        while (e != null) {
                            sb.append(e.getClass().getSimpleName() + ": ");
                            sb.append(e.getMessage());
                            sb.append("\n");
                            sb.append(Log.getStackTraceString(e));
                            sb.append("\n\n");
                            e = e.getCause();
                        }

                        test.log("Exception: " + sb.toString());
                    }

                    final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();

                        }

                    });
                    logWithTimestamp(test.getStartTime(),
                            "Logs for test " + test.getName() + " (" + result.getStatus().toString() + ")");
                    String testLogs = test.getLog();
                    if (testLogs.length() > 0) {
                        if (testLogs.endsWith("\n")) {
                            testLogs = testLogs.substring(0, testLogs.length() - 1);
                        }
                        log(testLogs);
                    }

                    logWithTimestamp(test.getEndTime(), "Test " + result.getStatus().toString());
                    logWithTimestamp(test.getEndTime(), "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
                    logSeparator();
                }
            });
        }
    };

    thread.start();
}