Example usage for java.util Vector iterator

List of usage examples for java.util Vector iterator

Introduction

In this page you can find the example usage for java.util Vector iterator.

Prototype

public synchronized Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:org.energy_home.jemma.ah.internal.zigbee.InstallationStatus.java

private void nodeDiscovered(Address a) {
    if (enableDiscoveryLogs)
        this.printTables();

    String nodePid = getNodePid(a);
    Vector devices = (Vector) this.getDevices(nodePid);
    if (devices == null) {
        // This is a new node
        if (enableDiscoveryLogs)
            log.debug(getIeeeAddressHex(a) + ": announcement from a new node");

        // starts installation process
        InstallationStatus installationStatus = this.getInstallingDevice(a);
        if (installationStatus == null) {
            if (enableDiscoveryLogs)
                log.debug(getIeeeAddressHex(a) + ": discovered new device ... installing it");
            installationStatus = this.addInstallingDevice(a);
            installationStatus.refreshTime();
            installationStatus.setStatus(InstallationStatus.ANNOUNCEMENT_RECEIVED);
            this.discoveredNodesQueue.addLast(installationStatus);
        } else {/*from   w ww.  j ava  2s. c  o  m*/
            if (installationStatus.getStatus() == InstallationStatus.ANNOUNCEMENT_RECEIVED) {
                if (enableDiscoveryLogs)
                    log.debug(getIeeeAddressHex(a) + ": duplicate announcement");

                long age = System.currentTimeMillis() - installationStatus.getTime();
                if (enableDiscoveryLogs)
                    log.debug(getIeeeAddressHex(a) + ": the announcement has an age of " + age + " ms");

                if (age > 20000) {
                    if (!this.discoveredNodesQueue.contains(installationStatus)) {
                        this.discoveredNodesQueue.addLast(installationStatus);
                    } else {
                        log.error(getIeeeAddressHex(a) + ": too old ... restartarting discovery");
                    }
                }
            } else {
                if (enableDiscoveryLogs)
                    log.debug(getIeeeAddressHex(a) + ": discovery process in progress for device ");
            }
        }

        this.handleNextDiscoveredNode();
    } else {
        if (enableDiscoveryLogs)
            log.info(getIeeeAddressHex(a) + ": received announcement from an already known node");
        // notifies all devices
        Iterator it = devices.iterator();
        while (it.hasNext()) {
            ZigBeeDeviceImpl device = (ZigBeeDeviceImpl) it.next();
            device.announce();
        }
    }
}

From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java

/**
 * Tunnels a request to the online application using given URL mapping and SSLSocketFactory.
 * This method returns the ResponseCode of the request to the online application. 
 * @param req HTTP request/*from   w ww . j a va 2  s  .co m*/
 * @param resp HTTP response
 * @param loginHeaders header field/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param loginParameters parameter name/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param publicURLPrefix prefix of request URL to be substituted for the <code>realURLPrefix</code>
 * @param realURLPrefix prefix of online application URL to substitute the <code>publicURLPrefix</code>
 * @param ssf SSLSocketFactory to use
 * @throws IOException if an I/O error occurs
 */
