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:com.altamiracorp.lumify.twitter.DefaultLumifyTwitterProcessor.java

@Override
public void retrieveProfileImage(final String processId, final JSONObject jsonTweet, Vertex tweeterVertex) {
    Visibility visibility = new Visibility("");
    JSONObject tweeter = JSON_USER_PROPERTY.getFrom(jsonTweet);
    String screenName = JSON_SCREEN_NAME_PROPERTY.getFrom(tweeter);
    if (screenName != null) {
        screenName = screenName.trim();//w ww.  j av  a 2 s  . c  om
    }
    String imageUrl = JSON_PROFILE_IMAGE_URL_PROPERTY.getFrom(tweeter);
    if (imageUrl != null) {
        imageUrl = imageUrl.trim();
    }
    if (screenName != null && !screenName.isEmpty() && imageUrl != null && !imageUrl.isEmpty()) {
        try {
            InputStream imgIn = urlStreamCreator.openUrlStream(imageUrl);
            ByteArrayOutputStream imgOut = new ByteArrayOutputStream();
            IOUtils.copy(imgIn, imgOut);

            byte[] rawImg = imgOut.toByteArray();
            String rowKey = RowKeyHelper.buildSHA256KeyString(rawImg);

            User user = getUser();
            Graph graph = getGraph();
            AuditRepository auditRepo = getAuditRepository();
            StreamingPropertyValue raw = new StreamingPropertyValue(new ByteArrayInputStream(rawImg),
                    byte[].class);
            raw.searchIndex(false);

            Concept concept = getOntologyRepository().getConceptByName(CONCEPT_TWITTER_PROFILE_IMAGE);
            ElementMutation<Vertex> imageBuilder = findOrPrepareArtifactVertex(rowKey);
            CONCEPT_TYPE.setProperty(imageBuilder, concept.getId(), visibility);
            TITLE.setProperty(imageBuilder, String.format(IMAGE_ARTIFACT_TITLE_FMT, screenName), visibility);
            SOURCE.setProperty(imageBuilder, IMAGE_ARTIFACT_SOURCE, visibility);
            MIME_TYPE.setProperty(imageBuilder, PROFILE_IMAGE_MIME_TYPE, visibility);
            PROCESS.setProperty(imageBuilder, processId, visibility);
            RAW.setProperty(imageBuilder, raw, visibility);

            Vertex imageVertex = null;
            if (!(imageBuilder instanceof ExistingElementMutation)) {
                imageVertex = imageBuilder.save();
                auditRepo.auditVertexElementMutation(imageBuilder, imageVertex, processId, user, visibility);
            } else {
                auditRepo.auditVertexElementMutation(imageBuilder, imageVertex, processId, user, visibility);
                imageVertex = imageBuilder.save();
            }

            LOGGER.debug("Saved Twitter User [%s] Profile Photo to Accumulo and as graph vertex: %s",
                    screenName, imageVertex.getId());
            String labelDisplay = getOntologyRepository().getDisplayNameForLabel(ENTITY_HAS_IMAGE_HANDLE_PHOTO);
            auditRepo.auditRelationship(AuditAction.CREATE, tweeterVertex, imageVertex, labelDisplay, processId,
                    "", user, visibility);

            // TO-DO: Replace GLYPH_ICON with ENTITY_IMAGE_URL
            ElementMutation<Vertex> tweeterVertexMutation = tweeterVertex.prepareMutation();
            tweeterVertexMutation.setProperty(GLYPH_ICON.getKey(),
                    new Text(String.format(GLYPH_ICON_FMT, imageVertex.getId()), TextIndexHint.EXACT_MATCH),
                    visibility);
            imageBuilder.setProperty(GLYPH_ICON.getKey(),
                    new Text(String.format(GLYPH_ICON_FMT, imageVertex.getId()), TextIndexHint.EXACT_MATCH),
                    visibility);

            auditRepo.auditVertexElementMutation(tweeterVertexMutation, tweeterVertex, processId, user,
                    visibility);
            auditRepo.auditVertexElementMutation(imageBuilder, imageVertex, processId, user, visibility);

            tweeterVertex = tweeterVertexMutation.save();
            imageVertex = imageBuilder.save();

            Iterator<Edge> edges = tweeterVertex.getEdges(imageVertex, Direction.IN,
                    ENTITY_HAS_IMAGE_HANDLE_PHOTO, user.getAuthorizations()).iterator();
            if (!edges.hasNext()) {
                String displayName = getOntologyRepository()
                        .getDisplayNameForLabel(ENTITY_HAS_IMAGE_HANDLE_PHOTO);
                graph.addEdge(tweeterVertex, imageVertex, ENTITY_HAS_IMAGE_HANDLE_PHOTO, visibility,
                        user.getAuthorizations());
                auditRepo.auditRelationship(AuditAction.CREATE, tweeterVertex, imageVertex, displayName,
                        processId, "", user, visibility);
            }
            graph.flush();
        } catch (MalformedURLException mue) {
            LOGGER.warn("Invalid Profile Photo URL [%s] for Twitter User [%s]: %s", imageUrl, screenName,
                    mue.getMessage());
        } catch (IOException ioe) {
            LOGGER.warn("BLB [%s] for Twitter User [%s]: %s", imageUrl, screenName, ioe.getMessage());
        }
    }
}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * upload multipart//  w ww  .jav  a  2s .  c  o m
 * this method receive the file to be uploaded
 * */
