Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net URLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:com.qualogy.qafe.gwt.server.RPCServiceImpl.java

public String getUI(String xmlUI) throws GWTServiceException {
    String url = null;/*from w  ww  .  j av a2  s .c o m*/
    if (service.isValidXML(xmlUI)) {
        logger.fine("XML Send by client : \n" + xmlUI);

        try {

            String urlBase = ApplicationCluster.getInstance()
                    .getConfigurationItem(Configuration.FLEX_DEMO_WAR_URL);
            if (urlBase == null || urlBase.length() == 0) {
                urlBase = getThreadLocalRequest().getScheme() + "://" + getThreadLocalRequest().getServerName()
                        + ":" + getThreadLocalRequest().getServerPort() + "/qafe-web-flex";
            }

            String urlStore = urlBase + "/store";
            logger.fine("URL Store is =" + urlStore);

            OutputStreamWriter wr = null;
            BufferedReader rd = null;

            try {
                // Send data
                URL requestURL = new URL(urlStore);
                URLConnection conn = requestURL.openConnection();
                conn.setDoOutput(true);
                wr = new OutputStreamWriter(conn.getOutputStream());
                String data = "xml" + "=" + xmlUI;
                wr.write(data);
                wr.flush();

                // Get the response
                rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    url = urlBase + "/index.jsp?uuid=" + line;
                    logger.fine(url);
                }
            } finally {
                wr.close();
                rd.close();
            }
        } catch (Exception e) {
            throw handleException(e);
        }
    } else {
        try {
            service.getUIFromXML(xmlUI, null, null, getLocale());
        } catch (Exception e) {
            throw handleException(e);
        }
    }
    return url;
}

From source file:com.bigdata.gom.TestRemoteGOM.java

public void testSimpleJSON() throws RepositoryException, IOException {
    final NanoSparqlObjectManager om = new NanoSparqlObjectManager(m_repo, m_namespace);
    final ValueFactory vf = om.getValueFactory();

    final URI keyname = vf.createURI("attr:/test#name");
    final Resource id = vf.createURI("gpo:test#1");
    //      om.checkValue(id);
    final int transCounter = om.beginNativeTransaction();
    try {//from   ww  w.  ja  v a2 s.c  om
        IGPO gpo = om.getGPO(id);

        gpo.setValue(keyname, vf.createLiteral("Martyn"));

        om.commitNativeTransaction(transCounter);
    } catch (Throwable t) {
        om.rollbackNativeTransaction();

        throw new RuntimeException(t);
    }

    // Now let's read the data as JSON by connecting directly with the serviceurl
    URL url = new URL(m_serviceURL);
    URLConnection server = url.openConnection();
    try {
        // server.setRequestProperty("Accept", TupleQueryResultFormat.JSON.toString());
        server.setDoOutput(true);
        server.connect();
        PrintWriter out = new PrintWriter(server.getOutputStream());
        out.print("query=SELECT ?p ?v WHERE {<" + id.stringValue() + "> ?p ?v}");
        out.close();
        InputStream inst = server.getInputStream();
        byte[] buf = new byte[2048];
        int curs = 0;
        while (true) {
            int len = inst.read(buf, curs, buf.length - curs);
            if (len == -1) {
                break;
            }
            curs += len;
        }
        if (log.isInfoEnabled())
            log.info("Read in " + curs + " - " + new String(buf, 0, curs));
    } catch (Exception e) {
        e.printStackTrace();
    }

    // clear cached data
    ((ObjectMgrModel) om).clearCache();

    IGPO gpo = om.getGPO(id); // reads from backing journal

    assertTrue("Martyn".equals(gpo.getValue(keyname).stringValue()));
}

From source file:org.infoglue.igide.helper.http.HTTPTextDocumentListenerEngine.java

