Example usage for org.json.simple JSONObject clear

List of usage examples for org.json.simple JSONObject clear

Introduction

In this page you can find the example usage for org.json.simple JSONObject clear.

Prototype

void clear();

Source Link

Document

Removes all of the mappings from this map (optional operation).

Usage

From source file:com.capitalone.dashboard.client.project.ProjectDataClientImpl.java

/**
 * Updates the MongoDB with a JSONArray received from the source system
 * back-end with story-based data./*from  w  w w . j  av a 2 s.c  o  m*/
 *
 * @param tmpMongoDetailArray
 *            A JSON response in JSONArray format from the source system
 * @param featureCollector
 * @return
 * @return
 */
@SuppressWarnings("unchecked")
protected void updateMongoInfo(JSONArray tmpMongoDetailArray) {
    try {
        JSONObject dataMainObj = new JSONObject();
        for (int i = 0; i < tmpMongoDetailArray.size(); i++) {
            if (dataMainObj != null) {
                dataMainObj.clear();
            }
            dataMainObj = (JSONObject) tmpMongoDetailArray.get(i);
            Scope scope = new Scope();

            @SuppressWarnings("unused") // ?
            boolean deleted = this
                    .removeExistingEntity(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

            // collectorId
            scope.setCollectorId(featureCollectorRepository.findByName(Constants.VERSIONONE).getId());

            // ID;
            scope.setpId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

            // name;
            scope.setName(TOOLS.sanitizeResponse((String) dataMainObj.get("Name")));

            // beginDate;
            scope.setBeginDate(
                    TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("BeginDate"))));

            // endDate;
            scope.setEndDate(
                    TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("EndDate"))));

            // changeDate;
            scope.setChangeDate(
                    TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("ChangeDate"))));

            // assetState;
            scope.setAssetState(TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")));

            // isDeleted;
            scope.setIsDeleted(TOOLS.sanitizeResponse((String) dataMainObj.get("IsDeleted")));

            // path;
            String projPath = new String(scope.getName());
            List<String> projList = (List<String>) dataMainObj.get("ParentAndUp.Name");
            if (projList != null) {
                for (String proj : projList) {
                    projPath = proj + "-->" + projPath;
                }
                projPath = "All-->" + projPath;
            } else {
                projPath = "All-->" + projPath;
            }
            scope.setProjectPath(TOOLS.sanitizeResponse(projPath));

            try {
                projectRepo.save(scope);
            } catch (Exception e) {
                LOGGER.error("Unexpected error caused when attempting to save data\nCaused by: " + e.getCause(),
                        e);
            }
        }
    } catch (Exception e) {
        LOGGER.error("FAILED: " + e.getMessage() + ", " + e.getClass());
    }
}

From source file:com.capitalone.dashboard.client.team.TeamDataClientImpl.java

/**
 * Updates the MongoDB with a JSONArray received from the source system
 * back-end with story-based data./*  ww  w .  j  a v  a 2s  .  com*/
 * 
 * @param tmpMongoDetailArray
 *            A JSON response in JSONArray format from the source system
 * @param featureCollector
 * @return
 * @return
 */