@SuppressWarnings("deprecation")
public String uploadMultiPart(Map<String, File> files) throws Exception {
    disableSSLCertificateChecking();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    try {
        URL endpoint = new URL(url);
        conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        dos = new DataOutputStream(conn.getOutputStream());
        String post = "";

        //WRITE ALL THE PARAMS
        for (NameValuePair p : params)
            post += writeMultipartParam(p);
        dos.flush();
        //END WRITE ALL THE PARAMS

        //BEGIN THE UPLOAD
        ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>();
        for (Entry<String, File> entry : files.entrySet()) {
            post += lineEnd;
            post += twoHyphens + boundary + lineEnd;
            String NameParamImage = entry.getKey();
            File file = entry.getValue();
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            FileInputStream fileInputStream = new FileInputStream(file);

            post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\""
                    + file.getName() + "\"" + lineEnd;
            String mimetype = getMimeType(file.getName());
            post += "Content-Type: " + mimetype + lineEnd;
            post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

            dos.write(post.toString().getBytes("UTF-8"));

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            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);
                inputStreams.add(fileInputStream);
            }

            Log.d("Test", post);
            dos.flush();
            post = "";
        }

        //END THE UPLOAD

        dos.writeBytes(lineEnd);

        dos.writeBytes(twoHyphens + boundary + twoHyphens);
        //            for(FileInputStream inputStream: inputStreams){
        //               inputStream.close();
        //            }
        dos.flush();
        dos.close();
        conn.connect();
        Log.d("upload", "finish flush:" + conn.getResponseCode());
    } catch (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    try {
        String response_data = "";
        inStream = new DataInputStream(conn.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null) {
            response_data += str;
        }
        inStream.close();
        return response_data;
    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
    return null;
}

From source file:com.sfs.whichdoctor.dao.BulkEmailDAOImpl.java

/**
 * Prepare the email message bean./*from   w ww . j a v  a  2  s  . c o  m*/
 *
 * @param bulkEmail the bulk email
 * @param recipient the recipient
 * @param preferences the preferences
 * @param includeWrapper the include wrapper
 * @param embedImage the embed image
 * @return the bulk email bean
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
public final EmailMessageBean prepareEmailMessage(final BulkEmailBean bulkEmail,
        final EmailRecipientBean recipient, final PreferencesBean preferences, final boolean includeWrapper,
        final boolean embedImage) throws WhichDoctorDaoException {

    EmailMessageBean message = new EmailMessageBean();

    BuilderBean loadDetails = new BuilderBean();
    loadDetails.setParameter("EMAIL", true);
    if (StringUtils.isNotBlank(bulkEmail.getEmailClass())) {
        loadDetails.setParameter("EMAIL_CLASS", bulkEmail.getEmailClass());
    }
    if (StringUtils.isNotBlank(bulkEmail.getEmailType())) {
        loadDetails.setParameter("EMAIL_TYPE", bulkEmail.getEmailType());
    }
    loadDetails.setParameter("FINANCIAL_SUMMARY", true);

    PersonBean person = null;
    OrganisationBean org = null;

    if (recipient != null) {
        if (recipient.getPersonGUID() > 0) {
            try {
                loadDetails.setParameter("MEMBERSHIP", true);
                person = this.personDAO.loadGUID(recipient.getPersonGUID(), loadDetails);
                if (person != null && person.getFirstEmailAddress() != null) {
                    message.setTo(person.getFirstEmailAddress().getEmail());
                }
            } catch (WhichDoctorDaoException wde) {
                dataLogger.error("Error loading recipient (person): " + wde.getMessage());
                throw new WhichDoctorDaoException("Error loading recipient (person): " + wde.getMessage());
            }
        }
        if (recipient.getOrganisationGUID() > 0) {
            try {
                org = this.organisationDAO.loadGUID(recipient.getOrganisationGUID(), loadDetails);
                if (org != null && org.getFirstEmailAddress() != null) {
                    message.setTo(org.getFirstEmailAddress().getEmail());
                }
            } catch (WhichDoctorDaoException wde) {
                dataLogger.error("Error loading email recipient organisation: " + wde.getMessage());
                throw new WhichDoctorDaoException(
                        "Error loading recipient " + "(organisation): " + wde.getMessage());
            }
        }
        if (StringUtils.isNotBlank(recipient.getCustomEmailAddress())) {
            message.setTo(recipient.getCustomEmailAddress());
        }
    }

    message.setFrom(bulkEmail.getEmailAddress());
    message.setFromName(bulkEmail.getSenderName());
    message.setPriority(bulkEmail.getPriority());
    message.setHtmlMessage(true);

    // Set the email subject
    message.setSubject(bulkEmail.getSubject());

    message.setMessage(bulkEmail.getHtmlMessage(preferences, includeWrapper, embedImage, person, org,
            this.getEmailFormatters()));

    if (StringUtils.isNotBlank(preferences.getOption("email", "logo"))) {
        // Add the logo as an attachment to this email
        try {
            message.addAttachment("whichdoctorLogo", new URL(preferences.getOption("email", "logo")));
        } catch (MalformedURLException me) {
            dataLogger.error("Error with attachment URL: " + me.getMessage());
        }
    }
    return message;
}

From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    parseInitParameters(config);/* w  ww. ja va2s  .c  o  m*/
    System.setProperty(SYSTEM_SERVLETCONFIG_PROPERTY, repositoryConfig);

    try {
        // get the local embedded repository
        repository = HippoRepositoryFactory.getHippoRepository(storageLocation);
        HippoRepositoryFactory.setDefaultRepository(repository);

        if (startRemoteServer) {
            // the the remote repository
            RepositoryUrl url = new RepositoryUrl(bindingAddress);
            rmiRepository = new ServerServicingAdapterFactory(url)
                    .getRemoteRepository(repository.getRepository());
            System.setProperty("java.rmi.server.useCodebaseOnly", "true");

            // Get or start registry and bind the remote repository
            try {
                registry = LocateRegistry.getRegistry(url.getHost(), url.getPort());
                registry.rebind(url.getName(), rmiRepository); // connection exception
                                                               // happens here
                log.info("Using existing rmi server on " + url.getHost() + ":" + url.getPort());
            } catch (ConnectException e) {
                registry = LocateRegistry.createRegistry(url.getPort());
                registry.rebind(url.getName(), rmiRepository);
                log.info("Started an RMI registry on port " + url.getPort());
                registryIsEmbedded = true;
            }
        }
        repositoryService = HippoServiceRegistry.getService(RepositoryService.class);
        if (repositoryService == null) {
            HippoServiceRegistry.registerService(
                    repositoryService = (RepositoryService) repository.getRepository(),
                    RepositoryService.class);
        }
        repositoryClusterService = HippoServiceRegistry.getService(RepositoryClusterService.class);
        if (repositoryClusterService == null) {
            HippoServiceRegistry.registerService(repositoryClusterService = new RepositoryClusterService() {
                @Override
                public boolean isExternalEvent(final Event event) {
                    if (!(event instanceof JackrabbitEvent)) {
                        throw new IllegalArgumentException("Event is not an instance of JackrabbitEvent");
                    }
                    return ((JackrabbitEvent) event).isExternal();
                }
            }, RepositoryClusterService.class);
        }
    } catch (MalformedURLException ex) {
        log.error("MalformedURLException exception: " + bindingAddress, ex);
        throw new ServletException("RemoteException: " + ex.getMessage());
    } catch (RemoteException ex) {
        log.error("Generic remoting exception: " + bindingAddress, ex);
        throw new ServletException("RemoteException: " + ex.getMessage());
    } catch (RepositoryException ex) {
        log.error("Error while setting up JCR repository: ", ex);
        throw new ServletException("RepositoryException: " + ex.getMessage());
    }

    freeMarkerConfiguration = createFreemarkerConfiguration();
}