private void listen() {
    String errorMessage;//w  w  w  . j a v  a2s. c  o m
    boolean error;
    errorMessage = "";
    error = false;
    try {
        Logger.logConsole("Starting listen thread");
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(3000);
        urlConn.setRequestProperty("Connection", "Keep-Alive");
        urlConn.setReadTimeout(0);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(false);
        if (urlConn.getHeaderFields().toString().indexOf("401 Unauthorized") > -1) {
            Logger.logConsole("User has no access to the CMS - closing connection");
            throw new AccessControlException("User has no access to the CMS - closing connection");
        }
        String boundary = urlConn.getHeaderField("boundary");
        DataInputStream input = new DataInputStream(urlConn.getInputStream());
        StringBuffer buf = new StringBuffer();
        if (listener != null)
            listener.onConnection(url);
        String str = null;
        while ((str = input.readLine()) != null) {
            if (str.indexOf("XMLNotificationWriter.ping") == -1) {
                if (str.equals(boundary)) {
                    String message = buf.toString();

                    // By checking there is more in the String than the XML declaration we assume the message is valid
                    if (message != null
                            && !message.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").equals("")) {
                        if (listener != null)
                            listener.recieveDocument(buf.toString());
                        else
                            Logger.logConsole((new StringBuilder("NEW DOCUMENT!!\r\n")).append(buf.toString())
                                    .append("\r\n").toString());
                    }
                    buf = new StringBuffer();
                } else {
                    buf.append(str);
                }
            }
        }
        input.close();
    } catch (MalformedURLException me) {
        error = true;
        errorMessage = (new StringBuilder("Faulty CMS-url:")).append(url).toString();
        if (listener != null)
            listener.onException(me);
        else
            System.err.println((new StringBuilder("MalformedURLException: ")).append(me).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (IOException ioe) {
        error = true;
        errorMessage = "Got an I/O-Exception talking to the CMS. Check that it is started and in valid state.";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ioe.getMessage()).toString());
        if (listener != null)
            listener.onException(ioe);
        else
            Logger.logConsole((new StringBuilder("TextDocumentListener cannot connect to: "))
                    .append(url.toExternalForm()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (AccessControlException ace) {
        error = true;
        errorMessage = "The user you tried to connect with did not have the correct access rights. Check that he/she has roles etc enough to access the CMS";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ace.getMessage()).toString());
        if (listener != null)
            listener.onException(ace);
        else
            Logger.logConsole((new StringBuilder()).append(ace.getMessage()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Exception exception) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Throwable e) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e2) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e2.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    }
}

From source file:net.ae97.totalpermissions.update.UpdateChecker.java

@Override
public void run() {
    if (disabled) {
        return;// ww w  . j  a va  2  s  . c om
    }
    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectIds=54850");
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        if (apikey != null && !apikey.isEmpty() && !apikey.equals("PUT_API_KEY_HERE")) {
            conn.addRequestProperty("X-API-Key", apikey);
        }
        conn.addRequestProperty("User-Agent", "Updater - TotalPermissions-v" + pluginVersion);
        conn.setDoOutput(true);

        BufferedReader reader = null;
        JsonElement details = null;
        try {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String json = reader.readLine();
            JsonArray array = new JsonParser().parse(json).getAsJsonArray();
            details = array.get(array.size() - 1);
        } catch (IOException e) {
            if (e.getMessage().contains("HTTP response code: 403")) {
                throw new IOException("CurseAPI rejected API-KEY", e);
            }
            throw e;
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        if (details == null) {
            return;
        }

        String onlineVersion = details.getAsJsonObject().get("name").getAsString();

        if (!checkForUpdate(pluginVersion, onlineVersion)) {
            return;
        }

        pluginLogger.log(Level.INFO, "Update found! Current: {0} Latest: {1}",
                new String[] { StringUtils.join(getVersionInts(pluginVersion), "."),
                        StringUtils.join(getVersionInts(onlineVersion), ".") });

        if (!download) {
            return;
        }

        String downloadLink = details.getAsJsonObject().get("downloadUrl").getAsString();

        String pluginFileName = pluginFile.getName();

        if (!pluginFileName.equalsIgnoreCase(pluginName + ".jar")) {
            pluginLogger.log(Level.WARNING, "FILE NAME IS NOT {0}.jar! Forcing rename", pluginName);
            pluginFile.deleteOnExit();
        }

        File output = new File(Bukkit.getUpdateFolderFile(), pluginName + ".jar");
        download(downloadLink, output);

    } catch (MalformedURLException ex) {
        pluginLogger.log(Level.SEVERE, "URL could not be created", ex);
    } catch (IOException ex) {
        pluginLogger.log(Level.SEVERE, "Error occurred on checking for update for " + pluginName, ex);
    }
}

