Java Code Examples for java.net.URLConnection

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project android-xbmcremote, under directory /src/org/xbmc/httpapi/.

Source file: Connection.java

  20 
vote

/** 
 * Create a new URLConnection with the request headers set, including authentication.
 * @param url The request url
 * @return URLConnection
 * @throws IOException
 */
private URLConnection getUrlConnection(URL url) throws IOException {
  final URLConnection uc=url.openConnection();
  uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT);
  uc.setReadTimeout(mSocketReadTimeout);
  uc.setRequestProperty("Connection","close");
  if (authEncoded != null) {
    uc.setRequestProperty("Authorization","Basic " + authEncoded);
  }
  return uc;
}
 

Example 2

From project addis, under directory /application/src/main/java/org/drugis/addis/.

Source file: AppInfo.java

  19 
vote

public String call(){
  URL updateWebService;
  try {
    updateWebService=new URL("http://drugis.org/service/currentVersion");
    URLConnection conn=updateWebService.openConnection();
    String line=new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
    return new StringTokenizer(line).nextToken();
  }
 catch (  Exception e) {
    System.err.println("Warning: Couldn't check for new versions. Connection issue?");
  }
  return null;
}
 

Example 3

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/net/.

Source file: HttpClient.java

  19 
vote

/** 
 * Get a byte array version of the target URL.
 * @param url The URL to fetch.
 * @return The results of the URL, if possible, or null.
 * @throws IOException If the file could not be fetched.
 */
public static byte[] getBytes(final String url) throws IOException {
  try {
    final URL ur=new URL(url);
    URLConnection conn;
    conn=ur.openConnection();
    return StreamUtils.toByteArray(conn.getInputStream());
  }
 catch (  final MalformedURLException e) {
    return null;
  }
}
 

Example 4

From project akubra, under directory /akubra-www/src/main/java/org/akubraproject/www/.

Source file: WWWBlob.java

  19 
vote

@Override public OutputStream openOutputStream(long estimatedSize,boolean overwrite) throws IOException {
  if (!overwrite && exists())   throw new DuplicateBlobException(id);
  URLConnection con=connect(false,false);
  OutputStream os=streamManager.manageOutputStream(owner,con.getOutputStream());
  exists=true;
  return os;
}
 

Example 5

From project android_external_tagsoup, under directory /src/org/ccil/cowan/tagsoup/.

Source file: Parser.java

  19 
vote

private InputStream getInputStream(String publicid,String systemid) throws IOException, SAXException {
  URL basis=new URL("file","",System.getProperty("user.dir") + "/.");
  URL url=new URL(basis,systemid);
  URLConnection c=url.openConnection();
  return c.getInputStream();
}
 

Example 6

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: URLUtils.java

  19 
vote

/** 
 * Verifies if the specified URL is reachable online.
 * @param url input URL.
 * @return <code>true</code> if the resource can be accessed, <code>false</code> otherwise.
 * @throws MalformedURLException if <code>url</code> is malformed.
 */
public static boolean isOnline(String url) throws MalformedURLException {
  try {
    final URLConnection connection=new URL(url).openConnection();
    connection.getInputStream().close();
    return true;
  }
 catch (  IOException ioe) {
    if (ioe instanceof MalformedURLException) {
      throw (MalformedURLException)ioe;
    }
    return false;
  }
}
 

Example 7

From project amber, under directory /oauth-2.0/integration-tests/src/test/java/org/apache/amber/oauth2/integration/.

Source file: ResourceTest.java

  18 
vote

@Test public void testResourceAccessBodyNoToken() throws Exception {
  URL url=new URL(Common.RESOURCE_SERVER + Common.PROTECTED_RESOURCE_BODY);
  URLConnection c=url.openConnection();
  if (c instanceof HttpURLConnection) {
    HttpURLConnection httpURLConnection=(HttpURLConnection)c;
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setAllowUserInteraction(false);
    httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    testNoTokenResponse(httpURLConnection);
  }
}
 

Example 8

From project anadix, under directory /anadix-api/src/main/java/org/anadix/factories/.

Source file: URLSource.java

  18 
vote

/** 
 * Constructor
 * @param url - URL to get the source from
 * @throws org.anadix.exceptions.SourceException if the stream to URL can't be opened
 */
public URLSource(URL url) throws SourceException {
  super(url.toExternalForm());
  this.url=url;
  try {
    URLConnection c=url.openConnection();
    c.setConnectTimeout(1000);
    c.connect();
  }
 catch (  IOException ex) {
    logger.error("Unable to open stream",ex);
    throw new SourceException("Unable to open stream " + url,ex);
  }
}
 

Example 9

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: DownloadTask.java

  18 
vote

@NotNull private URLConnection getConnection() throws IOException {
  URLConnection c=connection;
  if (c == null) {
    c=source.openConnection();
    if (!user.isEmpty() || !password.isEmpty()) {
      String encoding=StringUtils.encodeBase64((user + ":" + password).getBytes());
      c.setRequestProperty("Authorization","Basic " + encoding);
    }
    connection=c;
  }
  return c;
}
 

Example 10

From project arquillian-container-glassfish, under directory /glassfish-managed-3.1/src/test/java/org/jboss/arquillian/container/glassfish/managed_3_1/.

Source file: GlassFishManagedDeployEarTest.java

  18 
vote

@Test public void shouldBeAbleToDeployEnterpriseArchive() throws Exception {
  final String servletPath=GreeterServlet.class.getAnnotation(WebServlet.class).urlPatterns()[0];
  final URLConnection response=new URL(deploymentUrl.toString() + servletPath.substring(1)).openConnection();
  BufferedReader in=new BufferedReader(new InputStreamReader(response.getInputStream()));
  final String result=in.readLine();
  assertThat(result,equalTo("Hello"));
}
 

Example 11

From project arquillian_deprecated, under directory /containers/glassfish-remote-3.1/src/test/java/org/jboss/arquillian/container/glassfish/remote_3_1/.

Source file: GlassFishRestDeployEarTest.java

  18 
vote

@Test public void shouldBeAbleToDeployEnterpriseArchive() throws Exception {
  final String servletPath=GreeterServlet.class.getAnnotation(WebServlet.class).urlPatterns()[0];
  final URLConnection response=new URL("http://localhost:8080/test" + servletPath).openConnection();
  BufferedReader in=new BufferedReader(new InputStreamReader(response.getInputStream()));
  final String result=in.readLine();
  assertThat(result,equalTo("Hello"));
}
 

Example 12

From project BBC-News-Reader, under directory /src/com/digitallizard/bbcnewsreader/resource/web/.

Source file: HtmlParser.java

  18 
vote

/** 
 * @param args
 * @throws IOException
 * @throws ClientProtocolException
 */
public static byte[] getPage(String stringUrl) throws Exception {
  URL url=new URL(stringUrl);
  URLConnection connection=url.openConnection();
  System.setProperty("http.agent","");
  connection.setRequestProperty("User-Agent",USER_AGENT);
  InputStream stream=connection.getInputStream();
  BufferedInputStream inputbuffer=new BufferedInputStream(stream);
  ByteArrayBuffer arraybuffer=new ByteArrayBuffer(50);
  int current=0;
  while ((current=inputbuffer.read()) != -1) {
    arraybuffer.append((byte)current);
  }
  return arraybuffer.toByteArray();
}
 

Example 13

From project brix-cms, under directory /brix-demo/src/main/java/org/brixcms/demo/web/tile/stockquote/.

Source file: StockQuoteRequest.java

  18 
vote

/** 
 * Sets up the HTTP connection.
 * @param url    the url to connect to
 * @param length the length to the input message
 * @return the HttpurLConnection
 * @throws IOException
 * @throws ProtocolException
 */
private HttpURLConnection setUpHttpConnection(URL url,int length) throws IOException, ProtocolException {
  URLConnection connection=url.openConnection();
  HttpURLConnection httpConn=(HttpURLConnection)connection;
  httpConn.setRequestProperty("Content-Length",String.valueOf(length));
  httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
  httpConn.setRequestProperty("SOAPAction","\"http://www.webserviceX.NET/GetQuote\"");
  httpConn.setRequestMethod("POST");
  httpConn.setDoOutput(true);
  httpConn.setDoInput(true);
  return httpConn;
}
 

Example 14

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/web/.

Source file: MultiPartFormOutputStream.java

  18 
vote

/** 
 * Creates a new <code>java.net.URLConnection</code> object from the specified <code>java.net.URL</code>. This is a convenience method which will set the <code>doInput</code>, <code>doOutput</code>, <code>useCaches</code> and <code>defaultUseCaches</code> fields to the appropriate settings in the correct order.
 * @return a <code>java.net.URLConnection</code> object for the URL
 * @throws java.io.IOException on input/output errors
 */
public static URLConnection createConnection(URL url) throws IOException {
  URLConnection urlConn=url.openConnection();
  if (urlConn instanceof HttpURLConnection) {
    HttpURLConnection httpConn=(HttpURLConnection)urlConn;
    httpConn.setRequestMethod("POST");
  }
  urlConn.setDoInput(true);
  urlConn.setDoOutput(true);
  urlConn.setUseCaches(false);
  urlConn.setDefaultUseCaches(false);
  return urlConn;
}
 

Example 15

From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/runtime/internal/.

Source file: ModuleReader.java

  18 
vote

public ModuleImpl readFromManifest(URL manifestUrl,ProxyConfig proxyConfig) throws CoreException {
  try {
    final URLConnection urlConnection=UrlHelper.openConnection(manifestUrl,proxyConfig,"GET");
    final InputStream stream=urlConnection.getInputStream();
    return new ModuleManifestParser().parse(stream);
  }
 catch (  IOException e) {
    throw new CoreException("Failed to read module manifest from [" + manifestUrl + "]",e);
  }
}
 

Example 16

From project chililog-server, under directory /src/test/java/org/chililog/server/workbench/.

Source file: WorkbenchServiceTest.java

  18 
vote

/** 
 * Check if we redirect to index.html successfully
 * @throws IOException
 */
@Test() public void testRedirectToIndexHtml() throws IOException {
  URL url=new URL("http://localhost:8989/workbench");
  URLConnection conn=url.openConnection();
  HashMap<String,String> headers=new HashMap<String,String>();
  String responseCode=ApiUtils.getResponseHeaders(conn,headers);
  assertEquals("HTTP/1.1 200 OK",responseCode);
  url=new URL("http://localhost:8989/workbench/");
  conn=url.openConnection();
  headers=new HashMap<String,String>();
  responseCode=ApiUtils.getResponseHeaders(conn,headers);
  assertEquals("HTTP/1.1 200 OK",responseCode);
}
 

Example 17

From project commons-io, under directory /src/main/java/org/apache/commons/io/.

Source file: FileUtils.java

  18 
vote

/** 
 * Copies bytes from the URL <code>source</code> to a file <code>destination</code>. The directories up to <code>destination</code> will be created if they don't already exist. <code>destination</code> will be overwritten if it already exists.
 * @param source  the <code>URL</code> to copy bytes from, must not be {@code null}
 * @param destination  the non-directory <code>File</code> to write bytes to(possibly overwriting), must not be  {@code null}
 * @param connectionTimeout the number of milliseconds until this methodwill timeout if no connection could be established to the <code>source</code>
 * @param readTimeout the number of milliseconds until this method willtimeout if no data could be read from the <code>source</code> 
 * @throws IOException if <code>source</code> URL cannot be opened
 * @throws IOException if <code>destination</code> is a directory
 * @throws IOException if <code>destination</code> cannot be written
 * @throws IOException if <code>destination</code> needs creating but can't be
 * @throws IOException if an IO error occurs during copying
 * @since 2.0
 */
public static void copyURLToFile(URL source,File destination,int connectionTimeout,int readTimeout) throws IOException {
  URLConnection connection=source.openConnection();
  connection.setConnectTimeout(connectionTimeout);
  connection.setReadTimeout(readTimeout);
  InputStream input=connection.getInputStream();
  copyInputStreamToFile(input,destination);
}
 