From source file:kbSRU.kbSRU.java

public String symantic_query(String query) {
    String st = query.split("\\[")[1].split("\\]")[0];

    String res = "";
    try {/* w  w w  .  j a  v a  2s . c om*/
        res = helpers.getExpand("http://www.kbresearch.nl/tripple.cgi?query=" + helpers.urlEncode(st), log);
    } catch (MalformedURLException e) {
        res = (e.getMessage());
    }
    return (res);

}

From source file:argendata.web.controller.SearchController.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView searchDataHome() {
    ModelAndView mav = new ModelAndView();

    List<FacetPair> respKw = new ArrayList<FacetPair>();
    List<FacetPair> respFormat = new ArrayList<FacetPair>();
    List<FacetPair> respRt = new ArrayList<FacetPair>();

    List<Count> solrKeywords = null;
    List<Count> solrFormats = null;
    List<Count> solrLocations = null;
    try {//  w  w w .j  a va 2  s. com
        solrKeywords = datasetService.getAllIndexKeywords();
        solrFormats = datasetService.getAllIndexFormats();
        solrLocations = datasetService.getIndexAllLocations();
    } catch (MalformedURLException e) {
        logger.error("No se han podido obtener datos del servicio. " + e.getMessage());
        mav.setViewName("redirect:../main/home");
        return mav;
    } catch (SolrServerException e) {
        logger.error("No se han podido obtener datos del servicio. " + e.getMessage());
        mav.setViewName("redirect:../main/home");
        return mav;
    }
    if (solrKeywords != null) {
        for (Count c : solrKeywords) {
            respKw.add(new FacetPair(c.getName(), (int) c.getCount(), null, null));
        }
    }

    if (solrFormats != null) {
        for (Count c : solrFormats) {
            respFormat.add(new FacetPair(c.getName(), (int) c.getCount(), null, null));
        }
    }
    if (solrLocations != null) {
        for (Count c : solrLocations) {
            respRt.add(new FacetPair(c.getName(), (int) c.getCount(), null, null));
        }
    }

    mav.addObject("listKeywords", respKw);
    mav.addObject("listFormats", respFormat);
    mav.addObject("listLocations", respRt);
    return mav;

}

