Example usage for java.net MalformedURLException getMessage

List of usage examples for java.net MalformedURLException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:crawlercommons.fetcher.http.SimpleHttpFetcher.java

@Override
public FetchedResult get(String url, Payload payload) throws BaseFetchException {
    try {//from   w  w w .java 2 s.c  om
        URL realUrl = new URL(url);
        String protocol = realUrl.getProtocol();
        if (!protocol.equals("http") && !protocol.equals("https")) {
            throw new BadProtocolFetchException(url);
        }
    } catch (MalformedURLException e) {
        throw new UrlFetchException(url, e.getMessage());
    }

    return request(new HttpGet(), url, payload);
}

From source file:edu.harvard.i2b2.navigator.CRCNavigator.java

/**
 * @return new thread to show broswer with logger html file
 *//*from   ww  w  .jav a 2s. c  o m*/
public Thread showLoggerBrowser(Shell shell) {
    // final Button theButton = button;
    final Shell myShell = shell;
    File file = new File(logFileName);
    URL url = null;
    // Convert the file object to a URL with an absolute path
    try {
        url = file.toURL();
    } catch (MalformedURLException e) {
        log.info(e.getMessage());
    }

    final URL myurl = url;
    return new Thread() {
        public void run() {
            new HelpBrowser().run(myurl.toString(), myShell);
        }
    };
}

From source file:com.dngames.mobilewebcam.PhotoSettings.java

public void DownloadImprintBitmap() {
    // get from URL
    Handler h = new Handler(mContext.getMainLooper());
    h.post(new Runnable() {
        @Override/* w w  w . ja v a2 s  . c om*/
        public void run() {
            try {
                new AsyncTask<String, Void, Bitmap>() {
                    @Override
                    protected Bitmap doInBackground(String... params) {
                        try {
                            URL url = new URL(mImprintPictureURL);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                            InputStream is = connection.getInputStream();
                            return BitmapFactory.decodeStream(is);
                        } catch (MalformedURLException e) {
                            if (e.getMessage() != null)
                                MobileWebCam.LogE("Imprint picture URL error: " + e.getMessage());
                            else
                                MobileWebCam.LogE("Imprint picture URL invalid!");
                            e.printStackTrace();
                        } catch (IOException e) {
                            if (e.getMessage() != null)
                                MobileWebCam.LogE(e.getMessage());
                            e.printStackTrace();
                        }

                        return null;
                    }

                    @Override
                    protected void onPostExecute(Bitmap result) {
                        if (result == null && !mNoToasts)
                            Toast.makeText(mContext, "Imprint picture download failed!", Toast.LENGTH_SHORT)
                                    .show();

                        synchronized (PhotoSettings.gImprintBitmapLock) {
                            PhotoSettings.gImprintBitmap = result;
                        }
                    }
                }.execute().get();
            } catch (Exception e) {
                if (e.getMessage() != null)
                    MobileWebCam.LogE(e.getMessage());
                e.printStackTrace();
            }
        }
    });
}

From source file:org.mule.modules.salesforce.SalesforceModule.java

public SalesforceBayeuxClient getBayeuxClient() {
    try {//from   w ww .ja  v a 2  s.  c om
        if (bc == null) {
            bc = new SalesforceBayeuxClient(this);

            if (!bc.isHandshook()) {
                bc.handshake();
            }
        }
    } catch (MalformedURLException e) {
        LOGGER.error(e.getMessage());
    }

    return bc;
}

From source file:eu.aniketos.scpm.impl.CompositionPlanner.java