Example 18

From project cp-common-utils, under directory /src/com/clarkparsia/common/util/.

Source file: ClassPath.java

  18 
vote

/** 
 * Returns the list of classes at the specified jar URL
 * @param theURL the jar URL
 * @return returns the list of classes at the jar location, or an empty collection if there are no classes, it's nota Jar URL or the URL cannot be opened.
 */
public static Collection<? extends Class> listClassesFromJar(URL theURL){
  try {
    URLConnection aConn=theURL.openConnection();
    if (!(aConn instanceof JarURLConnection)) {
      return new HashSet<Class>();
    }
    JarURLConnection aJarConn=(JarURLConnection)aConn;
    return listClassesFromJarFile(aJarConn.getJarFile());
  }
 catch (  IOException e) {
    return new HashSet<Class>();
  }
}
 

Example 19

From project Custom-Salem, under directory /src/haven/.

Source file: JarSignersHardLinker.java

  18 
vote

/** 
 * get the jarFile object for the given url
 * @param jarUrl
 * @return
 * @throws IOException
 */
public static JarFile getJarFile(URL jarUrl) throws IOException {
  URLConnection urlConnnection=jarUrl.openConnection();
  if (urlConnnection instanceof JarURLConnection) {
    JarURLConnection jcon=(JarURLConnection)urlConnnection;
    return jcon.getJarFile();
  }
 else {
    throw new AssertionError("Expected JarURLConnection");
  }
}
 

Example 20

From project dolphin, under directory /dolphinmaple/test/.

Source file: Demo.java

  18 
vote

/** 
 * @param args
 */
public static void main(String[] args) throws Throwable {
  String address="ftp://10.30.1.168/ITS/%B3%A3%D3%C3%CF%C2%D4%D8/Office%20Professional%20Plus%202007_cn.7z";
  URL url=new URL(address);
  URLConnection conn=url.openConnection();
  int length=conn.getContentLength();
  System.out.println(length);
  FtpClient client=new FtpClient();
  client.openServer("10.81.34.230",21);
  client.login("admin","admin");
  int response=client.readServerResponse();
  System.out.println(response);
}
 

Example 21

From project Eclipse, under directory /com.mobilesorcery.sdk.html5/src/com/mobilesorcery/sdk/html5/live/.

Source file: ReloadManager.java

  18 
vote

public void reload(IProject projectToReload) throws IOException {
  URL reloadServerURL=new URL("http","localhost",8282,"/" + projectToReload.getName() + "/LocalFiles.html");
  URLConnection connection=reloadServerURL.openConnection();
  connection.connect();
  connection.getInputStream().close();
}
 

Example 22

From project elw, under directory /datapath-gui/src/main/java/elw/dp/app/.

Source file: RunnableLoadTask.java

  18 
vote

private URLConnection setupGet(URL url) throws IOException {
  URLConnection uc=url.openConnection();
  uc.setRequestProperty("Cookie",setup.getUploadHeader());
  uc.setAllowUserInteraction(false);
  uc.setUseCaches(false);
  if (uc instanceof HttpURLConnection) {
    ((HttpURLConnection)uc).setInstanceFollowRedirects(false);
  }
  if (uc instanceof HttpsURLConnection) {
    ((HttpsURLConnection)uc).setInstanceFollowRedirects(false);
  }
  return uc;
}
 

Example 23

From project encog-java-core, under directory /src/main/java/org/encog/bot/browse/.

Source file: Browser.java

  18 
vote

/** 
 * Navigate to a page based on a URL object. This will be an HTTP GET operation.
 * @param url The URL to navigate to.
 */
public final void navigate(final URL url){
  try {
    EncogLogging.log(EncogLogging.LEVEL_INFO,"Navigating to page:" + url);
    final URLConnection connection=url.openConnection();
    final InputStream is=connection.getInputStream();
    navigate(url,is);
    is.close();
  }
 catch (  final IOException e) {
    EncogLogging.log(EncogLogging.LEVEL_ERROR,e);
    throw new BrowseError(e);
  }
}
 

Example 24

From project Gemini-Blueprint, under directory /io/src/main/java/org/eclipse/gemini/blueprint/io/.

Source file: OsgiBundleResource.java

  18 
vote

public long lastModified() throws IOException {
  URLConnection con=getURL().openConnection();
  con.setUseCaches(false);
  long time=con.getLastModified();
  if (time == 0) {
    if (OsgiResourceUtils.PREFIX_TYPE_BUNDLE_JAR == searchType)     return bundle.getLastModified();
  }
  return time;
}
 

Example 25

From project gemini.web.gemini-web-container, under directory /org.eclipse.gemini.web.tomcat/src/main/java/org/eclipse/gemini/web/tomcat/internal/.

Source file: BundleDependenciesJarScanner.java

  18 
vote

private void scanBundleUrl(URL url,JarScannerCallback callback){
  try {
    URLConnection connection=url.openConnection();
    if (connection instanceof JarURLConnection) {
      callback.scan((JarURLConnection)connection);
    }
  }
 catch (  IOException e) {
    LOGGER.warn("Failure when attempting to scan bundle via jar URL '" + url + "'.",e);
  }
}
 

Example 26

From project generic-store-for-android, under directory /src/com/wareninja/opensource/common/.

Source file: HttpUtils.java

  18 
vote

/** 
 * Open an URL connection. If HTTPS, accepts any certificate even if not valid, and connects to any host name.
 * @param url The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static URLConnection getConnection(URL url) throws IOException, NoSuchAlgorithmException, KeyManagementException {
  URLConnection conn=url.openConnection();
  if (conn instanceof HttpsURLConnection) {
    SSLContext context=SSLContext.getInstance("TLS");
    context.init(new KeyManager[0],TRUST_MANAGER,new SecureRandom());
    SSLSocketFactory socketFactory=context.getSocketFactory();
    ((HttpsURLConnection)conn).setSSLSocketFactory(socketFactory);
    ((HttpsURLConnection)conn).setHostnameVerifier(HOSTNAME_VERIFIER);
  }
  conn.setConnectTimeout(SOCKET_TIMEOUT);
  conn.setReadTimeout(SOCKET_TIMEOUT);
  return conn;
}
 

Example 27

From project gitblit, under directory /src/com/gitblit/utils/.

Source file: ConnectionUtils.java

  18 
vote

public static URLConnection openConnection(String url,String username,char[] password) throws IOException {
  URL urlObject=new URL(url);
  URLConnection conn=urlObject.openConnection();
  setAuthorization(conn,username,password);
  conn.setUseCaches(false);
  conn.setDoOutput(true);
  if (conn instanceof HttpsURLConnection) {
    HttpsURLConnection secureConn=(HttpsURLConnection)conn;
    secureConn.setSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
    secureConn.setHostnameVerifier(HOSTNAME_VERIFIER);
  }
  return conn;
}
 

Example 28

From project agile, under directory /agile-core/src/main/java/org/headsupdev/agile/core/notifiers/.

Source file: TwitterNotifier.java

  17 
vote

public void eventAdded(Event event){
  Project project=event.getProject();
  if (project == null) {
    project=StoredProject.getDefault();
  }
  String text="[" + Manager.getStorageInstance().getGlobalConfiguration().getProductName() + "] "+ event.getTitle()+ " ("+ project.getAlias()+ ")";
  OutputStreamWriter out=null;
  BufferedReader in=null;
  try {
    String data="status=" + URLEncoder.encode(text,"UTF-8");
    URL set=new URL("http://twitter.com/statuses/update.xml");
    URLConnection conn=set.openConnection();
    String auth="Basic " + new String(Base64.encodeBase64((getUsername() + ":" + getPassword()).getBytes()));
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Authorization",auth);
    conn.setAllowUserInteraction(false);
    out=new OutputStreamWriter(conn.getOutputStream());
    out.write(data);
    out.flush();
    in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while (in.readLine() != null) {
    }
  }
 catch (  IOException e) {
    Manager.getLogger(getClass().getName()).error("Error sending twitter notification",e);
  }
 finally {
    if (in != null) {
      IOUtil.close(in);
    }
    if (out != null) {
      IOUtil.close(out);
    }
  }
}
 

Example 29

From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.

Source file: DownloadableLessonList.java

  17 
vote

public void run(){
  try {
    URL url=new URL("http://secretsockssoftware.com/androidflashcards/lessons/lesson_list.xml");
    URLConnection conn=url.openConnection();
    XMLReader xr=XMLReaderFactory.createXMLReader();
    LessonXMLParser lxp=new LessonXMLParser();
    xr.setContentHandler(lxp);
    xr.setErrorHandler(lxp);
    xr.parse(new InputSource(conn.getInputStream()));
    handler.sendMessage(handler.obtainMessage(0,lxp.getLessons()));
  }
 catch (  Exception e) {
    e.printStackTrace();
    handler.sendMessage(handler.obtainMessage(1,e.getMessage()));
  }
}
 

Example 30

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: UriTexture.java

  17 
vote

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,ClientConnectionManager connectionManager){
  InputStream contentInput=null;
  if (connectionManager == null) {
    try {
      URL url=new URI(uri).toURL();
      URLConnection conn=url.openConnection();
      conn.connect();
      contentInput=conn.getInputStream();
    }
 catch (    Exception e) {
      Log.w(TAG,"Request failed: " + uri);
      e.printStackTrace();
      return null;
    }
  }
 else {
    final DefaultHttpClient mHttpClient=new DefaultHttpClient(connectionManager,HTTP_PARAMS);
    HttpUriRequest request=new HttpGet(uri);
    HttpResponse httpResponse=null;
    try {
      httpResponse=mHttpClient.execute(request);
      HttpEntity entity=httpResponse.getEntity();
      if (entity != null) {
        contentInput=entity.getContent();
      }
    }
 catch (    Exception e) {
      Log.w(TAG,"Request failed: " + request.getURI());
      return null;
    }
  }
  if (contentInput != null) {
    return new BufferedInputStream(contentInput,4096);
  }
 else {
    return null;
  }
}
 

Example 31

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: PostReporter.java

  17 
vote

/** 
 * Executes the given request as a HTTP POST action.
 * @param url the url
 * @param params the parameter
 * @return the response as a String.
 * @throws IOException if the server cannot be reached
 */
public static void post(URL url,String params) throws IOException {
  URLConnection conn=url.openConnection();
  if (conn instanceof HttpURLConnection) {
    ((HttpURLConnection)conn).setRequestMethod("POST");
    conn.setRequestProperty("Content-Type","application/json");
  }
  OutputStreamWriter writer=null;
  try {
    conn.setDoOutput(true);
    writer=new OutputStreamWriter(conn.getOutputStream(),Charset.forName("UTF-8"));
    writer.write(params);
    writer.flush();
  }
  finally {
    if (writer != null) {
      writer.close();
    }
  }
}
 

Example 32

From project AntiCheat, under directory /src/main/java/net/h31ix/anticheat/update/.

Source file: Updater.java

  17 
vote

/** 
 * Obtain the direct download file url from the file's page.
 */
private String getFile(String link){
  String download=null;
  try {
    URL url=new URL(link);
    URLConnection urlConn=url.openConnection();
    InputStreamReader inStream=new InputStreamReader(urlConn.getInputStream());
    BufferedReader buff=new BufferedReader(inStream);
    int counter=0;
    String line;
    while ((line=buff.readLine()) != null) {
      counter++;
      if (line.contains("<li class=\"user-action user-action-download\">")) {
        download=line.split("<a href=\"")[1].split("\">Download</a>")[0];
      }
 else       if (line.contains("<dt>Size</dt>")) {
        sizeLine=counter + 1;
      }
 else       if (counter == sizeLine) {
        String size=line.replaceAll("<dd>","").replaceAll("</dd>","");
        multiplier=size.contains("MiB") ? 1048576 : 1024;
        size=size.replace(" KiB","").replace(" MiB","");
        totalSize=(long)(Double.parseDouble(size) * multiplier);
      }
    }
    urlConn=null;
    inStream=null;
    buff.close();
    buff=null;
  }
 catch (  Exception ex) {
    ex.printStackTrace();
    plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
    result=Updater.UpdateResult.FAIL_DBO;
    return null;
  }
  return download;
}
 

