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:net.sf.jabref.importer.fileformat.FreeCiteImporter.java

public ParserResult importEntries(String text) {
    // URLencode the string for transmission
    String urlencodedCitation = null;
    try {//from  www  .  j  a  v a  2  s .c om
        urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unsupported encoding", e);
    }

    // Send the request
    URL url;
    URLConnection conn;
    try {
        url = new URL("http://freecite.library.brown.edu/citations/create");
        conn = url.openConnection();
    } catch (MalformedURLException e) {
        LOGGER.warn("Bad URL", e);
        return new ParserResult();
    } catch (IOException e) {
        LOGGER.warn("Could not download", e);
        return new ParserResult();
    }
    try {
        conn.setRequestProperty("accept", "text/xml");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        String data = "citation=" + urlencodedCitation;
        // write parameters
        writer.write(data);
        writer.flush();
    } catch (IllegalStateException e) {
        LOGGER.warn("Already connected.", e);
    } catch (IOException e) {
        LOGGER.warn("Unable to connect to FreeCite online service.", e);
        return ParserResult
                .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
    }
    // output is in conn.getInputStream();
    // new InputStreamReader(conn.getInputStream())
    List<BibEntry> res = new ArrayList<>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
        while (parser.hasNext()) {
            if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT)
                    && "citation".equals(parser.getLocalName())) {
                parser.nextTag();

                StringBuilder noteSB = new StringBuilder();

                BibEntry e = new BibEntry();
                // fallback type
                EntryType type = BibtexEntryTypes.INPROCEEDINGS;

                while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT)
                        && "citation".equals(parser.getLocalName()))) {
                    if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                        String ln = parser.getLocalName();
                        if ("authors".equals(ln)) {
                            StringBuilder sb = new StringBuilder();
                            parser.nextTag();

                            while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                                // author is directly nested below authors
                                assert "author".equals(parser.getLocalName());

                                String author = parser.getElementText();
                                if (sb.length() == 0) {
                                    // first author
                                    sb.append(author);
                                } else {
                                    sb.append(" and ");
                                    sb.append(author);
                                }
                                assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
                                assert "author".equals(parser.getLocalName());
                                parser.nextTag();
                                // current tag is either begin:author or
                                // end:authors
                            }
                            e.setField(FieldName.AUTHOR, sb.toString());
                        } else if (FieldName.JOURNAL.equals(ln)) {
                            // we guess that the entry is a journal
                            // the alternative way is to parse
                            // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
                            // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
                            // we would have to change the whole parser to parse that format.
                            type = BibtexEntryTypes.ARTICLE;
                            e.setField(ln, parser.getElementText());
                        } else if ("tech".equals(ln)) {
                            type = BibtexEntryTypes.TECHREPORT;
                            // the content of the "tech" field seems to contain the number of the technical report
                            e.setField(FieldName.NUMBER, parser.getElementText());
                        } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln)
                                || FieldName.NUMBER.equals(ln) || "note".equals(ln)
                                || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln)
                                || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln)
                                || FieldName.YEAR.equals(ln)) {
                            e.setField(ln, parser.getElementText());
                        } else if ("booktitle".equals(ln)) {
                            String booktitle = parser.getElementText();
                            if (booktitle.startsWith("In ")) {
                                // special treatment for parsing of
                                // "In proceedings of..." references
                                booktitle = booktitle.substring(3);
                            }
                            e.setField("booktitle", booktitle);
                        } else if ("raw_string".equals(ln)) {
                            // raw input string is ignored
                        } else {
                            // all other tags are stored as note
                            noteSB.append(ln);
                            noteSB.append(':');
                            noteSB.append(parser.getElementText());
                            noteSB.append(Globals.NEWLINE);
                        }
                    }
                    parser.next();
                }

                if (noteSB.length() > 0) {
                    String note;
                    if (e.hasField("note")) {
                        // "note" could have been set during the parsing as FreeCite also returns "note"
                        note = e.getFieldOptional("note").get().concat(Globals.NEWLINE)
                                .concat(noteSB.toString());
                    } else {
                        note = noteSB.toString();
                    }
                    e.setField("note", note);
                }

                // type has been derived from "genre"
                // has to be done before label generation as label generation is dependent on entry type
                e.setType(type);

                // autogenerate label (BibTeX key)
                LabelPatternUtil.makeLabel(
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs);

                res.add(e);
            }
            parser.next();
        }
        parser.close();
    } catch (IOException | XMLStreamException ex) {
        LOGGER.warn("Could not parse", ex);
        return new ParserResult();
    }

    return new ParserResult(res);
}

