Example usage for java.net URLConnection setDoInput

List of usage examples for java.net URLConnection setDoInput

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

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

Usage

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Requests that the Rule with the current parameter selection be added to the PolicySet of the user
 * /*from  www  .j a  va  2 s . com*/
 * @return
 */
private boolean requestAddRule() {

    try {
        String toBeURL = strRelURL + "/" + privilegedServlet + "CreateConsentServiceServlet?type=addRule&"
                + "&organisation=" + organisation + "&persons=" + persons + "&affectedOID=" + affectedOID
                + "&documents=" + documents + "&documentsOID=" + documentsOID + "&accessType=" + accessType
                + "&grantAccess=" + grantAccess;

        System.out.println(organisation);
        System.out.println(persons);
        System.out.println(affectedOID);
        System.out.println(documents);
        System.out.println(documentsOID);
        System.out.println(accessType);
        System.out.println(grantAccess);

        toBeURL = encodeString(toBeURL);
        URL url = new URL(toBeURL);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("cookie", strCookie);
        conn.setDoInput(true);

        InputStream is = conn.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(is, "UTF8"), writer);
        String s = writer.toString();

        is.close();

        JSONObject ss = new JSONObject(s);

        if (ss.getBoolean("added")) {
            requestRuleList();

            cap.setRuleList(ruleListModel, null);

            return true;
        }

    } catch (Exception e) {
        return false;

    }
    return false;
}

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Requests the root of the organisations tree and it's children
 *//*from  w w  w  .j  a  v a  2s .co m*/