From source file:com.gmail.bleedobsidian.itemcase.Updater.java

/**
 * Query ServerMods API for project variables.
 *
 * @return If successful or not.//from   w w w.j av  a2s.  c o  m
 */
private boolean query() {
    try {
        final URLConnection con = this.url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        if (this.apiKey != null) {
            con.addRequestProperty("X-API-Key", this.apiKey);
        }

        con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater");

        con.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.result = UpdateResult.ERROR_ID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name");
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl");
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType");
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion");

        return true;
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.result = UpdateResult.ERROR_APIKEY;
        } else {
            this.result = UpdateResult.ERROR_SERVER;
        }

        return false;
    }

}

From source file:net.pms.configuration.DownloadPlugins.java

private boolean downloadFile(String url, String dir, String name) throws Exception {
    URL u = new URL(url);
    ensureCreated(dir);// w w  w .  j ava 2 s.c  om
    String fName = extractFileName(url, name);

    LOGGER.debug("fetch file " + url);
    if (updateLabel != null) {
        updateLabel.setText(Messages.getString("NetworkTab.47") + ": " + fName);
    }

    File f = new File(dir + File.separator + fName);
    if (f.exists()) {
        // no need to download it twice
        return true;
    }
    URLConnection connection = u.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    try (InputStream in = connection.getInputStream(); FileOutputStream out = new FileOutputStream(f)) {
        byte[] buf = new byte[4096];
        int len;

        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }

        out.flush();
    } catch (Exception e) {
        LOGGER.warn("Plugin download error: " + e);
    }

    if (fName.endsWith(".zip")) {
        for (String prop : props) {
            if (prop.equalsIgnoreCase("unzip")) {
                unzip(f, dir);
            }
        }
    }

    // If we got down here add the jar to the list (if it is a jar)
    if (f.getAbsolutePath().endsWith(".jar")) {
        jars.add(f.toURI().toURL());
    }
    return true;
}

From source file:org.dataconservancy.dcs.access.http.SeadDatastreamServlet.java

private void getFile(SeadFile file, OutputStream destination) {

    String filePath = null;// www .  ja va  2  s.  c om
    if (file.getPrimaryLocation().getType() != null && file.getPrimaryLocation().getType().length() > 0
            && file.getPrimaryLocation().getLocation() != null
            && file.getPrimaryLocation().getLocation().length() > 0
            && file.getPrimaryLocation().getName() != null
            && file.getPrimaryLocation().getName().length() > 0) {
        if ((file.getPrimaryLocation().getName()
                .equalsIgnoreCase(ArchiveEnum.Archive.IU_SCHOLARWORKS.getArchive()))
                || (file.getPrimaryLocation().getName()
                        .equalsIgnoreCase(ArchiveEnum.Archive.UIUC_IDEALS.getArchive()))) {
            URLConnection connection = null;
            try {
                String location = file.getPrimaryLocation().getLocation();
                location = location.replace("http://maple.dlib.indiana.edu:8245/",
                        "https://scholarworks.iu.edu/");
                connection = new URL(location).openConnection();
                connection.setDoOutput(true);
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
                    }

                    @Override
                    public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                } };
                if (connection.getURL().getProtocol().equalsIgnoreCase("https")) {
                    final SSLContext sslContext = SSLContext.getInstance("SSL");
                    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                    ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
                }
                IOUtils.copy(connection.getInputStream(), destination);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            } catch (KeyManagementException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            return;
        } else if (file.getPrimaryLocation().getType()
                .equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText())
                && file.getPrimaryLocation().getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) {
            filePath = file.getPrimaryLocation().getLocation();

            String[] pathArr = filePath.split("/");

            try {
                sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(),
                        config.getSdamount());
                sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')), pathArr[pathArr.length - 1],
                        destination);
                sftp.disConnectSession();
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (SftpException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (file.getSecondaryDataLocations() != null && file.getSecondaryDataLocations().size() > 0) {
            for (SeadDataLocation dataLocation : file.getSecondaryDataLocations()) {
                if (dataLocation.getType().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText())
                        && dataLocation.getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) {
                    filePath = dataLocation.getLocation();

                    String[] pathArr = filePath.split("/");

                    try {
                        sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(),
                                config.getSdamount());
                        sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')),
                                pathArr[pathArr.length - 1], destination);
                        sftp.disConnectSession();
                    } catch (JSchException e) {
                        e.printStackTrace();
                    } catch (SftpException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return;
}

From source file:com.allblacks.utils.web.HttpUtil.java

/**
 * Gets data from URL as char[] throws {@link RuntimeException} If anything
 * goes wrong// w  w  w.  j  a v a  2s  .  com
 * 
 * @return The content of the URL as a char[]
 * @throws java.io.IOException
 */
public byte[] postDataAsByteArray(String url, String contentType, String contentName, byte[] content)
        throws IOException {

    URLConnection urlc = null;
    OutputStream os = null;
    InputStream is = null;
    ByteArrayOutputStream bis = null;
    byte[] dat = null;
    final String boundary = "" + new Date().getTime();

    try {
        urlc = new URL(url).openConnection();
        urlc.setDoOutput(true);
        urlc.setRequestProperty(HttpUtil.CONTENT_TYPE,
                "multipart/form-data; boundary=---------------------------" + boundary);
        os = urlc.getOutputStream();

        String message1 = "-----------------------------" + boundary + HttpUtil.BNL;
        message1 += "Content-Disposition: form-data; name=\"nzbfile\"; filename=\"" + contentName + "\""
                + HttpUtil.BNL;
        message1 += "Content-Type: " + contentType + HttpUtil.BNL;
        message1 += HttpUtil.BNL;
        String message2 = HttpUtil.BNL + "-----------------------------" + boundary + "--" + HttpUtil.BNL;

        os.write(message1.getBytes());
        os.write(content);
        os.write(message2.getBytes());
        os.flush();

        if (urlc.getContentEncoding() != null && urlc.getContentEncoding().equalsIgnoreCase(HttpUtil.GZIP)) {
            is = new GZIPInputStream(urlc.getInputStream());
        } else {
            is = urlc.getInputStream();
        }

        bis = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bis.write(ch);
        }
        dat = bis.toByteArray();
    } catch (IOException exception) {
        throw exception;
    } finally {
        try {
            bis.close();
            os.close();
            is.close();
        } catch (Exception e) {
            // we do not care about this
        }
    }
    return dat;
}