Example 33

From project apps-for-android, under directory /CLiCkin2DaBeaT/src/com/google/clickin2dabeat/.

Source file: Unzipper.java

  17 
vote

public static String download(String fileUrl){
  URLConnection cn;
  try {
    fileUrl=(new URL(new URL(fileUrl),fileUrl)).toString();
    URL url=new URL(fileUrl);
    cn=url.openConnection();
    cn.connect();
    InputStream stream=cn.getInputStream();
    File outputDir=new File("/sdcard/c2b/");
    outputDir.mkdirs();
    String filename=fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    filename=filename.substring(0,filename.indexOf("c2b.zip") + 7);
    File outputFile=new File("/sdcard/c2b/",filename);
    outputFile.createNewFile();
    FileOutputStream out=new FileOutputStream(outputFile);
    byte buf[]=new byte[16384];
    do {
      int numread=stream.read(buf);
      if (numread <= 0) {
        break;
      }
 else {
        out.write(buf,0,numread);
      }
    }
 while (true);
    stream.close();
    out.close();
    return "/sdcard/c2b/" + filename;
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
    return "";
  }
catch (  IOException e) {
    e.printStackTrace();
    return "";
  }
}
 

Example 34

From project arquillian-container-openshift, under directory /openshift-express/src/main/java/org/jboss/arquillian/container/openshift/express/.

Source file: OpenShiftExpressContainer.java

  17 
vote

private boolean isUrlPresent(String url){
  HttpURLConnection httpConnection=null;
  try {
    URLConnection connection=new URL(url).openConnection();
    if (!(connection instanceof HttpURLConnection)) {
      throw new IllegalStateException("Not an http connection! " + connection);
    }
    httpConnection=(HttpURLConnection)connection;
    httpConnection.setUseCaches(false);
    httpConnection.setDefaultUseCaches(false);
    httpConnection.setDoInput(true);
    httpConnection.setRequestMethod("GET");
    httpConnection.setDoOutput(false);
    httpConnection.connect();
    httpConnection.getResponseCode();
    if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      return true;
    }
    return false;
  }
 catch (  IOException e) {
    e.printStackTrace();
    return false;
  }
 finally {
    if (httpConnection != null) {
      httpConnection.disconnect();
    }
  }
}
 

Example 35

From project arquillian-container-tomcat, under directory /tomcat-common/src/main/java/org/jboss/arquillian/container/tomcat/.

Source file: CommonTomcatManager.java

  17 
vote

public void deploy(String name,URL content) throws IOException, DeploymentException {
  final String contentType="application/octet-stream";
  Validate.notNullOrEmpty(name,"Name must not be null or empty");
  Validate.notNull(content,"Content to be deployed must not be null");
  URLConnection conn=content.openConnection();
  int contentLength=conn.getContentLength();
  InputStream stream=new BufferedInputStream(conn.getInputStream());
  StringBuilder command=new StringBuilder(getDeployCommand());
  try {
    command.append(URLEncoder.encode(name,configuration.getUrlCharset()));
  }
 catch (  UnsupportedEncodingException e) {
    throw new DeploymentException("Unable to construct path for Tomcat manager",e);
  }
  execute(command.toString(),stream,contentType,contentLength);
}
 

Example 36

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-impl/src/main/java/org/jboss/arquillian/ajocado/utils/.

Source file: URLUtils.java

  17 
vote

/** 
 * Gets a MD5 digest of some resource obtains as input stream from connection to URL given by URL string.
 * @param url of the resource
 * @return MD5 message digest of resource
 * @throws IOException when connection to URL fails
 */
public static String resourceMd5Digest(String url) throws IOException {
  URLConnection connection=new URL(url).openConnection();
  InputStream in=connection.getInputStream();
  MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new IllegalStateException("MD5 hashing is unsupported",ex);
  }
  byte[] buffer=new byte[MD5_BUFFER_SIZE];
  int read=0;
  while ((read=in.read(buffer)) > 0) {
    digest.update(buffer,0,read);
  }
  byte[] md5sum=digest.digest();
  BigInteger bigInt=new BigInteger(1,md5sum);
  return bigInt.toString(HEX_RADIX);
}
 

Example 37

From project AuthDB, under directory /src/main/java/com/craftfire/util/managers/.

Source file: CraftFireManager.java

  17 
vote

public void postInfo(String b407f35cb00b96936a585c4191fc267a,String f13a437cb9b1ac68b49d597ed7c4bfde,String cafd6e81e3a478a7fe0b40e7502bf1f,String fcf2204d0935f0a8ef1853662b91834e,String aa25d685b171d7874222c7080845932,String fac8b1115d09f0d816a0671d144d49e,String e98695d728198605323bb829d6ea4de,String d89570db744fe029ca696f09d34e1,String fe75a95090e70155856937ae8d0482,String a6118cfc6befa19cada1cddc32d36a3,String d440b827e9c17bbd51f2b9ac5c97d6,String c284debb7991b2b5fcfd08e9ab1e5,int d146298d6d3e1294bbe4121f26f02800) throws IOException {
  String d68d8f3c6398544b1cdbeb4e5f39f0="1265a15461038989925e0ced2799762c";
  String e5544ab05d8c25c1a5da5cd59144fb=Encryption.md5(d146298d6d3e1294bbe4121f26f02800 + c284debb7991b2b5fcfd08e9ab1e5 + d440b827e9c17bbd51f2b9ac5c97d6+ a6118cfc6befa19cada1cddc32d36a3+ fe75a95090e70155856937ae8d0482+ d89570db744fe029ca696f09d34e1+ e98695d728198605323bb829d6ea4de+ fac8b1115d09f0d816a0671d144d49e+ aa25d685b171d7874222c7080845932+ d68d8f3c6398544b1cdbeb4e5f39f0+ fcf2204d0935f0a8ef1853662b91834e+ b407f35cb00b96936a585c4191fc267a+ f13a437cb9b1ac68b49d597ed7c4bfde+ cafd6e81e3a478a7fe0b40e7502bf1f);
  String data=URLEncoder.encode("b407f35cb00b96936a585c4191fc267a","UTF-8") + "=" + URLEncoder.encode(b407f35cb00b96936a585c4191fc267a,"UTF-8");
  data+="&" + URLEncoder.encode("f13a437cb9b1ac68b49d597ed7c4bfde","UTF-8") + "="+ URLEncoder.encode(f13a437cb9b1ac68b49d597ed7c4bfde,"UTF-8");
  data+="&" + URLEncoder.encode("9cafd6e81e3a478a7fe0b40e7502bf1f","UTF-8") + "="+ URLEncoder.encode(cafd6e81e3a478a7fe0b40e7502bf1f,"UTF-8");
  data+="&" + URLEncoder.encode("58e5544ab05d8c25c1a5da5cd59144fb","UTF-8") + "="+ URLEncoder.encode(e5544ab05d8c25c1a5da5cd59144fb,"UTF-8");
  data+="&" + URLEncoder.encode("fcf2204d0935f0a8ef1853662b91834e","UTF-8") + "="+ URLEncoder.encode(fcf2204d0935f0a8ef1853662b91834e,"UTF-8");
  data+="&" + URLEncoder.encode("3aa25d685b171d7874222c7080845932","UTF-8") + "="+ URLEncoder.encode(aa25d685b171d7874222c7080845932,"UTF-8");
  data+="&" + URLEncoder.encode("6fac8b1115d09f0d816a0671d144d49e","UTF-8") + "="+ URLEncoder.encode(fac8b1115d09f0d816a0671d144d49e,"UTF-8");
  data+="&" + URLEncoder.encode("5e98695d728198605323bb829d6ea4de","UTF-8") + "="+ URLEncoder.encode(e98695d728198605323bb829d6ea4de,"UTF-8");
  data+="&" + URLEncoder.encode("189d89570db744fe029ca696f09d34e1","UTF-8") + "="+ URLEncoder.encode(d89570db744fe029ca696f09d34e1,"UTF-8");
  data+="&" + URLEncoder.encode("70fe75a95090e70155856937ae8d0482","UTF-8") + "="+ URLEncoder.encode(fe75a95090e70155856937ae8d0482,"UTF-8");
  data+="&" + URLEncoder.encode("9a6118cfc6befa19cada1cddc32d36a3","UTF-8") + "="+ URLEncoder.encode(a6118cfc6befa19cada1cddc32d36a3,"UTF-8");
  data+="&" + URLEncoder.encode("94d440b827e9c17bbd51f2b9ac5c97d6","UTF-8") + "="+ URLEncoder.encode(d440b827e9c17bbd51f2b9ac5c97d6,"UTF-8");
  data+="&" + URLEncoder.encode("234c284debb7991b2b5fcfd08e9ab1e5","UTF-8") + "="+ URLEncoder.encode(c284debb7991b2b5fcfd08e9ab1e5,"UTF-8");
  data+="&" + URLEncoder.encode("41d68d8f3c6398544b1cdbeb4e5f39f0","UTF-8") + "="+ URLEncoder.encode(d68d8f3c6398544b1cdbeb4e5f39f0,"UTF-8");
  data+="&" + URLEncoder.encode("d146298d6d3e1294bbe4121f26f02800","UTF-8") + "="+ URLEncoder.encode("" + d146298d6d3e1294bbe4121f26f02800,"UTF-8");
  loggingManager.Debug("Preparing usage stats for submission.");
  URL url=new URL("http://www.craftfire.com/stats.php");
  URLConnection conn=url.openConnection();
  conn.setConnectTimeout(4000);
  conn.setReadTimeout(4000);
  loggingManager.Debug("Usage stats submission timeout is 4000 ms (4 seconds).");
  conn.setRequestProperty("X-AuthDB",e5544ab05d8c25c1a5da5cd59144fb);
  conn.setDoOutput(true);
  OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream());
  loggingManager.Debug("Attempting to submit usage stats.");
  wr.write(data);
  wr.flush();
  wr.close();
  BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream()));
  Util.logging.Debug("Successfully sent usage stats to CraftFire.");
  rd.close();
}
 

Example 38

From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.

Source file: CraftFireManager.java

  17 
vote

