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:junk.gui.HazardDataSetCalcCondorApp.java

/**
 * sets up the connection with the servlet on the server (gravity.usc.edu)
 *//*from w w  w  .j  a va  2s  .  c  om*/
private void sendParametersToServlet(SitesInGriddedRegion regionSites,
        ScalarIntensityMeasureRelationshipAPI imr, String eqkRupForecastLocation) {

    try {
        if (D)
            System.out.println("starting to make connection with servlet");
        URL hazardMapServlet = new URL(SERVLET_URL);

        URLConnection servletConnection = hazardMapServlet.openConnection();
        if (D)
            System.out.println("connection established");

        // inform the connection that we will send output and accept input
        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);

        // Don't use a cached version of URL connection.
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        // Specify the content type that we will send binary data
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream());

        //sending the object of the gridded region sites to the servlet
        toServlet.writeObject(regionSites);
        //sending the IMR object to the servlet
        toServlet.writeObject(imr);
        //sending the EQK forecast object to the servlet
        toServlet.writeObject(eqkRupForecastLocation);
        //send the X values in a arraylist
        ArrayList list = new ArrayList();
        for (int i = 0; i < function.getNum(); ++i)
            list.add(new String("" + function.getX(i)));
        toServlet.writeObject(list);
        // send the MAX DISTANCE
        toServlet.writeObject(maxDistance);

        //sending email address to the servlet
        toServlet.writeObject(emailText.getText());
        //sending the parameters info. to the servlet
        toServlet.writeObject(getParametersInfo());

        //sending the dataset id to the servlet
        toServlet.writeObject(datasetIdText.getText());

        toServlet.flush();
        toServlet.close();

        // Receive the datasetnumber from the servlet after it has received all the data
        ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream());
        String dataset = fromServlet.readObject().toString();
        JOptionPane.showMessageDialog(this, dataset);
        if (D)
            System.out.println("Receiving the Input from the Servlet:" + dataset);
        fromServlet.close();

    } catch (Exception e) {
        ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo());
        bugWindow.setVisible(true);
        bugWindow.pack();
    }
}

From source file:org.n52.wps.server.request.strategy.WCS111XMLEmbeddedBase64OutputReferenceStrategy.java