private int tunnelRequest(HttpServletRequest req, HttpServletResponse resp, Map loginHeaders,
        Map loginParameters, String publicURLPrefix, String realURLPrefix, SSLSocketFactory ssf, String binding)
        throws IOException {

    String originBinding = binding;
    String browserUserID = "";
    String browserPassword = "";
    //URL url = new URL(realURLPrefix); 
    //String realURLHost = url.getHost(); 
    if (INTERNAL_DEBUG && !binding.equals(""))
        Logger.debug("Binding: " + binding);

    // collect headers from request
    Map headers = new HashMap();
    for (Enumeration enu = req.getHeaderNames(); enu.hasMoreElements();) {
        String headerKey = (String) enu.nextElement();
        String headerKeyValue = req.getHeader(headerKey);
        if (INTERNAL_DEBUG)
            Logger.debug("Incoming:" + headerKey + "=" + headerKeyValue);
        //Analyze Basic-Auth-Headers from the client
        if (headerKey.equalsIgnoreCase("Authorization")) {
            if (headerKeyValue.substring(0, 6).equalsIgnoreCase("Basic ")) {
                String credentials = headerKeyValue.substring(6);
                byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                String plaintextcredentials = new String(bplaintextcredentials);
                browserUserID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                browserPassword = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
            if (headerKeyValue.substring(0, 9).equalsIgnoreCase("Negotiate")) {
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: Found NTLM Aut.: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
        } else {
            /* Headers MUST NOT be repaced according to our Spec.
            if (headerKey.equalsIgnoreCase("Host")) {
               headerKeyValue = realURLHost; 
                 //headerKeyValue= realURLPrefix.substring(hoststartpos);
              if (INTERNAL_DEBUG) Logger.debug("replaced:" + headerKey + "=" + headerKeyValue);           
            }
            */
            headers.put(headerKey, headerKeyValue);
        }
    }

    // collect login headers, possibly overwriting headers from request
    String authorizationvalue = "";
    if (req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {

        if (OAConfiguration.BINDUNG_NOMATCH.equals(binding)) {
            int loginTry = getLoginTry(req);
            Logger.debug("Binding: mode = " + OAConfiguration.BINDUNG_NOMATCH + "(try #"
                    + Integer.toString(loginTry) + ")");
            if (loginTry == 1) {
                binding = OAConfiguration.BINDUNG_FULL;
            } else {
                binding = OAConfiguration.BINDUNG_USERNAME;
            }
        }

        /* Soll auch bei anderen bindings zuerst ein passwort probiert werden knnen:
        //if we have the first Login-Try and we have Binding to Username and a predefined Password we try this one first
         // full binding will be covered by next block
         if (loginTry==1 && !OAConfiguration.BINDUNG_FULL.equals(binding)) {
           //1st try: if we have a password, try this one first
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
              String headerKey = (String) iter.next();
              String headerKeyValue = (String) loginHeaders.get(headerKey);
              if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
               String credentials = headerKeyValue.substring(6);
               byte [] bplaintextcredentials = Base64Utils.decode(credentials, true);
              String plaintextcredentials = new String(bplaintextcredentials);
              String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":")+1);
              if (password!=null && !password.equals("")) {
                  Logger.debug("Binding: found predefined password. Trying full binding first");
                 binding = OAConfiguration.BINDUNG_FULL;
                 break;
                }
              }
            }
         }
         */

        //we have a connection with not having logged on
        if (loginHeaders != null && (browserPassword.length() != 0 || browserUserID.length() != 0
                || OAConfiguration.BINDUNG_FULL.equals(binding))) {
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
                String headerKey = (String) iter.next();
                String headerKeyValue = (String) loginHeaders.get(headerKey);
                //customize loginheaders if necessary
                if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
                    if (OAConfiguration.BINDUNG_FULL.equals(binding)) {
                        authorizationvalue = headerKeyValue;
                        Logger.debug("Binding: full binding to user established");
                    } else {
                        String credentials = headerKeyValue.substring(6);
                        byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                        String plaintextcredentials = new String(bplaintextcredentials);
                        String userID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                        String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                        String userIDPassword = ":";
                        if (OAConfiguration.BINDUNG_USERNAME.equals(binding)) {
                            Logger.debug("Binding: Access with necessary binding to user");
                            userIDPassword = userID + ":" + browserPassword;
                        } else if (OAConfiguration.BINDUNG_NONE.equals(binding)) {
                            Logger.debug("Binding: Access without binding to user");
                            //If first time
                            if (browserUserID.length() == 0)
                                browserUserID = userID;
                            if (browserPassword.length() == 0)
                                browserPassword = password;
                            userIDPassword = browserUserID + ":" + browserPassword;
                        } else {
                            userIDPassword = userID + ":" + password;
                        }
                        credentials = Base64Utils.encode(userIDPassword.getBytes());
                        authorizationvalue = "Basic " + credentials;
                        headerKeyValue = authorizationvalue;
                    }
                }
                headers.put(headerKey, headerKeyValue);
            }
        }
    } else {
        //if OA needs Authorization header in each further request
        authorizationvalue = (String) req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER);
        if (loginHeaders != null)
            headers.put("Authorization", authorizationvalue);
    }

    Vector parameters = new Vector();
    for (Enumeration enu = req.getParameterNames(); enu.hasMoreElements();) {
        String paramName = (String) enu.nextElement();
        if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
            if (INTERNAL_DEBUG)
                Logger.debug("Req Parameter-put: " + paramName + ":" + req.getParameter(paramName));
            String parameter[] = new String[2];
            parameter[0] = paramName;
            parameter[1] = req.getParameter(paramName);
            parameters.add(parameter);
        }
    }
    // collect login parameters, possibly overwriting parameters from request
    if (loginParameters != null) {
        for (Iterator iter = loginParameters.keySet().iterator(); iter.hasNext();) {
            String paramName = (String) iter.next();
            if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
                if (INTERNAL_DEBUG)
                    Logger.debug(
                            "Req Login-Parameter-put: " + paramName + ":" + loginParameters.get(paramName));
                String parameter[] = new String[2];
                parameter[0] = paramName;
                parameter[1] = (String) loginParameters.get(paramName);
                parameters.add(parameter);
            }
        }
    }

    ConnectionBuilder cb = ConnectionBuilderFactory.getConnectionBuilder(publicURLPrefix);
    HttpURLConnection conn = cb.buildConnection(req, publicURLPrefix, realURLPrefix, ssf, parameters);

    // set headers as request properties of URLConnection
    for (Iterator iter = headers.keySet().iterator(); iter.hasNext();) {
        String headerKey = (String) iter.next();
        String headerValue = (String) headers.get(headerKey);
        String LogStr = "Req header " + headerKey + ": " + headers.get(headerKey);
        if (isBasicAuthenticationHeader(headerKey, headerValue)) {
            String credentials = headerValue.substring(6);
            byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
            String plaintextcredentials = new String(bplaintextcredentials);
            String uid = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
            String pwd = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
            //Sollte AuthorizationInfo vom HTTPClient benutzt werden:  cb.addBasicAuthorization(publicURLPrefix, uid, pwd);
            //deactivate following line for security
            //if (INTERNAL_DEBUG && Logger.isDebugEnabled()) LogStr = LogStr + "  >UserID:Password< >" + uid + ":" + pwd + "<";
        }
        conn.setRequestProperty(headerKey, headerValue);
        if (INTERNAL_DEBUG)
            Logger.debug(LogStr);
    }

    StringWriter sb = new StringWriter();

    // Write out parameters into output stream of URLConnection.
    // On GET request, do not send parameters in any case,
    // otherwise HttpURLConnection would send a POST.
    if (!"get".equalsIgnoreCase(req.getMethod()) && !parameters.isEmpty()) {
        boolean firstParam = true;
        String parameter[] = new String[2];
        for (Iterator iter = parameters.iterator(); iter.hasNext();) {
            parameter = (String[]) iter.next();
            String paramName = parameter[0];
            String paramValue = parameter[1];
            if (firstParam)
                firstParam = false;
            else
                sb.write("&");
            sb.write(paramName);
            sb.write("=");
            sb.write(paramValue);
            if (INTERNAL_DEBUG)
                Logger.debug("Req param " + paramName + ": " + paramValue);
        }
    }

    // For WebDAV and POST: copy content
    if (!"get".equalsIgnoreCase(req.getMethod())) {
        if (INTERNAL_DEBUG && !"post".equalsIgnoreCase(req.getMethod()))
            Logger.debug("---- WEBDAV ----  copying content");
        try {
            OutputStream out = conn.getOutputStream();
            InputStream in = req.getInputStream();
            if (!parameters.isEmpty())
                out.write(sb.toString().getBytes()); //Parameter nicht mehr mittels Printwriter schreiben 
            copyStream(in, out, null, req.getMethod());
            out.flush();
            out.close();
        } catch (IOException e) {
            if (!"post".equalsIgnoreCase(req.getMethod()))
                Logger.debug("---- WEBDAV ----  streamcopy problem");
            else
                Logger.debug("---- POST ----  streamcopy problem");
        }
    }

    // connect
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Request");
    conn.connect();
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Response");

    // check login tries
    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        int loginTry = getLoginTry(req);
        req.getSession().setAttribute(ATT_OA_LOGINTRY, Integer.toString(loginTry));
        if (loginTry > MAX_OA_LOGINTRY) {
            Logger.debug("Found 401 UNAUTHORIZED, maximum tries exceeded; leaving...");
            cb.disconnect(conn);
            return -401;
        }
    }

    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED
            && OAConfiguration.BINDUNG_FULL.equals(originBinding)) {
        Logger.debug("Found 401 UNAUTHORIZED, leaving...");
        cb.disconnect(conn);
        return conn.getResponseCode();
    }

    resp.setStatus(conn.getResponseCode());
    //Issue by Gregor Karlinger - content type was annotated twice
    //resp.setContentType(conn.getContentType());

    if (loginHeaders != null
            && (conn.getResponseCode() == HttpURLConnection.HTTP_OK
                    || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
            && req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {
        req.getSession().setAttribute(ATT_OA_AUTHORIZATION_HEADER, authorizationvalue);
        Logger.debug("Login OK. Saving authorization header to remember in further requests");
    }

    // Read response headers
    // Omit response header "content-length" if response header "Transfer-encoding: chunked" is set.
    // Otherwise, the connection will not be kept alive, resulting in subsequent missing requests.
    // See JavaDoc of javax.servlet.http.HttpServlet:
    // When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.
    Vector respHeaders = new Vector();

    boolean chunked = false;
    String contentLengthKey = null;
    String transferEncodingKey = null;
    int i = 1;
    String headerKey;
    String loginType = (String) req.getSession().getAttribute(ATT_OA_LOGINTYPE);
    while ((headerKey = conn.getHeaderFieldKey(i)) != null) {
        String headerValue = conn.getHeaderField(i);

        if (headerKey.equalsIgnoreCase("WWW-Authenticate")) {
            int start = headerValue.indexOf("Basic realm=\"");
            boolean requestsBasicAuth = headerValue.substring(start).startsWith("Basic realm=\"");
            if (requestsBasicAuth) {
                headerValue = "Basic realm=\"" + publicURLPrefix + "\"";

                if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding)
                        || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding))
                    headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
                else if ("none".equals(originBinding)) {
                    headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
                }
            }
        }

        //    // berschrift im Browser-Passworteingabedialog setzen (sonst ist der reale host eingetragen)
        //    if (headerKey.equalsIgnoreCase("WWW-Authenticate") && headerValue.startsWith("Basic realm=\"")) {
        //      headerValue = "Basic realm=\"" + publicURLPrefix + "\"";
        //      if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding) || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
        //      } else if (OAConfiguration.BINDUNG_NONE.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
        //      }
        //    }

        String respHeader[] = new String[2];
        if ((conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
                && headerKey.equalsIgnoreCase("content-length")) {
            //alter the unauthorized message with template for login 
            //TODO: supply a special login form on unauthorized messages with bindings!=full
            headerValue = Integer.toString(RET_401_MSG.length());
        }
        respHeader[0] = headerKey;
        respHeader[1] = headerValue;

        if (!(OAConfiguration.BINDUNG_FULL.equals(originBinding)
                && OAConfiguration.LOGINTYPE_STATELESS.equals(loginType)
                && headerKey.equalsIgnoreCase("WWW-Authenticate")
                && headerValue.startsWith("Basic realm=\""))) {
            respHeaders.add(respHeader);
            if (INTERNAL_DEBUG)
                Logger.debug("Resp header " + headerKey + ": " + headerValue);
        } else {
            Logger.debug("Resp header ---REMOVED--- " + headerKey + ": " + headerValue);
        }
        if (isTransferEncodingChunkedHeader(headerKey, headerValue)
                || "content-length".equalsIgnoreCase(headerKey)) {
            respHeaders.remove(respHeader);
            Logger.debug("Resp header " + headerKey + " REMOVED");
        }

        i++;
    }

    String headerValue;
    String respHeader[] = new String[2];

    //write out all Responseheaders 
    for (Iterator iter = respHeaders.iterator(); iter.hasNext();) {
        respHeader = (String[]) iter.next();
        headerKey = respHeader[0];
        headerValue = respHeader[1];
        resp.addHeader(headerKey, headerValue);
    }

    //Logger.debug(">>>> Copy Content");
    //Logger.debug("  from ()" + conn.getURL());
    //Logger.debug("  to (" + req.getRemoteAddr() + ":"+ ") " +req.getRequestURL());

    // read response stream
    Logger.debug("Resp from " + conn.getURL().toString() + ": status " + conn.getResponseCode());
    // Load content unless the server lets us know that the content is NOT MODIFIED...
    if (conn.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED) {
        BufferedInputStream respIn = new BufferedInputStream(conn.getInputStream());
        //Logger.debug("Got Inputstream");
        BufferedOutputStream respOut = new BufferedOutputStream(resp.getOutputStream());
        //Logger.debug("Got Outputstream");

        byte[] buffer = new byte[4096];
        if (respOut != null) {
            int bytesRead;
            while ((bytesRead = respIn.read(buffer)) >= 0) {
                if (conn.getResponseCode() != HttpURLConnection.HTTP_UNAUTHORIZED)
                    respOut.write(buffer, 0, bytesRead);
            }
        } else {
            while (respIn.read(buffer) >= 0)
                ;
        }

        /*
        int ch;
        StringBuffer strBuf = new StringBuffer("");
        while ((ch = respIn.read()) >= 0) {
          if (conn.getResponseCode()!=HttpURLConnection.HTTP_UNAUTHORIZED) respOut.write(ch);
          strBuf.append((char)ch);
        }
        Logger.debug("Resp Content:");
        if (strBuf.toString().length()>500)
          Logger.debug(strBuf.toString().substring(0,500));
        else
          Logger.debug(strBuf.toString());
        */

        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            respOut.write(RET_401_MSG.getBytes());
        }
        respOut.flush();
        respOut.close();
        respIn.close();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            Logger.debug("Found 401 UNAUTHORIZED...");
            cb.disconnect(conn);
            return conn.getResponseCode();
        }
    } else {
        //if (conn.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED) 
        Logger.debug("Found 304 NOT MODIFIED...");
    }

    cb.disconnect(conn);
    Logger.debug("Request done");

    return conn.getResponseCode();
}