From source file:io.starter.datamodel.Sys.java

/**
 * Get the /1.0/application.wadl/* ww w .j a v a2 s .c  om*/
 * 
 * TODO: implement extended WADL Apply XSLT to the WADL output to generate
 * human-readable api docs per: https://wikis.oracle.com/display/Jersey/WADL
 * 
 * 
 * @return
 * @throws IOException
 * @throws TransformerException
 */
@GET
@Path("apidocs")
@Produces(MediaType.TEXT_HTML)
public String getWADL(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse)
        throws IOException, TransformerException {

    servletResponse.addHeader("Access-Control-Allow-Origin", "*");

    // Transform the WADL to HTML using XSLT
    TransformerFactory factory = TransformerFactory.newInstance();

    // Make a URL to the XML
    String iserv = servletRequest.getScheme() + "://" + servletRequest.getServerName() + ":"
            + servletRequest.getServerPort() + "/" + SystemConstants.REST_BASE_PATH + "/";
    URL url = new URL(iserv + WADL_SOURCE_URL);

    URLConnection con = url.openConnection();
    con.setDoOutput(true);
    Source text = new StreamSource(con.getInputStream());

    // path to the XSLT
    URL urlx = new URL(SystemConstants.REST_API_SERVER_HOST + "/wadl_html_doc.xslt");
    HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();

    InputStream is = null;

    is = new BufferedInputStream(urlConnection.getInputStream());

    Source xslt = new StreamSource(is);

    Transformer transformer = factory.newTransformer(xslt);
    servletResponse.setContentType("text/html");
    OutputStream ous = servletResponse.getOutputStream();

    transformer.transform(text, new StreamResult(ous));
    ous.flush();
    ous.close();

    return "ok";
}

From source file:org.ixdhof.speechrecognizer.Recognizer.java

private void do_recognize(String waveString, String language) throws Exception {
    //"en-US"// w w w  .j  a  v a 2 s .c om

    URL url;
    URLConnection urlConn;
    OutputStream outputStream;
    BufferedReader br;

    File waveFile = new File(parent.sketchPath(waveString));

    FlacEncoder flacEncoder = new FlacEncoder();
    File flacFile = new File(waveFile + ".flac");

    flacEncoder.convertWaveToFlac(waveFile, flacFile);

    // URL of Remote Script.
    url = new URL(GOOGLE_RECOGNIZER_URL_NO_LANG + language);

    // Open New URL connection channel.
    urlConn = url.openConnection();

    // we want to do output.
    urlConn.setDoOutput(true);

    // No caching
    urlConn.setUseCaches(false);

    // Specify the header content type.
    urlConn.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");

    // Send POST output.
    outputStream = urlConn.getOutputStream();

    FileInputStream fileInputStream = new FileInputStream(flacFile.getAbsolutePath());

    byte[] buffer = new byte[256];

    while ((fileInputStream.read(buffer, 0, 256)) != -1) {
        outputStream.write(buffer, 0, 256);
    }

    fileInputStream.close();
    outputStream.close();

    // Get response data.
    br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

    response = br.readLine();

    br.close();

    flacFile.delete();
    waveFile.delete();

    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(response);
        JSONObject jsonObject = (JSONObject) obj;
        HashMap returnValues = new HashMap();

        if (response.contains("utterance")) {
            status = (int) (long) (Long) jsonObject.get("status");
            id = (String) jsonObject.get("id");
            JSONArray hypotheses_array = (JSONArray) jsonObject.get("hypotheses");
            JSONObject hypotheses = (JSONObject) hypotheses_array.get(0);
            utterance = (String) hypotheses.get("utterance");
            confidence = (float) (double) (Double) hypotheses.get("confidence");
        } else {
            utterance = null;
        }

        if (recognizerEvent != null) {
            try {
                recognizerEvent.invoke(parent, new Object[] { utterance });
            } catch (Exception e) {
                System.err.println("Disabling recognizerEvent()");
                e.printStackTrace();
                recognizerEvent = null;
            }
        }
    } catch (Exception e) {
        parent.println(e);
    }

    recognizing = false;
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageMetaInfo.java

