Example usage for org.json.simple.parser ParseException getLocalizedMessage

List of usage examples for org.json.simple.parser ParseException getLocalizedMessage

Introduction

In this page you can find the example usage for org.json.simple.parser ParseException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:de.fhg.fokus.odp.portal.datasets.searchresults.BrowseDataSetsSearchResults.java

/**
 * This method retrieves the comments for a particular dataset. If we find
 * some comments, reverse them (last to first) and add for each comment the
 * correct screenname. Finally, store comments and screennames in
 * {@link RenderRequest}/*  www. j av a2  s .  c  o  m*/
 * 
 * @param request
 *            the {@link RenderRequest}
 * @param resultObject
 *            the {@link JSONObject}
 */
private void addCommentsAndNamesToRequest(RenderRequest request, JSONObject resultObject) {
    // get user comments
    JSONObject extras = (JSONObject) resultObject.get("extras");
    if (extras == null) {
        return;
    } else {
        JSONArray comments = null;
        if (extras.get(BrowseDataSetsSearchResults.COMMENTS_STRING) instanceof java.lang.String) {
            JSONParser parser = new JSONParser();
            try {
                comments = (JSONArray) parser
                        .parse((String) extras.get(BrowseDataSetsSearchResults.COMMENTS_STRING));
            } catch (ParseException e) {
                LOGGER.error(e.getLocalizedMessage(), e);
            }
        } else {
            comments = (JSONArray) extras.get(BrowseDataSetsSearchResults.COMMENTS_STRING);
        }
        if (comments == null) {
            return;
        } else {
            comments = reverseJSONArray(comments);
            String[] screenNames = getCommentersScreennames(comments);
            request.setAttribute(BrowseDataSetsSearchResults.COMMENTS_STRING, comments);
            request.setAttribute("commentersNames", screenNames);
        }
    }
}

From source file:Main_Window.java