From source file:org.sakaiproject.announcement.tool.AnnouncementAction.java

/**
 * Action is to use when ddoDelete requested, to perform deletion corresponding to chef_announcements-delete "eventSubmit_doDelete"
 *///from w ww. j av a2  s  .com
public void doDelete(RunData rundata, Context context) {

    // retrieve the state from state object
    AnnouncementActionState state = (AnnouncementActionState) getState(context, rundata,
            AnnouncementActionState.class);

    String peid = ((JetspeedRunData) rundata).getJs_peid();
    SessionState sstate = ((JetspeedRunData) rundata).getPortletSessionState(peid);

    // get the messages to be deleted from state object
    Vector v = state.getDelete_messages();
    Iterator delete_messages = v.iterator();

    while (delete_messages.hasNext()) {
        try {
            AnnouncementMessage message = (AnnouncementMessage) delete_messages.next();

            // get the channel id throught announcement service
            AnnouncementChannel channel = AnnouncementService
                    .getAnnouncementChannel(this.getChannelIdFromReference(message.getReference()));

            if (channel.allowRemoveMessage(message)) {
                // remove message from channel
                //AnnouncementMessageEdit edit = channel.editAnnouncementMessage(message.getId());
                //channel.removeMessage(edit); 
                channel.removeAnnouncementMessage(message.getId());

                // make sure auto-updates are enabled
                enableObservers(sstate);
            } else {
                addAlert(sstate, rb.getString("java.alert.youdel"));
            }
        } catch (IdUnusedException e) {
            if (M_log.isDebugEnabled())
                M_log.debug(this + ".doDeleteannouncement()", e);
        } catch (PermissionException e) {
            if (M_log.isDebugEnabled())
                M_log.debug(this + ".doDeleteannouncement()", e);
        } catch (NoSuchElementException e) {
            if (M_log.isDebugEnabled())
                M_log.debug(this + ".doDeleteannouncement()", e);
        }
    }

    state.setIsListVM(true);
    state.setStatus("FinishDeleting");

}