From source file:com.gargoylesoftware.htmlunit.javascript.host.Stylesheet.java

/**
 * Returns the URL of the stylesheet.// w  ww . ja v a2s  . co  m
 * @return the URL of the stylesheet
 */
public String jsxGet_href() {
    final BrowserVersion version = getBrowserVersion();

    if (ownerNode_ != null) {
        final DomNode node = ownerNode_.getDomNodeOrDie();
        if (node instanceof HtmlLink) {
            // <link rel="stylesheet" type="text/css" href="..." />
            final HtmlLink link = (HtmlLink) node;
            final HtmlPage page = (HtmlPage) link.getPage();
            final String href = link.getHrefAttribute();
            if (!version.hasFeature(BrowserVersionFeatures.STYLESHEET_HREF_EXPANDURL)) {
                // Don't expand relative URLs.
                return href;
            }
            // Expand relative URLs.
            try {
                final URL url = page.getFullyQualifiedUrl(href);
                return url.toExternalForm();
            } catch (final MalformedURLException e) {
                // Log the error and fall through to the return values below.
                LOG.warn(e.getMessage(), e);
            }
        }
    }

    // <style type="text/css"> ... </style>
    if (version.hasFeature(BrowserVersionFeatures.STYLESHEET_HREF_STYLE_EMPTY)) {
        return "";
    } else if (version.hasFeature(BrowserVersionFeatures.STYLESHEET_HREF_STYLE_NULL)) {
        return null;
    } else {
        final DomNode node = ownerNode_.getDomNodeOrDie();
        final HtmlPage page = (HtmlPage) node.getPage();
        final URL url = page.getWebResponse().getRequestSettings().getUrl();
        return url.toExternalForm();
    }
}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @param url//  w ww.  j  a va  2  s . c  o  m
 *            the remote Solr URL. A default localhost URL is assumed when null.
 * @param coreNames
 *            the Solr core names for the main collection and the webgraph
 * @param defaultCoreName
 *            the core name of the main collection
 * @param timeout
 *            the connection timeout in milliseconds
 * @param trustSelfSignedOnAuthenticatedServer
 *            when true, self-signed certificates are accepcted for an https
 *            connection to a remote server with authentication credentials
 * @param maxBytesPerReponse
 *            maximum acceptable decompressed size in bytes for a response from
 *            the remote Solr server. Negative value or Long.MAX_VALUE means no
 *            limit.
 * @param concurrentUpdates
 *            when true, the instance will be used for update operations. The
 *            Solr client is adjusted for better performance of multiple
 *            updates.
 * @throws IOException
 *             when a connection could not be opened to the remote Solr instance
 */