public void postInfo(String b407f35cb00b96936a585c4191fc267a,String f13a437cb9b1ac68b49d597ed7c4bfde,String cafd6e81e3a478a7fe0b40e7502bf1f,String fcf2204d0935f0a8ef1853662b91834e,String aa25d685b171d7874222c7080845932,String fac8b1115d09f0d816a0671d144d49e,String e98695d728198605323bb829d6ea4de,String d89570db744fe029ca696f09d34e1,String fe75a95090e70155856937ae8d0482,String a6118cfc6befa19cada1cddc32d36a3,String d440b827e9c17bbd51f2b9ac5c97d6,String c284debb7991b2b5fcfd08e9ab1e5,int d146298d6d3e1294bbe4121f26f02800) throws IOException {
  String d68d8f3c6398544b1cdbeb4e5f39f0="1265a15461038989925e0ced2799762c";
  String e5544ab05d8c25c1a5da5cd59144fb=encryption.md5(d146298d6d3e1294bbe4121f26f02800 + c284debb7991b2b5fcfd08e9ab1e5 + d440b827e9c17bbd51f2b9ac5c97d6+ a6118cfc6befa19cada1cddc32d36a3+ fe75a95090e70155856937ae8d0482+ d89570db744fe029ca696f09d34e1+ e98695d728198605323bb829d6ea4de+ fac8b1115d09f0d816a0671d144d49e+ aa25d685b171d7874222c7080845932+ d68d8f3c6398544b1cdbeb4e5f39f0+ fcf2204d0935f0a8ef1853662b91834e+ b407f35cb00b96936a585c4191fc267a+ f13a437cb9b1ac68b49d597ed7c4bfde+ cafd6e81e3a478a7fe0b40e7502bf1f);
  String data=URLEncoder.encode("b407f35cb00b96936a585c4191fc267a","UTF-8") + "=" + URLEncoder.encode(b407f35cb00b96936a585c4191fc267a,"UTF-8");
  data+="&" + URLEncoder.encode("f13a437cb9b1ac68b49d597ed7c4bfde","UTF-8") + "="+ URLEncoder.encode(f13a437cb9b1ac68b49d597ed7c4bfde,"UTF-8");
  data+="&" + URLEncoder.encode("9cafd6e81e3a478a7fe0b40e7502bf1f","UTF-8") + "="+ URLEncoder.encode(cafd6e81e3a478a7fe0b40e7502bf1f,"UTF-8");
  data+="&" + URLEncoder.encode("58e5544ab05d8c25c1a5da5cd59144fb","UTF-8") + "="+ URLEncoder.encode(e5544ab05d8c25c1a5da5cd59144fb,"UTF-8");
  data+="&" + URLEncoder.encode("fcf2204d0935f0a8ef1853662b91834e","UTF-8") + "="+ URLEncoder.encode(fcf2204d0935f0a8ef1853662b91834e,"UTF-8");
  data+="&" + URLEncoder.encode("3aa25d685b171d7874222c7080845932","UTF-8") + "="+ URLEncoder.encode(aa25d685b171d7874222c7080845932,"UTF-8");
  data+="&" + URLEncoder.encode("6fac8b1115d09f0d816a0671d144d49e","UTF-8") + "="+ URLEncoder.encode(fac8b1115d09f0d816a0671d144d49e,"UTF-8");
  data+="&" + URLEncoder.encode("5e98695d728198605323bb829d6ea4de","UTF-8") + "="+ URLEncoder.encode(e98695d728198605323bb829d6ea4de,"UTF-8");
  data+="&" + URLEncoder.encode("189d89570db744fe029ca696f09d34e1","UTF-8") + "="+ URLEncoder.encode(d89570db744fe029ca696f09d34e1,"UTF-8");
  data+="&" + URLEncoder.encode("70fe75a95090e70155856937ae8d0482","UTF-8") + "="+ URLEncoder.encode(fe75a95090e70155856937ae8d0482,"UTF-8");
  data+="&" + URLEncoder.encode("9a6118cfc6befa19cada1cddc32d36a3","UTF-8") + "="+ URLEncoder.encode(a6118cfc6befa19cada1cddc32d36a3,"UTF-8");
  data+="&" + URLEncoder.encode("94d440b827e9c17bbd51f2b9ac5c97d6","UTF-8") + "="+ URLEncoder.encode(d440b827e9c17bbd51f2b9ac5c97d6,"UTF-8");
  data+="&" + URLEncoder.encode("234c284debb7991b2b5fcfd08e9ab1e5","UTF-8") + "="+ URLEncoder.encode(c284debb7991b2b5fcfd08e9ab1e5,"UTF-8");
  data+="&" + URLEncoder.encode("41d68d8f3c6398544b1cdbeb4e5f39f0","UTF-8") + "="+ URLEncoder.encode(d68d8f3c6398544b1cdbeb4e5f39f0,"UTF-8");
  data+="&" + URLEncoder.encode("d146298d6d3e1294bbe4121f26f02800","UTF-8") + "="+ URLEncoder.encode("" + d146298d6d3e1294bbe4121f26f02800,"UTF-8");
  Managers.logging.debug("Preparing usage stats for submission.");
  URL url=new URL("http://www.craftfire.com/stats.php");
  URLConnection conn=url.openConnection();
  conn.setConnectTimeout(4000);
  conn.setReadTimeout(4000);
  Managers.logging.debug("Usage stats submission timeout is 4000 ms (4 seconds).");
  conn.setRequestProperty("X-AuthDB",e5544ab05d8c25c1a5da5cd59144fb);
  conn.setDoOutput(true);
  OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream());
  Managers.logging.debug("Attempting to submit usage stats.");
  wr.write(data);
  wr.flush();
  wr.close();
  BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream()));
  Managers.logging.debug("Successfully sent usage stats to CraftFire.");
  rd.close();
}
 

Example 39

From project bel-editor, under directory /org.openbel.editor.core/src/org/openbel/editor/core/index/.

Source file: Parser.java

  17 
vote

private NamespaceInfo parseNamespaceResource(final String resource) throws IOException {
  final URL url=new URL(resource);
  final URLConnection urlc=url.openConnection();
  BufferedReader rdr=null;
  String keyword, name, description, queryValueURL;
  keyword=name=description=queryValueURL=null;
  try {
    rdr=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
    String line;
    while ((line=rdr.readLine()) != null) {
      if (line.startsWith("[Values]")) {
        break;
      }
      if (line.startsWith("Keyword=")) {
        keyword=line.substring(8).trim();
      }
 else       if (line.startsWith("NameString=")) {
        name=line.substring(11).trim();
      }
 else       if (line.startsWith("DescriptionString=")) {
        description=line.substring(18).trim();
      }
 else       if (line.startsWith("QueryValueURL=")) {
        queryValueURL=line.substring(14);
      }
    }
    return new NamespaceInfo(resource,keyword,name,description,queryValueURL);
  }
  finally {
    closeSilently(rdr);
  }
}
 

Example 40

From project BetterShop_1, under directory /src/me/jascotty2/lib/net/.

Source file: FileDownloader.java

  17 
vote

public static synchronized void download(String location,String filename) throws IOException {
  cancelled=false;
  URLConnection connection=new URL(location).openConnection();
  connection.setUseCaches(false);
  File parentDirectory=new File(filename).getParentFile();
  if (parentDirectory != null) {
    parentDirectory.mkdirs();
  }
  InputStream in=connection.getInputStream();
  OutputStream out=new FileOutputStream(filename);
  byte[] buffer=new byte[65536];
  for (int count; !cancelled && (count=in.read(buffer)) >= 0; ) {
    out.write(buffer,0,count);
  }
  in.close();
  out.close();
}
 

Example 41

From project BibleQuote-for-Android, under directory /src/com/BibleQuote/utils/.

Source file: FsUtils.java

  17 
vote

public static boolean loadContentFromURL(String fromURL,String toFile){
  try {
    URL url=new URL("http://bible-desktop.com/xml" + fromURL);
    File file=new File(toFile);
    URLConnection ucon=url.openConnection();
    InputStream is=ucon.getInputStream();
    BufferedInputStream bis=new BufferedInputStream(is);
    ByteArrayBuffer baf=new ByteArrayBuffer(50);
    int current=0;
    while ((current=bis.read()) != -1) {
      baf.append((byte)current);
    }
    FileOutputStream fos=new FileOutputStream(file);
    fos.write(baf.toByteArray());
    fos.close();
  }
 catch (  IOException e) {
    Log.e(TAG,String.format("loadContentFromURL(%1$s, %2$s)",fromURL,toFile),e);
    return false;
  }
  return true;
}
 

Example 42

From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.

Source file: PubchemStructureGenerator.java

  17 
vote

public static List<IMolecule> doDownload(String formula,IProgressMonitor monitor) throws TransformerConfigurationException, ParserConfigurationException, IOException, SAXException, FactoryConfigurationError, TransformerFactoryConfigurationError, TransformerException, NodeNotAvailableException {
  PubchemStructureGenerator request=new PubchemStructureGenerator();
  request.submitInitalRequest(formula);
  worked=0;
  while (!request.getStatus().isFinished()) {
    if (monitor.isCanceled())     return null;
    request.refresh();
    worked++;
    monitor.worked(worked);
  }
  request.submitDownloadRequest();
  while (!request.getStatusDownload().isFinished()) {
    if (monitor.isCanceled())     return null;
    request.refresh();
    worked++;
    monitor.worked(worked);
  }
  URLConnection uc=request.getResponseURL().openConnection();
  String contentType=uc.getContentType();
  int contentLength=uc.getContentLength();
  if (contentType.startsWith("text/") || contentLength == -1) {
    throw new IOException("This is not a binary file.");
  }
  InputStream raw=uc.getInputStream();
  InputStream in=new BufferedInputStream(raw);
  List<IMolecule> list=new ArrayList<IMolecule>();
  IteratingMDLReader reader=new IteratingMDLReader(in,DefaultChemObjectBuilder.getInstance());
  while (reader.hasNext()) {
    list.add((IMolecule)reader.next());
  }
  return list;
}
 

Example 43

From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/tools/.

Source file: TwitterAccess.java

  17 
vote

/** 
 * Uploads an image
 * @param image The image to upload
 * @param tweet The text of the tweet that needs to be posted with the image
 */