From source file:org.sakaiproject.announcement.tool.AnnouncementAction.java

/**
 * Build the context for asking for the delete confirmation
 *///w  ww.j  a va2s .com
protected String buildDeleteAnnouncementContext(VelocityPortlet portlet, Context context, RunData rundata,
        AnnouncementActionState state) {
    Vector v = state.getDelete_messages();
    if (v == null)
        v = new Vector();
    context.put("delete_messages", v.iterator());

    try {
        Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
        context.put("site", site);
    } catch (IdUnusedException e) {
        // No site available.
    } catch (NullPointerException e) {
    }
    context.put("channelAccess", MessageHeader.MessageAccess.CHANNEL);

    String template = (String) getContext(rundata).get("template");
    return template + "-delete";

}

From source file:org.geefive.salesforce.soqleditor.RESTfulQuery.java

public void executeQuery() throws Exception {
    Vector soqlResults = new Vector();

    HttpClient restClient = new HttpClient();
    restClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    restClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);

    //      String restfulURLTarget = serverDomain + REST_LOGIN;
    String restfulURLTarget = serverDomain + REST_QUERY;
    System.out.println("RESTful URL Target: " + restfulURLTarget);
    GetMethod method = null;//from   w  w  w  .ja va 2s .  c  o m
    try {
        method = new GetMethod(restfulURLTarget);
        System.out.println("Setting authorization header with SID [" + SID + "]");
        method.setRequestHeader("Authorization", "OAuth " + SID);

        NameValuePair[] params = new NameValuePair[1];
        params[0] = new NameValuePair("q", "SELECT Name, Id, Phone, CreatedById from Account LIMIT 100");
        method.setQueryString(params);

        int httpResponseCode = restClient.executeMethod(method);
        System.out.println("HTTP_RESPONSE_CODE [" + httpResponseCode + "]");
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out
                .println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXECUTING QUERY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        if (httpResponseCode == HttpStatus.SC_OK) {
            try {
                JSONObject response = new JSONObject(
                        new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream())));
                System.out.println("_____________________________________");
                System.out.println("RESPONSE [" + response + "]");
                //               Iterator itr = response.keys();
                //               while(itr.hasNext()){
                //                  String key = (String)itr.next();
                //                  System.out.println("KEY: " + (String)itr.next());
                //               }

                JSONArray resultArray = response.getJSONArray("records");
                StringBuffer soqlQueryResults = new StringBuffer();
                String token = "";
                JSONObject inner = null;
                System.out.println(resultArray.getString(0));
                inner = resultArray.getJSONObject(0);

                Iterator keys = inner.keys();
                HashMap columnNames = new HashMap();
                while (keys.hasNext()) {
                    String column = (String) keys.next();
                    System.out.println("KEY>> " + column);
                    columnNames.put(column, "");
                    soqlQueryResults.append(token + column);
                    token = " * ";
                }
                soqlResults.add(soqlQueryResults.toString());

                //System.out.println("******* UNCOMMENT ME FOR RELEASE *******");

                Iterator keyset = null;
                JSONArray results = response.getJSONArray("records");
                for (int i = 0; i < results.length(); i++) {
                    soqlQueryResults.setLength(0);
                    keyset = columnNames.keySet().iterator();
                    token = "";
                    while (keyset.hasNext()) {
                        String columnName = (String) keyset.next();
                        if (!columnName.equalsIgnoreCase("attributes")) {
                            soqlQueryResults.append(token + results.getJSONObject(i).getString(columnName));
                            token = " * ";
                        }
                    }

                    //                  System.out.println("=====>>>>>>> " + soqlQueryResults.toString());
                    soqlResults.add(soqlQueryResults.toString());

                    //                  System.out.println(results.getJSONObject(i).getString("Id") + ", "
                    //                        + results.getJSONObject(i).getString("Name") + ", "
                    //                        + results.getJSONObject(i).getString("Phone")
                    //                        + ", " + results.getJSONObject(i).getString("CreatedById"));
                } //end for
            } catch (JSONException jsonex) {
                throw jsonex;
            }
        }
    } finally {
        method.releaseConnection();
    }

    Iterator finalData = soqlResults.iterator();
    while (finalData.hasNext()) {
        System.out.println("-||=========>> " + (String) finalData.next());
    }

    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXIT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
}