From source file:com.allblacks.utils.web.HttpUtil.java

/**
 * Gets data from URL as char[] throws {@link RuntimeException} If anything
 * goes wrong//from ww w . j ava 2  s.  c om
 * 
 * @return The content of the URL as a char[]
 * @throws java.io.IOException
 */
public char[] postDataAsCharArray(String url, String contentType, String contentName, char[] content)
        throws IOException {

    URLConnection urlc = null;
    OutputStream os = null;
    InputStream is = null;
    CharArrayWriter dat = null;
    BufferedReader reader = null;
    String boundary = "" + new Date().getTime();

    try {
        urlc = new URL(url).openConnection();
        urlc.setDoOutput(true);
        urlc.setRequestProperty(HttpUtil.CONTENT_TYPE,
                "multipart/form-data; boundary=---------------------------" + boundary);

        String message1 = "-----------------------------" + boundary + HttpUtil.BNL;
        message1 += "Content-Disposition: form-data; name=\"nzbfile\"; filename=\"" + contentName + "\""
                + HttpUtil.BNL;
        message1 += "Content-Type: " + contentType + HttpUtil.BNL;
        message1 += HttpUtil.BNL;
        String message2 = HttpUtil.BNL + "-----------------------------" + boundary + "--" + HttpUtil.BNL;

        os = urlc.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName(HttpUtil.UTF_8)));

        writer.write(message1);
        writer.write(content);
        writer.write(message2);
        writer.flush();

        dat = new CharArrayWriter();
        if (urlc.getContentEncoding() != null && urlc.getContentEncoding().equalsIgnoreCase(HttpUtil.GZIP)) {
            is = new GZIPInputStream(urlc.getInputStream());
        } else {
            is = urlc.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(is, Charset.forName(HttpUtil.UTF_8)));

        int c;
        while ((c = reader.read()) != -1) {
            dat.append((char) c);
        }
    } catch (IOException exception) {
        throw exception;
    } finally {
        try {
            reader.close();
            os.close();
            is.close();
        } catch (Exception e) {
            // we do not care about this
        }
    }

    return dat.toCharArray();
}