public void uploadImage(byte[] image,String tweet){
  if (!enabled)   return;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  RenderedImage img=getImageFromCamera(image);
  try {
    ImageIO.write(img,"jpg",baos);
    URL url=new URL("http://api.imgur.com/2/upload.json");
    String data=URLEncoder.encode("image","UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()),"UTF-8");
    data+="&" + URLEncoder.encode("key","UTF-8") + "="+ URLEncoder.encode("f9c4861fc0aec595e4a64dd185751d28","UTF-8");
    URLConnection conn=url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    StringBuffer buffer=new StringBuffer();
    InputStreamReader isr=new InputStreamReader(conn.getInputStream());
    Reader in=new BufferedReader(isr);
    int ch;
    while ((ch=in.read()) > -1)     buffer.append((char)ch);
    String imgURL=processJSON(buffer.toString());
    setStatus(tweet + " " + imgURL,100);
  }
 catch (  IOException e1) {
    e1.printStackTrace();
  }
}
 

Example 44

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/.

Source file: DetermineFirstSeenThread.java

  17 
vote

@Override public void run(){
  try {
    final URLConnection connection=new URL(Constants.BLOCKEXPLORER_BASE_URL + "address/" + address).openConnection();
    connection.connect();
    final Reader is=new InputStreamReader(new BufferedInputStream(connection.getInputStream()));
    final StringBuilder content=new StringBuilder();
    IOUtils.copy(is,content);
    is.close();
    final Matcher m=P_FIRST_SEEN.matcher(content);
    if (m.find()) {
      succeed(Iso8601Format.parseDateTime(m.group(1)));
    }
 else {
      succeed(null);
    }
  }
 catch (  final IOException x) {
    failed(x);
  }
catch (  final ParseException x) {
    failed(x);
  }
}
 

Example 45

From project boilerpipe_1, under directory /boilerpipe-core/src/main/de/l3s/boilerpipe/sax/.

Source file: HTMLFetcher.java

  17 
vote

/** 
 * Fetches the document at the given URL, using  {@link URLConnection}.
 * @param url
 * @return
 * @throws IOException
 */
public static HTMLDocument fetch(final URL url) throws IOException {
  final URLConnection conn=url.openConnection();
  final String ct=conn.getContentType();
  Charset cs=Charset.forName("Cp1252");
  if (ct != null) {
    Matcher m=PAT_CHARSET.matcher(ct);
    if (m.find()) {
      final String charset=m.group(1);
      try {
        cs=Charset.forName(charset);
      }
 catch (      UnsupportedCharsetException e) {
      }
    }
  }
  InputStream in=conn.getInputStream();
  final String encoding=conn.getContentEncoding();
  if (encoding != null) {
    if ("gzip".equalsIgnoreCase(encoding)) {
      in=new GZIPInputStream(in);
    }
 else {
      System.err.println("WARN: unsupported Content-Encoding: " + encoding);
    }
  }
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  byte[] buf=new byte[4096];
  int r;
  while ((r=in.read(buf)) != -1) {
    bos.write(buf,0,r);
  }
  in.close();
  final byte[] data=bos.toByteArray();
  return new HTMLDocument(data,cs);
}
 

Example 46

From project Carolina-Digital-Repository, under directory /djatoka-cdr/src/gov/lanl/adore/djatoka/util/.

Source file: IOUtils.java

  17 
vote

/** 
 * Gets an InputStream object for provide URL location.  If an AuthenticationManager object was instantiated, it will be used for authenticating if applicable.
 * @param location File, http, or ftp URL to open connection and obtain InputStream
 * @return InputStream containing the requested resource
 * @throws Exception
 */
public static InputStream getInputStream(URL location) throws Exception {
  InputStream in=null;
  if (location.getProtocol().equals("file")) {
    in=new BufferedInputStream(new FileInputStream(location.getFile()));
  }
 else {
    try {
      String userPassword=null;
      if (authManager != null) {
        logger.debug("Getting input from domain: " + location.getHost());
        AuthenticationCredentials authCreds=authManager.getDomainCredentials(location.getHost());
        userPassword=authCreds.getUsername() + ":" + authCreds.getPassword();
      }
      URLConnection huc=location.openConnection();
      if (userPassword != null) {
        String encoding=new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
        huc.setRequestProperty("Authorization","Basic " + encoding);
      }
      huc.connect();
      in=huc.getInputStream();
    }
 catch (    MalformedURLException e) {
      throw new Exception("A MalformedURLException occurred for " + location.toString(),e);
    }
catch (    IOException e) {
      throw new Exception("An IOException occurred attempting to connect to " + location.toString(),e);
    }
  }
  return in;
}
 

Example 47

From project ceylon-module-resolver, under directory /impl/src/main/java/com/redhat/ceylon/cmr/impl/.

Source file: RemoteContentStore.java

  17 
vote

protected InputStream openStream(final URL url) throws IOException {
  final URLConnection conn=url.openConnection();
  if (conn instanceof HttpURLConnection) {
    HttpURLConnection huc=(HttpURLConnection)conn;
    addCredentials(huc);
    InputStream stream=conn.getInputStream();
    int code=huc.getResponseCode();
    if (code != -1 && code != 200) {
      log.info("Got " + code + " for url: "+ url);
      return null;
    }
    log.debug("Got " + code + " for url: "+ url);
    return stream;
  }
  return null;
}
 

Example 48

From project code_swarm, under directory /src/.

Source file: AvatarFetcher.java

  17 
vote

protected static boolean fetchImage(String filename,URL url){
  try {
    new File("image_cache").mkdirs();
    URLConnection con=url.openConnection();
    InputStream input=con.getInputStream();
    FileOutputStream output=new FileOutputStream(filename);
    int length=con.getContentLength();
    if (length == -1) {
      while (true) {
        int val=input.read();
        if (val == -1)         break;
        output.write(input.read());
      }
    }
 else {
      for (int i=0; i < length; i++)       output.write(input.read());
    }
    output.close();
    input.close();
    return true;
  }
 catch (  IOException e) {
    e.printStackTrace();
    return false;
  }
}
 

Example 49

From project code_swarm-gource-my-conf, under directory /src/.

Source file: AvatarFetcher.java

  17 
vote

protected static boolean fetchImage(String filename,URL url){
  try {
    new File("image_cache").mkdirs();
    URLConnection con=url.openConnection();
    InputStream input=con.getInputStream();
    FileOutputStream output=new FileOutputStream(filename);
    int length=con.getContentLength();
    if (length == -1) {
      while (true) {
        int val=input.read();
        if (val == -1)         break;
        output.write(input.read());
      }
    }
 else {
      for (int i=0; i < length; i++)       output.write(input.read());
    }
    output.close();
    input.close();
    return true;
  }
 catch (  IOException e) {
    e.printStackTrace();
    return false;
  }
}
 

Example 50

From project CommitCoin, under directory /src/commitcoin/.

Source file: CommitCoinVerify.java

  17 
vote

public static CharSequence getURLContent(URL url) throws IOException {
  URLConnection conn=url.openConnection();
  String encoding=conn.getContentEncoding();
  if (encoding == null) {
    encoding="ISO-8859-1";
  }
  BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),encoding));
  StringBuilder sb=new StringBuilder(16384);
  try {
    String line;
    while ((line=br.readLine()) != null) {
      sb.append(line);
      sb.append('\n');
    }
  }
  finally {
    br.close();
  }
  return sb;
}
 

Example 51

From project core_1, under directory /src/com/iCo6/util/.

Source file: wget.java

  17 
vote

protected static synchronized void download(String location,String filename) throws IOException {
  URLConnection connection=new URL(location).openConnection();
  connection.setUseCaches(false);
  lastModified=connection.getLastModified();
  String destination="lib" + File.separator + filename;
  File parentDirectory=new File(destination).getParentFile();
  if (parentDirectory != null)   parentDirectory.mkdirs();
  InputStream in=connection.getInputStream();
  OutputStream out=new FileOutputStream(destination);
  byte[] buffer=new byte[65536];
  int currentCount=0;
  for (; ; ) {
    if (cancelled)     break;
    int count=in.read(buffer);
    if (count < 0)     break;
    out.write(buffer,0,count);
    currentCount+=count;
  }
  in.close();
  out.close();
}
 

Example 52

From project core_4, under directory /api/src/main/java/org/ajax4jsf/resource/util/.

Source file: URLToStreamHelper.java

  17 
vote

/** 
 * Returns  {@link InputStream} corresponding to argument {@link URL} but with caching disabled
 * @param url {@link URL} of the resource
 * @return {@link InputStream} instance or <code>null</code>
 * @throws IOException
 */
public static InputStream urlToStream(URL url) throws IOException {
  if (url != null) {
    URLConnection connection=url.openConnection();
    try {
      connection.setUseCaches(false);
    }
 catch (    IllegalArgumentException e) {
      LOG.error(e.getLocalizedMessage(),e);
    }
    return connection.getInputStream();
  }
 else {
    return null;
  }
}
 

Example 53

From project craftbook, under directory /common/src/main/java/com/sk89q/craftbook/bukkit/.

Source file: MetricsLite.java

  17 
vote

/** 
 * Generic method that posts a plugin to the metrics website
 */
private void postPlugin(boolean isPing) throws IOException {
  final PluginDescriptionFile description=plugin.getDescription();
  final StringBuilder data=new StringBuilder();
  data.append(encode("guid")).append('=').append(encode(guid));
  encodeDataPair(data,"version",description.getVersion());
  encodeDataPair(data,"server",Bukkit.getVersion());
  encodeDataPair(data,"players",Integer.toString(Bukkit.getServer().getOnlinePlayers().length));
  encodeDataPair(data,"revision",String.valueOf(REVISION));
  if (isPing) {
    encodeDataPair(data,"ping","true");
  }
  URL url=new URL(BASE_URL + String.format(REPORT_URL,encode(plugin.getDescription().getName())));
  URLConnection connection;
  if (isMineshafterPresent()) {
    connection=url.openConnection(Proxy.NO_PROXY);
  }
 else {
    connection=url.openConnection();
  }
  connection.setDoOutput(true);
  final OutputStreamWriter writer=new OutputStreamWriter(connection.getOutputStream());
  writer.write(data.toString());
  writer.flush();
  final BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
  final String response=reader.readLine();
  writer.close();
  reader.close();
  if (response == null || response.startsWith("ERR")) {
    throw new IOException(response);
  }
}
 

Example 54

From project curator, under directory /curator-x-discovery-server/src/test/java/com/netflix/curator/x/discovery/server/jetty_resteasy/.

Source file: TestStringsWithRestEasy.java

  17 
vote

private String getJson(String urlStr,String body) throws IOException {
  URL url=new URL(urlStr);
  URLConnection urlConnection=url.openConnection();
  urlConnection.addRequestProperty("Accept","application/json");
  if (body != null) {
    ((HttpURLConnection)urlConnection).setRequestMethod("PUT");
    urlConnection.addRequestProperty("Content-Type","application/json");
    urlConnection.addRequestProperty("Content-Length",Integer.toString(body.length()));
    urlConnection.setDoOutput(true);
    OutputStream out=urlConnection.getOutputStream();
    ByteStreams.copy(ByteStreams.newInputStreamSupplier(body.getBytes()),out);
  }
  BufferedReader in=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
  try {
    return CharStreams.toString(in);
  }
  finally {
    in.close();
  }
}
 

Example 55

From project daisy-android-common, under directory /src/com/daisyworks/android/widget/.

Source file: ImageDownloader.java

  17 
vote

Bitmap downloadBitmap(final String url){
  try {
    final URL urlObj=new URL(url);
    final URLConnection conn=urlObj.openConnection();
    conn.connect();
    final InputStream inputStream=conn.getInputStream();
    try {
      return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
    }
  finally {
      if (inputStream != null) {
        inputStream.close();
      }
    }
  }
 catch (  IOException e) {
    if (BTCommThread.DEBUG_BLUETOOTH)     Log.w(LOG_TAG,"I/O error while retrieving bitmap from " + url,e);
  }
catch (  Exception e) {
    if (BTCommThread.DEBUG_BLUETOOTH)     Log.w(LOG_TAG,"Error while retrieving bitmap from " + url,e);
  }
  return null;
}
 

Example 56

From project db2triples, under directory /src/main/java/net/antidot/semantic/rdf/model/impl/sesame/.

Source file: SesameDataSet.java

  17 
vote

/** 
 * Import data from URI source Request is made with proper HTTP ACCEPT header and will follow redirects for proper LOD source negotiation
 * @param urlstring absolute URI of the data source
 * @param format RDF format to request/parse from data source
 */