/**
 * Attempts to establish what the last modified date of the given resource is. If the last modified date cannot
 * be etablished -1 is returned//from w  ww. java  2 s  . co m
 *
 * @param resource The Resource to evaluate
 * @return The last modified date or -1
 */
private long establishLastModified(Resource resource) {
    if (resource == null)
        return -1;

    if (resource instanceof FileSystemResource) {
        return ((FileSystemResource) resource).getFile().lastModified();
    }

    long last;
    URLConnection urlc = null;

    try {
        URL url = resource.getURL();
        if ("file".equals(url.getProtocol())) {
            File file = new File(url.getFile());
            if (file.exists()) {
                return file.lastModified();
            }
        }
        urlc = url.openConnection();
        urlc.setDoInput(false);
        urlc.setDoOutput(false);
        last = urlc.getLastModified();
    } catch (FileNotFoundException fnfe) {
        last = -1;
    } catch (IOException e) {
        last = -1;
    } finally {
        if (urlc != null) {
            try {
                InputStream is = urlc.getInputStream();
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return last;
}

From source file:com.krawler.spring.mailIntegration.mailIntegrationController.java

public JSONObject getRecentEmailDetails(HttpServletRequest request, String recid, String emailadd)
        throws ServiceException {
    JSONObject jobj = new JSONObject();
    try {/*w  ww. jav a  2 s  .c o  m*/
        DateFormat userdft = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        String dateFormatId = sessionHandlerImpl.getDateFormatID(request);
        String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request);
        String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request);
        String userid = sessionHandlerImpl.getUserid(request);
        userdft = KwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId, timeZoneDiff);
        String url = StorageHandler.GetSOAPServerUrl();
        String res = "";
        String str = "";
        String pass = "";
        String currUser = sessionHandlerImplObj.getUserName(request) + "_";
        String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
        //String emailadd = request.getParameter("email");
        JSONObject currUserAuthInfo = new JSONObject(jsonStr);
        if (currUserAuthInfo.has("userhash")) {
            currUser += currUserAuthInfo.getString("subdomain");
            pass = currUserAuthInfo.getString("userhash");
        }
        str = "username=" + currUser + "&user_hash=" + pass;
        str = str
                + "&action=EmailUIAjax&emailUIAction=rebuildShowAccount&krawler_body_only=true&module=Emails&to_pdf=true";

        URL u = new URL(url + "krawlermails.php");
        URLConnection uc = u.openConnection();
        uc.setDoOutput(true);
        uc.setUseCaches(false);
        uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.println(str);
        pw.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line = "";

        while ((line = in.readLine()) != null) {
            res += line;
        }
        in.close();
        boolean flag = true;
        try {
            JSONArray jarr = new JSONArray(res);
        } catch (JSONException ex) {
            flag = false;
        }
        if (flag) {
            String ieId = "";
            JSONArray jarr = new JSONArray(res);
            for (int cnt = 0; cnt < jarr.length(); cnt++) {
                JSONObject tempObj = jarr.getJSONObject(cnt);
                if (!StringUtil.isNullOrEmpty(tempObj.getString("value"))) {
                    ieId += tempObj.getString("value") + ",";
                }
            }

            if (ieId.length() > 0) {
                ieId = ieId.substring(0, ieId.length() - 1);
                str = "username=" + currUser + "&user_hash=" + pass;
                str = str + "&ieId=" + ieId + "&fromaddr=" + emailadd + "&mbox=INBOX";
                res = StringUtil.makeExternalRequest(url + "getSendersMails.php", str);
            } else {
                res = "{\"count\":0,\"data\":{}}";
            }

            JSONObject resJobj = new JSONObject();
            try {
                resJobj = new JSONObject(res);
            } catch (Exception ex) {
                resJobj = new JSONObject("{\"count\":0,\"data\":{}}");
            }
            JSONArray FinalArr = new JSONArray();
            if (resJobj.optInt("count", 0) > 0) {
                JSONArray jArr = resJobj.getJSONArray("data");
                for (int i = 0; i < jArr.length(); i++) {
                    JSONObject tmpobj = jArr.getJSONObject(i);
                    Date sendDateObj = sdf.parse(tmpobj.getString("senddate"));
                    String senddate = userdft.format(sendDateObj);
                    JSONObject obj = new JSONObject();
                    obj.put("docid", tmpobj.getString("imap_uid"));
                    obj.put("subject", tmpobj.getString("subject"));
                    obj.put("fromaddr", tmpobj.getString("fromaddr"));
                    obj.put("toaddr", tmpobj.getString("toaddr"));
                    obj.put("senddate", senddate);
                    obj.put("ie_id", tmpobj.getString("ie_id"));
                    obj.put("seen", tmpobj.getString("seen"));
                    //                    obj.put("time", AuthHandler.getUserDateFormatter(request, session).format(sdf.parse(tmpobj.getString("senddate"))));
                    obj.put("time", senddate);
                    obj.put("timeobj", sendDateObj);
                    obj.put("details", tmpobj.getString("subject"));
                    obj.put("folder", "Inbox");
                    obj.put("imgsrc", "../../images/inbox.png");
                    FinalArr.put(obj);
                }
            }

            // fetched Sent Items

            // get sent folder id
            //            String sentid = "";
            //            str = "username="+currUser+"&user_hash="+pass;
            //            str = str + "&action=EmailUIAjax&emailUIAction=refreshKrawlerFolders&krawler_body_only=true&module=Emails&to_pdf=true";
            //            res = StringUtil.makeExternalRequest(url+"getSendersMails.php",str);
            //            resJobj = new JSONObject(res);
            //            if(resJobj.has("children")) {
            //                JSONArray childArray = resJobj.getJSONArray("children");
            //                for(int cnt = 0; cnt< childArray.length(); cnt++) {
            //                    if(childArray.getJSONObject(cnt).getString("folder_type").equals("folder_type")) {
            //                        sentid = childArray.getJSONObject(cnt).getString("folder_type");
            //                    }
            //                }
            //            }
            //
            //            if(!StringUtil.isNullOrEmpty(sentid)) {
            //                str = "username="+currUser+"&user_hash="+pass;
            //                str = str + "&action=EmailUIAjax&emailUIAction=getMessageListKrawlerFoldersXML&module=Emails&to_pdf=true&start=0&limit=20&forceRefresh=false&mbox=Sent%20Emails&ieId="+sentid;
            //                res = StringUtil.makeExternalRequest(url+"krawlermails.php",str);
            //            }

            str = "userid=" + userid + "&username=" + currUser + "&user_hash=" + pass;
            str = str + "&fromaddr=" + emailadd + "&mbox=sent";
            res = StringUtil.makeExternalRequest(url + "getSendersMails.php", str);
            try {
                resJobj = new JSONObject(res);
            } catch (Exception ex) {
                resJobj = new JSONObject("{\"count\":0,\"data\":{}}");
            }
            if (resJobj.optInt("count", 0) > 0) {
                JSONArray jArr = resJobj.getJSONArray("data");
                for (int i = 0; i < jArr.length(); i++) {
                    JSONObject tmpobj = jArr.getJSONObject(i);
                    Date sendDateObj = sdf.parse(tmpobj.getString("date_sent"));
                    String senddate = userdft.format(sendDateObj);
                    JSONObject obj = new JSONObject();
                    obj.put("docid", tmpobj.getString("id"));
                    obj.put("subject", tmpobj.getString("name"));
                    obj.put("fromaddr", tmpobj.getString("from_addr"));
                    obj.put("toaddr", tmpobj.getString("to_addrs"));
                    obj.put("senddate", senddate);
                    //                    obj.put("ie_id", tmpobj.getString("ieId"));
                    obj.put("seen", tmpobj.getString("status").equals("unread") ? 0 : 1);
                    obj.put("time", senddate);
                    obj.put("details", tmpobj.getString("name"));
                    obj.put("timeobj", sendDateObj);
                    obj.put("folder", "Sent Item");
                    obj.put("imgsrc", "../../images/outbox.png");
                    FinalArr.put(obj);
                }
            }

            for (int i = 0; i < FinalArr.length(); i++) {
                for (int j = 0; j < FinalArr.length(); j++) {
                    if (((Date) (FinalArr.getJSONObject(i).get("timeobj")))
                            .after((Date) (FinalArr.getJSONObject(j).get("timeobj")))) {
                        JSONObject jobj1 = FinalArr.getJSONObject(i);
                        FinalArr.put(i, FinalArr.getJSONObject(j));
                        FinalArr.put(j, jobj1);
                    }
                }
            }
            jobj.put("emailList", FinalArr);
        } else {
            jobj.put("emailList", new JSONArray());
        }

    } catch (JSONException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (SessionExpiredException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (HibernateException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (Exception e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return jobj;
}

From source file:com.dsh105.commodus.data.Updater.java

private boolean read() {
    try {/*w w w  . j  av  a  2 s  .  c om*/
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", "Updater (by Gravity)");

        conn.setDoOutput(true);

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

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

        if (array.size() == 0) {
            this.plugin.getLogger()
                    .warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1))
                .get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.plugin.getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
            this.plugin.getLogger().warning(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        e.printStackTrace();
        return false;
    }
}

From source file:com.senseidb.servlet.AbstractSenseiClientServlet.java

private void handleJMXRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    InputStream is = null;/*from   www.j  a  v a  2s  .  co  m*/
    OutputStream os = null;
    try {
        String myPath = req.getRequestURI().substring(req.getServletPath().length() + 11);
        URL adminUrl = null;
        if (myPath.indexOf('/') > 0) {
            adminUrl = new URL(
                    new StringBuilder(URLDecoder.decode(myPath.substring(0, myPath.indexOf('/')), "UTF-8"))
                            .append("/admin/jmx").append(myPath.substring(myPath.indexOf('/'))).toString());
        } else {
            adminUrl = new URL(
                    new StringBuilder(URLDecoder.decode(myPath, "UTF-8")).append("/admin/jmx").toString());
        }

        URLConnection conn = adminUrl.openConnection();

        byte[] buffer = new byte[8192]; // 8k
        int len = 0;

        InputStream ris = req.getInputStream();

        while ((len = ris.read(buffer)) > 0) {
            if (!conn.getDoOutput()) {
                conn.setDoOutput(true);
                os = conn.getOutputStream();
            }
            os.write(buffer, 0, len);
        }
        if (os != null)
            os.flush();

        is = conn.getInputStream();
        OutputStream ros = resp.getOutputStream();

        while ((len = is.read(buffer)) > 0) {
            ros.write(buffer, 0, len);
        }
        ros.flush();
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    } finally {
        if (is != null)
            is.close();
        if (os != null)
            os.close();
    }
}

From source file:bammerbom.ultimatecore.bukkit.UltimateUpdater.java

/**
 * Make a connection to the BukkitDev API and request the newest file's
 * details.//from  www .  j  a  v  a 2  s.co  m
 *
 * @return true if successful.
 */
private boolean read() {
    try {
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        conn.addRequestProperty("User-Agent", UltimateUpdater.USER_AGENT);

        conn.setDoOutput(true);

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

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

        if (array.isEmpty()) {
            r.log("No updates found.");
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        UltimateUpdater.versionName = (String) ((Map) array.get(array.size() - 1))
                .get(UltimateUpdater.TITLE_VALUE);
        this.versionLink = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.LINK_VALUE);
        this.versionType = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.TYPE_VALUE);
        this.versionGameVersion = (String) ((Map) array.get(array.size() - 1))
                .get(UltimateUpdater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            r.log("Invalid API key.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            r.log("Could not connect to bukkit.org, update check failed. "
                    + (e.getCause() != null ? "(" + e.getCause() + ")" : ""));
            this.result = UpdateResult.FAIL_DBO;
        }
        return false;
    }
}

From source file:com.quartercode.quarterbukkit.api.query.ServerModsAPIQuery.java

/**
 * Executes the stored query and returns the result as a {@link JSONArray}.
 * The query string ({@link #getQuery()}) is attached to {@code https://api.curseforge.com/servermods/}.
 * The GET response of that {@link URL} is then parsed to a {@link JSONArray}.
 * //from www  .  j a v  a  2 s.  c  o m
 * @return The response of the server mods api.
 * @throws QueryException Something goes wrong while querying the server mods api.
 */
public JSONArray execute() throws QueryException {

    // Build request url using the query
    URL requestUrl = null;
    try {
        requestUrl = new URL(HOST + query);
    } catch (MalformedURLException e) {
        throw new QueryException(QueryExceptionType.MALFORMED_URL, this, HOST + query, e);
    }

    // Open connection to request url
    URLConnection request = null;
    try {
        request = requestUrl.openConnection();
    } catch (IOException e) {
        throw new QueryException(QueryExceptionType.CANNOT_OPEN_CONNECTION, this, requestUrl.toExternalForm(),
                e);
    }

    // Set connection timeout
    request.setConnectTimeout(CONNECTION_TIMEOUT);

    // Set user agent
    request.addRequestProperty("User-Agent", USER_AGENT);

    // Set api key (if provided)
    String apiKey = QuarterBukkit.getPlugin().getConfig().getString("server-mods-api-key");
    if (apiKey != null && !apiKey.isEmpty()) {
        request.addRequestProperty("X-API-Key", apiKey);
    }

    // We want to read the results
    request.setDoOutput(true);

    // Read first line from the response
    BufferedReader reader = null;
    String response = null;
    try {
        reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        response = reader.readLine();
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            throw new QueryException(QueryExceptionType.INVALID_API_KEY, this, requestUrl.toExternalForm(), e);
        } else {
            throw new QueryException(QueryExceptionType.CANNOT_READ_RESPONSE, this, requestUrl.toExternalForm(),
                    e);
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this,
                        requestUrl.toExternalForm(), e);
            }
        }
    }

    // Parse the response
    Object jsonResponse = JSONValue.parse(response);

    if (jsonResponse instanceof JSONArray) {
        return (JSONArray) jsonResponse;
    } else {
        throw new QueryException(QueryExceptionType.INVALID_RESPONSE, this, requestUrl.toExternalForm());
    }
}