From source file:org.apache.hadoop.mapred.JobTracker.java

public synchronized TaskReport[] getReduceTaskReports(JobID jobid) throws IOException {
    JobInProgress job = jobs.get(jobid);
    if (job != null) {
        // Check authorization
        aclsManager.checkAccess(job, UserGroupInformation.getCurrentUser(), Operation.VIEW_JOB_DETAILS);
    }/*from  w ww .j av a  2  s . co m*/
    if (job == null || !isJobInited(job)) {
        return EMPTY_TASK_REPORTS;
    } else {
        Vector<TaskReport> reports = new Vector<TaskReport>();
        Vector completeReduceTasks = job.reportTasksInProgress(false, true);
        for (Iterator it = completeReduceTasks.iterator(); it.hasNext();) {
            TaskInProgress tip = (TaskInProgress) it.next();
            reports.add(tip.generateSingleReport());
        }
        Vector incompleteReduceTasks = job.reportTasksInProgress(false, false);
        for (Iterator it = incompleteReduceTasks.iterator(); it.hasNext();) {
            TaskInProgress tip = (TaskInProgress) it.next();
            reports.add(tip.generateSingleReport());
        }
        return reports.toArray(new TaskReport[reports.size()]);
    }
}

From source file:org.apache.hadoop.mapred.JobTracker.java

