Example usage for java.net URLConnection setUseCaches

List of usage examples for java.net URLConnection setUseCaches

Introduction

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

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:org.apache.beehive.netui.pageflow.AutoRegisterActionServlet.java

/**
 * This method is almost exactly the same as the base class initModuleConfig.  The only difference
 * is that it does not throw an UnavailableException if a module configuration file is missing or
 * invalid./*from  w w w .  ja v a 2 s  .  com*/
 */
protected ModuleConfig initModuleConfig(String prefix, String paths) throws ServletException {

    if (_log.isDebugEnabled()) {
        _log.debug("Initializing module path '" + prefix + "' configuration from '" + paths + '\'');
    }

    // Parse the configuration for this module
    ModuleConfig moduleConfig = null;
    InputStream input = null;
    String mapping;

    try {
        ModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory();
        moduleConfig = factoryObject.createModuleConfig(prefix);

        // Support for module-wide ActionMapping type override
        mapping = getServletConfig().getInitParameter("mapping");
        if (mapping != null) {
            moduleConfig.setActionMappingClass(mapping);
        }

        // Configure the Digester instance we will use
        Digester digester = initConfigDigester();

        // Process each specified resource path
        while (paths.length() > 0) {
            digester.push(moduleConfig);
            String path;
            int comma = paths.indexOf(',');
            if (comma >= 0) {
                path = paths.substring(0, comma).trim();
                paths = paths.substring(comma + 1);
            } else {
                path = paths.trim();
                paths = "";
            }
            if (path.length() < 1) {
                break;
            }

            URL url = getConfigResource(path);

            //
            // THIS IS THE MAIN DIFFERENCE: we're doing a null-check here.
            //
            if (url != null) {
                URLConnection conn = url.openConnection();
                conn.setUseCaches(false);
                InputStream in = conn.getInputStream();

                try {
                    InputSource is = new InputSource(in);
                    is.setSystemId(url.toString());
                    input = getConfigResourceAsStream(path);
                    is.setByteStream(input);

                    // also, we're not letting it fail here either.
                    try {
                        digester.parse(is);
                        getServletContext().setAttribute(Globals.MODULE_KEY + prefix, moduleConfig);
                    } catch (Exception e) {
                        _log.error(Bundle.getString("PageFlow_Struts_ModuleParseError", path), e);
                    }
                    input.close();
                } finally {
                    in.close();
                }
            } else {
                //
                // Special case.  If this is the default (root) module and the module path is one that's normally
                // generated by the page flow compiler, then we don't want to error out if it's missing, since
                // this probably just means that there's no root-level page flow.  Set up a default, empty,
                // module config.
                //
                if (prefix.equals("") && isAutoLoadModulePath(path, prefix)) {
                    if (_log.isInfoEnabled()) {
                        _log.info("There is no root module at " + path + "; initializing a default module.");
                    }

                    //
                    // Set the ControllerConfig to a MissingRootModuleControllerConfig.  This is used by
                    // PageFlowRequestProcessor.
                    //
                    moduleConfig.setControllerConfig(new MissingRootModuleControllerConfig());
                } else {
                    _log.error(Bundle.getString("PageFlow_Struts_MissingModuleConfig", path));
                }
            }
        }

    } catch (Throwable t) {
        _log.error(internal.getMessage("configParse", paths), t);
        throw new UnavailableException(internal.getMessage("configParse", paths));
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    // Force creation and registration of DynaActionFormClass instances
    // for all dynamic form beans we will be using
    FormBeanConfig fbs[] = moduleConfig.findFormBeanConfigs();
    for (int i = 0; i < fbs.length; i++) {
        if (fbs[i].getDynamic()) {
            DynaActionFormClass.createDynaActionFormClass(fbs[i]);
        }
    }

    // Special handling for the default module (for
    // backwards compatibility only, will be removed later)
    if (prefix.length() < 1) {
        defaultControllerConfig(moduleConfig);
        defaultMessageResourcesConfig(moduleConfig);
    }

    // Return the completed configuration object
    //config.freeze();  // Now done after plugins init
    return moduleConfig;

}

From source file:org.seasar.struts.hotdeploy.impl.ModuleConfigLoaderImpl.java

protected void parseModuleConfigFile(Digester digester, URL url) throws UnavailableException {
    InputStream input = null;/*from  ww w  .  jav  a2  s.  c  o m*/

    try {
        InputSource is = new InputSource(url.toExternalForm());
        URLConnection conn = url.openConnection();

        conn.setUseCaches(false);
        conn.connect();
        input = conn.getInputStream();
        is.setByteStream(input);
        digester.parse(is);
    } catch (IOException e) {
        handleConfigException(url.toString(), e);
    } catch (SAXException e) {
        handleConfigException(url.toString(), e);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                throw new UnavailableException(e.getMessage());
            }
        }
    }
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java