From source file:com.moviejukebox.plugin.AnimatorPlugin.java

/**
 * Retrieve Animator matching the specified movie name and year.
 *
 * This routine is base on a Google request.
 *///from ww w .java 2 s  . c o  m
private String getAnimatorId(String movieName, String year) {
    try {
        String animatorId = Movie.UNKNOWN;
        String allmultsId = Movie.UNKNOWN;

        String sb = movieName;
        // Unaccenting letters
        sb = Normalizer.normalize(sb, Normalizer.Form.NFD);
        // Return simple letters '' & ''
        sb = sb.replaceAll("" + (char) 774, "");
        sb = sb.replaceAll("" + (char) 774, "");
        sb = sb.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");

        sb = "text=" + URLEncoder.encode(sb, "Cp1251").replace(" ", "+");

        // Get ID from animator.ru
        if (animatorDiscovery) {
            String uri = "http://www.animator.ru/db/?p=search&SearchMask=1&" + sb;
            if (StringTools.isValidString(year)) {
                uri = uri + "&year0=" + year;
                uri = uri + "&year1=" + year;
            }
            String xml = httpClient.request(uri);
            // Checking for zero results
            if (xml.contains("[?? ]")) {
                // It's search results page, searching a link to the movie page
                int beginIndex;
                if (-1 != xml.indexOf("? ")) {
                    for (String tmp : HTMLTools.extractTags(xml, "? ", HTML_TD, HTML_HREF,
                            "<br><br>")) {
                        if (0 < tmp.indexOf("[?? ]")) {
                            beginIndex = tmp.indexOf(" .)");
                            if (beginIndex >= 0) {
                                String year2 = tmp.substring(beginIndex - 4, beginIndex);
                                if (year2.equals(year)) {
                                    beginIndex = tmp.indexOf("http://www.animator.ru/db/?p=show_film&fid=",
                                            beginIndex);
                                    if (beginIndex >= 0) {
                                        StringTokenizer st = new StringTokenizer(tmp.substring(beginIndex + 43),
                                                " ");
                                        animatorId = st.nextToken();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Get ID from allmults.org
        if (multsDiscovery) {
            URL url = new URL("http://allmults.org/search.php");
            URLConnection conn = url.openConnection(YamjHttpClientBuilder.getProxy());
            conn.setDoOutput(true);

            OutputStreamWriter osWriter = null;
            StringBuilder xmlLines = new StringBuilder();

            try {
                osWriter = new OutputStreamWriter(conn.getOutputStream());
                osWriter.write(sb);
                osWriter.flush();

                try (InputStreamReader inReader = new InputStreamReader(conn.getInputStream(), "cp1251");
                        BufferedReader bReader = new BufferedReader(inReader)) {
                    String line;
                    while ((line = bReader.readLine()) != null) {
                        xmlLines.append(line);
                    }
                }

                osWriter.flush();
            } finally {
                if (osWriter != null) {
                    osWriter.close();
                }
            }

            if (xmlLines.indexOf("<div class=\"post\"") != -1) {
                for (String tmp : HTMLTools.extractTags(xmlLines.toString(),
                        "  ?  ", "<ul><li>", "<div class=\"entry\"",
                        "</div>")) {
                    int pos = tmp.indexOf("<img ");
                    if (pos != -1) {
                        int temp = tmp.indexOf(" alt=\"");
                        if (temp != -1) {
                            String year2 = tmp.substring(temp + 6, tmp.indexOf("\"", temp + 6) - 1);
                            year2 = year2.substring(year2.length() - 4);
                            if (year2.equals(year)) {
                                temp = tmp.indexOf(" src=\"/images/multiki/");
                                if (temp != -1) {
                                    allmultsId = tmp.substring(temp + 22, tmp.indexOf(".jpg", temp + 22));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        return (animatorId.equals(Movie.UNKNOWN) && allmultsId.equals(Movie.UNKNOWN)) ? Movie.UNKNOWN
                : animatorId + ":" + allmultsId;
    } catch (IOException error) {
        LOG.error("Failed retreiving Animator Id for movie : {}", movieName);
        LOG.error("Error : {}", error.getMessage());
        return Movie.UNKNOWN;
    }
}