public synchronized TaskReport[] getMapTaskReports(JobID jobid) throws IOException {
    JobInProgress job = jobs.get(jobid);
    if (job != null) {
        // Check authorization
        aclsManager.checkAccess(job, UserGroupInformation.getCurrentUser(), Operation.VIEW_JOB_DETAILS);
    }/* w w w .jav a  2  s.c o m*/
    if (job == null || !isJobInited(job)) {
        return EMPTY_TASK_REPORTS;
    } else {
        Vector<TaskReport> reports = new Vector<TaskReport>();
        Vector<TaskInProgress> completeMapTasks = job.reportTasksInProgress(true, true);
        for (Iterator it = completeMapTasks.iterator(); it.hasNext();) {
            TaskInProgress tip = (TaskInProgress) it.next();
            reports.add(tip.generateSingleReport());
        }
        Vector<TaskInProgress> incompleteMapTasks = job.reportTasksInProgress(true, false);
        for (Iterator it = incompleteMapTasks.iterator(); it.hasNext();) {
            TaskInProgress tip = (TaskInProgress) it.next();
            reports.add(tip.generateSingleReport());
        }
        return reports.toArray(new TaskReport[reports.size()]);
    }
}

From source file:org.apache.hadoop.mapred.JobTracker.java

public synchronized TaskReport[] getSetupTaskReports(JobID jobid) throws IOException {
    JobInProgress job = jobs.get(jobid);
    if (job != null) {
        // Check authorization
        aclsManager.checkAccess(job, UserGroupInformation.getCurrentUser(), Operation.VIEW_JOB_DETAILS);
    }/* w  w w . ja va2 s . com*/
    if (job == null || !isJobInited(job)) {
        return EMPTY_TASK_REPORTS;
    } else {
        Vector<TaskReport> reports = new Vector<TaskReport>();
        Vector<TaskInProgress> completeTasks = job.reportSetupTIPs(true);
        for (Iterator<TaskInProgress> it = completeTasks.iterator(); it.hasNext();) {
            TaskInProgress tip = it.next();
            reports.add(tip.generateSingleReport());
        }
        Vector<TaskInProgress> incompleteTasks = job.reportSetupTIPs(false);
        for (Iterator<TaskInProgress> it = incompleteTasks.iterator(); it.hasNext();) {
            TaskInProgress tip = it.next();
            reports.add(tip.generateSingleReport());
        }
        return reports.toArray(new TaskReport[reports.size()]);
    }
}