/**
 * Connect to the JMarkets server and start the session defined by the given SessionDef object.
 *  Return the session Id of the created session
 *///from  w w w.  ja  v  a2 s.  c o  m
private int executeSession(String path, String name, SessionDef session) {
    try {
        URL servlet = new URL(path + "/servlet/ServletReceiver");
        Request req = new Request(Request.SERVER_INIT_REQUEST);

        req.addIntInfo("numClients", numSubjects);
        req.addIntInfo("updateProtocol", JMConstants.HTTP_UPDATE_PROTOCOL);
        req.addIntInfo("updateTime", 100);
        req.addStringInfo("name", name);
        req.addInfo("session", session);

        URLConnection servletConnection = servlet.openConnection();

        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

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

        outputToServlet.writeObject(req);
        outputToServlet.flush();
        outputToServlet.close();

        ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
        Response res = (Response) inputFromServlet.readObject();
        int sessionId = res.getIntInfo("sessionId");

        inputFromServlet.close();

        return sessionId;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

private String sendRequest(Map<String, String> parameters) {
    URL url = createRequestUrl(parameters);
    URLConnection urlConn;

    try {//w ww  .java  2  s.c o m
        urlConn = url.openConnection();
        // setup url connection
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        // add content type
        urlConn.setRequestProperty("Content-Type", CONTENT_TYPE);
        // add cookie information
        if (cookie != null)
            urlConn.setRequestProperty("Cookie", COOKIE + cookie);

        // send request
        urlConn.connect();

        // read response
        BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = input.readLine()) != null)
            response.append(line);
        input.close();

        if (isLogDebugEnabled()) {
            logDebug("Requested URL: " + url);
            logDebug("Response: " + response);
        }

        return response.toString();
    } catch (IOException e) {
        logError("Sending request to Adobe Connect failed. Request: " + url.toString(), e);
        return "";
    }
}

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