public RemoteInstance(final String url, final Collection<String> coreNames, final String defaultCoreName,
        final int timeout, final boolean trustSelfSignedOnAuthenticatedServer, final long maxBytesPerResponse,
        final boolean concurrentUpdates) throws IOException {
    this.timeout = timeout;
    this.concurrentUpdates = concurrentUpdates;
    this.server = new HashMap<String, SolrClient>();
    this.solrurl = url == null ? "http://127.0.0.1:8983/solr/" : url; // that should work for the example configuration of solr 4.x.x
    this.coreNames = coreNames == null ? new ArrayList<String>() : coreNames;
    if (this.coreNames.size() == 0) {
        this.coreNames.add(CollectionSchema.CORE_NAME);
        this.coreNames.add(WebgraphSchema.CORE_NAME);
    }
    this.defaultCoreName = defaultCoreName == null ? CollectionSchema.CORE_NAME : defaultCoreName;
    if (!this.coreNames.contains(this.defaultCoreName))
        this.coreNames.add(this.defaultCoreName);

    // check the url
    if (this.solrurl.endsWith("/")) {
        // this could mean that we have a path without a core name (correct)
        // or that the core name is appended and contains a badly '/' at the end (must be corrected)
        if (this.solrurl.endsWith(this.defaultCoreName + "/")) {
            this.solrurl = this.solrurl.substring(0, this.solrurl.length() - this.defaultCoreName.length() - 1);
        }
    } else {
        // this could mean that we have an url which ends with the core name (must be corrected)
        // or that the url has a mising '/' (must be corrected)
        if (this.solrurl.endsWith(this.defaultCoreName)) {
            this.solrurl = this.solrurl.substring(0, this.solrurl.length() - this.defaultCoreName.length());
        } else {
            this.solrurl = this.solrurl + "/";
        }
    }

    // Make a http client, connect using authentication. An url like
    // http://127.0.0.1:8983/solr/shard0
    // is proper, and contains the core name as last element in the path
    final MultiProtocolURL u;
    try {
        u = new MultiProtocolURL(this.solrurl + this.defaultCoreName);
    } catch (final MalformedURLException e) {
        throw new IOException(e.getMessage());
    }
    String solraccount, solrpw;
    String host = u.getHost();
    final String userinfo = u.getUserInfo();
    if (userinfo == null || userinfo.isEmpty()) {
        solraccount = "";
        solrpw = "";
    } else {
        final int p = userinfo.indexOf(':');
        if (p < 0) {
            solraccount = userinfo;
            solrpw = "";
        } else {
            solraccount = userinfo.substring(0, p);
            solrpw = userinfo.substring(p + 1);
        }
    }
    if (solraccount.length() > 0) {
        this.client = buildCustomHttpClient(timeout, u, solraccount, solrpw, host,
                trustSelfSignedOnAuthenticatedServer, maxBytesPerResponse);
    } else if (u.isHTTPS()) {
        /* Here we must trust self-signed certificates as most peers with SSL enabled use such certificates */
        this.client = buildCustomHttpClient(timeout, u, solraccount, solrpw, host, true, maxBytesPerResponse);
    } else {
        /* Build a http client using the Solr utils as in the HttpSolrClient constructor implementation. 
         * The main difference is that a shared connection manager is used (configured in the buildConnectionManager() function) */
        final ModifiableSolrParams params = new ModifiableSolrParams();
        params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false);
        /* Accept gzip compression of responses to reduce network usage */
        params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true);

        /* Set the maximum time to establish a connection to the remote server */
        params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, this.timeout);
        /* Set the maximum time between data packets reception once a connection has been established */
        params.set(HttpClientUtil.PROP_SO_TIMEOUT, this.timeout);

        this.client = HttpClientUtil.createClient(params, CONNECTION_MANAGER);
        if (this.client instanceof DefaultHttpClient) {
            if (this.client.getParams() != null) {
                /* Set the maximum time to get a connection from the shared connections pool */
                HttpClientParams.setConnectionManagerTimeout(this.client.getParams(), timeout);
            }

            if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) {
                /*
                 * Add in last position the eventual interceptor limiting the response size, so
                 * that this is the decompressed amount of bytes that is considered
                 */
                ((DefaultHttpClient) this.client).addResponseInterceptor(
                        new StrictSizeLimitResponseInterceptor(maxBytesPerResponse),
                        ((DefaultHttpClient) this.client).getResponseInterceptorCount());
            }
        }
    }

    this.defaultServer = getServer(this.defaultCoreName);
    if (this.defaultServer == null)
        throw new IOException("cannot connect to url " + url + " and connect core " + defaultCoreName);
}