From source file:org.apache.hadoop.mapred.JobTracker.java

public synchronized TaskReport[] getCleanupTaskReports(JobID jobid) throws IOException {
    JobInProgress job = jobs.get(jobid);
    if (job != null) {
        // Check authorization
        aclsManager.checkAccess(job, UserGroupInformation.getCurrentUser(), Operation.VIEW_JOB_DETAILS);
    }//from w  ww  . ja v  a  2  s.c  o m
    if (job == null || !isJobInited(job)) {
        return EMPTY_TASK_REPORTS;
    } else {
        Vector<TaskReport> reports = new Vector<TaskReport>();
        Vector<TaskInProgress> completeTasks = job.reportCleanupTIPs(true);
        for (Iterator<TaskInProgress> it = completeTasks.iterator(); it.hasNext();) {
            TaskInProgress tip = it.next();
            reports.add(tip.generateSingleReport());
        }
        Vector<TaskInProgress> incompleteTasks = job.reportCleanupTIPs(false);
        for (Iterator<TaskInProgress> it = incompleteTasks.iterator(); it.hasNext();) {
            TaskInProgress tip = it.next();
            reports.add(tip.generateSingleReport());
        }
        return reports.toArray(new TaskReport[reports.size()]);
    }

}

From source file:org.sakaiproject.announcement.tool.AnnouncementAction.java