@Override
public List<ICompositionPlan> orderSecureCompositions(List<ICompositionPlan> securedCompositions,
        List<IConsumerPolicy> consumerPolicies, List<IAgreementTemplate> agreementTemplates,
        OrderCriteria criteria) {//from ww  w.jav a 2 s.  c  om

    try {
        System.out.println("Connecting to SPDM");
        URL spdmurl = new URL(URL_SPDM);
    } catch (MalformedURLException e) {

        System.out.println(e.getMessage());
        //e.printStackTrace();
    }

    List<ICompositionPlan> orderedCompositions = new Vector<ICompositionPlan>();

    try {

        String value = criteria.getCriteria().get("Trustworthiness");
        System.out.println("Weight set by consumer for Trustworthiness: " + Double.parseDouble(value));
        value = criteria.getCriteria().get("Credibility");
        System.out.println("Weight set by consumer for Credibility: " + value);
        value = criteria.getCriteria().get("Validness");
        System.out.println("Weight set by consumer for Validness: " + value);

        String criteriaValueString = null;

        for (int index = 0; index < securedCompositions.size(); index++) {

            double overallValue = getOrderValue(securedCompositions.get(index), criteria);
            //Subtle action: use the bpmnstring to save the value. It will not affect the userinterface part as the bpmnstring already saved there.

            criteriaValueString = Double.toString(overallValue);
            securedCompositions.get(index).setBPMNXML(criteriaValueString);

            int position = 0;
            String comparedValueString = null;
            if (orderedCompositions.size() == 0)
                orderedCompositions.add(position, securedCompositions.get(index));
            else {
                comparedValueString = orderedCompositions.get(position).getBPMNXML();

                while (criteriaValueString.compareTo(comparedValueString) < 0) {
                    position++;
                    if (position < orderedCompositions.size())
                        comparedValueString = orderedCompositions.get(position).getBPMNXML();

                    else
                        break;

                }
                orderedCompositions.add(position, securedCompositions.get(index));
            }

        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
        //e.printStackTrace();

    }

    return orderedCompositions;
}

From source file:com.fluidops.iwb.deepzoom.CXMLServlet.java

/**
 * Returns the image URL for the given value
 * //from  w  ww .jav  a  2s.  c o m
 * a) uploaded file ({@link IWBCmsUtil#isUploadedFile(URI)}) and {@link ImageResolver#isImage(String)}
 *       => the {@link File#toURI()} URL representation
 * b) the {@link Value#stringValue()} otherwise
 * 
 * @param value
 * @return
 */
private String getImageURLForValue(Value value) {
    if (value instanceof URI) {
        if (IWBCmsUtil.isUploadedFile((URI) value) && ImageResolver.isImage(value.stringValue())) {
            try {
                return IWBFileUtil.getFileInUploadFolder(((URI) value).getLocalName()).toURI().toURL()
                        .toExternalForm();
            } catch (MalformedURLException e) {
                logger.debug("Invalid url for value '" + value + "': " + e.getMessage());
                return IWBCmsUtil.getAccessUrl((URI) value); // fallback
            }
        }
    }
    return value.stringValue();
}

From source file:com.streamreduce.util.JiraClient.java

/**
 * Returns the URL object from the link element
 *
 * @param linkElement the link element/*  ww w . ja v a  2  s . c o  m*/
 * @return a URL for the href attribute of the link element or null if there was problem
 */
private URL getURLFromLinkElement(org.apache.abdera.model.Element linkElement) {
    // Just in case, return null if there is no link to parse
    if (linkElement == null || !linkElement.getQName().getLocalPart().equals("link")) {
        return null;
    }

    String linkValue = linkElement.getAttributeValue("href");

    try {
        return URI.create(linkValue).toURL();
    } catch (MalformedURLException e) {
        // Should never happen
        LOGGER.error(String.format("Error creating a URL for %s: %s", linkValue, e.getMessage()), e);
        return null;
    }
}

From source file:org.fao.geonet.component.harvester.csw.Harvest.java

/**
 * Verifies Source parameter is present and well-formed.
 * <p>/*from  www  .j ava2 s  .  co m*/
 * OGC 07-006 10.12.4.1 : The Source parameter is used to specify a URI reference to the
 * metadata resource to be harvested.
 *
 * @param request - the request
 * @return - the harvesting target uri
 * @throws InvalidParameterValueEx hmm
 * @throws MissingParameterValueEx hmm
 */
private String checkSource(Element request) throws MissingParameterValueEx, InvalidParameterValueEx {
    String source = request.getChildText("Source", Csw.NAMESPACE_CSW);
    //
    // source is a required parameter
    //
    if (source == null) {
        throw new MissingParameterValueEx("Source");
    }
    //
    // check that source is a valid url by constructing URL object from it
    //
    try {
        new URL(source);
    }
    // not a valid url
    catch (MalformedURLException x) {
        throw new InvalidParameterValueEx("Source", "Invalid source URL:" + source + " - " + x.getMessage());
    }

    if (Log.isDebugEnabled(Geonet.CSW_HARVEST))
        Log.debug(Geonet.CSW_HARVEST, "CSW Harvest checkSource OK, returns: " + source);
    return source;
}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

public int uploadFile(String sourceFileUri) {
    String upLoadServerUri = "";
    upLoadServerUri = "http://ip.roaming4world.com/esstel/fetch_contacts_upload.php";
    String fileName = sourceFileUri;
    Log.d("file upload url", upLoadServerUri);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;//from   w w w  . j  av a 2s  .  c o m
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.d("uploadFile", "Source File Does not exist");
        return 0;
    }
    int serverResponseCode = 0;
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", fileName);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + selfNumber + "-"
                + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        Log.d("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        //close the streams //
        fileInputStream.close();
        dos.flush();
        dos.close();
        Log.d("Contact file ", "uploaded");
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }
    return serverResponseCode;

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.FedoraDatastreamController.java

@Override
public void doPost(HttpServletRequest rawRequest, HttpServletResponse res)
        throws ServletException, IOException {
    try {//  ww  w.j a  v  a  2 s .  c  o m
        VitroRequest req = new VitroRequest(rawRequest);
        if (req.hasFileSizeException()) {
            throw new FdcException("Size limit exceeded: " + req.getFileSizeException().getLocalizedMessage());
        }
        if (!req.isMultipart()) {
            throw new FdcException("Must POST a multipart encoded request");
        }

        //check if fedora is on line
        OntModel sessionOntModel = ModelAccess.on(getServletContext()).getOntModel();
        synchronized (FedoraDatastreamController.class) {
            if (fedoraUrl == null) {
                setup(sessionOntModel, getServletContext());
                if (fedoraUrl == null)
                    throw new FdcException("Connection to the file repository is "
                            + "not setup correctly.  Could not read fedora.properties file");
            } else {
                if (!canConnectToFedoraServer()) {
                    fedoraUrl = null;
                    throw new FdcException("Could not connect to Fedora.");
                }
            }
        }
        FedoraClient fedora;
        try {
            fedora = new FedoraClient(fedoraUrl, adminUser, adminPassword);
        } catch (MalformedURLException e) {
            throw new FdcException("Malformed URL for fedora Repository location: " + fedoraUrl);
        }
        FedoraAPIM apim;
        try {
            apim = fedora.getAPIM();
        } catch (Exception e) {
            throw new FdcException("could not create fedora APIM:" + e.getMessage());
        }

        //get the parameters from the request
        String pId = req.getParameter("pid");
        String dsId = req.getParameter("dsid");
        String fileUri = req.getParameter("fileUri");

        boolean useNewName = false;
        if ("true".equals(req.getParameter("useNewName"))) {
            useNewName = true;
        }
        if (pId == null || pId.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing pid parameter)");
        if (dsId == null || dsId.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing dsid parameter)");
        if (fileUri == null || fileUri.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing fileUri parameter)");

        FileItem fileRes = req.getFileItem("fileRes");
        if (fileRes == null)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing fileRes)");

        //check if file individual has a fedora:PID for a data stream
        VitroRequest vreq = new VitroRequest(rawRequest);
        IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao();
        Individual fileEntity = iwDao.getIndividualByURI(fileUri);

        //check if logged in
        //TODO: check if logged in

        //check if user is allowed to edit datastream
        //TODO:check if can edit datastream

        //check if digital object and data stream exist in fedora
        Datastream ds = apim.getDatastream(pId, dsId, null);
        if (ds == null)
            throw new FdcException(
                    "There was no datastream in the " + "repository for " + pId + " " + DEFAULT_DSID);

        //upload to temp holding area
        String originalName = fileRes.getName();
        String name = originalName.replaceAll("[,+\\\\/$%^&*#@!<>'\"~;]", "_");
        name = name.replace("..", "_");
        name = name.trim().toLowerCase();

        String saveLocation = baseDirectoryForFiles + File.separator + name;
        String savedName = name;
        int next = 0;
        boolean foundUnusedName = false;
        while (!foundUnusedName) {
            File test = new File(saveLocation);
            if (test.exists()) {
                next++;
                savedName = name + '(' + next + ')';
                saveLocation = baseDirectoryForFiles + File.separator + savedName;
            } else {
                foundUnusedName = true;
            }
        }

        File uploadedFile = new File(saveLocation);

        try {
            fileRes.write(uploadedFile);
        } catch (Exception ex) {
            log.error("Unable to save POSTed file. " + ex.getMessage());
            throw new FdcException("Unable to save file to the disk. " + ex.getMessage());
        }

        //upload to temp area on fedora
        File file = new File(saveLocation);
        String uploadFileUri = fedora.uploadFile(file);
        // System.out.println("Fedora upload temp = upload file uri is " + uploadFileUri);
        String md5 = md5hashForFile(file);
        md5 = md5.toLowerCase();

        //make change to data stream on fedora
        apim.modifyDatastreamByReference(pId, dsId, null, null, fileRes.getContentType(), null, uploadFileUri,
                "MD5", null, null, false);

        String checksum = apim.compareDatastreamChecksum(pId, dsId, null);

        //update properties like checksum, file size, and content type

        WebappDaoFactory wdf = vreq.getWebappDaoFactory();
        DataPropertyStatement dps = null;
        DataProperty contentType = wdf.getDataPropertyDao().getDataPropertyByURI(this.contentTypeProperty);
        if (contentType != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, contentType);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(contentType.getURI());
            dps.setData(fileRes.getContentType());
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
        }

        DataProperty fileSize = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileSizeProperty);
        if (fileSize != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileSize);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(fileSize.getURI());
            dps.setData(Long.toString(fileRes.getSize()));
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            //System.out.println("Updated file size with " + fileRes.getSize());
        }

        DataProperty checksumDp = wdf.getDataPropertyDao().getDataPropertyByURI(this.checksumDataProperty);
        if (checksumDp != null) {
            //System.out.println("Checksum data property is also not null");
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, checksumDp);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(checksumDp.getURI());
            dps.setData(checksum);
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
        }

        //I'm leaving if statement out for now as the above properties are obviously being replaced as well
        //if( "true".equals(useNewName)){
        //Do we need to encapuslate in this if OR is this path always for replacing a file
        //TODO: Put in check to see if file name has changed and only execute these statements if file name has changed
        DataProperty fileNameProperty = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileNameProperty);
        if (fileNameProperty != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileNameProperty);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(fileNameProperty.getURI());
            dps.setData(originalName); //This follows the pattern of the original file upload - the name returned from the uploaded file object
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            //System.out.println("File name property is not null = " + fileNameProperty.getURI() + " updating to " + originalName);
        } else {
            //System.out.println("file name property is null");
        }

        //Need to also update the check sum node - how would we do that
        //Find checksum node related to this particular file uri, then go ahead and update two specific fields

        List<ObjectPropertyStatement> csNodeStatements = fileEntity.getObjectPropertyMap()
                .get(this.checksumNodeProperty).getObjectPropertyStatements();
        if (csNodeStatements.size() == 0) {
            System.out.println("No object property statements correspond to this property");
        } else {
            ObjectPropertyStatement cnodeStatement = csNodeStatements.get(0);
            String cnodeUri = cnodeStatement.getObjectURI();
            //System.out.println("Checksum node uri is " + cnodeUri);

            Individual checksumNodeObject = iwDao.getIndividualByURI(cnodeUri);

            DataProperty checksumDateTime = wdf.getDataPropertyDao()
                    .getDataPropertyByURI(this.checksumNodeDateTimeProperty);
            if (checksumDateTime != null) {
                String newDatetime = sessionOntModel.createTypedLiteral(new DateTime()).getString();
                //Review how to update date time
                wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(
                        checksumNodeObject, checksumDateTime);
                dps = new DataPropertyStatementImpl();
                dps.setIndividualURI(checksumNodeObject.getURI());
                dps.setDatapropURI(checksumDateTime.getURI());
                dps.setData(newDatetime);
                wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);

            }
            DataProperty checksumNodeValue = wdf.getDataPropertyDao()
                    .getDataPropertyByURI(this.checksumDataProperty);
            if (checksumNodeValue != null) {
                wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(
                        checksumNodeObject, checksumNodeValue);
                dps = new DataPropertyStatementImpl();
                dps.setIndividualURI(checksumNodeObject.getURI());
                dps.setDatapropURI(checksumNodeValue.getURI());
                dps.setData(checksum); //Same as fileName above - change if needed
                wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            }

        }

        //Assumes original entity name is equal to the location - as occurs with regular file upload
        String originalEntityName = fileEntity.getName();
        if (originalEntityName != originalName) {
            //System.out.println("Setting file entity to name of uploaded file");
            fileEntity.setName(originalName);
        } else {
            //System.out.println("Conditional for file entity name and uploaded name is saying same");
        }
        iwDao.updateIndividual(fileEntity);
        //}

        req.setAttribute("fileUri", fileUri);
        req.setAttribute("originalFileName", fileEntity.getName());
        req.setAttribute("checksum", checksum);
        if ("true".equals(useNewName)) {
            req.setAttribute("useNewName", "true");
            req.setAttribute("newFileName", originalName);
        } else {
            req.setAttribute("newFileName", fileEntity.getName());
        }

        //forward to form     
        req.setAttribute("bodyJsp", "/fileupload/datastreamModificationSuccess.jsp");
        RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
        rd.forward(req, res);
    } catch (FdcException ex) {
        rawRequest.setAttribute("errors", ex.getMessage());
        RequestDispatcher rd = rawRequest.getRequestDispatcher("/edit/fileUploadError.jsp");
        rd.forward(rawRequest, res);
        return;
    }
}