public void addURI(String urlstring,RDFFormat format){
  try {
    RepositoryConnection con=currentRepository.getConnection();
    try {
      URL url=new URL(urlstring);
      URLConnection uricon=(URLConnection)url.openConnection();
      uricon.addRequestProperty("accept",format.getDefaultMIMEType());
      InputStream instream=uricon.getInputStream();
      con.add(instream,urlstring,format);
    }
  finally {
      con.close();
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 57

From project des, under directory /daemon/lib/apache-log4j-1.2.16/src/main/java/org/apache/log4j/.

Source file: PropertyConfigurator.java

  17 
vote

/** 
 * Read configuration options from url <code>configURL</code>.
 */
public void doConfigure(java.net.URL configURL,LoggerRepository hierarchy){
  Properties props=new Properties();
  LogLog.debug("Reading configuration from URL " + configURL);
  InputStream istream=null;
  URLConnection uConn=null;
  try {
    uConn=configURL.openConnection();
    uConn.setUseCaches(false);
    istream=uConn.getInputStream();
    props.load(istream);
  }
 catch (  Exception e) {
    if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
      Thread.currentThread().interrupt();
    }
    LogLog.error("Could not read configuration file from URL [" + configURL + "].",e);
    LogLog.error("Ignoring configuration file [" + configURL + "].");
    return;
  }
 finally {
    if (istream != null) {
      try {
        istream.close();
      }
 catch (      InterruptedIOException ignore) {
        Thread.currentThread().interrupt();
      }
catch (      IOException ignore) {
      }
catch (      RuntimeException ignore) {
      }
    }
  }
  doConfigure(props,hierarchy);
}
 

Example 58

From project droidkit, under directory /src/org/droidkit/image/.

Source file: ImageLoaderOperation.java

  17 
vote

public boolean downloadToCache(){
  try {
    if (url != null) {
      File tempFile=new File(cacheFile + "-tmp");
      URLConnection conn=url.openConnection();
      conn.connect();
      InputStream is=conn.getInputStream();
      BufferedInputStream bis=new BufferedInputStream(is,BUFFER_SIZE);
      FileOutputStream cacheOut=new FileOutputStream(tempFile);
      IOTricks.copyStreamToStream(bis,cacheOut,BUFFER_SIZE);
      try {
        cacheOut.getFD().sync();
      }
 catch (      SyncFailedException e) {
      }
      cacheOut.close();
      bis.close();
      is.close();
      if (cacheFile.canRead())       cacheFile.delete();
      tempFile.renameTo(cacheFile);
      return true;
    }
  }
 catch (  IOException ioe) {
    Log.e(TAG,"Could not download image file from " + url,ioe);
  }
catch (  Exception e) {
    Log.e(TAG,"Could not download image file from " + url,e);
  }
  return false;
}
 

Example 59

From project drools-mas, under directory /drools-mas-generic-client/src/main/java/org/drools/mas/helpers/.

Source file: DialogueHelper.java

  17 
vote

private void checkEndpointAvailability(int wSDLRetrievalTimeout){
  if (wSDLRetrievalTimeout <= 0) {
    if (WSDL_RETRIEVAL_TIMEOUT <= 0) {
      return;
    }
    wSDLRetrievalTimeout=WSDL_RETRIEVAL_TIMEOUT;
  }
  try {
    URLConnection openConnection;
    openConnection=this.endpointURL.openConnection();
    openConnection.setConnectTimeout(wSDLRetrievalTimeout);
    openConnection.connect();
  }
 catch (  IOException ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 60

From project DTRules, under directory /dtrules-engine/src/main/java/com/dtrules/session/.

Source file: StreamSource.java

  17 
vote

/** 
 * We attempt to open the streamname as a resource in our jar. Then failing that, we attempt to open it as a URL. Then failing that, we attempt to open it as a file.
 * @param tag A String that identifies what sort of file it is to be opened. If you are using some program to encrypt your decision tables for instance, then this will let you know if you need to decrypt the source or not.
 * @param streamname The name of the file/resource to use for the stream.
 * @return
 */
@Override public InputStream openstream(FileType tag,String streamname){
  InputStream s=getClass().getResourceAsStream(streamname);
  if (s != null)   return s;
  try {
    URL url=new URL(streamname);
    URLConnection urlc=url.openConnection();
    s=urlc.getInputStream();
    if (s != null)     return s;
  }
 catch (  MalformedURLException e) {
  }
catch (  Exception e) {
  }
  try {
    s=new FileInputStream(streamname);
    return s;
  }
 catch (  FileNotFoundException e) {
  }
  return null;
}
 

Example 61

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/util/.

Source file: BitmapManager.java

  17 
vote

public Bitmap getBitmap(long id,String url){
  Bitmap bm=cache.get(id);
  if (bm != null) {
    return bm;
  }
 else {
    try {
      URL aURL=new URL(url);
      URLConnection conn=aURL.openConnection();
      conn.connect();
      InputStream is=conn.getInputStream();
      BufferedInputStream bis=new BufferedInputStream(is);
      Bitmap newBm=BitmapFactory.decodeStream(bis);
      bis.close();
      is.close();
      if (newBm != null) {
        cache.put(id,newBm);
      }
      return newBm;
    }
 catch (    IOException e) {
      System.err.println();
      return null;
    }
  }
}
 

Example 62

From project EasySOA, under directory /easysoa-distribution/easysoa-distribution-startup-monitor/src/main/java/org/easysoa/startup/.

Source file: StartupMonitor.java

  17 
vote

/** 
 * @param url
 * @param timeout in ms
 * @return
 */
public static boolean isAvailable(String url,int timeout,boolean expectRequestSuccess){
  try {
    URLConnection connection=new URL(url).openConnection();
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);
    connection.connect();
    InputStream is=connection.getInputStream();
    is.close();
  }
 catch (  ConnectException e) {
    return false;
  }
catch (  IOException e) {
    return !expectRequestSuccess;
  }
  return true;
}
 

Example 63

From project echo2, under directory /src/testapp/interactive/eclipse/.

Source file: TestAppRun.java

  17 
vote

public static void main(String[] arguments) throws Exception {
  try {
    URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/");
    URLConnection conn=url.openConnection();
    InputStream in=conn.getInputStream();
    in.close();
  }
 catch (  ConnectException ex) {
  }
  Server server=new Server(PORT);
  final Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS);
  testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC);
  Context shutdownContext=new Context(server,"/__SHUTDOWN__");
  shutdownContext.addServlet(new ServletHolder(new HttpServlet(){
    private static final long serialVersionUID=1L;
    protected void service(    HttpServletRequest req,    HttpServletResponse resp) throws ServletException, IOException {
      try {
        testContext.getSessionHandler().stop();
        System.out.println("Shutdown request received: terminating.");
        System.exit(0);
      }
 catch (      Exception ex) {
        ex.printStackTrace();
      }
    }
  }
),"/");
  System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC);
  server.start();
  server.join();
}
 

Example 64

From project echo3, under directory /src/server-java/testapp-interactive/eclipse/.

Source file: TestAppRun.java

  17 
vote

public static void main(String[] arguments) throws Exception {
  try {
    URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/");
    URLConnection conn=url.openConnection();
    InputStream in=conn.getInputStream();
    in.close();
  }
 catch (  ConnectException ex) {
  }
  Server server=new Server(PORT);
  final Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS);
  testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC);
  Context shutdownContext=new Context(server,"/__SHUTDOWN__");
  shutdownContext.addServlet(new ServletHolder(new HttpServlet(){
    private static final long serialVersionUID=1L;
    protected void service(    HttpServletRequest req,    HttpServletResponse resp) throws ServletException, IOException {
      try {
        testContext.getSessionHandler().stop();
        System.out.println("Shutdown request received: terminating.");
        System.exit(0);
      }
 catch (      Exception ex) {
        ex.printStackTrace();
      }
    }
  }
),"/");
  System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC);
  server.start();
  server.join();
}
 

Example 65

From project echo3extras, under directory /src/server-java/testapp-interactive/eclipse/.

Source file: TestAppRun.java

  17 
vote

public static void main(String[] arguments) throws Exception {
  try {
    URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/");
    URLConnection conn=url.openConnection();
    InputStream in=conn.getInputStream();
    in.close();
  }
 catch (  ConnectException ex) {
  }
  Server server=new Server(PORT);
  Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS);
  testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC);
  Context shutdownContext=new Context(server,"/__SHUTDOWN__");
  shutdownContext.addServlet(new ServletHolder(new HttpServlet(){
    private static final long serialVersionUID=1L;
    protected void service(    HttpServletRequest req,    HttpServletResponse resp) throws ServletException, IOException {
      System.out.println("Shutdown request received: terminating.");
      System.exit(0);
    }
  }
),"/");
  System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC);
  server.start();
  server.join();
}
 

Example 66

From project egit-github, under directory /org.eclipse.mylyn.github.ui/src/org/eclipse/mylyn/internal/github/ui/.

Source file: AvatarStore.java

  17 
vote

/** 
 * Load avatar image data from url
 * @param url
 * @return avatar image data
 * @throws IOException
 */
public ImageData loadAvatar(String url) throws IOException {
  url=normalize(url);
  URL parsed=new URL(url);
  byte[] data=this.avatars.get(url);
  if (data != null)   return getData(data);
  URLConnection connection=parsed.openConnection();
  connection.setConnectTimeout(TIMEOUT);
  ByteArrayOutputStream output=new ByteArrayOutputStream();
  InputStream input=connection.getInputStream();
  try {
    byte[] buffer=new byte[BUFFER_SIZE];
    int read=input.read(buffer);
    while (read != -1) {
      output.write(buffer,0,read);
      read=input.read(buffer);
    }
  }
  finally {
    try {
      input.close();
    }
 catch (    IOException ignore) {
    }
    try {
      output.close();
    }
 catch (    IOException ignore) {
    }
  }
  data=output.toByteArray();
  this.avatars.put(url,data);
  return getData(data);
}
 

Example 67

From project elasticsearch-cloud-aws, under directory /src/main/java/org/elasticsearch/cloud/aws/network/.

Source file: Ec2NameResolver.java

  17 
vote

/** 
 * @param type the ec2 hostname type to discover.
 * @return the appropriate host resolved from ec2 meta-data.
 * @throws IOException if ec2 meta-data cannot be obtained.
 * @see CustomNameResolver#resolveIfPossible(String)
 */
public InetAddress resolve(Ec2HostnameType type,boolean warnOnFailure){
  URLConnection urlConnection=null;
  InputStream in=null;
  try {
    URL url=new URL(AwsEc2Service.EC2_METADATA_URL + type.ec2Name);
    logger.debug("obtaining ec2 hostname from ec2 meta-data url {}",url);
    urlConnection=url.openConnection();
    urlConnection.setConnectTimeout(2000);
    in=urlConnection.getInputStream();
    BufferedReader urlReader=new BufferedReader(new InputStreamReader(in));
    String metadataResult=urlReader.readLine();
    if (metadataResult == null || metadataResult.length() == 0) {
      logger.error("no ec2 metadata returned from {}",url);
      return null;
    }
    return InetAddress.getByName(metadataResult);
  }
 catch (  IOException e) {
    if (warnOnFailure) {
      logger.warn("failed to get metadata for [" + type.configName + "]: "+ ExceptionsHelper.detailedMessage(e));
    }
 else {
      logger.debug("failed to get metadata for [" + type.configName + "]: "+ ExceptionsHelper.detailedMessage(e));
    }
    return null;
  }
 finally {
    Closeables.closeQuietly(in);
  }
}
 

Example 68

From project embedmongo.flapdoodle.de, under directory /src/main/java/de/flapdoodle/embedmongo/.

Source file: Downloader.java

  17 
vote

public static File download(RuntimeConfig runtime,Distribution distribution) throws IOException {
  String progressLabel="Download " + distribution;
  IProgressListener progress=runtime.getProgressListener();
  progress.start(progressLabel);
  File ret=Files.createTempFile(runtime.getDefaultfileNaming().nameFor("embedmongo-download","." + Paths.getArchiveType(distribution)));
  if (ret.canWrite()) {
    BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(ret));
    URL url=new URL(getDownloadUrl(runtime,distribution));
    URLConnection openConnection=url.openConnection();
    openConnection.setConnectTimeout(10000);
    openConnection.setReadTimeout(10000);
    InputStream downloadStream=openConnection.getInputStream();
    long length=openConnection.getContentLength();
    progress.info(progressLabel,"DownloadSize: " + length);
    if (length == -1)     length=20 * 1024 * 1024;
    try {
      BufferedInputStream bis=new BufferedInputStream(downloadStream);
      byte[] buf=new byte[1024 * 8];
      int read=0;
      long readCount=0;
      while ((read=bis.read(buf)) != -1) {
        bos.write(buf,0,read);
        readCount=readCount + read;
        if (readCount > length)         length=readCount;
        progress.progress(progressLabel,(int)(readCount * 100 / length));
      }
    }
  finally {
      downloadStream.close();
      bos.flush();
      bos.close();
    }
  }
 else {
    throw new IOException("Can not write " + ret);
  }
  progress.done(progressLabel);
  return ret;
}
 

Example 69

From project evodroid, under directory /src/com/commonsware/cwac/cache/.

Source file: SimpleWebImageCache.java

  17 
vote

@SuppressWarnings("unchecked") @Override protected Void doInBackground(Object... params){
  String url=params[1].toString();
  File cache=(File)params[2];
  try {
    URLConnection connection=new URL(url).openConnection();
    InputStream stream=connection.getInputStream();
    BufferedInputStream in=new BufferedInputStream(stream);
    ByteArrayOutputStream out=new ByteArrayOutputStream(10240);
    int read;
    byte[] b=new byte[4096];
    while ((read=in.read(b)) != -1) {
      out.write(b,0,read);
    }
    out.flush();
    out.close();
    byte[] raw=out.toByteArray();
    put(url,new BitmapDrawable(new ByteArrayInputStream(raw)));
    M message=(M)params[0];
    if (message != null) {
      bus.send(message);
    }
    if (cache != null) {
      FileOutputStream file=new FileOutputStream(cache);
      file.write(raw);
      file.flush();
      file.close();
    }
  }
 catch (  Throwable t) {
  }
  return (null);
}
 

Example 70

From project examples_5, under directory /twittertopiccount/src/main/java/io/s4/example/twittertopiccount/.

Source file: TwitterFeedListener.java

  17 
vote