public void Send_Receive_Data_Google_Service(boolean State) {
    try {//from w  w w. j  av  a  2s . c  o m
        ServerAddress = new URL("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                + Double.parseDouble(Latitude_TextField.getText()) + ","
                + Double.parseDouble(Longitude_TextField.getText()) + "&radius="
                + Double.parseDouble(Radius_TextField.getText()) + "&opennow=" + Boolean.toString(State)
                + "&types=" + Categories.getSelectedItem().toString() + "&key=" + API_KEY);
        //DELTE
        String str = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
                + Double.parseDouble(Latitude_TextField.getText()) + ","
                + Double.parseDouble(Longitude_TextField.getText()) + "&radius="
                + Double.parseDouble(Radius_TextField.getText()) + "&opennow=" + Boolean.toString(State)
                + "&types=" + Categories.getSelectedItem().toString() + "&key=" + API_KEY;
        System.out.println(" To url einai -> " + str);
        //set up out communications stuff
        Connection = null;
        //Set up the initial connection
        Connection = (HttpURLConnection) ServerAddress.openConnection();
        Connection.setRequestMethod("GET");
        Connection.setDoOutput(true); //Set the DoOutput flag to true if you intend to use the URL connection for output
        Connection.setDoInput(true);
        Connection.setRequestProperty("Content-type", "text/xml"); //Sets the general request property
        Connection.setAllowUserInteraction(false);
        Encode_String = URLEncoder.encode("test", "UTF-8");
        Connection.setRequestProperty("Content-length", "" + Encode_String.length());
        Connection.setReadTimeout(10000);
        // A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource. 
        //If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised. 
    } catch (IOException IOE) {
        JOptionPane.showMessageDialog(null, "Error -> " + IOE.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    try {
        wr = new DataOutputStream(Connection.getOutputStream());
        //open output stream to write
    } catch (IOException IOE) {
        JOptionPane.showMessageDialog(null, "Error -> " + IOE.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    try {
        wr.writeBytes("q=" + strData);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    try {
        wr.flush();
        //Force all data to write in channel
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    try {
        //read the result from the server
        Buffered_Reader = new BufferedReader(new InputStreamReader(Connection.getInputStream()));
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException",
                JOptionPane.ERROR_MESSAGE, null);
    }

    jsonParser = new JSONParser(); //JSON Parser

    try {
        JsonObject = (JSONObject) jsonParser.parse(Buffered_Reader); //Parse whole BuffererReader IN Object
        JSONArray Results_Array_Json = (JSONArray) JsonObject.get("results"); //take whole array - from json format
        //results - is as string unique that contains all the essential information such as arrays, and strings. So to extract all info we extract results into JSONarray
        //And this comes up due to json format
        for (int i = 0; i < Results_Array_Json.size(); i++) // Loop over each each part of array that contains info we must extract
        {
            JSONObject o = (JSONObject) Results_Array_Json.get(i);

            try { //We assume that for every POI exists for sure an address !!! thats why the code is not insida a try-catch
                Temp_Name = (String) o.get("name");
                Temp_Address = (String) o.get("vicinity");
                JSONObject Str_1 = (JSONObject) o.get("geometry"); //Geometry is object so extract geometry
                JSONArray Photo_1 = (JSONArray) o.get("photos");
                JSONObject Photo_2 = (JSONObject) Photo_1.get(0);
                String Photo_Ref = (String) Photo_2.get("photo_reference");
                JSONObject Str_2 = (JSONObject) Str_1.get("location");
                Temp_X = (double) Str_2.get("lat");
                Temp_Y = (double) Str_2.get("lng");
                //In case some POI has no Rating
                try {
                    //Inside try-catch block because may some POI has no rating
                    Temp_Rating = (double) o.get("rating");
                    Point POI_Object = new Point(Temp_Name, Temp_Address, Photo_Ref, Temp_Rating, Temp_X,
                            Temp_Y);
                    POI_List.add(POI_Object); //Add POI in List to keep it
                } catch (Exception Er) {
                    //JOptionPane.showMessageDialog ( null, "No rating for this POI " ) ;
                    Point POI_Object_2 = new Point(Temp_Name, Temp_Address, Photo_Ref, 0.0, Temp_X, Temp_Y);
                    POI_List.add(POI_Object_2); //Add POI in List to keep it
                }
            } catch (Exception E) {
                //JOptionPane.showMessageDialog ( this, "Error -> " + E.getLocalizedMessage ( ) + ", " + E.getMessage ( ) ) ;
            }
            o.clear();
        }
    } catch (ParseException PE) {
        JOptionPane.showMessageDialog(this, "Error -> " + PE.getLocalizedMessage(),
                "Parse, inside while JSON ERROR", JOptionPane.ERROR_MESSAGE, null);
    } catch (IOException IOE) {
        JOptionPane.showMessageDialog(this, "Error -> " + IOE.getLocalizedMessage(), "IOExcpiton",
                JOptionPane.ERROR_MESSAGE, null);
    }

    if (POI_List.isEmpty()) {
        JOptionPane.showMessageDialog(this, "No Results");
    } else {
        //Calculate Distance every POI from Longitude and latitude of User

        for (int k = 0; k < POI_List.size(); k++) {
            double D1 = Double.parseDouble(Latitude_TextField.getText()) - POI_List.get(k).Get_Distance_X();
            double D2 = Double.parseDouble(Longitude_TextField.getText()) - POI_List.get(k).Get_Distance_Y();
            double a = pow(sin(D1 / 2), 2) + cos(POI_List.get(k).Get_Distance_X())
                    * cos(Double.parseDouble(Latitude_TextField.getText())) * pow(sin(D2 / 2), 2);
            double c = 2 * atan2(sqrt(a), sqrt(1 - a));
            double d = 70000 * c; // (where R is the radius of the Earth)  in meters
            //add to list
            Distances_List.add(d);
        }

        //COPY array because Distances_List will be corrupted
        for (int g = 0; g < Distances_List.size(); g++) {
            Distances_List_2.add(Distances_List.get(g));
        }

        for (int l = 0; l < Distances_List.size(); l++) {
            int Dou = Distances_List.indexOf(Collections.min(Distances_List)); //Take the min , but the result is the position that the min is been placed
            Number_Name N = new Number_Name(POI_List.get(Dou).Get_Name()); //Create an object  with the name of POI in the min position in the POI_List
            Temp_List.add(N);
            Distances_List.set(Dou, 9999.99); //Make the number in the min position so large so be able to find the next min
        }
        String[] T = new String[Temp_List.size()]; //String array to holds all names of POIS that are going to be dispayled in ascending order
        //DISPLAY POI IN JLIST - Create String Array with Names in ascending order to create JList
        for (int h = 0; h < Temp_List.size(); h++) {
            T[h] = Temp_List.get(h).Get_Name();
        }
        //System.out.println ( " Size T -> " + T.length ) ;
        //Make JList and put String names 
        list = new JList(T);
        list.setForeground(Color.BLACK);
        list.setBackground(Color.GRAY);
        list.setBounds(550, 140, 400, 400);
        //list.setSelectionMode ( ListSelectionModel.SINGLE_SELECTION ) ;
        JScrollPane p = new JScrollPane(list);
        P.add(p);
        setContentPane(pane);
        //OK
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent event) {
                String selected = list.getSelectedValue().toString();
                System.out.println("Selected string" + selected);
                for (int n = 0; n < POI_List.size(); n++) {
                    if (selected.equals(POI_List.get(n).Get_Name())) {
                        try {
                            //read the result from the server
                            BufferedImage img = null;
                            URL u = new URL(
                                    "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference="
                                            + POI_List.get(n).Get_Photo_Ref() + "&key=" + API_KEY);
                            Image image = ImageIO.read(u);
                            IMAGE_LABEL.setText("");
                            IMAGE_LABEL.setIcon(new ImageIcon(image));
                            IMAGE_LABEL.setBounds(550, 310, 500, 200); //SOSOSOSOSOS
                            pane.add(IMAGE_LABEL);
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(),
                                    "Exception - IOException", JOptionPane.ERROR_MESSAGE, null);
                        }

                        Distance_L.setBounds(550, 460, 350, 150);
                        Distance_L.setText("");
                        Distance_L.setText(
                                "Distance from the current location: " + Distances_List_2.get(n) + "m");
                        pane.add(Distance_L);

                        Address_L.setBounds(550, 500, 350, 150);
                        Address_L.setText("");
                        Address_L.setText("Address: " + POI_List.get(n).Get_Address());
                        pane.add(Address_L);

                        Rating_L.setBounds(550, 540, 350, 150);
                        Rating_L.setText("");
                        Rating_L.setText("Rating: " + POI_List.get(n).Get_Rating());
                        pane.add(Rating_L);
                    }
                }
            }
        });
    } //Else not empty
}

From source file:org.kuali.mobility.academics.dao.AcademicsDaoJSONImpl.java

public List<Term> getTerms(final Map<String, String> query) {
    List<Term> lTerms = new ArrayList<Term>();

    try {/*from w  w  w.  ja va  2s.  c o m*/
        URLConnection connection = new URL(getTermUrl()).openConnection();
        InputStream response = connection.getInputStream();

        String jsonData = IOUtils.toString(response, DEFAULT_CHARACTER_SET);

        LOG.debug("JSON Data is: [" + jsonData + "]");

        JSONParser parser = new JSONParser();

        Object rootObj = parser.parse(jsonData);

        JSONObject jsonObject = (JSONObject) rootObj;
        JSONArray jsonTerms = (JSONArray) jsonObject.get("term");

        for (Object o : jsonTerms) {
            Term term = (Term) getApplicationContext().getBean("termBean");

            JSONObject jsonTerm = (JSONObject) o;

            if (jsonTerm.get("id") instanceof Long) {
                term.setId(((Long) (jsonTerm.get("id"))).toString());
            } else {
                term.setId((String) jsonTerm.get("id"));
            }
            term.setDescription((String) jsonTerm.get("description"));
            term.setShortDescription((String) jsonTerm.get("shortDescription"));
            if (jsonTerm.get("active") instanceof Boolean) {
                term.setActive(((Boolean) jsonTerm.get("active")).booleanValue());
            } else {
                term.setActive(Boolean.parseBoolean((String) jsonTerm.get("active")));
            }
            lTerms.add(term);
        }
    } catch (UnsupportedEncodingException uee) {
        LOG.error(uee.getLocalizedMessage());
    } catch (IOException ioe) {
        LOG.error(ioe.getLocalizedMessage());
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
    }

    return lTerms;
}

From source file:org.kuali.mobility.academics.dao.AcademicsDaoJSONImpl.java

public List<Career> getCareers(final Map<String, String> query) {
    List<Career> lCareers = new ArrayList<Career>();

    try {//from www .  j  a v  a 2s  .  c  om
        URLConnection connection = new URL(getCareerUrl()).openConnection();
        InputStream response = connection.getInputStream();

        String jsonData = IOUtils.toString(response, DEFAULT_CHARACTER_SET);

        LOG.debug("JSON Data is: [" + jsonData + "]");

        JSONParser parser = new JSONParser();

        Object rootObj = parser.parse(jsonData);

        JSONObject jsonObject = (JSONObject) rootObj;
        JSONArray jsonTerms = (JSONArray) jsonObject.get("academicCareer");

        for (Object o : jsonTerms) {
            Career career = (Career) getApplicationContext().getBean("careerBean");

            JSONObject jsonTerm = (JSONObject) o;

            if (jsonTerm.get("id") instanceof Long) {
                career.setId(((Long) (jsonTerm.get("id"))).toString());
            } else {
                career.setId((String) jsonTerm.get("id"));
            }
            career.setDescription((String) jsonTerm.get("description"));
            career.setShortDescription((String) jsonTerm.get("shortDescription"));
            lCareers.add(career);
        }
    } catch (UnsupportedEncodingException uee) {
        LOG.error(uee.getLocalizedMessage());
    } catch (IOException ioe) {
        LOG.error(ioe.getLocalizedMessage());
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
    }

    return lCareers;
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

@Override
public SearchResultImpl findEntries(SearchCriteria search) {
    SearchResultImpl results = null;//from ww  w .  j  a  v  a2 s. c  om
    String searchText = search.getSearchText();
    if (searchText != null && searchText.contains("<script>")) {
        // Do not perform any search
    }
    if (searchText != null && searchText.contains(";")) {
        // Do not perform any search
    } else if (searchText != null && searchText.contains("eval")) {
        // Do not perform any search
    } else {
        results = (SearchResultImpl) getApplicationContext().getBean("searchResult");

        StringBuilder queryString = new StringBuilder();

        if (search.getSearchText() != null && !search.getSearchText().trim().isEmpty()) {
            searchText = searchText.replaceAll("[^\\w\\s]", ""); //Removes all special character
            queryString.append("searchCriteria=");
            queryString.append(searchText.trim());
        } else if (search.getUserName() != null && !search.getUserName().isEmpty()) {
            queryString.append("uniqname=");
            queryString.append(search.getUserName().trim());
        } else {
            if ("starts".equalsIgnoreCase(search.getExactness())) {
                search.setExactness("starts with");
            }
            if (search.getFirstName() != null && !search.getFirstName().trim().isEmpty()) {
                queryString.append("givenName=");
                queryString.append(search.getFirstName().trim());
                queryString.append("&givenNameSearchType=");
                queryString.append(search.getExactness());
                queryString.append("&");
            }
            if (search.getLastName() != null && !search.getLastName().trim().isEmpty()) {
                queryString.append("sn=");
                queryString.append(search.getLastName().trim());
                queryString.append("&snSearchType=");
                queryString.append(search.getExactness());
            }
        }

        LOG.debug("QueryString will be : " + queryString.toString());

        try {
            URLConnection connection = new URL(SEARCH_URL).openConnection();

            connection.setDoOutput(true); // Triggers POST.
            connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET);
            OutputStream output = null;

            output = connection.getOutputStream();
            output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET));

            InputStream response = connection.getInputStream();
            String contentType = connection.getHeaderField("Content-Type");

            if (contentType != null && "application/json".equalsIgnoreCase(contentType)) {
                //               LOG.debug("Attempting to parse JSON using Gson.");

                List<Person> peeps = new ArrayList<Person>();
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(response, DEFAULT_CHARACTER_SET));

                    String jsonData = IOUtils.toString(response, DEFAULT_CHARACTER_SET);

                    LOG.debug("Attempting to parse JSON using JSON.simple.");
                    LOG.debug(jsonData);

                    JSONParser parser = new JSONParser();

                    Object rootObj = parser.parse(jsonData);

                    JSONObject jsonObject = (JSONObject) rootObj;
                    JSONArray jsonPerson = (JSONArray) jsonObject.get("person");
                    for (Object o : jsonPerson) {
                        peeps.add(parsePerson((JSONObject) o));
                    }
                } catch (UnsupportedEncodingException uee) {
                    LOG.error(uee.getLocalizedMessage());
                } catch (IOException ioe) {
                    LOG.error(ioe.getLocalizedMessage());
                } catch (ParseException pe) {
                    LOG.error(pe.getLocalizedMessage(), pe);
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException logOrIgnore) {
                            LOG.error(logOrIgnore.getLocalizedMessage());
                        }
                    }
                }
                results.setPeople(peeps);
            } else {
                LOG.debug("Content type was not application/json.");
            }
        } catch (IOException ioe) {
            LOG.error(ioe.getLocalizedMessage());
        }
        LOG.debug("Searching for groups.");
        results.setGroups(searchForGroup(search));
    }
    return results;
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

