Example usage for java.net MalformedURLException printStackTrace

List of usage examples for java.net MalformedURLException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.orchestra.portale.profiler.FbProfiler.java

public String testServer() {

    try {//from   w ww .ja  v a 2 s  . c o m

        HttpURLConnection connection = openConnection("/", "GET");
        String json_response = streamToString(connection.getInputStream());
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(json_response);
        JsonObject j_object = (JsonObject) element;
        String msg = j_object.get("msg").getAsString();

        return msg;

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }

    return null;
}

From source file:eu.optimis.mi.gui.server.MonitoringManagerWebServiceImpl.java

public List<MonitoringResource> getMonitoringResources(String level, String id) {
    String xml = new String("");
    String urlString;/*  www.  j  a va 2 s.c  o m*/
    if (level.equals("service")) {
        //urlString = MMANAGER_URL + "QueryResources/group/complete/service/"+ id;
        urlString = MMANAGER_URL + "QueryResources/group/type/service/" + id;
    } else if (level.equals("virtual")) {
        urlString = MMANAGER_URL + "QueryResources/group/complete/virtual/" + id;
    } else if (level.equals("physical")) {
        urlString = MMANAGER_URL + "QueryResources/group/complete/physical/" + id;
    } else if (level.equals("energy")) {
        urlString = MMANAGER_URL + "QueryResources/group/complete/energy/" + id;
    } else {
        return new ArrayList<MonitoringResource>();
    }

    try {

        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/XML");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String li;
        while ((li = br.readLine()) != null) {
            xml = xml.concat(li);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {
        logger.error("cannot get resource by url:" + urlString);
        e.printStackTrace();

    } catch (IOException e) {
        logger.error("IO connection timeout");
        //GWT.log("IO connection timeout");
        e.printStackTrace();

    }

    XmlUtil util = new XmlUtil();
    List<MonitoringResource> list;
    if (xml != null && xml.contains("metric_name")) {
        list = util.getMonitoringRsModel(xml);
    } else {
        list = new ArrayList<MonitoringResource>();
    }
    logger.info("OK calling " + urlString);
    return list;
}

From source file:WebCrawler.java

  public void run() {
  String strURL = "http://www.google.com";
  String strTargetType = "text/html";
  int numberSearched = 0;
  int numberFound = 0;

  if (strURL.length() == 0) {
    System.out.println("ERROR: must enter a starting URL");
    return;// w w w.j  a v  a 2  s .c  o  m
  }

  vectorToSearch = new Vector();
  vectorSearched = new Vector();
  vectorMatches = new Vector();

  vectorToSearch.addElement(strURL);

  while ((vectorToSearch.size() > 0)
      && (Thread.currentThread() == searchThread)) {
    strURL = (String) vectorToSearch.elementAt(0);

    System.out.println("searching " + strURL);

    URL url = null;
    try {
      url = new URL(strURL);
    } catch (MalformedURLException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    vectorToSearch.removeElementAt(0);
    vectorSearched.addElement(strURL);

    try {
      URLConnection urlConnection = url.openConnection();

      urlConnection.setAllowUserInteraction(false);

      InputStream urlStream = url.openStream();
      String type = urlConnection.guessContentTypeFromStream(urlStream);
      if (type == null)
        break;
      if (type.compareTo("text/html") != 0)
        break;

      byte b[] = new byte[5000];
      int numRead = urlStream.read(b);
      String content = new String(b, 0, numRead);
      while (numRead != -1) {
        if (Thread.currentThread() != searchThread)
          break;
        numRead = urlStream.read(b);
        if (numRead != -1) {
          String newContent = new String(b, 0, numRead);
          content += newContent;
        }
      }
      urlStream.close();

      if (Thread.currentThread() != searchThread)
        break;

      String lowerCaseContent = content.toLowerCase();

      int index = 0;
      while ((index = lowerCaseContent.indexOf("<a", index)) != -1) {
        if ((index = lowerCaseContent.indexOf("href", index)) == -1)
          break;
        if ((index = lowerCaseContent.indexOf("=", index)) == -1)
          break;

        if (Thread.currentThread() != searchThread)
          break;

        index++;
        String remaining = content.substring(index);

        StringTokenizer st = new StringTokenizer(remaining, "\t\n\r\">#");
        String strLink = st.nextToken();

        URL urlLink;
        try {
          urlLink = new URL(url, strLink);
          strLink = urlLink.toString();
        } catch (MalformedURLException e) {
          System.out.println("ERROR: bad URL " + strLink);
          continue;
        }

        if (urlLink.getProtocol().compareTo("http") != 0)
          break;

        if (Thread.currentThread() != searchThread)
          break;

        try {
          URLConnection urlLinkConnection = urlLink.openConnection();
          urlLinkConnection.setAllowUserInteraction(false);
          InputStream linkStream = urlLink.openStream();
          String strType = urlLinkConnection
              .guessContentTypeFromStream(linkStream);
          linkStream.close();

          if (strType == null)
            break;
          if (strType.compareTo("text/html") == 0) {
            if ((!vectorSearched.contains(strLink))
                && (!vectorToSearch.contains(strLink))) {

              vectorToSearch.addElement(strLink);
            }
          }

          if (strType.compareTo(strTargetType) == 0) {
            if (vectorMatches.contains(strLink) == false) {
              System.out.println(strLink);
              vectorMatches.addElement(strLink);
              numberFound++;
              if (numberFound >= SEARCH_LIMIT)
                break;
            }
          }
        } catch (IOException e) {
          System.out.println("ERROR: couldn't open URL " + strLink);
          continue;
        }
      }
    } catch (IOException e) {
      System.out.println("ERROR: couldn't open URL " + strURL);
      break;
    }

    numberSearched++;
    if (numberSearched >= SEARCH_LIMIT)
      break;
  }

  if (numberSearched >= SEARCH_LIMIT || numberFound >= SEARCH_LIMIT)
    System.out.println("reached search limit of " + SEARCH_LIMIT);
  else
    System.out.println("done");
  searchThread = null;
}

From source file:com.cxic.ip.WebUrl.java

public ArrayList<String> getData() {
    ArrayList<String> data = new ArrayList<String>();
    String line = null;// w  ww . java 2  s.c o  m
    URL address = null;
    try {
        address = new URL(url);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    URLConnection urlconn = null;

    if (useProxy) {
        SocketAddress addr = new InetSocketAddress(ip, port);
        java.net.Proxy httpProxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, addr);
        try {
            urlconn = address.openConnection(httpProxy);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        try {
            urlconn = address.openConnection();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        urlconn.connect();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        return null;
    }
    BufferedReader buffreader = null;
    try {
        buffreader = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        line = buffreader.readLine();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    while (line != null) {

        data.add(line);

        try {
            line = buffreader.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return data;
}

From source file:com.rastating.droidbeard.net.SickbeardAsyncTask.java

protected Bitmap getBitmap(String cmd, List<Pair<String, Object>> params) {
    Bitmap bitmap = null;/*w  ww .j  ava  2 s .  c  o  m*/
    Preferences preferences = new Preferences(mContext);
    String format = "%sapi/%s/?cmd=%s";

    String uri = String.format(format, preferences.getSickbeardUrl(), preferences.getApiKey(), cmd);
    if (params != null) {
        for (Pair<String, Object> pair : params) {
            uri += "&" + pair.first + "=" + pair.second.toString();
        }
    }

    try {
        HttpClient client = HttpClientManager.INSTANCE.getClient();
        HttpGet request = new HttpGet(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
    } catch (MalformedURLException e) {
        mLastException = new SickBeardException("", e);
        e.printStackTrace();
    } catch (IOException e) {
        mLastException = new SickBeardException("", e);
        e.printStackTrace();
    }

    return bitmap;
}

From source file:de.matzefratze123.heavyspleef.util.Updater.java

public void update(final CommandSender announceTo) {
    if (!updateAvailable) {
        return;//from  www  .  j a v  a 2  s  . co m
    }

    new Thread(new Runnable() {

        @Override
        public void run() {

            URL url;

            try {
                url = new URL(downloadUrl);
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return;
            }

            try {
                URLConnection conn = url.openConnection();

                InputStream in = conn.getInputStream();

                File folder = Bukkit.getServer().getUpdateFolderFile();
                File out = new File(folder, fileName);

                if (!out.exists()) {
                    out.createNewFile();
                }

                FileOutputStream writer = new FileOutputStream(out);

                int read;
                byte[] buffer = new byte[1024];

                long size = conn.getContentLengthLong();
                long downloaded = 0;

                int lastPercentPrinted = 0;

                while ((read = in.read(buffer, 0, 1024)) > 0) {
                    downloaded += read;

                    writer.write(buffer, 0, read);

                    int percent = (int) ((downloaded / (double) size) * 100);
                    if (percent % 10 == 0 && announceTo != null && percent != lastPercentPrinted) {
                        announceTo.sendMessage(ChatColor.GREEN + "Progress: " + percent + "%");
                        lastPercentPrinted = percent;
                    }
                }

                writer.flush();
                writer.close();
                in.close();
                Logger.info("Downloaded " + fileName + " into update-folder " + updateFolder.getAbsolutePath()
                        + "!");

                if (announceTo != null) {
                    announceTo.sendMessage(ChatColor.DARK_GREEN + "Finished! Please " + ChatColor.UNDERLINE
                            + "restart" + ChatColor.DARK_GREEN + " to activate the version.");
                }
            } catch (IOException e) {
                Logger.severe("Error while downloading new version: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }).start();
}

From source file:eu.planets_project.pp.plato.services.action.planets.PlanetsMigrationService.java

/**
 * Performs the preservation action./* w w w  .  j  a v a2s .c  o  m*/
 * 
 * For Planets migration services url in {@link PreservationActionDefinition} carries the wsdl location of the migration service. 
 */
public boolean perform(PreservationActionDefinition action, SampleObject sampleObject)
        throws PlatoServiceException {

    URL wsdlLocation;
    try {
        wsdlLocation = new URL(action.getUrl());
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
        return false;
    }

    Service service = null;
    try {
        service = Service.create(wsdlLocation, Migrate.QNAME);
    } catch (WebServiceException e) {
        throw new PlatoServiceException("Error creating web service.", e);
    }

    Migrate m = (Migrate) service.getPort(Migrate.class);

    // create digital object that contains our sample object
    DigitalObject dob = new DigitalObject.Builder(Content.byValue(sampleObject.getData().getData()))
            .title("data").build();

    FormatRegistry formatRegistry = FormatRegistryFactory.getFormatRegistry();

    // create Planets URI from extension
    URI sourceFormat = formatRegistry.createExtensionUri(sampleObject.getFormatInfo().getDefaultExtension());

    URI targetFormat;
    try {
        targetFormat = new URI(action.getTargetFormat());
    } catch (URISyntaxException e) {
        throw new PlatoServiceException("Error in target format.", e);
    }

    List<Parameter> serviceParams = getParameters(action.getParamByName("settings"));

    if (serviceParams.size() <= 0) {
        serviceParams = null;
    }

    // perform migration
    MigrateResult result = m.migrate(dob, sourceFormat, targetFormat, serviceParams);

    MigrationResult migrationResult = new MigrationResult();
    migrationResult.setSuccessful((result != null) && (result.getDigitalObject() != null));

    if (migrationResult.isSuccessful()) {
        migrationResult.setReport(String.format("Service %s successfully migrated object.", wsdlLocation));
    } else {
        migrationResult.setReport(String.format(
                "Service %s failed migrating object. " + ((result == null) ? "" : result.getReport()),
                wsdlLocation));
        lastResult = migrationResult;
        return true;
    }

    InputStream in = result.getDigitalObject().getContent().getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    byte[] b = new byte[1024];

    try {
        while ((in.read(b)) != -1) {
            out.write(b);
        }
    } catch (IOException e) {
        throw new PlatoServiceException("Unable to read result data from service response.", e);
    }

    migrationResult.getMigratedObject().getData().setData(out.toByteArray());

    String fullName = sampleObject.getFullname();

    String ext;
    try {
        ext = formatRegistry.getFirstExtension(new URI(action.getTargetFormat()));
    } catch (URISyntaxException e) {
        ext = "";
    }

    // if we find an extension, cut if off ...
    if (fullName.lastIndexOf('.') > 0) {
        fullName = fullName.substring(0, fullName.lastIndexOf('.'));
    }

    // ... so we can append the new one.
    if (!"".equals(ext)) {
        fullName += ("." + ext);
    }

    migrationResult.getMigratedObject().setFullname(fullName);

    lastResult = migrationResult;

    return true;
}

From source file:net.refractions.udig.catalog.internal.shp.ShpGeoResourceImpl.java

/**
 * This transforms all external graphics references that are relative to absolute.
 * This is a workaround to be able to visualize png and svg in relative mode, which 
 * doesn't work right now in geotools. See: http://jira.codehaus.org/browse/GEOT-3235
 * /*from  w  w w .j a  v a 2 s . c  o  m*/
 * This will not be necessary any more as soon as the geotools bug is fixed.
 * 
 * @param relatedFile the related shapefile.
 * @param style the style to check.
 */
private void makeGraphicsAbsolute(File relatedFile, Style style) {
    File parentFolder = relatedFile.getParentFile();
    Rule[] rules = SLDs.rules(style);
    for (Rule rule : rules) {
        Symbolizer[] onlineResource = rule.getSymbolizers();

        for (Symbolizer symbolizer : onlineResource) {
            if (symbolizer instanceof PointSymbolizer) {
                PointSymbolizer pointSymbolizer = (PointSymbolizer) symbolizer;
                Graphic graphic = SLDs.graphic(pointSymbolizer);
                List<GraphicalSymbol> graphicalSymbols = graphic.graphicalSymbols();
                for (GraphicalSymbol graphicalSymbol : graphicalSymbols) {
                    if (graphicalSymbol instanceof ExternalGraphic) {
                        ExternalGraphic externalGraphic = (ExternalGraphic) graphicalSymbol;
                        try {
                            URL location = externalGraphic.getLocation();
                            File urlToFile = URLUtils.urlToFile(location);
                            if (urlToFile != null && !urlToFile.exists()) {
                                File newFile = new File(parentFolder, urlToFile.getPath());
                                if (newFile.exists()) {
                                    externalGraphic.setLocation(newFile.toURI().toURL());
                                }
                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

From source file:com.swdouglass.joid.server.OpenIdServlet.java

private void returnError(String query, HttpServletResponse response) throws ServletException, IOException {
    Map map = MessageFactory.parseQuery(query);
    String returnTo = (String) map.get("openid.return_to");
    boolean goodReturnTo = false;
    try {/*from  w  w w  .j  a  v a2s .c  om*/
        URL url = new URL(returnTo);
        goodReturnTo = true;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    if (goodReturnTo) {
        String s = "?openid.ns:http://specs.openid.net/auth/2.0"
                + "&openid.mode=error&openid.error=BAD_REQUEST";
        s = response.encodeRedirectURL(returnTo + s);
        response.sendRedirect(s);
    } else {
        PrintWriter out = response.getWriter();
        // response.setContentLength() seems to be broken,
        // so set the header manually
        String s = "ns:http://specs.openid.net/auth/2.0\n" + "&mode:error" + "&error:BAD_REQUEST\n";
        int len = s.length();
        response.setHeader("Content-Length", Integer.toString(len));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.print(s);
        out.flush();
    }
}

From source file:com.orchestra.portale.profiler.FbProfiler.java

public String basicProfile() {

    if (access_token == null) {
        return null;
    }//from w  ww. j a  va  2 s  .co  m

    try {

        HttpURLConnection connection = openConnection("/mom_profile", "GET");

        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", access_token);
        connection = addParameter(connection, params);

        String json_response = streamToString(connection.getInputStream());
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(json_response);
        JsonObject j_object = (JsonObject) element;
        JsonObject msg = (JsonObject) j_object.get("msg");

        return msg.toString();

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }

    return null;
}