public void connectAndRead() throws Exception {
  URL url=new URL(urlString);
  URLConnection connection=url.openConnection();
  String userPassword=userid + ":" + password;
  String encoded=EncodingUtil.getAsciiString(Base64.encodeBase64(EncodingUtil.getAsciiBytes(userPassword)));
  connection.setRequestProperty("Authorization","Basic " + encoded);
  connection.connect();
  InputStream is=connection.getInputStream();
  InputStreamReader isr=new InputStreamReader(is);
  BufferedReader br=new BufferedReader(isr);
  String inputLine=null;
  while ((inputLine=br.readLine()) != null) {
    if (inputLine.trim().length() == 0) {
      blankCount++;
      continue;
    }
    messageCount++;
    messageQueue.add(inputLine);
  }
}
 

Example 71

From project facebook-android-sdk, under directory /examples/Hackbook/src/com/facebook/android/.

Source file: Utility.java

  17 
vote

public static Bitmap getBitmap(String url){
  Bitmap bm=null;
  try {
    URL aURL=new URL(url);
    URLConnection conn=aURL.openConnection();
    conn.connect();
    InputStream is=conn.getInputStream();
    BufferedInputStream bis=new BufferedInputStream(is);
    bm=BitmapFactory.decodeStream(new FlushedInputStream(is));
    bis.close();
    is.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    if (httpclient != null) {
      httpclient.close();
    }
  }
  return bm;
}
 

Example 72

From project fakereplace, under directory /core/src/main/java/org/fakereplace/core/.

Source file: DefaultEnvironment.java

  17 
vote

public void recordTimestamp(String className,ClassLoader loader){
  log.trace("Recording timestamp for " + className);
  if (loader == null) {
    return;
  }
  final URL file=loader.getResource(className.replace(".","/") + ".class");
  className=className.replace("/",".");
  if (file != null) {
    URLConnection connection=null;
    try {
      connection=file.openConnection();
      timestamps.put(className,connection.getLastModified());
      loaders.put(className,loader);
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
  }
}
 

Example 73

From project FlipDroid, under directory /boilerpipe/src/main/java/de/l3s/boilerpipe/sax/.

Source file: HTMLFetcher.java

  17 
vote

public static HTMLDocument fetch(final URL url,String charsetStr) throws IOException {
  final URLConnection conn=url.openConnection();
  conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6");
  final String charset=conn.getContentEncoding();
  Charset cs=Charset.forName(charsetStr);
  if (charset != null) {
    try {
      cs=Charset.forName(charset);
    }
 catch (    UnsupportedCharsetException e) {
    }
  }
  InputStream in=conn.getInputStream();
  final String encoding=conn.getContentEncoding();
  if (encoding != null) {
    if ("gzip".equalsIgnoreCase(encoding)) {
      in=new GZIPInputStream(in);
    }
 else {
      System.err.println("WARN: unsupported Content-Encoding: " + encoding);
    }
  }
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  byte[] buf=new byte[4096];
  int r;
  while ((r=in.read(buf)) != -1) {
    bos.write(buf,0,r);
  }
  in.close();
  final byte[] data=bos.toByteArray();
  return new HTMLDocument(data,cs);
}
 

Example 74

From project Flow, under directory /src/com/github/JamesNorris/Flow/.

Source file: MetricsLite.java

  17 
vote

/** 
 * Generic method that posts a plugin to the metrics website
 */
private void postPlugin(boolean isPing) throws IOException {
  final PluginDescriptionFile description=plugin.getDescription();
  final StringBuilder data=new StringBuilder();
  data.append(encode("guid")).append('=').append(encode(guid));
  encodeDataPair(data,"version",description.getVersion());
  encodeDataPair(data,"server",Bukkit.getVersion());
  encodeDataPair(data,"players",Integer.toString(Bukkit.getServer().getOnlinePlayers().length));
  encodeDataPair(data,"revision",String.valueOf(REVISION));
  if (isPing) {
    encodeDataPair(data,"ping","true");
  }
  URL url=new URL(BASE_URL + String.format(REPORT_URL,encode(plugin.getDescription().getName())));
  URLConnection connection;
  if (isMineshafterPresent()) {
    connection=url.openConnection(Proxy.NO_PROXY);
  }
 else {
    connection=url.openConnection();
  }
  connection.setDoOutput(true);
  final OutputStreamWriter writer=new OutputStreamWriter(connection.getOutputStream());
  writer.write(data.toString());
  writer.flush();
  final BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
  final String response=reader.readLine();
  writer.close();
  reader.close();
  if (response == null || response.startsWith("ERR")) {
    throw new IOException(response);
  }
}
 

Example 75

From project flume_1, under directory /flume-core/src/test/java/com/cloudera/flume/master/.

Source file: TestMasterJersey.java

  17 
vote

/** 
 * Gra b a url's contents. Since most are json, this should be small.
 * @param urlString
 * @return
 * @throws IOException
 */
public static String curl(String urlString) throws IOException {
  URL url=new URL(urlString);
  URLConnection urlConn=url.openConnection();
  urlConn.setDoInput(true);
  urlConn.setUseCaches(false);
  int len=urlConn.getContentLength();
  String type=urlConn.getContentType();
  LOG.info("pulled " + urlString + "[ type="+ type+ " len="+ len+ "]");
  InputStreamReader isr=new InputStreamReader(urlConn.getInputStream());
  BufferedReader br=new BufferedReader(isr);
  StringBuilder sb=new StringBuilder();
  String s;
  while ((s=br.readLine()) != null) {
    sb.append(s);
    sb.append('\n');
  }
  return sb.toString();
}
 

Example 76

From project flyingsaucer, under directory /flying-saucer-core/src/main/java/org/xhtmlrenderer/util/.

Source file: IOUtil.java

  17 
vote

/** 
 * Attempts to open a connection, and a stream, to the URI provided. timeouts will be set for opening the connection and reading from it. will return the stream, or null if unable to open or read or a timeout occurred. Does not buffer the stream.
 */
public static InputStream openStreamAtUrl(String uri){
  InputStream is=null;
  try {
    final URLConnection uc=new URL(uri).openConnection();
    System.setProperty("sun.net.client.defaultConnectTimeout",String.valueOf(10 * 1000));
    System.setProperty("sun.net.client.defaultReadTimeout",String.valueOf(30 * 1000));
    uc.connect();
    is=uc.getInputStream();
  }
 catch (  java.net.MalformedURLException e) {
    XRLog.exception("bad URL given: " + uri,e);
  }
catch (  FileNotFoundException e) {
    XRLog.exception("item at URI " + uri + " not found");
  }
catch (  IOException e) {
    XRLog.exception("IO problem for " + uri,e);
  }
  return is;
}
 

Example 77

From project FML, under directory /common/cpw/mods/fml/relauncher/.

Source file: RelaunchLibraryManager.java

  17 
vote

private static void downloadFile(File libFile,String rootUrl,String hash){
  try {
    URL libDownload=new URL(String.format(rootUrl,libFile.getName()));
    String infoString=String.format("Downloading file %s",libDownload.toString());
    downloadMonitor.updateProgressString(infoString);
    FMLRelaunchLog.info(infoString);
    URLConnection connection=libDownload.openConnection();
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(5000);
    connection.setRequestProperty("User-Agent","FML Relaunch Downloader");
    int sizeGuess=connection.getContentLength();
    performDownload(connection.getInputStream(),sizeGuess,hash,libFile);
    downloadMonitor.updateProgressString("Download complete");
    FMLRelaunchLog.info("Download complete");
  }
 catch (  Exception e) {
    if (downloadMonitor.shouldStopIt()) {
      FMLRelaunchLog.warning("You have stopped the downloading operation before it could complete");
      return;
    }
    if (e instanceof RuntimeException)     throw (RuntimeException)e;
    FMLRelaunchLog.severe("There was a problem downloading the file %s automatically. Perhaps you " + "have an environment without internet access. You will need to download " + "the file manually or restart and let it try again\n",libFile.getName());
    libFile.delete();
    throw new RuntimeException("A download error occured",e);
  }
}
 

Example 78

From project gatein-common, under directory /common/src/main/java/org/gatein/common/net/.

Source file: URLTools.java

  17 
vote

/** 
 * Fetches content from URL as an InputStream. The timeout values must not be negative integers, when it is equals to zero it means that it does not setup a timeout and use the default values.
 * @param url               the URL the URL of the resource
 * @param soTimeoutMillis   the socket connection timeout in millis
 * @param connTimeoutMillis the connection timeout in millis
 * @return the buffered content for the URL
 * @throws IllegalArgumentException if the URL is null or any time out value is negative
 * @since 1.1
 */
public static InputStream getContentAsInputStream(URL url,int soTimeoutMillis,int connTimeoutMillis) throws IOException {
  if (url == null) {
    throw new IllegalArgumentException();
  }
  if (soTimeoutMillis < 0) {
    throw new IllegalArgumentException("No negative socket timeout " + soTimeoutMillis);
  }
  if (connTimeoutMillis < 0) {
    throw new IllegalArgumentException("No negative connection timeout" + connTimeoutMillis);
  }
  if (System.getProperty("http.proxyUser") != null) {
    Authenticator.setDefault(new Authenticator(){
      protected PasswordAuthentication getPasswordAuthentication(){
        return (new PasswordAuthentication(System.getProperty("http.proxyUser"),System.getProperty("http.proxyPassword").toCharArray()));
      }
    }
);
  }
  URLConnection conn;
  try {
    conn=url.openConnection();
  }
 catch (  IOException e) {
    return null;
  }
  conn.setConnectTimeout(soTimeoutMillis);
  conn.setReadTimeout(connTimeoutMillis);
  conn.connect();
  try {
    return new BufferedInputStream(conn.getInputStream());
  }
 catch (  SocketTimeoutException e) {
    log.debug("Time out on: " + url);
    throw e;
  }
}
 

Example 79

From project GeoBI, under directory /print/src/main/java/org/mapfish/print/map/renderers/.

Source file: SVGTileRenderer.java

  17 
vote

private TranscoderInput getTranscoderInput(URL url,Transformer transformer,RenderingContext context){
  final float zoomFactor=transformer.getSvgFactor() * context.getStyleFactor();
  if (svgZoomOut != null && zoomFactor != 1.0f) {
    try {
      DOMResult transformedSvg=new DOMResult();
      final TransformerFactory factory=TransformerFactory.newInstance();
      javax.xml.transform.Transformer xslt=factory.newTransformer(new DOMSource(svgZoomOut));
      xslt.setParameter("zoomFactor",zoomFactor);
      final URLConnection urlConnection=url.openConnection();
      if (context.getReferer() != null) {
        urlConnection.setRequestProperty("Referer",context.getReferer());
      }
      final InputStream inputStream=urlConnection.getInputStream();
      Document doc;
      try {
        xslt.transform(new StreamSource(inputStream),transformedSvg);
        doc=(Document)transformedSvg.getNode();
        if (LOGGER.isDebugEnabled()) {
          printDom(doc);
        }
      }
  finally {
        inputStream.close();
      }
      return new TranscoderInput(doc);
    }
 catch (    Exception e) {
      context.addError(e);
      return null;
    }
  }
 else {
    return new TranscoderInput(url.toString());
  }
}
 

Example 80

From project Gmote, under directory /gmoteclient/src/org/gmote/client/android/.

Source file: ImageBrowser.java

  17 
vote

public Bitmap getBitmap(int position){
  Bitmap bitmap=null;
  try {
    URL aURL=new URL(mImages.get(position) + "?sessionId=" + getSessionId());
    URLConnection conn=aURL.openConnection();
    conn.connect();
    InputStream is=conn.getInputStream();
    BufferedInputStream bis=new BufferedInputStream(is);
    Bitmap bm=BitmapFactory.decodeStream(bis);
    bis.close();
    is.close();
    bitmap=bm;
  }
 catch (  IOException e) {
    bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.image_viewer);
    Log.e("DEBUGTAG","Remote Image Exception",e);
  }
  return bitmap;
}
 

Example 81

From project commons-logging, under directory /src/java/org/apache/commons/logging/.

Source file: LogFactory.java

  16 
vote