@Override
public Person lookupPerson(String personId) {
    Person person = null;/*from  www  .  ja  va  2s .  c  o  m*/

    BufferedReader reader = null;
    try {
        URL service = new URL(PERSON_LOOKUP_URL + personId);
        LOG.debug("Personlookupurl :" + PERSON_LOOKUP_URL + personId);

        String jsonData = null;
        jsonData = IOUtils.toString(service, DEFAULT_CHARACTER_SET);

        LOG.debug("Attempting to parse JSON using JSON.simple.");
        LOG.debug(jsonData);

        JSONParser parser = new JSONParser();

        Object rootObj = parser.parse(jsonData);

        JSONObject jsonObject = (JSONObject) rootObj;
        JSONObject jsonPerson = (JSONObject) jsonObject.get("person");

        if (jsonPerson == null) {
            LOG.debug("Results were not parsed, " + personId + " not found.");
        } else if (jsonPerson.containsKey("errors") && jsonPerson.get("errors") != null
                && jsonPerson.get("errors").hashCode() != 0) {
            // TODO get error description
            // Object v = raw.get("errors");
            LOG.debug("errors:" + jsonPerson.get("errors"));
        } else {
            person = parsePerson(jsonPerson);
        }

    } catch (UnsupportedEncodingException uee) {
        LOG.error(uee.toString());
    } catch (IOException ioe) {
        LOG.error(ioe.toString());
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException logOrIgnore) {
                LOG.error(logOrIgnore.getLocalizedMessage());
            }
        }
    }
    return person;
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