From source file:com.taiter.ce.Main.java

public void updateCheck() {
    try {//from  w w w.j  a  va  2s.com
        Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] Checking for updates...");

        URLConnection connection = updateListURL.openConnection();
        connection.setConnectTimeout(5000);
        connection.addRequestProperty("User-Agent", "Custom Enchantments - Update Checker");
        connection.setDoOutput(true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        JSONObject newestUpdate = (JSONObject) array.get(array.size() - 1);

        newVersion = newestUpdate.get("name").toString().replace("Custom Enchantments ", "").trim();
        newMD5 = newestUpdate.get("md5").toString();

        int newLength = newVersion.length();
        int currentLength = currentVersion.length();

        double versionNew;
        double versionCurrent;

        Boolean newHasSubVersion = false;
        Boolean currentHasSubVersion = false;

        try {
            versionNew = Double.parseDouble(newVersion);
        } catch (NumberFormatException ex) {
            newHasSubVersion = true;
            versionNew = Double.parseDouble(newVersion.substring(0, newVersion.length() - 1));
        }

        try {
            versionCurrent = Double.parseDouble(currentVersion);
        } catch (NumberFormatException ex) {
            currentHasSubVersion = true;
            versionCurrent = Double.parseDouble(currentVersion.substring(0, currentVersion.length() - 1));
        }

        if ((versionNew > versionCurrent) || ((versionNew == versionCurrent) && newHasSubVersion
                && currentHasSubVersion && ((byte) newVersion.toCharArray()[newLength
                        - 1] > (byte) currentVersion.toCharArray()[currentLength - 1]))) {
            hasUpdate = true;
            updateDownloadURL = new URL(newestUpdate.get("downloadUrl").toString().replace("\\.", ""));
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] A new update is available!");
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] The new version is " + ChatColor.AQUA
                    + newVersion + ChatColor.GREEN + ".");
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] You are currently using "
                    + ChatColor.AQUA + currentVersion + ChatColor.GREEN + ".");
            Bukkit.getConsoleSender().sendMessage(
                    ChatColor.GREEN + "[CE] You can use '/ce update applyupdate' to update automatically.");

        } else {
            hasUpdate = false;
            Bukkit.getConsoleSender()
                    .sendMessage(ChatColor.GREEN + "[CE] You are using the latest Version of CE!");
        }
        hasChecked = true;
    } catch (IOException ioex) {
        Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] Failed to check for updates");
    }

}