public void buildSortedContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState sstate) {
    //SAK-21532: making one list of messages in order to allow uniform sorting
    Vector messageList = new Vector();
    Vector showMessagesList = new Vector();

    List messages = prepPage(sstate);
    for (int i = 0; i < messages.size(); i++) {
        final AnnouncementMessage m = (AnnouncementMessage) messages.get(i);
        messageList.addElement(m);/*from  w ww .ja  v  a  2s  .c o m*/
    }

    AnnouncementActionState state = (AnnouncementActionState) getState(portlet, rundata,
            AnnouncementActionState.class);

    SortedIterator sortedMessageIterator;
    //For Announcement in User's MyWorkspace, the sort order for announcement is by date SAK-22667
    if (isOnWorkspaceTab()) {
        sortedMessageIterator = new SortedIterator(messageList.iterator(),
                new AnnouncementComparator(SORT_DATE, state.getCurrentSortAsc()));
    } else {
        sortedMessageIterator = new SortedIterator(messageList.iterator(),
                new AnnouncementComparator(state.getCurrentSortedBy(), state.getCurrentSortAsc()));
    }

    while (sortedMessageIterator.hasNext())
        showMessagesList.add((AnnouncementMessage) sortedMessageIterator.next());

    context.put("showMessagesList", showMessagesList.iterator());
    context.put("messageListVector", showMessagesList);
    context.put("showMessagesList2", showMessagesList.iterator());
    context.put("totalPageNumber", sstate.getAttribute(STATE_TOTAL_PAGENUMBER));
    context.put("formPageNumber", FORM_PAGE_NUMBER);
    context.put("prev_page_exists", sstate.getAttribute(STATE_PREV_PAGE_EXISTS));
    context.put("next_page_exists", sstate.getAttribute(STATE_NEXT_PAGE_EXISTS));
    context.put("current_page", sstate.getAttribute(STATE_CURRENT_PAGE));
    pagingInfoToContext(sstate, context);

    // SAK-9116: to use Viewing {0} - {1} of {2} items
    // find the position of the message that is the top first on the page
    if ((sstate.getAttribute(STATE_TOP_PAGE_MESSAGE) != null)
            && (sstate.getAttribute(STATE_PAGESIZE) != null)) {
        int topMsgPos = ((Integer) sstate.getAttribute(STATE_TOP_PAGE_MESSAGE)).intValue() + 1;
        int btmMsgPos = topMsgPos + ((Integer) sstate.getAttribute(STATE_PAGESIZE)).intValue() - 1;
        int allMsgNumber = btmMsgPos;
        if (sstate.getAttribute(STATE_NUM_MESSAGES) != null) {
            allMsgNumber = ((Integer) sstate.getAttribute(STATE_NUM_MESSAGES)).intValue();
            if (btmMsgPos > allMsgNumber)
                btmMsgPos = allMsgNumber;
        }

        String[] viewValues = { (new Integer(topMsgPos)).toString(), (new Integer(btmMsgPos)).toString(),
                (new Integer(allMsgNumber)).toString() };

        context.put("announcementItemRangeArray", viewValues);
    }
    // context.put("jsfutil", JsfUtil.this);

}