private void requestTreeRoot() {
    try {
        URL url = new URL(strRelURL + "/" + privilegedServlet + "CreateConsentServiceServlet?type=treeroot");
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("cookie", strCookie);
        conn.setDoInput(true);

        InputStream is = conn.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(is, "UTF8"), writer);
        String s = writer.toString();

        is.close();

        JSONObject jso = new JSONObject(s);

        OIDObject root = new OIDObject(jso.getString("identifier"), jso.getString("name"),
                jso.getBoolean("isActive"));

        root.setHasChildren(jso.getBoolean("hasChildren"));

        LazyOIDTreeNode rootNode = new LazyOIDTreeNode(root);

        JSONArray jsa = jso.getJSONArray("children");

        for (int i = 0; i < jsa.length(); i++) {

            JSONObject jsoo = (JSONObject) jsa.get(i);

            OIDObject oi = new OIDObject(jsoo.getString("identifier"), jsoo.getString("name"),
                    jsoo.getBoolean("isActive"));

            oi.setHasChildren(jsoo.getBoolean("hasChildren"));
            LazyOIDTreeNode oin = new LazyOIDTreeNode(oi);

            rootNode.add(oin);
        }

        oidTreeModel = new DefaultTreeModel(rootNode);
        cap.setOIDTree(oidTreeModel, null, new OIDTreeSelectionListener());
        cap.mainPanel.mp.cp.tp.orgaTree.collapseRow(1);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Requests all TreeNodes containing the given String in their Name-attribute
 *  /*from w w  w  .j  av  a2s . com*/
 * @param searchString
 */
private void requestSearchTree(String searchString) {

    if (searchString.trim().equalsIgnoreCase("")) {
        requestTreeRoot();
    } else {

        try {
            String toBeURL = strRelURL + "/" + privilegedServlet
                    + "CreateConsentServiceServlet?type=searchtree&searchstring=" + searchString;

            URL url = new URL(encodeString(toBeURL));
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("cookie", strCookie);
            conn.setDoInput(true);

            InputStream is = conn.getInputStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(new InputStreamReader(is, "UTF8"), writer);
            String s = writer.toString();

            is.close();

            JSONObject jso = new JSONObject(s);

            OIDObject root = new OIDObject(jso.getString("identifier"), jso.getString("name"),
                    jso.getBoolean("isActive"));

            root.setHasChildren(jso.getBoolean("hasChildren"));

            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(root);

            reconstructTree(rootNode, jso);

            oidTreeModel = new DefaultTreeModel(rootNode);
            cap.setOIDTree(oidTreeModel, null, new OIDTreeSelectionListener());

            int row = 0;
            while (row < cap.mainPanel.mp.cp.tp.orgaTree.getRowCount()) {
                cap.mainPanel.mp.cp.tp.orgaTree.expandRow(row);
                row++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

/**
 * Post registration data to our server.
 *//*from w  ww  .  ja  v a 2s  .c om*/
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.jab.docsearch.spider.LinkFinder.java

/**
 * Get all links from page/*from ww  w  . java2s  .  c om*/
 */
public void getAllLinks() {
    // writes links from a page out to a file
    String urlStr = pageName;
    String shortUrl = "";
    numUnChanged = 0;
    numSkips = 0;
    int numSuccesses = 0;
    int numFailed = 0;
    int numNoRobots = 0;
    addLink(urlStr);
    domainUrl = Utils.getDomainURL(urlStr);
    if (logger.isDebugEnabled()) {
        logger.debug("getAllLinks() domain url='" + domainUrl + "'");
    }
    SpiderUrl curl = new SpiderUrl(urlStr);
    baseUrlFolder = Utils.getBaseURLFolder(urlStr);
    int curLinkNo = 0;
    boolean completedSpider = false;
    boolean isDead = false;
    int curPread = 0;
    if (ds != null) {
        ds.setIsWorking(true);
        ds.setProgressMax(maxLinksToFind);
        ds.setCurProgressMSG("Spidering Files...");
    }
    int numSpidered = 0;
    int curSuccessNo = 0;

    // start spider
    while (curLinkNo != -1) {
        BufferedInputStream urlStream = null;
        FileOutputStream fileOutStream = null;

        try {
            completedSpider = false;
            isDead = false;
            if (ds != null) {
                ds.setCurProgress(curPread);
                if (!ds.getIsWorking()) {
                    break;
                }
            }
            curLinkNo = getNextUrlNo();
            if (curLinkNo == -1) {
                logger.debug("getAllLinks() end of links reached.");
                break;
            } else {
                urlStr = getLinkNameByNo(curLinkNo);
                logger.info("getAllLinks() analyzing page='" + urlStr + "'");
                curl = getSpiderUrl(curLinkNo);
            }

            shortUrl = Utils.concatEnd(urlStr, 33);
            setStatus(I18n.getString("connecting_to") + " " + shortUrl);

            // open url
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("User-Agent", "DocSearcher " + I18n.getString("ds.version"));
            conn.connect();
            urlStream = new BufferedInputStream(conn.getInputStream());

            // filesize
            int fileSize = conn.getContentLength();
            if (fileSize > maxFileSizeToGet) {
                String ex = I18n.getString("skipping_file_too_big") + " (" + fileSize + " > " + maxFileSizeToGet
                        + ") " + shortUrl;
                setStatus(ex);
                throw new Exception(ex);
            }

            setStatus(I18n.getString("downloading_uc") + "... " + shortUrl + " " + fileSize + " "
                    + I18n.getString("bytes"));
            curl.setSize(fileSize);

            // last modified
            long curModified = conn.getLastModified(); // was .getDate();
            curl.setLastModified(curModified);

            // content type
            String curContentType = netUtils.getContentType(conn);
            curl.setContentType(curContentType);

            // build the value for downloadFile
            String dnldTmpName = getDownloadFileName(curl.getContentType(), urlStr.toLowerCase());
            String downloadFile = FileUtils.addFolder(downloadFileDir, dnldTmpName);

            // TODO it is better to use content type!
            boolean curIsWebPage = isHtml(urlStr.toLowerCase())
                    || (curContentType.toLowerCase().indexOf("html") != -1);

            logger.debug("getAllLinks() saving to " + downloadFile);
            fileOutStream = new FileOutputStream(downloadFile);
            int curSize = 0;
            int curI;
            int lastPercent = 0;
            StringBuilder tag = new StringBuilder();
            String link = null;
            boolean inTag = false;
            boolean getFileSizeFromStream = false;
            if (fileSize == -1) {
                getFileSizeFromStream = true;
            }

            while ((curI = urlStream.read()) != -1) {
                fileOutStream.write(curI);

                curSize++;
                if (ds != null) {
                    if (!ds.getIsWorking()) {
                        break;
                    }
                }

                // fix problem if filesize not in content length
                if (getFileSizeFromStream) {
                    fileSize = curSize + urlStream.available();
                }

                // notify of download progress
                if (curSize > 0 && (curSize % 10) == 0) {
                    int curPercent = (curSize * 100) / fileSize;
                    if (curPercent != lastPercent) {
                        lastPercent = curPercent;
                        setStatus(I18n.getString("downloading_uc") + "... : (" + shortUrl + ") --> "
                                + curPercent + " %" + " ( " + (numSuccesses + numFailed + numNoRobots) + "/"
                                + getNumLinksFound() + ")");
                    }
                } // end for percent updates
                else if (curSize % 40 == 0) {
                    setStatus(I18n.getString("downloading_uc") + "... : (" + shortUrl + ") --> " + curSize + " "
                            + I18n.getString("bytes"));
                }

                // handle links
                if (curIsWebPage) {
                    char c = (char) curI;
                    // LOOK AT THE TAGS

                    // start tag
                    if (c == '<') {
                        inTag = true;
                        tag = new StringBuilder();
                    }
                    // end tag
                    else if (c == '>') {
                        inTag = false;
                        tag.append(c);
                        String realTag = tag.toString();
                        String lowerTag = realTag.toLowerCase();

                        // TODO fix problem with spaces before =

                        // link
                        if (lowerTag.startsWith("<a ")) {
                            link = Utils.getTagString("href=", realTag);
                            link = Utils.getNormalUrl(link);
                            doPossibleAdd(urlStr, link);
                        }
                        // area
                        else if (lowerTag.startsWith("<area")) {
                            link = Utils.getTagString("href=", realTag);
                            link = Utils.getNormalUrl(link);
                            doPossibleAdd(urlStr, link);
                        }
                        // TODO is in param realy a link?
                        else if (lowerTag.startsWith("<param")) {
                            String appletParam = Utils.getTagString("name=", realTag);
                            if (appletParam.toLowerCase().equals("url")) {
                                link = Utils.getTagString("value=", realTag);
                                link = Utils.getNormalUrl(link);
                                doPossibleAdd(urlStr, link);
                            }
                        }
                    }

                    // in tag
                    if (inTag) {
                        tag.append(c);
                    }
                }

                // filesize ok
                if (getFileSizeFromStream && fileSize > maxFileSizeToGet) {
                    break;
                }
            } // end while downloading
            curPread++;
            fileOutStream.close();
            urlStream.close();
            curl.setMd5(FileUtils.getMD5Sum(downloadFile));

            // now add out document
            if (ds != null) {
                curSuccessNo = ds.idx.addDocToIndex(downloadFile, iw, dsi, false, curl);
                switch (curSuccessNo) {
                case 0: // good
                    numSuccesses++;
                    break;
                case 1: // bad
                    numFailed++;
                    break;
                case 2: // meta robots - no index
                    numNoRobots++;
                    break;
                }
            }

            // delete temp file
            if (!FileUtils.deleteFile(downloadFile)) {
                logger.warn("getAllLinks() can't delete file '" + downloadFile + "'");
            }

            numSpidered++;
            completedSpider = true;

            // max links found
            if (numSpidered > maxLinksToFind) {
                break;
            }
        } catch (Exception e) {
            logger.fatal("getAllLinks() failed", e);
            setStatus(I18n.getString("error") + " : " + e.toString());
            isDead = true;
        } finally {
            // close resources
            IOUtils.closeQuietly(urlStream);
            IOUtils.closeQuietly(fileOutStream);

            curl.setSpidered(completedSpider);
            curl.setIsDeadLink(isDead);
            setStatus(I18n.getString("download_complete") + " " + shortUrl);
        }
    } // end for iterating over links

    if (ds != null) {
        ds.resetProgress();
    }
    saveAllLinks();

    logger.info("getAllLinks() " + numSpidered + " total web pages spidered for links.");

    showMessage(I18n.getString("spidering_complete") + " (" + Utils.concatStrToEnd(pageName, 28) + ") ",
            numSpidered + " " + I18n.getString("documents_indexed") + " " + getNumLinksFound() + " "
                    + I18n.getString("links_found") + "\n\n" + numSuccesses + " "
                    + I18n.getString("documents_spidered_successful") + "\n\n" + numFailed + " "
                    + I18n.getString("documents_spidered_failed") + "\n\n" + numNoRobots + " "
                    + I18n.getString("documents_not_spidered"));
}

From source file:org.orbeon.oxf.util.Connection.java

/**
 * Open the connection. This sends request headers, request body, and reads status and response headers.
 *
 * @return                  connection result
 *///from  w  w w .  ja  v  a2s  .c  o m
public ConnectionResult connect() {

    final boolean isDebugEnabled = indentedLogger.isDebugEnabled();

    // Perform connection
    final String scheme = connectionURL.getProtocol();
    if (isHTTPOrHTTPS(scheme)
            || (httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf")))) {
        // http MUST be supported
        // https SHOULD be supported
        // file SHOULD be supported
        try {
            // Create URL connection object
            final URLConnection urlConnection = connectionURL.openConnection();
            final HTTPURLConnection httpURLConnection = (urlConnection instanceof HTTPURLConnection)
                    ? (HTTPURLConnection) urlConnection
                    : null;

            // Whether a message body must be sent
            final boolean hasRequestBody = httpMethod.equals("POST") || httpMethod.equals("PUT");

            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(hasRequestBody);

            // Configure HTTPURLConnection
            if (httpURLConnection != null) {
                // Set state if possible
                httpURLConnection.setCookieStore(this.cookieStore);

                // Set method
                httpURLConnection.setRequestMethod(httpMethod);

                // Set credentials
                if (credentials != null) {

                    httpURLConnection.setUsername(credentials.username);
                    if (credentials.password != null)
                        httpURLConnection.setPassword(credentials.password);
                    if (credentials.preemptiveAuthentication != null)
                        httpURLConnection.setPreemptiveAuthentication(credentials.preemptiveAuthentication);
                    if (credentials.domain != null)
                        httpURLConnection.setDomain(credentials.domain);
                }
            }

            // Update request headers
            {
                // Handle SOAP
                // Set request Content-Type, SOAPAction or Accept header if needed
                final boolean didSOAP = handleSOAP(indentedLogger, httpMethod, headersMap, contentType,
                        hasRequestBody);

                // Set request content type
                if (!didSOAP && hasRequestBody) {
                    final String actualContentType = (contentType != null) ? contentType : "application/xml";
                    headersMap.put("Content-Type", new String[] { actualContentType });
                    indentedLogger.logDebug(LOG_TYPE, "setting header", "Content-Type", actualContentType);
                }
            }

            // Set headers on connection
            final List<String> headersToLog;
            if (headersMap != null && headersMap.size() > 0) {

                headersToLog = isDebugEnabled ? new ArrayList<String>() : null;

                for (Map.Entry<String, String[]> currentEntry : headersMap.entrySet()) {
                    final String currentHeaderName = currentEntry.getKey();
                    final String[] currentHeaderValues = currentEntry.getValue();
                    if (currentHeaderValues != null) {
                        // Add all header values as "request properties"
                        for (String currentHeaderValue : currentHeaderValues) {
                            urlConnection.addRequestProperty(currentHeaderName, currentHeaderValue);

                            if (headersToLog != null) {
                                headersToLog.add(currentHeaderName);
                                headersToLog.add(currentHeaderValue);
                            }
                        }
                    }
                }
            } else {
                headersToLog = null;
            }

            // Log request details except body
            if (isDebugEnabled) {
                // Basic connection information
                final URI connectionURI;
                try {
                    String userInfo = connectionURL.getUserInfo();
                    if (userInfo != null) {
                        final int colonIndex = userInfo.indexOf(':');
                        if (colonIndex != -1)
                            userInfo = userInfo.substring(0, colonIndex + 1) + "xxxxxxxx";// hide password in logs
                    }
                    connectionURI = new URI(connectionURL.getProtocol(), userInfo, connectionURL.getHost(),
                            connectionURL.getPort(), connectionURL.getPath(), connectionURL.getQuery(),
                            connectionURL.getRef());
                } catch (URISyntaxException e) {
                    throw new OXFException(e);
                }
                indentedLogger.logDebug(LOG_TYPE, "opening URL connection", "method", httpMethod, "URL",
                        connectionURI.toString(), "request Content-Type", contentType);

                // Log all headers
                if (headersToLog != null) {
                    final String[] strings = new String[headersToLog.size()];
                    indentedLogger.logDebug(LOG_TYPE, "request headers", headersToLog.toArray(strings));
                }
            }

            // Write request body if needed
            if (hasRequestBody) {

                // Case of empty body
                if (messageBody == null)
                    messageBody = new byte[0];

                // Log message body for debugging purposes
                if (logBody)
                    logRequestBody(indentedLogger, contentType, messageBody);

                // Set request body on connection
                httpURLConnection.setRequestBody(messageBody);
            }

            // Connect
            urlConnection.connect();

            if (httpURLConnection != null) {
                // Get state if possible
                // This is either the state we set above before calling connect(), or a new state if we didn't provide any
                this.cookieStore = httpURLConnection.getCookieStore();
            }

            // Create result
            final ConnectionResult connectionResult = new ConnectionResult(connectionURL.toExternalForm()) {
                @Override
                public void close() {
                    if (getResponseInputStream() != null) {
                        try {
                            getResponseInputStream().close();
                        } catch (IOException e) {
                            throw new OXFException(
                                    "Exception while closing input stream for action: " + connectionURL);
                        }
                    }

                    if (httpURLConnection != null)
                        httpURLConnection.disconnect();
                }
            };

            // Get response information that needs to be forwarded
            {
                // Status code
                connectionResult.statusCode = (httpURLConnection != null) ? httpURLConnection.getResponseCode()
                        : 200;

                // Headers
                connectionResult.responseHeaders = urlConnection.getHeaderFields();
                connectionResult.setLastModified(NetUtils.getLastModifiedAsLong(urlConnection));

                // Content-Type
                connectionResult.setResponseContentType(urlConnection.getContentType(), "application/xml");
            }

            // Log response details except body
            if (isDebugEnabled) {
                connectionResult.logResponseDetailsIfNeeded(indentedLogger, Level.DEBUG, LOG_TYPE);
            }

            // Response stream
            connectionResult.setResponseInputStream(urlConnection.getInputStream());

            // Log response body
            if (isDebugEnabled) {
                connectionResult.logResponseBody(indentedLogger, Level.DEBUG, LOG_TYPE, logBody);
            }

            return connectionResult;

        } catch (IOException e) {
            throw new ValidationException(e, new LocationData(connectionURL.toExternalForm(), -1, -1));
        }
    } else if (!httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf"))) {
        // TODO: implement writing to file: and oxf:
        // SHOULD be supported (should probably support oxf: as well)
        throw new OXFException("submission URL scheme not yet implemented: " + scheme);
    } else if (scheme.equals("mailto")) {
        // TODO: implement sending mail
        // MAY be supported
        throw new OXFException("submission URL scheme not yet implemented: " + scheme);
    } else {
        throw new OXFException("submission URL scheme not supported: " + scheme);
    }
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java

/**
 * Retrieves all available organisations from the Provider and Organisation
 * Registry Service./*from  ww w  .  j a v  a 2s.  c om*/
 * 
 * @TODO Correct?
 * 
 * @return - null if no list could be obtained
 * @throws HL7Exception
 */
private Vector<OIDObject> getOrganisations() throws HL7Exception {

    GenericParser parser = new GenericParser();

    Vector<OIDObject> voo = new Vector<OIDObject>();

    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmm");
    String timestamp = sd.format(new Date());
    long controllid = new Date().getTime();
    String msgControllID = new StringBuffer(String.valueOf(controllid)).reverse().toString();

    URI uri;
    String responseString = "";
    Message response = null;
    try {
        uri = new URI("http", (porsIP + ":" + porsPort), "/communication-servlet/PorsServlet",
                "user=" + porsUser + "&password=" + porsPassword + "&msg=MSH|^~\\&|COC|UKHD|PORS||" + timestamp
                        + "||QBP^Q82^QBP_Q21|" + msgControllID + "|P|2.5.1\rQPD|Q82^Find Organisation^UKHD0002|"
                        + controllid + "|@STF.3.1^*\rRCP|I||R",
                null);

        URL url = consentCreatorUtilities.formatURI(uri);

        URLConnection conn = url.openConnection();
        conn.setDoInput(true);

        InputStream is = conn.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(is, "UTF-8"), writer);
        responseString = writer.toString();
        response = parser.parse(responseString);
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
    }

    logging.debug("ResponseString: " + responseString);

    if (response instanceof RSP_K25) {
        RSP_K25 k25 = (RSP_K25) response;
        if (k25.getQAK().getQak2_QueryResponseStatus().toString().equals("OK")) {

            for (int i = 0; i < k25.getSTAFFReps(); i++) {

                try {
                    boolean ac = false;
                    String active = String.valueOf(k25.getSTAFF(i).getSTF().getStf7_ActiveInactiveFlag());
                    if (active.equalsIgnoreCase("A")) {
                        ac = true;
                    }

                    String name = k25.getSTAFF(i).getSTF().getStf3_StaffName(0).getXpn1_FamilyName()
                            .getFn1_Surname().toString();
                    String forename = k25.getSTAFF(i).getSTF().getStf3_StaffName(0).getXpn2_GivenName()
                            .toString();

                    String orgaIdentifier = k25.getSTAFF(i).getSTF().getStf1_PrimaryKeyValueSTF()
                            .getCe1_Identifier().toString();
                    String staffIdentifier = k25.getSTAFF(i).getSTF().getStf1_PrimaryKeyValueSTF()
                            .getCe1_Identifier().toString();

                    voo.add(new OIDObject(orgaIdentifier + "^" + staffIdentifier, forename + " " + name, ac));

                } catch (Exception e) {
                    Logger.getLogger(this.getClass()).error(e);

                }
            }

            return voo;

        }
    }

    return null;
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java

/**
 * Retrieves all available organisations from the Provider and Organisation
 * Registry Service./*from w  ww .  j ava 2 s.c o m*/
 * 
 * @return - null if no list could be obtained
 * @throws HL7Exception
 */
private Vector<OIDObject> getProvider() throws HL7Exception {

    GenericParser parser = new GenericParser();

    Vector<OIDObject> voo = new Vector<OIDObject>();

    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmm");
    String timestamp = sd.format(new Date());
    long controllid = new Date().getTime();
    String msgControllID = new StringBuffer(String.valueOf(controllid)).reverse().toString();

    URI uri;
    String responseString = "";
    Message response = null;
    try {
        uri = new URI("http", (porsIP + ":" + porsPort), "/communication-servlet/PorsServlet",
                "user=" + porsUser + "&password=" + porsPassword + "&msg=MSH|^~\\&|COC|UKHD|PORS||" + timestamp
                        + "||QBP^Q81^QBP_Q21|" + msgControllID + "|P|2.5.1\rQPD|Q81^Find Provider^UKHD0002|"
                        + controllid + "|@STF.3.1^*\rRCP|I||R",
                null);

        System.out.println(uri);

        URL url = consentCreatorUtilities.formatURI(uri);

        System.out.println(url);

        URLConnection conn = url.openConnection();
        conn.setDoInput(true);

        System.out.println(conn);

        InputStream is = conn.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(is, "UTF-8"), writer);
        responseString = writer.toString();
        response = parser.parse(responseString);
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
        e.printStackTrace();
    }

    logging.debug("ResponseString: " + responseString);

    if (response instanceof RSP_K25) {
        RSP_K25 k25 = (RSP_K25) response;
        if (k25.getQAK().getQak2_QueryResponseStatus().toString().equals("OK")) {

            for (int i = 0; i < k25.getSTAFFReps(); i++) {

                try {
                    boolean ac = false;
                    String active = String.valueOf(k25.getSTAFF(i).getSTF().getStf7_ActiveInactiveFlag());
                    if (active.equalsIgnoreCase("A")) {
                        ac = true;
                    }

                    String name = k25.getSTAFF(i).getSTF().getStf3_StaffName(0).getXpn1_FamilyName()
                            .getFn1_Surname().toString();
                    String forename = k25.getSTAFF(i).getSTF().getStf3_StaffName(0).getXpn2_GivenName()
                            .toString();
                    String title = k25.getSTAFF(i).getSTF().getStf3_StaffName(0).getXpn5_PrefixEgDR()
                            .toString();

                    String orgaIdentifier = k25.getSTAFF(i).getSTF().getStf1_PrimaryKeyValueSTF()
                            .getCe3_NameOfCodingSystem().getExtraComponents().getComponent(0).getData()
                            .toString();
                    String staffIdentifier = k25.getSTAFF(i).getSTF().getStf1_PrimaryKeyValueSTF()
                            .getCe1_Identifier().toString();

                    voo.add(new OIDObject(orgaIdentifier + "^" + staffIdentifier,
                            title + " " + forename + " " + name, ac));

                } catch (Exception e) {
                    Logger.getLogger(this.getClass()).error(e);
                }
            }
            return voo;
        }
    }
    return null;
}

From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java

@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting
private void tsaRequest() throws Exception {
    final Random rand = new Random();
    final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    boolean doRun = true;
    do {/* w  ww  .j  a  v  a 2 s .  com*/

        final int nonce = rand.nextInt();

        byte[] digest = new byte[20];
        if (instring != null) {
            final byte[] digestBytes = instring.getBytes("UTF-8");
            final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC");
            dig.update(digestBytes);
            digest = dig.digest();
            // When we have given input, we don't want to loop
            doRun = false;
        }
        if (infilestring != null) {
            // TSPAlgorithms constants changed from Strings to ASN1Encoded objects
            digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId());
            doRun = false;
        }
        final byte[] hexDigest = Hex.encode(digest);

        if (LOG.isDebugEnabled()) {
            LOG.debug("MessageDigest=" + new String(hexDigest));
        }

        final TimeStampRequest timeStampRequest;
        if (inreqstring == null) {
            LOG.debug("Generating a new request");
            timeStampRequestGenerator.setCertReq(certReq);
            if (reqPolicy != null) {
                timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy));
            }
            timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest,
                    BigInteger.valueOf(nonce));
        } else {
            LOG.debug("Reading request from file");
            timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring));
        }
        final byte[] requestBytes = timeStampRequest.getEncoded();

        if (outreqstring != null) {
            // Store request
            byte[] outBytes;
            if (base64) {
                outBytes = Base64.encode(requestBytes);
            } else {
                outBytes = requestBytes;
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outreqstring);
                fos.write(outBytes);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }

        keyStoreOptions.setupHTTPS();

        URL url;
        URLConnection urlConn;
        DataOutputStream printout;
        DataInputStream input;

        url = new URL(urlstring);

        // Take start time
        final long startMillis = System.currentTimeMillis();
        final long startTime = System.nanoTime();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending request at: " + startMillis);
        }

        urlConn = url.openConnection();

        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/timestamp-query");

        // Send POST output.
        printout = new DataOutputStream(urlConn.getOutputStream());
        printout.write(requestBytes);
        printout.flush();
        printout.close();

        // Get response data.
        input = new DataInputStream(urlConn.getInputStream());

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int b;
        while ((b = input.read()) != -1) {
            baos.write(b);
        }

        // Take stop time
        final long estimatedTime = System.nanoTime() - startTime;

        LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms");

        final byte[] replyBytes = baos.toByteArray();
        if (outrepstring != null) {
            // Store request
            byte[] outBytes;
            if (base64) {
                outBytes = Base64.encode(replyBytes);
            } else {
                outBytes = replyBytes;
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outrepstring);
                fos.write(outBytes);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }

        final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes);
        timeStampResponse.validate(timeStampRequest);

        LOG.info("TimeStampRequest validated");

        if (LOG.isDebugEnabled()) {
            final Date genTime;
            if (timeStampResponse.getTimeStampToken() != null
                    && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) {
                genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime();
            } else {
                genTime = null;
            }
            LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo()
                    + "): " + timeStampResponse.getStatusString()
                    + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n");

        }

        if (doRun) {
            Thread.sleep(sleep);
        }
    } while (doRun);
}

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Requests that a electronically signed CDA Document object be stored
 * // w w w.  ja  va 2s. c  o  m
 * @param storeUrl
 */
private void requestStoreSignedConsent(String storeUrl) {
    try {

        URL url = new URL(strRelURL + storeUrl);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("cookie", strCookie);
        conn.setRequestProperty("Content-Type", "text/xml");
        conn.setRequestProperty("Character-Encoding", "UTF-8");

        conn.setDoOutput(true);
        conn.setDoInput(true);

        DOMSource domSource = new DOMSource(cda);
        StringWriter owriter = new StringWriter();
        StreamResult result = new StreamResult(owriter);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        ObjectOutputStream oStream = new ObjectOutputStream(bStream);
        oStream.writeObject(cda);
        byte[] byteVal = bStream.toByteArray();

        OutputStream ops = conn.getOutputStream();
        ops.write(byteVal);

        InputStream is = conn.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(is, "UTF8"), writer);
        String s = writer.toString();

        is.close();

        JSONObject jso = new JSONObject(s);

        boolean success = jso.getBoolean("success");
        String message = jso.getString("message");

        if (success) {

            JOptionPane.showMessageDialog(this, message, "Erfolg", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(this, message, "Fehler", JOptionPane.ERROR_MESSAGE);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}