@SuppressWarnings("unchecked")
@Override/*from  w w w .  j a  v a2s  .c  o m*/
public Group lookupGroup(String dn) {
    Group group = (Group) getApplicationContext().getBean("directoryGroup");
    ;

    try {
        String newdn;
        if (!dn.startsWith("cn=")) {
            newdn = "cn=" + dn + ",ou=User Groups,ou=Groups,dc=umich,dc=edu";
        } else {
            newdn = dn;
        }
        newdn = newdn.replaceAll("\\s", "%20").trim();

        URL url = new URL(GROUP_LOOKUP_URL + newdn);

        LOG.debug("grouplookupurl :" + GROUP_LOOKUP_URL + newdn);

        String jsonData = null;
        jsonData = IOUtils.toString(url, DEFAULT_CHARACTER_SET);

        LOG.debug("Attempting to parse JSON using JSON.simple.");
        LOG.debug(jsonData);

        JSONParser parser = new JSONParser();

        Object rootObj = parser.parse(jsonData);

        JSONObject jsonObject = (JSONObject) rootObj;
        JSONObject jsonGroup = (JSONObject) jsonObject.get("group");

        if (null != jsonGroup.get("errors") && !"".equalsIgnoreCase((String) jsonGroup.get("errors"))) {
            // Process the errors.
        } else {
            group.setDN((String) jsonGroup.get("distinguishedName"));
            group.setDisplayName((String) jsonGroup.get("displayName"));
            group.setEmail((String) jsonGroup.get("email") + "@umich.edu");

            if (null != jsonGroup.get("description")) {
                if ((jsonGroup.get("description")) instanceof String) {
                    List<String> tDesc = new ArrayList<String>();
                    tDesc.add((String) jsonGroup.get("description"));
                    group.setDescriptions(tDesc);
                } else {
                    group.setDescriptions((List<String>) jsonGroup.get("description"));
                }
            }

            List<String> desc = new ArrayList<String>();
            desc.add((String) jsonGroup.get("description"));
            group.setDescriptions(desc);

            List<Person> owners = new ArrayList<Person>();
            if (null != jsonGroup.get("groupOwners")) {
                if ((jsonGroup.get("groupOwners")) instanceof JSONArray) {
                    JSONArray jsonOwners = (JSONArray) jsonGroup.get("groupOwners");
                    for (Object owner : jsonOwners) {
                        JSONObject o = (JSONObject) owner;
                        Person person = parsePerson(o);
                        owners.add(person);
                    }
                } else {
                    JSONObject o = (JSONObject) jsonGroup.get("groupOwners");
                    Person person = parsePerson(o);
                    owners.add(person);
                }
            }
            group.setOwners(owners);
        }

        url = new URL(GROUP_MEMBER_URL + newdn);
        jsonData = IOUtils.toString(url, DEFAULT_CHARACTER_SET);
        LOG.debug("Attempting to parse JSON using JSON.simple.");
        LOG.debug(jsonData);

        rootObj = parser.parse(jsonData);

        jsonObject = (JSONObject) rootObj;
        jsonGroup = (JSONObject) jsonObject.get("group");

        if (null != jsonObject.get("errors") && !"".equalsIgnoreCase((String) jsonObject.get("errors"))) {
            // Process the errors.
        } else {
            List<Person> members = new ArrayList<Person>();
            if ((jsonGroup.get("members")) instanceof JSONArray) {
                JSONArray jsonMembers = (JSONArray) jsonGroup.get("members");
                for (Object member : jsonMembers) {
                    JSONObject m = (JSONObject) member;
                    Person person = parsePerson(m);
                    members.add(person);
                }
            } else {
                JSONObject m = (JSONObject) jsonGroup.get("members");
                Person person = parsePerson(m);
                members.add(person);
            }
            LOG.debug("Adding " + members.size() + " members to the group.");
            group.setMembers(members);
            LOG.debug("Group's member list is " + group.getMembers().size() + " in length.");

            List<Group> subGroups = new ArrayList<Group>();

            if (null != jsonGroup.get("subGroups")) {
                // && !"".equalsIgnoreCase(
                // (String)jsonGroup.get("subGroups") ) ) {
                if (jsonGroup.get("subGroups") instanceof JSONArray) {
                    JSONArray jsonGroups = (JSONArray) jsonGroup.get("subGroups");
                    for (Object tsg : jsonGroups) {
                        Group subGroup = (Group) getApplicationContext().getBean("directoryGroup");
                        JSONObject sg = (JSONObject) tsg;
                        subGroup.setDN((String) sg.get("distinguishedName"));
                        if (null != sg.get("groupDescription")) {
                            if ((sg.get("groupDescription")) instanceof String) {
                                List<String> tDesc = new ArrayList<String>();
                                tDesc.add((String) sg.get("groupDescription"));
                                subGroup.setDescriptions(tDesc);
                            } else {
                                subGroup.setDescriptions((List) sg.get("groupDescription"));
                            }
                        }
                        subGroup.setDisplayName((String) sg.get("displayName"));
                        subGroup.setEmail((String) sg.get("groupEmail"));
                        subGroups.add(subGroup);
                    }
                } else {
                    Group subGroup = (Group) getApplicationContext().getBean("directoryGroup");
                    JSONObject sg = (JSONObject) jsonGroup.get("subGroups");
                    subGroup.setDN((String) sg.get("distinguishedName"));
                    if (null != sg.get("groupDescription")) {
                        if ((sg.get("groupDescription")) instanceof String) {
                            List<String> tDesc = new ArrayList<String>();
                            tDesc.add((String) sg.get("groupDescription"));
                            subGroup.setDescriptions(tDesc);
                        } else {
                            subGroup.setDescriptions((List) sg.get("groupDescription"));
                        }
                    }
                    subGroup.setDisplayName((String) sg.get("displayName"));
                    subGroup.setEmail((String) sg.get("groupEmail"));
                    subGroups.add(subGroup);
                }
            }
            group.setSubGroups(subGroups);
        }
    } catch (IOException ioe) {
        LOG.error(ioe.getLocalizedMessage(), ioe);
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
    }
    return group;
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

public List<Group> findSimpleGroup(String search) {

    List<Group> searchResults = new ArrayList<Group>();
    Group entry = null;//from   ww  w.  j  a  va2  s  .c  om
    StringBuilder queryString = new StringBuilder();

    if (search != null && !search.trim().isEmpty()) {
        queryString.append("searchCriteria=");
        queryString.append(search.trim());
    }

    LOG.debug("Group serach QueryString will be : " + queryString.toString());
    try {
        URLConnection connection = new URL(GROUP_SEARCH_URL).openConnection();

        connection.setDoOutput(true); // Triggers POST.
        connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET);
        OutputStream output = null;

        output = connection.getOutputStream();
        output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET));

        String jsonData = null;
        jsonData = IOUtils.toString(connection.getInputStream(), DEFAULT_CHARACTER_SET);

        LOG.debug("Attempting to parse JSON using JSON.simple.");
        LOG.debug(jsonData);

        JSONParser parser = new JSONParser();

        Object rootObj = parser.parse(jsonData);

        JSONObject jsonObject = (JSONObject) rootObj;

        JSONArray groups = (JSONArray) jsonObject.get("group");
        for (Object group : groups) {
            JSONObject g = (JSONObject) group;
            LOG.debug(g.toString());
            entry = (Group) getApplicationContext().getBean("directoryGroup");
            entry.setDN((String) g.get("distinguishedName"));
            if (null != g.get("errors") && (g.get("errors")) instanceof JSONObject) {
                JSONObject error = (JSONObject) g.get("errors");
                if (null != error.get("global")) {
                    JSONObject globalError = (JSONObject) error.get("global");
                    entry.setDisplayName("Error");
                    List<String> tDesc = new ArrayList<String>();
                    tDesc.add((String) globalError.get("description"));
                    entry.setDescriptions(tDesc);
                }
            } else {
                if (null != g.get("description")) {
                    if ((g.get("description")) instanceof String) {
                        List<String> tDesc = new ArrayList<String>();
                        tDesc.add((String) g.get("description"));
                        entry.setDescriptions(tDesc);
                    } else {
                        entry.setDescriptions((List) g.get("description"));
                    }
                }
                entry.setDisplayName((String) g.get("displayName"));
                entry.setEmail((String) g.get("email"));
            }
            searchResults.add(entry);
        }

    } catch (IOException ioe) {
        LOG.error(ioe.getLocalizedMessage(), ioe);
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
    }
    return searchResults;
}