From source file:argendata.web.controller.DatasetController.java

private int getResourceLength(PreDataset ds) {
    // String length = null;

    int len = 0;// w ww. java  2s  .c  om

    String format = null;
    if (ds.getDistribution() != null && ds.getFormat() != null) {
        format = ds.getFormat().toLowerCase();
    }

    if (format != null && (format.endsWith("doc") || format.endsWith("docx") || format.endsWith("xls")
            || format.endsWith("xlsx") || format.endsWith("ppt") || format.endsWith("pptx")
            || format.endsWith("pps") || format.endsWith("odt") || format.endsWith("ods")
            || format.endsWith("odp") || format.endsWith("swx") || format.endsWith("sxi")
            || format.endsWith("wpd") || format.endsWith("pdf") || format.endsWith("rtf")
            || format.endsWith("txt") || format.endsWith("csv") || format.endsWith("tsv"))) {

        // me conecto y pido el content-length
        URL url;
        try {
            url = new URL(ds.getAccessURL());
            URLConnection conn = url.openConnection();

            len = conn.getContentLength();

            if (len != -1) {

                Integer l = (len / 1024);
                // length= l.toString()+"KB";
                len = l;
            } else {
                // length = "desconocido";
                len = 0;
            }

        } catch (MalformedURLException e) {
            logger.error("No se pudo obtener los headers del recurso " + ds.getAccessURL());
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error("No se pudo obtener los headers del recurso " + ds.getAccessURL());
            logger.error(e.getMessage(), e);
        }

    } else {
        // length = "-";
        len = 0;
    }

    return len;
}

From source file:org.sventon.appl.Application.java

/**
 * Gets the base URL to use for relative URL:s.
 *
 * @return The base URL or null if property <tt>sventon.baseURL</tt> was not set.
 *//* w w  w.  jav a 2  s  .c om*/
public URL getBaseURL() {
    String baseURL = StringUtils.trimToEmpty(System.getProperty(PROPERTY_KEY_SVENTON_BASE_URL));
    if (!baseURL.isEmpty()) {
        if (!baseURL.endsWith("/")) {
            baseURL = baseURL + "/";
        }
        try {
            return new URL(baseURL);
        } catch (MalformedURLException e) {
            logger.warn("Value of property '" + PROPERTY_KEY_SVENTON_BASE_URL + "' is not a valid URL: "
                    + e.getMessage());
        }
    }
    return null;
}