protected void updateMongoInfo(JSONArray tmpMongoDetailArray) {
    try {
        JSONObject dataMainObj = new JSONObject();
        for (int i = 0; i < tmpMongoDetailArray.size(); i++) {
            if (dataMainObj != null) {
                dataMainObj.clear();
            }
            dataMainObj = (JSONObject) tmpMongoDetailArray.get(i);
            ScopeOwnerCollectorItem team = new ScopeOwnerCollectorItem();

            /*
             * Checks to see if the available asset state is not active from
             * the V1 Response and removes it if it exists and not active:
             */
            if (!TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")).equalsIgnoreCase("Active")) {

                this.removeInactiveScopeOwnerByTeamId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

            } else {
                boolean deleted = this
                        .removeExistingEntity(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));
                // Id
                if (deleted) {
                    team.setId(this.getOldTeamId());
                    team.setEnabled(this.isOldTeamEnabledState());
                }

                // collectorId
                team.setCollectorId(featureCollectorRepository.findByName(Constants.VERSIONONE).getId());

                // teamId
                team.setTeamId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

                // name
                team.setName(TOOLS.sanitizeResponse((String) dataMainObj.get("Name")));

                // changeDate;
                team.setChangeDate(
                        TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("ChangeDate"))));

                // assetState
                team.setAssetState(TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")));

                // isDeleted;
                team.setIsDeleted(TOOLS.sanitizeResponse((String) dataMainObj.get("IsDeleted")));

                try {
                    teamRepo.save(team);
                } catch (Exception e) {
                    LOGGER.error(
                            "Unexpected error caused when attempting to save data\nCaused by: " + e.getCause(),
                            e);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("FAILED: " + e.getMessage() + ", " + e.getClass(), e);
    }
}

From source file:com.punyal.medusaserver.californiumServer.core.MedusaAuthenticationThread.java

@Override
public void run() {
    running = true;/* w w  w  .ja va2s.c o  m*/
    Logger.getLogger("org.eclipse.californium.core.network.CoAPEndpoint").setLevel(Level.OFF);
    Logger.getLogger("org.eclipse.californium.core.network.EndpointManager").setLevel(Level.OFF);
    Logger.getLogger("org.eclipse.californium.core.network.stack.ReliabilityLayer").setLevel(Level.OFF);

    CoapResponse response;

    while (running) {
        if (ticket.isValid()) {
            //System.out.println("Valid Ticket");
        } else {
            //System.out.println("Not Valid Ticket");

            try {
                coapClient.setURI(medusaServerAddress + "/" + MEDUSA_SERVER_AUTHENTICATION_SERVICE_NAME);
                response = coapClient.get();

                if (response != null) {
                    try {
                        JSONObject json = (JSONObject) JSONValue.parse(response.getResponseText());
                        ticket.setAuthenticator(json.get(JSON_AUTHENTICATOR).toString());
                        //System.out.println(ticket.getAuthenticator());

                        json.clear();
                        json.put(JSON_USER_NAME, medusaUserName);
                        json.put(JSON_USER_PASSWORD, Cryptonizer.encryptCoAP(medusaSecretKey,
                                ticket.getAuthenticator(), medusaUserPass));
                        json.put(JSON_INFO, medusaUserInfo);
                        //System.out.println(json.toString());

                        response = coapClient.put(json.toString(), 0);

                        if (response != null) {
                            json.clear();
                            try {
                                json = (JSONObject) JSONValue.parse(response.getResponseText());
                                ticket.setTicket(
                                        UnitConversion.hexStringToByteArray(json.get(JSON_TICKET).toString()));
                                ticket.setExpireTime(
                                        (Long) json.get(JSON_TIME_TO_EXPIRE) + (new Date()).getTime());
                                //System.out.println((Long)json.get(JSON_TIME_TO_EXPIRE));
                                noAuthenticationResponseCounter = 0;
                                noTicketResponseCounter = 0;
                                if (authenticated == false) {
                                    //LOGGER.log(Level.INFO, SMS_AUTHENTICATED);
                                    System.err.println(SMS_AUTHENTICATED);
                                    authenticated = true;
                                }
                            } catch (Exception e) {
                                noTicketResponseCounter++;
                                //System.out.println("JSON Error "+e);
                            }
                        } else {
                            //System.out.println("No Ticket received.");
                            noTicketResponseCounter++;
                        }
                    } catch (Exception e) {
                        noAuthenticationResponseCounter++;
                        //System.out.println("JSON Error "+e);
                    }

                } else {
                    //System.out.println("No Authentication received.");
                    noAuthenticationResponseCounter++;

                }
            } catch (IllegalArgumentException ex) {
                noAuthenticationResponseCounter++;
            }

            if ((authenticated == true)
                    && ((noAuthenticationResponseCounter != 0) || (noTicketResponseCounter != 0))) {
                //LOGGER.log(Level.INFO, SMS_NO_AUTHENTICATED);
                System.err.println(SMS_NO_AUTHENTICATED);
                authenticated = false;
            }

            if (noAuthenticationResponseCounter > MAX_NO_AUTHENTICATION_RESPONSES) {
                try {
                    //LOGGER.log(Level.WARNING, SMS_NO_AUTHENTICATION_RESPONSE);
                    System.err.println(SMS_NO_AUTHENTICATION_RESPONSE);
                    sleep(NO_AUTHENTICATION_RESPONSES_DELAY);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MedusaAuthenticationThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                noAuthenticationResponseCounter = 0;
                noTicketResponseCounter = 0;
            }
            if (noTicketResponseCounter > MAX_NO_TICKET_RESPONSES) {
                try {
                    //LOGGER.log(Level.WARNING, SMS_NO_TICKET_RESPONSE);
                    System.err.println(SMS_NO_TICKET_RESPONSE);
                    sleep(NO_TICKET_RESPONSES_DELAY);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MedusaAuthenticationThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                noAuthenticationResponseCounter = 0;
                noTicketResponseCounter = 0;
            }
        }

    }

    LOGGER.log(Level.WARNING, "Thread [{0}] dying", MedusaAuthenticationThread.class.getSimpleName());
}

From source file:jp.aegif.nemaki.rest.UserResource.java

@SuppressWarnings("unchecked")
private JSONObject convertUserToJson(User user) {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    String created = new String();
    try {// ww w . j av  a 2 s  .c  om
        if (user.getCreated() != null) {
            created = sdf.format(user.getCreated().getTime());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    String modified = new String();
    try {
        if (user.getModified() != null) {
            modified = sdf.format(user.getModified().getTime());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    JSONObject userJSON = new JSONObject();
    userJSON.clear();
    userJSON.put(ITEM_USERID, user.getUserId());
    userJSON.put(ITEM_USERNAME, user.getName());
    userJSON.put(ITEM_FIRSTNAME, user.getFirstName());
    userJSON.put(ITEM_LASTNAME, user.getLastName());
    userJSON.put(ITEM_EMAIL, user.getEmail());
    userJSON.put(ITEM_TYPE, user.getType());
    userJSON.put(ITEM_CREATOR, user.getCreator());
    userJSON.put(ITEM_CREATED, created);
    userJSON.put(ITEM_MODIFIER, user.getModifier());
    userJSON.put(ITEM_MODIFIED, modified);

    boolean isAdmin = (user.isAdmin() == null) ? false : user.isAdmin();
    userJSON.put(ITEM_IS_ADMIN, isAdmin);

    JSONArray jfs = new JSONArray();
    Set<String> ufs = user.getFavorites();
    if (CollectionUtils.isNotEmpty(ufs)) {
        Iterator<String> ufsItr = ufs.iterator();
        while (ufsItr.hasNext()) {
            jfs.add(ufsItr.next());
        }
    }
    userJSON.put("favorites", jfs);

    return userJSON;
}

From source file:modelo.AutenticacionManager.PermisosAcceso.java

public JSONArray SeleccionarPermisos(String rol) throws SQLException {

    JSONArray permisos = new JSONArray();
    JSONArray ArrayPantallas = new JSONArray();
    JSONObject modulos = new JSONObject();
    JSONObject pantallas = new JSONObject();
    Boolean flag = true;/* w ww.j a va 2 s  .c  o m*/
    String modulo = "";
    String codigo_modulo = "";
    SeleccionarPermisos select = new SeleccionarPermisos();

    ResultSet result = select.getModulos();

    while (result.next()) {

        modulo = result.getString("VAR_MODULO");
        codigo_modulo = result.getString("PK_CODIGO");
        modulos.put("modulo", modulo);

        ResultSet rstPantallas = select.getPantallas(rol, codigo_modulo);

        while (rstPantallas.next()) {

            pantallas.put("codigo", rstPantallas.getString("PK_CODIGO"));
            pantallas.put("jsp", rstPantallas.getString("VAR_PANTALLA"));
            pantallas.put("pantalla", rstPantallas.getString("VAR_DESCRIPCION"));
            pantallas.put("existe", rstPantallas.getString("EXISTE"));

            ArrayPantallas.add(pantallas.clone());
            pantallas.clear();
        }

        modulos.put("pantallas", ArrayPantallas.clone());
        ArrayPantallas.clear();
        permisos.add(modulos.clone());
    }

    select.desconectar();
    return permisos;
}

From source file:com.piusvelte.taplock.server.ConnectionThread.java

@SuppressWarnings("unchecked")
@Override/*from   ww  w  .j a  v  a 2 s .  co  m*/
public void run() {
    TapLockServer.writeLog("ConnectionThread started");
    // retrieve the local Bluetooth device object
    // setup the server to listen for connection
    try {
        local = LocalDevice.getLocalDevice();
        local.setDiscoverable(DiscoveryAgent.GIAC);
        //         String url = "btspp://localhost:" + mRemoteAuthServerUUID.toString() + ";master=false;encrypt=false;authenticate=false;name=" + sSPD;
        String url = "btspp://localhost:" + sTapLockUUID.toString() + ";name=" + sSPD;
        notifier = (StreamConnectionNotifier) Connector.open(url);
    } catch (Exception e) {
        // no bluetooth present
        TapLockServer.writeLog("notifier init: " + e.getMessage());
        TapLockServer.shutdown();
        return;
    }
    JSONParser jsonParser = new JSONParser();
    while (notifier != null) {
        TapLockServer.writeLog("waiting for connection...");
        try {
            btConnection = notifier.acceptAndOpen();
        } catch (IOException e) {
            TapLockServer.writeLog("notifier.acceptAndOpen: " + e.getMessage());
            btConnection = null;
        }
        if (btConnection != null) {
            TapLockServer.writeLog("new connection...");
            try {
                btInStream = btConnection.openInputStream();
                btOutStream = btConnection.openOutputStream();
            } catch (IOException e) {
                TapLockServer.writeLog("inStream and outStream open: " + e.getMessage());
            }
            if ((btInStream != null) && (btOutStream != null)) {
                // send the challenge
                String challenge = Long.toString(System.currentTimeMillis());
                TapLockServer.writeLog("init challenge: " + challenge);
                JSONObject responseJObj = new JSONObject();
                responseJObj.put(TapLockServer.PARAM_CHALLENGE, challenge);
                String responseStr = responseJObj.toJSONString();
                try {
                    btOutStream.write(responseStr.getBytes());
                } catch (IOException e) {
                    TapLockServer.writeLog("outStream.write: " + e.getMessage());
                }
                // prepare to receive data
                byte[] btBuffer = new byte[1024];
                int btReadBytes = -1;
                try {
                    btReadBytes = btInStream.read(btBuffer);
                } catch (IOException e) {
                    TapLockServer.writeLog("inStream.read: " + e.getMessage());
                }
                while (btReadBytes != -1) {
                    responseJObj.clear();
                    String requestStr = new String(btBuffer, 0, btReadBytes);
                    TapLockServer.writeLog("request: " + requestStr);
                    JSONObject requestJObj = null;
                    try {
                        requestJObj = (JSONObject) jsonParser.parse(requestStr);
                    } catch (ParseException e) {
                        TapLockServer.writeLog("jsonParser.parse: " + e.getMessage());
                    }
                    if (requestJObj != null) {
                        if ((requestJObj != null) && requestJObj.containsKey(TapLockServer.PARAM_ACTION)
                                && requestJObj.containsKey(TapLockServer.PARAM_HMAC)) {
                            String requestAction = (String) requestJObj.get(TapLockServer.PARAM_ACTION);
                            TapLockServer.writeLog("action: " + requestAction);
                            String requestPassphrase = (String) requestJObj.get(TapLockServer.PARAM_PASSPHRASE);
                            if (requestPassphrase == null)
                                requestPassphrase = "";
                            String requestHMAC = (String) requestJObj.get(TapLockServer.PARAM_HMAC);
                            String validHMAC = null;
                            try {
                                validHMAC = TapLockServer.getHashString(challenge + TapLockServer.sPassphrase
                                        + requestAction + requestPassphrase);
                            } catch (NoSuchAlgorithmException e) {
                                TapLockServer.writeLog("getHashString: " + e.getMessage());
                            } catch (UnsupportedEncodingException e) {
                                TapLockServer.writeLog("getHashString: " + e.getMessage());
                            }
                            if (requestHMAC.equals(validHMAC)) {
                                if (TapLockServer.ACTION_PASSPHRASE.equals(requestAction))
                                    TapLockServer.setPassphrase(requestPassphrase);
                                else {
                                    if (TapLockServer.OS == TapLockServer.OS_WIN) {
                                        if (TapLockServer.ACTION_LOCK.equals(requestAction))
                                            runCommand("rundll32.exe user32.dll, LockWorkStation");
                                        else {
                                            // either unlock or toggle
                                            String password = "";
                                            Properties prop = new Properties();
                                            try {
                                                prop.load(new FileInputStream(TapLockServer.sProperties));
                                                if (prop.containsKey(TapLockServer.sPasswordKey))
                                                    password = TapLockServer.decryptString(
                                                            prop.getProperty(TapLockServer.sPasswordKey));
                                            } catch (FileNotFoundException e) {
                                                TapLockServer.writeLog("prop load: " + e.getMessage());
                                            } catch (IOException e) {
                                                TapLockServer.writeLog("prop load: " + e.getMessage());
                                            }
                                            Socket cpSocket = null;
                                            try {
                                                cpSocket = new Socket(TapLockServer.S_LOCALHOST,
                                                        TapLockServer.SERVER_PORT);
                                            } catch (UnknownHostException e) {
                                                TapLockServer.writeLog("socket: " + e.getMessage());
                                            } catch (IOException e) {
                                                TapLockServer.writeLog("socket: " + e.getMessage());
                                            }
                                            if (cpSocket != null) {
                                                InputStream cpInStream = null;
                                                OutputStream cpOutStream = null;
                                                try {
                                                    cpInStream = cpSocket.getInputStream();
                                                    cpOutStream = cpSocket.getOutputStream();
                                                } catch (IOException e) {
                                                    TapLockServer.writeLog("in/out stream: " + e.getMessage());
                                                }
                                                if ((cpInStream != null) && (cpOutStream != null)) {
                                                    // get the version
                                                    byte[] cpBuffer = new byte[1];
                                                    int cpReadBytes = -1;
                                                    try {
                                                        cpReadBytes = cpInStream.read(cpBuffer);
                                                    } catch (IOException e) {
                                                        TapLockServer
                                                                .writeLog("instream read: " + e.getMessage());
                                                    }
                                                    if (cpReadBytes != -1) {
                                                        TapLockServer.writeLog("credential provider version: "
                                                                + new String(cpBuffer, 0, cpReadBytes));
                                                        // pack the credentials
                                                        byte[] usernameBytes = System.getProperty("user.name")
                                                                .getBytes(Charset.forName("UTF-8"));
                                                        byte[] passwordBytes = password
                                                                .getBytes(Charset.forName("UTF-8"));
                                                        byte[] credentialsBuf = new byte[TapLockServer.S_CREDBUF];
                                                        for (int i = 0, l = usernameBytes.length; (i < l)
                                                                && (i < TapLockServer.S_USERBUF); i++)
                                                            credentialsBuf[i] = usernameBytes[i];
                                                        for (int i = 0, l = passwordBytes.length; (i < l)
                                                                && (i < TapLockServer.S_PASSBUF); i++)
                                                            credentialsBuf[i
                                                                    + TapLockServer.S_USERBUF] = passwordBytes[i];
                                                        try {
                                                            cpOutStream.write(credentialsBuf);
                                                        } catch (IOException e) {
                                                            TapLockServer.writeLog(
                                                                    "cpOutStream write: " + e.getMessage());
                                                        }
                                                        cpReadBytes = -1;
                                                        try {
                                                            cpReadBytes = cpInStream.read(credentialsBuf);
                                                        } catch (IOException e) {
                                                            TapLockServer.writeLog(
                                                                    "cpInStream read: " + e.getMessage());
                                                        }
                                                        // the socket should return "0" if no errors
                                                        if (cpReadBytes != -1) {
                                                            String cpResult = new String(credentialsBuf, 0,
                                                                    cpReadBytes);
                                                            TapLockServer.writeLog(
                                                                    "credential provider result: " + cpResult);
                                                            if (!TapLockServer.CREDENTIAL_PROVIDER_SUCCESS
                                                                    .equals(cpResult))
                                                                responseJObj.put(TapLockServer.PARAM_ERROR,
                                                                        "Authentication error, is the Windows password set in Tap Lock Server?");
                                                        }
                                                        try {
                                                            cpOutStream.close();
                                                        } catch (IOException e) {
                                                            TapLockServer.writeLog(
                                                                    "output close: " + e.getMessage());
                                                        }
                                                        try {
                                                            cpInStream.close();
                                                        } catch (IOException e) {
                                                            TapLockServer
                                                                    .writeLog("in close: " + e.getMessage());
                                                        }
                                                        try {
                                                            cpSocket.close();
                                                        } catch (IOException e) {
                                                            TapLockServer.writeLog(
                                                                    "socket close: " + e.getMessage());
                                                        }
                                                    }
                                                }
                                            } else
                                                runCommand("rundll32.exe user32.dll, LockWorkStation");
                                        }
                                    } else if (TapLockServer.OS == TapLockServer.OS_NIX) {
                                        if (TapLockServer.ACTION_TOGGLE.equals(requestAction))
                                            requestAction = TapLockServer.getToggleAction();
                                        String command = null;
                                        if (TapLockServer.ACTION_LOCK.equals(requestAction))
                                            command = "gnome-screensaver-command -a";
                                        else if (TapLockServer.ACTION_UNLOCK.equals(requestAction))
                                            command = "gnome-screensaver-command -d";
                                        if (command != null)
                                            runCommand(command);
                                    }
                                }
                            } else {
                                TapLockServer.writeLog("authentication failed");
                                responseJObj.put(TapLockServer.PARAM_ERROR, "authentication failed");
                            }
                        } else {
                            TapLockServer.writeLog("invalid request");
                            responseJObj.put(TapLockServer.PARAM_ERROR, "invalid request");
                        }
                    } else {
                        TapLockServer.writeLog("failed to parse request");
                        responseJObj.put(TapLockServer.PARAM_ERROR, "failed to parse request");
                    }
                    // send the new challenge
                    challenge = Long.toString(System.currentTimeMillis());
                    TapLockServer.writeLog("next challenge: " + challenge);
                    responseJObj.put(TapLockServer.PARAM_CHALLENGE, challenge);
                    responseStr = responseJObj.toJSONString();
                    try {
                        btOutStream.write(responseStr.getBytes());
                    } catch (IOException e) {
                        TapLockServer.writeLog("outStream.write: " + e.getMessage());
                    }
                    try {
                        btReadBytes = btInStream.read(btBuffer);
                    } catch (IOException e) {
                        TapLockServer.writeLog("inStream.read: " + e.getMessage());
                    }
                }
                if (btInStream != null) {
                    try {
                        btInStream.close();
                    } catch (IOException e) {
                        TapLockServer.writeLog("inStream.close: " + e.getMessage());
                    }
                }
                if (btOutStream != null) {
                    try {
                        btOutStream.close();
                    } catch (IOException e) {
                        TapLockServer.writeLog("outStream.close: " + e.getMessage());
                    }
                }
            }
            if (btConnection != null) {
                try {
                    btConnection.close();
                } catch (IOException e) {
                    TapLockServer.writeLog("connection.close: " + e.getMessage());
                }
                btConnection = null;
            }
        }
    }
}

From source file:com.fujitsu.dc.core.model.impl.es.DavCmpEsImpl.java

/**
 * ID?URL?. jsonObj?IDURL???//from  w  w w. java  2 s  . c  o  m
 * @param jsonObj ID??JSON
 * @param baseUrlStr xml:base
 */
@SuppressWarnings("unchecked")
private void roleIdToName(Object jsonObj, String baseUrlStr) {

    JSONArray array = new JSONArray();
    if (jsonObj instanceof JSONObject) {
        array.add(jsonObj);
    } else {
        array = (JSONArray) jsonObj;
    }
    if (array != null) {
        // xml:base
        for (int i = 0; i < array.size(); i++) {
            JSONObject aceJson = (JSONObject) array.get(i);
            JSONObject principal = (JSONObject) aceJson.get(KEY_ACL_PRINCIPAL);
            if (principal.get(KEY_ACL_HREF) != null) {
                // ID????????????????
                String roloResourceUrl = roleIdToRoleResourceUrl((String) principal.get(KEY_ACL_HREF));
                if (roloResourceUrl == null) {
                    // ID???????????????ACE???
                    array.remove(i);
                    --i;
                    // ????ID??????ACE??
                    if (array.isEmpty() && jsonObj instanceof JSONObject) {
                        JSONObject objJson = (JSONObject) jsonObj;
                        objJson.clear();
                    }
                    continue;
                }
                // base:xml?URL?
                roloResourceUrl = baseUrlToRoleResourceUrl(baseUrlStr, roloResourceUrl);
                principal.put(KEY_ACL_HREF, roloResourceUrl);
            } else if (principal.get(KEY_ACL_ALL) != null) {
                principal.put(KEY_ACL_ALL, null);
            }
        }
    }
}

From source file:com.capitalone.dashboard.util.ClientUtil.java

/**
 * Converts a Jira string representation of sprint artifacts into a
 * canonical JSONArray format.//from   www.j  a  v a 2  s . c  o  m
 * 
 * @param nativeRs
 *            a sanitized String representation of a sprint artifact link
 *            from Jira
 * @return A canonical JSONArray of Jira sprint artifacts
 */
@SuppressWarnings("unchecked")
public JSONObject toCanonicalSprintJSON(String nativeRs) {
    JSONObject canonicalRs = new JSONObject();
    CharSequence interrimChar;
    int start = 0;
    int end = 0;

    if ((nativeRs != null) && !(nativeRs.isEmpty())) {
        start = nativeRs.indexOf('[') + 1;
        end = nativeRs.length() - 1;
        StringBuffer interrimBuf = new StringBuffer(nativeRs);
        interrimChar = interrimBuf.subSequence(start, end);
        String interrimStr = interrimChar.toString();

        List<String> list = Arrays.asList(interrimStr.split(","));
        if ((list != null) && !(list.isEmpty())) {
            Iterator<String> listIt = list.iterator();
            while (listIt.hasNext()) {
                String temp = listIt.next();
                List<String> keyValuePair = Arrays.asList(temp.split("=", 2));
                if ((keyValuePair != null) && !(keyValuePair.isEmpty())) {
                    String key = keyValuePair.get(0).toString();
                    String value = keyValuePair.get(1).toString();
                    if ("<null>".equalsIgnoreCase(value)) {
                        value = "";
                    }
                    canonicalRs.put(key, value);
                }
            }
        }
    } else {
        canonicalRs.clear();
    }

    return canonicalRs;
}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Reads the modsecurity configuration file on modsecurity machine.
 * @param json//from www .j a v a2  s  . c  om
 */
@SuppressWarnings("unchecked")
public static void onReadMSConfig(JSONObject json) {

    log.info("onReadMSConfig called.. : " + json.toJSONString());
    MSConfig serviceCfg = MSConfig.getInstance();

    String fileName = serviceCfg.getConfigMap().get("MSConfigFile");
    InputStream ins;
    BufferedReader br;

    try {

        File file = new File(fileName);
        DataInputStream in;

        @SuppressWarnings("resource")
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        FileLock lock = channel.lock();

        try {

            ins = new FileInputStream(file);
            in = new DataInputStream(ins);
            br = new BufferedReader(new InputStreamReader(in));

            String line = "";

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

                //log.info("Line :" + line);
                for (ModSecConfigFields field : ModSecConfigFields.values()) {

                    if (line.startsWith(field.toString())) {

                        if (line.trim().split(" ")[0].equals(field.toString())) {
                            json.put(field.toString(), line.trim().split(" ")[1].replace("\"", ""));
                        }

                    }

                }

            }
            log.info("ModSecurity Configurations configurations Loaded ... ");

        } finally {

            lock.release();

        }
        br.close();
        in.close();
        ins.close();

    } catch (FileNotFoundException e1) {

        json.put("status", "1");
        json.put("message", "configuration file not found");
        e1.printStackTrace();

    } catch (IOException | NullPointerException e) {

        json.put("status", "1");
        json.put("message", "configuration file is corrupt");
        e.printStackTrace();

    }

    log.info("Sending Json :" + json.toJSONString());
    ConnectorService.getConnectorProducer().send(json.toJSONString());
    json.clear();

}

From source file:Main_Window.java

public void Send_Receive_Data_Google_Service(boolean State) {
    try {// w w w  .  j a v  a2 s .  c  om
        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
}