/** 
 * Given a URL that refers to a .properties file, load that file. This is done under an AccessController so that this method will succeed when this jarfile is privileged but the caller is not. This method must therefore remain private to avoid security issues. <p> Null is returned if the URL cannot be opened.
 */
private static Properties getProperties(final URL url){
  PrivilegedAction action=new PrivilegedAction(){
    public Object run(){
      InputStream stream=null;
      try {
        URLConnection connection=url.openConnection();
        connection.setUseCaches(false);
        stream=connection.getInputStream();
        if (stream != null) {
          Properties props=new Properties();
          props.load(stream);
          stream.close();
          stream=null;
          return props;
        }
      }
 catch (      IOException e) {
        if (isDiagnosticsEnabled()) {
          logDiagnostic("Unable to read URL " + url);
        }
      }
 finally {
        if (stream != null) {
          try {
            stream.close();
          }
 catch (          Throwable t) {
            if (isDiagnosticsEnabled()) {
              logDiagnostic("Unable to close stream for URL " + url);
            }
          }
        }
      }
      return null;
    }
  }
;
  return (Properties)AccessController.doPrivileged(action);
}
 

Example 82

From project crash, under directory /shell/core/src/main/java/org/crsh/vfs/spi/ram/.

Source file: RAMURLStreamHandler.java

  16 
vote

@Override protected URLConnection openConnection(URL u) throws IOException {
  Path path=Path.get(u.getFile());
  if (path.isDir()) {
    throw new IOException("Cannot open dir");
  }
  String file=driver.entries.get(path);
  if (file == null) {
    throw new IOException("Cannot open non existing dir " + path);
  }
  return new RAMURLConnection(u,file);
}
 

Example 83

From project eclim, under directory /org.eclim.installer/java/org/eclim/installer/.

Source file: URLProgressInputStream.java

  16 
vote

public URLProgressInputStream(JProgressBar progressBar,URLConnection con) throws IOException {
  super(con.getInputStream());
  this.progressBar=progressBar;
  progressBar.setValue(0);
  progressBar.setMaximum(con.getContentLength());
  progressBar.setIndeterminate(false);
}
 

Example 84

From project eik, under directory /plugins/org.ops4j.pax.url.mvn/src/main/java/org/ops4j/pax/url/mvn/.

Source file: MvnURLConnectionFactory.java

  16 
vote

/** 
 * Creates a  {@link URLConnection} from the specified {@link URL}
 * @param url the  {@code URL}
 * @return the {@code URLConnection}
 * @throws IOException
 */
public URLConnection create(final URL url) throws IOException {
  final PropertiesPropertyResolver systemProperties=new PropertiesPropertyResolver(System.getProperties());
  final PropertiesPropertyResolver configuredProperties=new PropertiesPropertyResolver(configuration,systemProperties);
  final MavenConfigurationImpl config=new MavenConfigurationImpl(configuredProperties,ServiceConstants.PID);
  config.setSettings(new MavenSettingsImpl(config.getSettingsFileUrl(),config.useFallbackRepositories()));
  return new Connection(url,config);
}
 

Example 85

From project gengweibo, under directory /src/net/oauth/client/.

Source file: URLConnectionResponse.java

  16 
vote

/** 
 * Construct an OAuthMessage from the HTTP response, including parameters from OAuth WWW-Authenticate headers and the body. The header parameters come first, followed by the ones from the response body.
 */
public URLConnectionResponse(HttpMessage request,String requestHeaders,byte[] requestExcerpt,URLConnection connection) throws IOException {
  super(request.method,request.url);
  this.requestHeaders=requestHeaders;
  this.requestExcerpt=requestExcerpt;
  this.requestEncoding=request.getContentCharset();
  this.connection=connection;
  this.headers.addAll(getHeaders());
}
 

Example 86

From project geronimo-xbean, under directory /xbean-classloader/src/main/java/org/apache/xbean/classloader/.

Source file: JarFileUrlStreamHandler.java

  16 
vote

public URLConnection openConnection(URL url) throws IOException {
  if (expectedUrl == null)   throw new IllegalStateException("expectedUrl was not set");
  if (!expectedUrl.equals(url)) {
    if (!url.getProtocol().equals("jar")) {
      throw new IllegalArgumentException("Unsupported protocol " + url.getProtocol());
    }
    String path=url.getPath();
    String[] chunks=path.split("!/",2);
    if (chunks.length == 1) {
      throw new MalformedURLException("Url does not contain a '!' character: " + url);
    }
    String file=chunks[0];
    String entryPath=chunks[1];
    if (!file.startsWith("file:")) {
      return new URL(url.toExternalForm()).openConnection();
    }
    file=file.substring("file:".length());
    if (!jarFile.getName().equals(file)) {
      return new URL(url.toExternalForm()).openConnection();
    }
    JarEntry newEntry=jarFile.getJarEntry(entryPath);
    if (newEntry == null) {
      throw new FileNotFoundException("Entry not found: " + url);
    }
    return new JarFileUrlConnection(url,jarFile,newEntry);
  }
  return new JarFileUrlConnection(url,jarFile,jarEntry);
}
 

Example 87

From project agit, under directory /agit/src/main/java/com/madgag/agit/.

Source file: BlobViewFragment.java

  15 
vote

BinaryBlobView(ObjectLoader objectLoader,String nameString) throws IOException {
  this.nameString=nameString;
  ObjectStream stream=objectLoader.openStream();
  tempFile=new File(getActivity().getExternalCacheDir(),nameString);
  copyInputStreamToFile(stream,tempFile);
  mimeType=URLConnection.getFileNameMap().getContentTypeFor(nameString);
  Log.d(TAG,"mimeType=" + mimeType + " tempFile="+ tempFile);
}
 

Example 88

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/.

Source file: ReportDetailsActivity.java

  15 
vote

public String getMimeType(String fileUrl) throws java.io.IOException {
  FileNameMap fileNameMap=URLConnection.getFileNameMap();
  String type=fileNameMap.getContentTypeFor(fileUrl);
  if (type == null)   return "unknown";
  return type;
}
 

Example 89

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.

Source file: OAuthSignpostClient.java

  15 
vote

@Override protected void setAuthentication(URLConnection connection,String name,String password){
  try {
    consumer.sign(connection);
  }
 catch (  OAuthException e) {
    throw new TwitterException(e);
  }
}
 

Example 90

From project android_external_oauth, under directory /core/src/main/java/net/oauth/client/.

Source file: URLConnectionResponse.java

  15 
vote

/** 
 * Construct an OAuthMessage from the HTTP response, including parameters from OAuth WWW-Authenticate headers and the body. The header parameters come first, followed by the ones from the response body.
 */
public URLConnectionResponse(HttpMessage request,String requestHeaders,byte[] requestExcerpt,URLConnection connection) throws IOException {
  super(request.method,request.url);
  this.requestHeaders=requestHeaders;
  this.requestExcerpt=requestExcerpt;
  this.requestEncoding=request.getContentCharset();
  this.connection=connection;
  this.headers.addAll(getHeaders());
}
 

Example 91

From project arquillian-container-openwebbeans, under directory /openwebbeans-embedded-1/src/main/java/org/jboss/arquillian/container/openwebbeans/embedded_1/.

Source file: ShrinkWrapClassLoader.java

  15 
vote

@Override protected URL findResource(final String name){
  final Node a=archive.get(name);
  if (a == null) {
    return null;
  }
  try {
    return new URL(null,ARCHIVE_PROTOCOL + name,new URLStreamHandler(){
      @Override protected java.net.URLConnection openConnection(      URL u) throws java.io.IOException {
        return new URLConnection(u){
          @Override public void connect() throws IOException {
          }
          @Override public InputStream getInputStream() throws IOException {
            return a.getAsset().openStream();
          }
        }
;
      }
    }
);
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 92

From project arquillian-container-weld, under directory /weld-se-embedded-1/src/main/java/org/jboss/arquillian/container/weld/se/embedded_1/shrinkwrap/.

Source file: ShrinkwrapBeanDeploymentArchiveImpl.java

  15 
vote

public Collection<URL> getBeansXml(){
  List<URL> beanClasses=new ArrayList<URL>();
  Map<ArchivePath,Node> classes=archive.getContent(Filters.include(".*/beans.xml"));
  for (  final Map.Entry<ArchivePath,Node> entry : classes.entrySet()) {
    try {
      beanClasses.add(new URL(null,"archive://" + entry.getKey().get(),new URLStreamHandler(){
        @Override protected java.net.URLConnection openConnection(        URL u) throws java.io.IOException {
          return new URLConnection(u){
            @Override public void connect() throws IOException {
            }
            @Override public InputStream getInputStream() throws IOException {
              return entry.getValue().getAsset().openStream();
            }
          }
;
        }
      }
));
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
  return beanClasses;
}
 

Example 93

From project bndtools, under directory /bndtools.core/src/bndtools/services/.

Source file: WorkspaceURLStreamHandlerService.java

  15 
vote

@Override public URLConnection openConnection(URL url) throws IOException {
  String protocol=url.getProtocol();
  if (!PROTOCOL.equals(protocol))   throw new MalformedURLException("Unsupported protocol");
  IPath path=new Path(url.getPath());
  IWorkspace workspace=(IWorkspace)workspaceTracker.getService();
  if (workspace == null)   throw new IOException("Workspace is not available");
  IPath workspaceLocation=workspace.getRoot().getLocation();
  if (workspaceLocation == null)   throw new IOException("Cannot determine workspace location.");
  IPath location=workspaceLocation.append(path);
  return new URL("file",null,location.toOSString()).openConnection();
}
 

Example 94

From project cameraptp, under directory /src/main/java/ste/ptp/.

Source file: ObjectInfo.java

  15 
vote

/** 
 * Construct an ObjectInfo data packet using the object at the other end of the specified connection.
 * @see BaselineInitiator#sendObjectInfo
 * @exception IllegalArgumentException if the object uses an imageformat the device doesn't support, or if the object's content type is not recognized.
 */
public ObjectInfo(URLConnection conn,DeviceInfo devInfo,NameFactory f){
  super(false,new byte[1024],f);
  String type=conn.getContentType();
  objectCompressedSize=conn.getContentLength();
  if (type.startsWith("image/")) {
    boolean error=false;
    if ("image/jpeg".equals(type)) {
      if (devInfo.supportsImageFormat(JFIF))       objectFormatCode=JFIF;
 else       if (devInfo.supportsImageFormat(EXIF_JPEG))       objectFormatCode=EXIF_JPEG;
 else       error=true;
    }
 else     if ("image/tiff".equals(type)) {
      if (devInfo.supportsImageFormat(TIFF))       objectFormatCode=TIFF;
 else       if (devInfo.supportsImageFormat(TIFF_EP))       objectFormatCode=TIFF_EP;
 else       if (devInfo.supportsImageFormat(TIFF_IT))       objectFormatCode=TIFF_IT;
 else       error=true;
    }
 else {
      if ("image/gif".equals(type))       objectFormatCode=GIF;
 else       if ("image/png".equals(type))       objectFormatCode=PNG;
 else       if ("image/vnd.fpx".equals(type))       objectFormatCode=FlashPix;
 else       if ("image/x-MS-bmp".equals(type))       objectFormatCode=BMP;
 else       if ("image/x-photo-cd".equals(type))       objectFormatCode=PCD;
 else       objectFormatCode=UnknownImage;
    }
    if (error || !devInfo.supportsImageFormat(objectFormatCode))     throw new IllegalArgumentException("device doesn't support " + type);
  }
 else   if ("text/html".equals(type))   objectFormatCode=HTML;
 else   if ("text/plain".equals(type))   objectFormatCode=Text;
 else   if ("audio/mp3".equals(type))   objectFormatCode=MP3;
 else   if ("audio/x-aiff".equals(type))   objectFormatCode=AIFF;
 else   if ("audio/x-wav".equals(type))   objectFormatCode=WAV;
 else   if ("video/mpeg".equals(type))   objectFormatCode=MPEG;
 else   objectFormatCode=Undefined;
  marshal();
}