public ModelAndView mailIntegrate(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    KwlReturnObject kmsg = null;/* ww w . j a  v a2  s .  co m*/
    JSONObject obj = new JSONObject();
    String url = storageHandlerImpl.GetSOAPServerUrl();
    String res = "";
    boolean isFormSubmit = false;
    boolean isDefaultModelView = true;
    ModelAndView mav = null;
    try {
        if (!StringUtil.isNullOrEmpty(request.getParameter("action"))
                && request.getParameter("action").equals("getoutboundconfid")) {
            String str = "";
            url += "getOutboundConfiId.php";
            URL u = new URL(url);
            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();
        } else if (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                && request.getParameter("emailUIAction").equals("uploadAttachment")) {
            isDefaultModelView = false;
            url += "krawlermails.php";

            String pass = "";
            String currUser = sessionHandlerImplObj.getUserName(request) + "_";
            String userid = sessionHandlerImplObj.getUserid(request);

            String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
            JSONObject currUserAuthInfo = new JSONObject(jsonStr);
            if (currUserAuthInfo.has("userhash")) {
                currUser += currUserAuthInfo.getString("subdomain");
                pass = currUserAuthInfo.getString("userhash");
            }

            Enumeration en = request.getParameterNames();
            String str = "username=" + currUser + "&user_hash=" + pass;
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String paramValue = request.getParameter(paramName);
                str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
            }

            List fileItems = null;
            HashMap<String, String> arrParam = new HashMap<String, String>();
            ArrayList<FileItem> fi = new ArrayList<FileItem>();
            //                if (request.getParameter("email_attachment") != null) {
            DiskFileUpload fu = new DiskFileUpload();
            fileItems = fu.parseRequest(request);
            //                    crmDocumentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload);
            FileItem fi1 = null;
            for (Iterator k = fileItems.iterator(); k.hasNext();) {
                fi1 = (FileItem) k.next();
                if (fi1.isFormField()) {
                    arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
                } else {
                    if (fi1.getSize() != 0) {
                        fi.add(fi1);
                    }
                }
            }
            //                }
            long sizeinmb = 10; // 10 MB
            long maxsize = sizeinmb * 1024 * 1024;
            if (fi.size() > 0) {
                for (int cnt = 0; cnt < fi.size(); cnt++) {

                    if (fi.get(cnt).getSize() <= maxsize) {
                        try {
                            byte[] filecontent = fi.get(cnt).get();

                            URL u = new URL(url + "?" + str);
                            URLConnection uc = u.openConnection();
                            uc.setDoOutput(true);
                            uc.setUseCaches(false);
                            uc.setRequestProperty("Content-Type",
                                    "multipart/form-data; boundary=---------------------------4664151417711");
                            uc.setRequestProperty("Content-length", "" + filecontent.length);
                            uc.setRequestProperty("Cookie", "");

                            OutputStream outstream = uc.getOutputStream();

                            String newline = "\r\n";
                            String b1 = "";
                            b1 += "-----------------------------4664151417711" + newline;
                            b1 += "Content-Disposition: form-data; name=\"email_attachment\"; filename=\""
                                    + fi.get(cnt).getName() + "\"" + newline;
                            b1 += "Content-Type: text" + newline;
                            b1 += newline;

                            String b2 = "";
                            b2 += newline + "-----------------------------4664151417711--" + newline;

                            String b3 = "";
                            b3 += "-----------------------------4664151417711" + newline;
                            b3 += "Content-Disposition: form-data; name=\"addval\";" + newline;
                            b3 += newline;

                            String b4 = "";
                            b4 += newline + "-----------------------------4664151417711--" + newline;

                            outstream.write(b1.getBytes());
                            outstream.write(b1.getBytes());
                            outstream.write(b1.getBytes());
                            outstream.write(fi.get(cnt).get());
                            outstream.write(b4.getBytes());
                            PrintWriter pw = new PrintWriter(outstream);
                            pw.println(str);
                            pw.close();
                            outstream.flush();

                            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                            String line = "";

                            while ((line = in.readLine()) != null) {
                                res += line;
                            }
                            in.close();
                        } catch (Exception e) {
                            throw ServiceException.FAILURE(e.getMessage(), e);
                        }
                    } else {
                        JSONObject jerrtemp = new JSONObject();
                        jerrtemp.put("Success", "Fail");
                        jerrtemp.put("errmsg", "Attachment size should be upto " + sizeinmb + "mb");
                        res = jerrtemp.toString();
                    }
                }
            } else {
                JSONObject jerrtemp = new JSONObject();
                jerrtemp.put("Success", "Fail");
                jerrtemp.put("errmsg", "Attachment file size should be greater than zero");
                res = jerrtemp.toString();
            }

        } else {

            url += "krawlermails.php";

            String pass = "";
            String currUser = sessionHandlerImplObj.getUserName(request) + "_";
            String userid = sessionHandlerImplObj.getUserid(request);

            String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
            JSONObject currUserAuthInfo = new JSONObject(jsonStr);
            if (currUserAuthInfo.has("userhash")) {
                currUser += currUserAuthInfo.getString("subdomain");
                pass = currUserAuthInfo.getString("userhash");
            }

            Enumeration en = request.getParameterNames();
            String str = "username=" + currUser + "&user_hash=" + pass;
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String paramValue = request.getParameter(paramName);
                str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
            }

            URL u = new URL(url);
            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();

            if ((!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                    && request.getParameter("emailUIAction").equals("getMessageListXML"))
                    || (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction")) && request
                            .getParameter("emailUIAction").equals("getMessageListKrawlerFoldersXML"))) {
                //response.setContentType("text/xml;charset=UTF-8");
                isFormSubmit = true;
                int totalCnt = 0;
                int unreadCnt = 0;
                JSONObject jobj = new JSONObject();
                JSONArray jarr = new JSONArray();
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(uc.getInputStream());

                NodeList cntentity = doc.getElementsByTagName("TotalCount");
                Node cntNode = cntentity.item(0);
                if (cntNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) cntNode;
                    totalCnt = Integer.parseInt(firstPersonElement.getChildNodes().item(0).getNodeValue());
                }

                cntentity = doc.getElementsByTagName("UnreadCount");
                cntNode = cntentity.item(0);
                if (cntNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) cntNode;
                    unreadCnt = Integer.parseInt(firstPersonElement.getChildNodes().item(0).getNodeValue());
                }
                String dateFormatId = sessionHandlerImpl.getDateFormatID(request);
                String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request);
                String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // check for Mail server protocol
                boolean isYahoo = false;

                if (request.getParameter("mbox").equals("INBOX")) {
                    u = new URL(url);
                    uc = u.openConnection();
                    uc.setDoOutput(true);
                    uc.setUseCaches(false);
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    str = "username=" + currUser + "&user_hash=" + pass
                            + "&action=EmailUIAjax&emailUIAction=getIeAccount&ieId="
                            + request.getParameter("ieId") + "&module=Emails&to_pdf=true";
                    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();

                    JSONObject ieIDInfo = new JSONObject(res);
                    if (ieIDInfo.getString("server_url").equals("pop.mail.yahoo.com"))
                        isYahoo = true;
                }
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
                DateFormat userdft = null;
                if (!isYahoo)
                    userdft = KwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId,
                            timeZoneDiff);
                else
                    userdft = KwlCommonTablesDAOObj.getOnlyDateFormatter(dateFormatId, timeFormatId);

                NodeList entity = doc.getElementsByTagName("Emails");
                NodeList email = ((Element) entity.item(0)).getElementsByTagName("Email");
                for (int i = 0; i < email.getLength(); i++) {
                    JSONObject tmpObj = new JSONObject();
                    Node rowElement = email.item(i);
                    if (rowElement.getNodeType() == Node.ELEMENT_NODE) {
                        NodeList childNodes = rowElement.getChildNodes();
                        for (int j = 0; j < childNodes.getLength(); j++) {
                            Node node = childNodes.item(j);
                            if (node.getNodeType() == Node.ELEMENT_NODE) {
                                Element firstPersonElement = (Element) node;
                                if (firstPersonElement != null) {
                                    NodeList textFNList = firstPersonElement.getChildNodes();
                                    if (textFNList.item(0) != null) {
                                        if (request.getSession().getAttribute("iPhoneCRM") != null) {
                                            String body = ((Node) textFNList.item(0)).getNodeValue().trim();
                                            if (body.contains("&lt;"))
                                                body = body.replace("&lt;", "<");
                                            if (body.contains("&gt;"))
                                                body = body.replace("&gt;", ">");
                                            tmpObj.put(node.getNodeName(), body);
                                        } else {
                                            String value = ((Node) textFNList.item(0)).getNodeValue().trim();
                                            if (node.getNodeName().equals("date")) {
                                                value = userdft.format(sdf.parse(value));
                                            }
                                            tmpObj.put(node.getNodeName(), value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    jarr.put(tmpObj);
                }
                jobj.put("data", jarr);
                jobj.put("totalCount", totalCnt);
                jobj.put("unreadCount", unreadCnt);
                res = jobj.toString();
            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                String line = "";

                while ((line = in.readLine()) != null) {
                    res += line;
                }
                in.close();
                if ((!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                        && request.getParameter("emailUIAction").equals("fillComposeCache"))) {
                    isFormSubmit = true;
                } else if (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                        && request.getParameter("emailUIAction").equals("refreshKrawlerFolders")) {
                    if (res.equals("Not a valid entry method")) {
                        ArrayList filter_names = new ArrayList();
                        ArrayList filter_params = new ArrayList();
                        filter_names.add("u.userID");
                        filter_params.add(userid);
                        HashMap<String, Object> requestParams = new HashMap<String, Object>();
                        KwlReturnObject kwlobject = profileHandlerDAOObj.getUserDetails(requestParams,
                                filter_names, filter_params);
                        List li = kwlobject.getEntityList();
                        if (li.size() >= 0) {
                            if (li.iterator().hasNext()) {
                                User user = (User) li.iterator().next();
                                String returnStr = addUserEntryForEmails(
                                        user.getCompany().getCreator().getUserID(), user, user.getUserLogin(),
                                        user.getUserLogin().getPassword(), false);
                                JSONObject emailresult = new JSONObject(returnStr);
                                if (Boolean.parseBoolean(emailresult.getString("success"))) {
                                    pw = new PrintWriter(uc.getOutputStream());
                                    pw.println(str);
                                    pw.close();
                                    in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                                    line = "";
                                    while ((line = in.readLine()) != null) {
                                        res += line;
                                    }
                                    in.close();
                                }
                            }
                        }
                    }
                } else if (res.equals("bool(false)")) {
                    res = "false";
                }
            }
        }
        if (!isFormSubmit) {
            JSONObject resjobj = new JSONObject();
            resjobj.put("valid", true);
            resjobj.put("data", res);
            res = resjobj.toString();
        }
        if (isDefaultModelView)
            mav = new ModelAndView("jsonView-ex", "model", res);
        else
            mav = new ModelAndView("jsonView", "model", res);
    } catch (SessionExpiredException e) {
        mav = new ModelAndView("jsonView-ex", "model", "{'valid':false}");
        System.out.println(e.getMessage());
    } catch (Exception e) {
        mav = new ModelAndView("jsonView-ex", "model",
                "{'valid':true,data:{success:false,errmsg:'" + e.getMessage() + "'}}");
        System.out.println(e.getMessage());
    }
    return mav;
}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * load the given url in a byte array/*from w w  w.  j  ava2 s  .  c o  m*/
 * 
 * @param urlToResource
 *            url to load
 * 
 * @return a byte array
 */
public static final byte[] loadByteArray(final URL urlToResource) {
    InputStream in = null;

    try {
        final URLConnection uc = urlToResource.openConnection();
        uc.setUseCaches(false);
        in = uc.getInputStream();

        return CClassLoader.loadByteArray(in);
    } catch (final IOException ioe) {
        return null;
    } finally {
        try {
            in.close();
        } catch (final Exception ignore) {
        }
    }
}

From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java

/**
 * This method is called whenever the AUVs have reached their destinations and new data is to be sent to the server.<br/>
 * As a result, new destinations will be received and vehicles will travel to the new destinations.
 * @throws Exception If there is a problem communicating with the server.
 *///from  www  .j a va 2s .  co m
public void controlLoop() throws Exception {

    TransferData send = localState();
    if (send == null)
        throw new Exception("Unable to compute local state");

    TransferData receive = new TransferData();

    for (int AUV = 0; AUV < AUVS; AUV++) {
        showText(nameTable.get(AUV) + " is at " + send.Location[AUV][0] + ", " + send.Location[AUV][1] + ", "
                + send.Location[AUV][2]);
    }

    Gson gson = new Gson();
    String json = gson.toJson(send);

    PrintWriter writer = null;
    writer = new PrintWriter(SessionID + "_Data.txt", "UTF-8");
    writer.write(json);
    writer.close();

    NeptusLog.pub().info("uploading to convcao..." + json.toString());
    Upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()),
            SessionID + "_Data.txt");

    showText("Upload complete, downloading new AUV destinations");

    int receivedTimestep = 0;
    while (!cancel && receivedTimestep < timestep) {
        Thread.sleep(100);

        try {
            URL url = new URL(
                    "http://www.convcao.com/caoagile/FilesFromAgent/NEPTUS/" + SessionID + "_NewActions.txt");
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            conn.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String jsonClient = in.readLine();
            receive = new Gson().fromJson(jsonClient, TransferData.class);
            receivedTimestep = receive.timeStep;
        } catch (IOException ex) {
            NeptusLog.pub().error(ex);
        }
    }

    showText("Received updated positions from convcao");

    timestep++;

    for (int AUV = 0; AUV < receive.Location.length; AUV++) {
        String name = nameTable.get(AUV);
        LocationType loc = coords.convert(receive.Location[AUV][0], receive.Location[AUV][1]);
        loc.setDepth(1 + AUV * 1.5);//coords.convertNoptilusDepthToWgsDepth(receive.Location[AUV][2]));
        destinations.put(name, loc);
        showText(name + " is being sent to " + receive.Location[AUV][0] + ", " + receive.Location[AUV][1]);
    }

    myDeleteFile(SessionID + "_Data.txt");
}

From source file:junk.gui.HazardDataSetCalcCondorApp.java

/**
 * this connects to the servlet on web server to check if dataset name already exists
 * or computation have already been for these parameter settings.
 * @return// w w w  . j  a v  a  2 s  .c  o m
 */
private Object checkForHazardMapComputation() {

    try {
        if (D)
            System.out.println("starting to make connection with servlet");
        URL hazardMapServlet = new URL(DATASET_CHECK_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 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());
        Object obj = fromServlet.readObject();
        //if(D) System.out.println("Receiving the Input from the Servlet:"+success);
        fromServlet.close();
        return obj;

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

    }
    return null;
}

From source file:junk.gui.HazardDataSetCalcCondorApp.java

/**
 * sets up the connection with the servlet on the server (gravity.usc.edu)
 *//*from  w  ww  .j a  va2 s. 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:convcao.com.agent.ConvcaoNeptusInteraction.java

/**
 * This method is called whenever the AUVs have reached their destinations and new data is to be sent to the server.<br/>
 * As a result, new destinations will be received and vehicles will travel to the new destinations.
 * @throws Exception If there is a problem communicating with the server.
 *//* w  ww  . j av  a  2  s.  c o  m*/
public void controlLoop() throws Exception {
    TransferData send = localState();
    if (send == null)
        throw new Exception("Unable to compute local state");

    TransferData receive = new TransferData();

    for (int AUV = 0; AUV < auvs; AUV++) {
        showText(nameTable.get(AUV) + " is at " + send.Location[AUV][0] + ", " + send.Location[AUV][1] + ", "
                + send.Location[AUV][2]);
    }

    Gson gson = new Gson();
    String json = gson.toJson(send);

    PrintWriter writer = null;
    writer = new PrintWriter(sessionID + "_Data.txt", "UTF-8");
    writer.write(json);
    writer.close();

    NeptusLog.pub().info("uploading to convcao..." + json.toString());
    upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(), new String(jPasswordField1.getPassword()),
            sessionID + "_Data.txt");

    showText("Upload complete, downloading new AUV destinations");

    int receivedTimestep = 0;
    while (!cancel && receivedTimestep < timestep) {
        Thread.sleep(100);

        try {
            URL url = new URL(
                    "http://www.convcao.com/caoagile/FilesFromAgent/NEPTUS/" + sessionID + "_NewActions.txt");
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            conn.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String jsonClient = in.readLine();
            receive = new Gson().fromJson(jsonClient, TransferData.class);
            receivedTimestep = receive.timeStep;
        } catch (IOException ex) {
            NeptusLog.pub().error(ex);
        }
    }

    showText("Received updated positions from convcao");

    timestep++;

    for (int AUV = 0; AUV < receive.Location.length; AUV++) {
        String name = nameTable.get(AUV);
        LocationType loc = coords.convert(receive.Location[AUV][0], receive.Location[AUV][1]);
        loc.setDepth(firstVehicleDepth + AUV * depthIncrements);//coords.convertNoptilusDepthToWgsDepth(receive.Location[AUV][2]));
        destinations.put(name, loc);
        showText(name + " is being sent to " + receive.Location[AUV][0] + ", " + receive.Location[AUV][1]);
    }
    // reset arrived states
    for (String auvName : nameTable.values()) {
        arrived.put(auvName, false);
    }

    myDeleteFile(sessionID + "_Data.txt");
}