@Override
public ReferenceInputStream fetchData(InputType input) throws ExceptionReport {

    String dataURLString = input.getReference().getHref();

    String schema = input.getReference().getSchema();
    String encoding = input.getReference().getEncoding();
    String mimeType = input.getReference().getMimeType();

    try {/*from   w w  w. ja  v  a 2  s .c  o  m*/
        URL dataURL = new URL(dataURLString);
        // Do not give a direct inputstream.
        // The XML handlers cannot handle slow connections
        URLConnection conn = dataURL.openConnection();
        conn.setRequestProperty("Accept-Encoding", "gzip");
        conn.setRequestProperty("Content-type", "multipart/mixed");
        //Handling POST with referenced document
        if (input.getReference().isSetBodyReference()) {
            String bodyReference = input.getReference().getBodyReference().getHref();
            URL bodyReferenceURL = new URL(bodyReference);
            URLConnection bodyReferenceConn = bodyReferenceURL.openConnection();
            bodyReferenceConn.setRequestProperty("Accept-Encoding", "gzip");
            InputStream referenceInputStream = retrievingZippedContent(bodyReferenceConn);
            IOUtils.copy(referenceInputStream, conn.getOutputStream());
        }
        //Handling POST with inline message
        else if (input.getReference().isSetBody()) {
            conn.setDoOutput(true);

            input.getReference().getBody().save(conn.getOutputStream());
        }
        InputStream inputStream = retrievingZippedContent(conn);

        BufferedReader bRead = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";

        //boundary between different content types
        String boundary = "";

        boolean boundaryFound = false;

        boolean encodedImagepart = false;

        String encodedImage = "";

        //e.g. base64
        String contentTransferEncoding = "";

        String imageContentType = "";

        int boundaryCount = 0;

        while ((line = bRead.readLine()) != null) {

            if (line.contains("boundary")) {
                boundary = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                boundaryFound = true;
                continue;
            }
            if (boundaryFound) {
                if (line.contains(boundary)) {
                    boundaryCount++;
                    continue;
                }
            }

            if (encodedImagepart) {
                encodedImage = encodedImage.concat(line);
            }
            //is the image always the third part?!
            else if (boundaryCount == 2) {
                if (line.contains("Content-Type")) {
                    imageContentType = line.substring(line.indexOf(":") + 1).trim();
                } else if (line.contains("Content-Transfer-Encoding")) {
                    contentTransferEncoding = line.substring(line.indexOf(":") + 1).trim();
                } else if (line.contains("Content-ID")) {
                    /*   just move further one line (which is hopefully empty)
                     *    and start parsing the encoded image             
                     */
                    line = bRead.readLine();
                    encodedImagepart = true;
                }
            }

        }

        return new ReferenceInputStream(
                new Base64InputStream(new ByteArrayInputStream(encodedImage.getBytes())), imageContentType,
                null); // encoding is null since encoding was removed
    } catch (RuntimeException e) {
        throw new ExceptionReport("Error occured while parsing XML", ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (MalformedURLException e) {
        String inputID = input.getIdentifier().getStringValue();
        throw new ExceptionReport(
                "The inputURL of the execute is wrong: inputID: " + inputID + " | dataURL: " + dataURLString,
                ExceptionReport.INVALID_PARAMETER_VALUE);
    } catch (IOException e) {
        String inputID = input.getIdentifier().getStringValue();
        throw new ExceptionReport("Error occured while receiving the complexReferenceURL: inputID: " + inputID
                + " | dataURL: " + dataURLString, ExceptionReport.INVALID_PARAMETER_VALUE);
    }
}

From source file:org.geotools.data.shapefile.ShpFiles.java

/**
 * Opens a output stream for the indicated file. A write lock is requested at the method call and
 * released on close.//from   w w  w . jav  a 2 s  . co  m
 * 
 * @param type
 *           the type of file to open the stream to.
 * @param requestor
 *           the object requesting the stream
 * @return an output stream
 * 
 * @throws IOException
 *            if a problem occurred opening the stream.
 */
public OutputStream getOutputStream(ShpFileType type, final FileWriter requestor) throws IOException {
    final URL url = acquireWrite(type, requestor);

    try {

        OutputStream out;
        if (isLocal()) {
            File file = DataUtilities.urlToFile(url);
            out = new FileOutputStream(file);
        } else {
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            out = connection.getOutputStream();
        }

        FilterOutputStream output = new FilterOutputStream(out) {

            private volatile boolean closed = false;

            @Override
            public void close() throws IOException {
                try {
                    super.close();
                } finally {
                    if (!closed) {
                        closed = true;
                        unlockWrite(url, requestor);
                    }
                }
            }

        };

        return output;
    } catch (Throwable e) {
        unlockWrite(url, requestor);
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof Error) {
            throw (Error) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:net.solarnetwork.node.support.HttpClientSupport.java

/**
 * Get a URLConnection for a specific URL and HTTP method.
 * /*ww w.  j ava2s.  c o m*/
 * <p>
 * If the httpMethod equals {@code POST} then the connection's
 * {@code doOutput} property will be set to <em>true</em>, otherwise it will
 * be set to <em>false</em>. The {@code doInput} property is always set to
 * <em>true</em>.
 * </p>
 * 
 * <p>
 * This method also sets up the request property
 * {@code Accept-Encoding: gzip,deflate} so the response can be compressed.
 * The {@link #getInputSourceFromURLConnection(URLConnection)} automatically
 * handles compressed responses.
 * </p>
 * 
 * <p>
 * If the {@link #getSslService()} property is configured and the URL
 * represents an HTTPS connection, then that factory will be used to for the
 * connection.
 * </p>
 * 
 * @param url
 *        the URL to connect to
 * @param httpMethod
 *        the HTTP method
 * @param accept
 *        the HTTP Accept header value
 * @return the URLConnection
 * @throws IOException
 *         if any IO error occurs
 */
protected URLConnection getURLConnection(String url, String httpMethod, String accept) throws IOException {
    URL connUrl = new URL(url);
    URLConnection conn = connUrl.openConnection();
    if (conn instanceof HttpURLConnection) {
        HttpURLConnection hConn = (HttpURLConnection) conn;
        hConn.setRequestMethod(httpMethod);
    }
    if (sslService != null && conn instanceof HttpsURLConnection) {
        SSLService service = sslService.service();
        if (service != null) {
            SSLSocketFactory factory = service.getSolarInSocketFactory();
            if (factory != null) {
                HttpsURLConnection hConn = (HttpsURLConnection) conn;
                hConn.setSSLSocketFactory(factory);
            }
        }
    }
    conn.setRequestProperty("Accept", accept);
    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
    conn.setDoInput(true);
    conn.setDoOutput(HTTP_METHOD_POST.equalsIgnoreCase(httpMethod));
    conn.setConnectTimeout(this.connectionTimeout);
    conn.setReadTimeout(connectionTimeout);
    return conn;
}

From source file:com.fluidops.iwb.widget.ImportRDFWidget.java

private FButton createRefineButton(final FTextInput2 context, final FTextInput2 baseURI, final FContainer stat,
        final FTextInput2 project, final FTextInput2 refineFormat, final FTextInput2 refineURL,
        final FTextInput2 engine, final FCheckBox keepSourceCtx, final FCheckBox contextEditable) {
    return new FButton("refineButton", "Import RDF Data") {
        @Override/*ww w  .j a  v  a2  s .  co  m*/
        public void onClick() {

            try {
                getBasicInput(context, baseURI);
            } catch (Exception e) {
                stat.hide(true);
                logger.info(e.getMessage());
                return;
            }

            if (engine.getInput().length() > 0 && project.getInput().length() > 0
                    && refineFormat.getInput().length() > 0 && refineURL.getInput().length() > 0) {
                Map<String, String> parameter = new HashMap<String, String>();
                parameter.put(engine.getName(), engine.getInput());
                parameter.put(project.getName(), project.getInput());
                parameter.put(refineFormat.getName(), refineFormat.getInput());
                URL urlValue = null;
                try {
                    urlValue = new URL(refineURL.getInput());
                } catch (MalformedURLException e) {
                    stat.hide(true);

                    getPage().getPopupWindowInstance().showError(refineURL.getInput() + " is not a valid URL");
                    logger.error(e.getMessage(), e);
                    return;
                }
                OutputStreamWriter wr = null;
                InputStream input = null;
                try {
                    // Collect the request parameters
                    StringBuilder params = new StringBuilder();
                    for (Entry<String, String> entry : parameter.entrySet())
                        params.append(StringUtil.urlEncode(entry.getKey())).append("=")
                                .append(StringUtil.urlEncode(entry.getValue())).append("&");

                    // Send data
                    URLConnection urlcon = urlValue.openConnection();
                    urlcon.setDoOutput(true);
                    wr = new OutputStreamWriter(urlcon.getOutputStream());
                    wr.write(params.toString());
                    wr.flush();

                    // Get the response
                    input = urlcon.getInputStream();
                    importData(this, input, baseUri, RDFFormat.RDFXML, contextUri, "Open Refine",
                            keepSourceCtx.getChecked(), contextEditable.getChecked());

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    getPage().getPopupWindowInstance().showError(e.getMessage());

                } finally {
                    stat.hide(true);
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(wr);
                }
            } else {
                stat.hide(true);
                getPage().getPopupWindowInstance().showError("All marked fields should be filled out");
            }
        }
    };
}

From source file:com.example.abrahamsofer.ident.Camera2Fragment.java

public void sendText() throws UnsupportedEncodingException {
    // Get user defined values
    // Create data variable for sent values to server

    JSONObject toSend = new JSONObject();
    try {//from   w  w  w.j av a 2s  .  co  m
        toSend.put("Price", price);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String text = "";
    BufferedReader reader = null;

    // Send data
    try {
        // Defined URL  where to send data
        URL url = new URL(serverAddress);
        // Send POST data request

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(toSend.toString());
        wr.flush();

        // Get the server response

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
        }

        text = sb.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {

            reader.close();
        }

        catch (Exception ex) {
        }
    }

    // Show response on activity

}

From source file:savant.view.swing.Savant.java

private static void logUsageStats() {
    try {/*  w w w .  j  a va  2 s.c om*/
        URLConnection urlConn;
        DataOutputStream printout;
        // URL of CGI-Bin script.
        // URL connection channel.
        urlConn = BrowserSettings.LOG_USAGE_STATS_URL.openConnection();
        // Let the run-time system (RTS) know that we want input.
        urlConn.setDoInput(true);
        // Let the RTS know that we want to do output.
        urlConn.setDoOutput(true);
        // No caching, we want the real thing.
        urlConn.setUseCaches(false);
        // Specify the content type.
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // Send POST output.
        printout = new DataOutputStream(urlConn.getOutputStream());

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        Locale locale = Locale.getDefault();

        String content = post("time", dateFormat.format(date)) + "&"
                + post("language", locale.getDisplayLanguage()) + "&"
                + post("user.timezone", System.getProperty("user.timezone")) + "&"
                + post("savant.version", BrowserSettings.VERSION) + "&"
                + post("savant.build", BrowserSettings.BUILD)
                //+ "&" + post("address", InetAddress.getLocalHost().getHostAddress())
                + "&" + post("java.version", System.getProperty("java.version")) + "&"
                + post("java.vendor", System.getProperty("java.vendor")) + "&"
                + post("os.name", System.getProperty("os.name")) + "&"
                + post("os.arch", System.getProperty("os.arch")) + "&"
                + post("os.version", System.getProperty("os.version")) + "&"
                + post("user.region", System.getProperty("user.region"));

        printout.writeBytes(content);
        printout.flush();
        printout.close();
        urlConn.getInputStream();
    } catch (Exception ex) {
        //LOG.error("Error logging usage stats.", ex);
    }
}

From source file:org.diorite.impl.metrics.Metrics.java

/**
 * Generic method that posts a plugin to the metrics website
 *//*from  w ww .  jav  a  2 s .  c o  m*/
private void postPlugin(final boolean isPing) throws IOException {
    final String serverVersion = this.getFullServerVersion();
    final int playersOnline = this.getPlayersOnline();

    // END server software specific section -- all code below does not use any code outside of this class / Java

    // Construct the post data
    final StringBuilder json = new StringBuilder(1024);
    json.append('{');

    // The plugin's description file containg all of the plugin data such as name, version, author, etc
    appendJSONPair(json, "guid", this.getUUID());
    appendJSONPair(json, "plugin_version", this.core.getVersion());
    appendJSONPair(json, "server_version", serverVersion);
    appendJSONPair(json, "players_online", Integer.toString(playersOnline));

    // New data as of R6
    final String osname = System.getProperty("os.name");
    String osarch = System.getProperty("os.arch");
    final String osversion = System.getProperty("os.version");
    final String java_version = System.getProperty("java.version");
    final int coreCount = Runtime.getRuntime().availableProcessors();

    // normalize os arch .. amd64 -> x86_64
    if (osarch.equals("amd64")) {
        osarch = "x86_64";
    }

    appendJSONPair(json, "osname", osname);
    appendJSONPair(json, "osarch", osarch);
    appendJSONPair(json, "osversion", osversion);
    appendJSONPair(json, "cores", Integer.toString(coreCount));
    appendJSONPair(json, "auth_mode", (this.core.getOnlineMode() == OnlineMode.FALSE) ? "0" : "1");
    appendJSONPair(json, "java_version", java_version);

    // If we're pinging, append it
    if (isPing) {
        appendJSONPair(json, "ping", "1");
    }

    if (!this.graphs.isEmpty()) {
        synchronized (this.graphs) {
            json.append(',');
            json.append('"');
            json.append("graphs");
            json.append('"');
            json.append(':');
            json.append('{');

            boolean firstGraph = true;

            for (final DynamicMetricsGraph graph : this.graphs) {
                final StringBuilder graphJson = new StringBuilder();
                graphJson.append('{');

                for (final MetricsPlotter plotter : graph.getPlotters()) {
                    appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
                }

                graphJson.append('}');

                if (!firstGraph) {
                    json.append(',');
                }

                json.append(escapeJSON(graph.getName()));
                json.append(':');
                json.append(graphJson);

                firstGraph = false;
            }

            json.append('}');
        }
    }

    // close json
    json.append('}');

    // Create the url
    final URL url = new URL(BASE_URL);

    // Connect to the website
    final URLConnection connection;

    connection = url.openConnection();

    final byte[] uncompressed = json.toString().getBytes();
    final byte[] compressed = gzip(json.toString());

    // Headers
    connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
    connection.addRequestProperty("Content-Type", "application/json");
    connection.addRequestProperty("Content-Encoding", "gzip");
    connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");

    connection.setDoOutput(true);

    if (CoreMain.isEnabledDebug()) {
        SpammyError.out("[Metrics] Prepared request for Diorite uncompressed=" + uncompressed.length
                + " compressed=" + compressed.length, (int) TimeUnit.MINUTES.toSeconds(5), this.hashCode() + 1);
    }

    // Write the data
    try (final OutputStream os = connection.getOutputStream()) {
        os.write(compressed);
        os.flush();
    }
    String response;
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        response = reader.readLine();
    }

    if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) {
        if (response == null) {
            response = "null";
        } else if (response.startsWith("7")) {
            response = response.substring(response.startsWith("7,") ? 2 : 1);
        }

        throw new IOException(response);
    } else {
        // Is this the first update this hour?
        if (response.equals("1") || response.contains("This is your first update this hour")) {
            synchronized (this.graphs) {
                this.graphs.forEach(DynamicMetricsGraph::resetPlotters);
            }
        }
    }
}

From source file:net.sf.taverna.t2.workbench.ui.impl.UserRegistrationForm.java

/**
 * Post registration data to our server.
 *//*from w  w w.  ja  v  a2  s  .  c  o m*/
private boolean postUserRegistrationDataToServer(UserRegistrationData regData) {
    StringBuilder parameters = new StringBuilder();

    /*
     * The 'submit' parameter - to let the server-side script know we are
     * submitting the user's registration form - all other requests will be
     * silently ignored
     */
    try {
        // value does not matter
        enc(parameters, TAVERNA_REGISTRATION_POST_PARAMETER_NAME, "submit");

        enc(parameters, TAVERNA_VERSION_POST_PARAMETER_NAME, regData.getTavernaVersion());
        enc(parameters, FIRST_NAME_POST_PARAMETER_NAME, regData.getFirstName());
        enc(parameters, LAST_NAME_POST_PARAMETER_NAME, regData.getLastName());
        enc(parameters, EMAIL_ADDRESS_POST_PARAMETER_NAME, regData.getEmailAddress());
        enc(parameters, KEEP_ME_INFORMED_POST_PARAMETER_PROPERTY_NAME, regData.getKeepMeInformed());
        enc(parameters, INSTITUTION_OR_COMPANY_POST_PARAMETER_NAME, regData.getInstitutionOrCompanyName());
        enc(parameters, INDUSTRY_TYPE_POST_PARAMETER_NAME, regData.getIndustry());
        enc(parameters, FIELD_POST_PARAMETER_NAME, regData.getField());
        enc(parameters, PURPOSE_POST_PARAMETER_NAME, regData.getPurposeOfUsingTaverna());
    } catch (UnsupportedEncodingException ueex) {
        logger.error(FAILED + "Could not url encode post parameters", ueex);
        showMessageDialog(null, REGISTRATION_FAILED_MSG, "Error encoding registration data", ERROR_MESSAGE);
        return false;
    }
    String server = REGISTRATION_URL;
    logger.info("Posting user registartion to " + server + " with parameters: " + parameters);
    String response = "";
    String failure;
    try {
        URL url = new URL(server);
        URLConnection conn = url.openConnection();
        /*
         * Set timeout to e.g. 7 seconds, otherwise we might hang too long
         * if server is not responding and it will block Taverna
         */
        conn.setConnectTimeout(7000);
        // Set connection parameters
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        // Make server believe we are HTML form data...
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // Write out the bytes of the content string to the stream.
        try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
            out.writeBytes(parameters.toString());
            out.flush();
        }
        // Read response from the input stream.
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String temp;
            while ((temp = in.readLine()) != null)
                response += temp + "\n";
            // Remove the last \n character
            if (!response.isEmpty())
                response = response.substring(0, response.length() - 1);
        }
        if (response.equals("Registration successful!"))
            return true;
        logger.error(FAILED + "Response form server was: " + response);
        failure = "Error saving registration data on the server";
    } catch (ConnectException ceex) {
        /*
         * the connection was refused remotely (e.g. no process is listening
         * on the remote address/port).
         */
        logger.error(FAILED + "Registration server is not listening of the specified url.", ceex);
        failure = "Registration server is not listening at the specified url";
    } catch (SocketTimeoutException stex) {
        // timeout has occurred on a socket read or accept.
        logger.error(FAILED + "Socket timeout occurred.", stex);
        failure = "Registration server timeout";
    } catch (MalformedURLException muex) {
        logger.error(FAILED + "Registartion server's url is malformed.", muex);
        failure = "Error with registration server's url";
    } catch (IOException ioex) {
        logger.error(
                FAILED + "Failed to open url connection to registration server or writing/reading to/from it.",
                ioex);
        failure = "Error opening connection to the registration server";
    }
    showMessageDialog(null, REGISTRATION_FAILED_MSG, failure, ERROR_MESSAGE);
    return false;
}

From source file:org.apache.jsp.fileUploader_jsp.java

private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId,
        Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request,
        HttpServletResponse response) {//from   w  ww  .j av a 2 s  .  c  o  m
    String charset = "UTF-8";
    String url = "";
    try {
        if (isJson) {
            //first check if bytes are actually json
            try {
                new JsonParser().parse(new String(bytes));
            } catch (Exception ex) {
                return "Failed, file was not valid JSON";
            }
            if (newShare)
                url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
            else
                url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset)
                        + "/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
        } else {
            if (newShare)
                url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
            else
                url = API_ROOT + "social/share/update/binary/" + prevId + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
        }

        if (localCookie)
            CookieHandler.setDefault(cm);
        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", charset);
        String cookieVal = getBrowserInfiniteCookie(request);
        if (cookieVal != null) {
            connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept-Charset", "UTF-8");
        }
        if (mimeType != null && mimeType.length() > 0)
            connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset);
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.write(bytes);
        DataInputStream responseStream = new DataInputStream(connection.getInputStream());

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = responseStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        String json = buffer.toString();
        String newCookie = getConnectionInfiniteCookie(connection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }
        buffer.flush();
        buffer.close();
        output.close();
        responseStream.close();

        if (isJson) {
            jsonResponse jr = new Gson().fromJson(json, jsonResponse.class);
            if (jr == null) {
                return "Failed: " + json;
            }
            if (jr.response.success == true) {
                if (jr.data != null && jr.data._id != null) {
                    addRemoveCommunities(jr.data._id, communities, request, response);
                    return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload
                }
            }
            return "Upload Failed: " + jr.response.message;
        } else {
            modResponse mr = new Gson().fromJson(json, modResponse.class);
            if (mr == null) {
                return "Failed: " + json;
            }
            if (mr.response.success == true) {
                if (prevId != null && mr.data == null) {
                    addRemoveCommunities(prevId, communities, request, response);
                    return prevId;
                } else {
                    addRemoveCommunities(mr.data, communities, request, response);
                    return mr.data; //When a new upload, mr.data contains the ShareID for the upload
                }
            } else {
                return "Upload Failed: " + mr.response.message;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        return "Upload Failed: " + e.getMessage();
    }
}