From source file:proci.WebHandler.java

@Override
public void handle(HttpExchange t) throws IOException {
    logger.debug("HttpExchange from: {}", t.getRemoteAddress().getHostString());
    for (Map.Entry entry : t.getRequestHeaders().entrySet()) {
        logger.debug("header: {},{}", entry.getKey(), entry.getValue());
    }/*www .ja va 2  s  .c  o  m*/
    URI uri = t.getRequestURI();
    logger.debug("Path: {}", uri.getPath());
    logger.debug("Query: {}", uri.getQuery());
    String page = uri.getPath().replaceAll(App.HTTPCONTEXT, "").substring(1);
    logger.debug("Page: {}", page);
    //
    int code = 0;
    String response;
    JSONObject respJSON = new JSONObject();
    t.getResponseHeaders().add("Content-type:", "application/json");
    // tratto per semplicit allo stesso modo tutti i request method (POST,GET..)
    switch (page) {
    // funzione di status
    case "status":
        respJSON.put("status", "OK");
        respJSON.put("message", "Proci ver.: " + App.VERSION);
        code = 200;
        break;
    // upload immagine (solo se nella funzione)
    case "send":
        StringWriter sw = new StringWriter();
        IOUtils.copy(t.getRequestBody(), sw, "UTF-8");
        String in = sw.toString();
        logger.debug("String in: {}", in);
        JSONParser parser = new JSONParser();
        try {
            JSONObject obj2 = (JSONObject) parser.parse(in);
        } catch (ParseException pe) {
            respJSON.put("status", "ERRORE!");
            respJSON.put("message", "PARSE EXCEPTION: " + pe.getLocalizedMessage());
        }
        code = 200;
        break;
    default:
        respJSON.put("status", "ERRORE!");
        respJSON.put("message", "Pagina non trovata!");
        code = 404;
    }
    // risposta
    response = respJSON.toJSONString();
    t.sendResponseHeaders(code, response.getBytes("UTF-8").length);
    try (OutputStream os = t.getResponseBody()) {
        os.write(response.getBytes());
    }
}

From source file:tk.halfgray.pcommandbot.PCommandBot.java

/**
 * Parse the configuration.//from   w  w w.ja  v  a  2  s . c  o  m
 * @param creader Reader pointing to a JSON-encoded object
 * @throws java.io.IOException If there is a problem reading from {@code creader}
 * @throws IllegalArgumentException If the configuration could not be parsed,
 * or if the root value is not a JSON object
 * @see #loadConfiguration(java.io.Reader)
 */
protected void parseConfiguration(java.io.Reader creader) throws java.io.IOException {
    Object temp;
    try {
        temp = new JSONParser().parse(creader);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Could not parse configuration: " + e.getLocalizedMessage(), e);
    }
    if (temp instanceof JSONObject) {
        config = (JSONObject) temp;
    } else {
        throw new IllegalArgumentException("Root value of the configuration is not an object");
    }
}