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

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

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.ooyala.api.OoyalaAPI.java

/**
 * Executes the request//from   w w  w  .ja  v  a2 s  .c o m
 * @param method The class containing the type of request (HttpGet, HttpDelete, etc)
 * @return The response from the server as an object of class Object. Must be casted to either a LinkedList<String> or an HashMap<String, Object>
 * @throws ClientProtocolException
 * @throws IOException
 * @throws HttpStatusCodeException 
 */
private Object executeRequest(HttpRequestBase method)
        throws ClientProtocolException, IOException, HttpStatusCodeException {
    HttpClient httpclient = new DefaultHttpClient();
    String response = httpclient.execute(method, createResponseHandler());
    if (!isResponseOK())
        throw new HttpStatusCodeException(response, getResponseCode());

    if (response.isEmpty())
        return null;

    JSONParser parser = new JSONParser();

    ContainerFactory containerFactory = new ContainerFactory() {
        @SuppressWarnings("rawtypes")
        public List creatArrayContainer() {
            return new LinkedList();
        }

        @SuppressWarnings("rawtypes")
        public java.util.Map createObjectContainer() {
            return new LinkedHashMap();
        }
    };

    //HashMap<String, Object> json = null;
    Object json = null;

    try {
        json = parser.parse(response, containerFactory);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    log.d("Response: " + json.toString());
    return json;
}

From source file:co.anarquianegra.rockolappServidor.mundo.ListaReproductor.java

private Cancion buscarCancionesEnApi(IListaOrdenada resultado, String pNombre, long id) {
    ApiWrapper wrapper = new ApiWrapper(client_id, client_secret, null, null);
    try {//from   w w  w .ja  v  a2s .  com
        Request r;
        if (id > -1)
            r = new Request("/tracks/" + id);
        else
            r = new Request("/tracks?q=" + pNombre);
        System.out.println("Buscando en sOUNDclOUD");
        HttpResponse resp = wrapper.get(r);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String s = Http.formatJSON(Http.getString(resp));
            try {
                if (id > -1) {
                    JSONObject json = (JSONObject) new JSONParser().parse(s);
                    System.out.println(json);
                    Cancion c = new Cancion((String) json.get("title"), (String) json.get("stream_url"));
                    c.setId((long) json.get("id"));
                    return c;
                } else {
                    JSONArray canciones = (JSONArray) new JSONParser().parse(s);
                    for (int i = 0; i < canciones.size(); i++) {
                        JSONObject json = (JSONObject) canciones.get(i);
                        System.out.println(json);
                        Cancion c = new Cancion((String) json.get("title"), (String) json.get("stream_url"));
                        c.setId((long) json.get("id"));
                        resultado.agregar(c);
                    }
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

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

@PUT
@Path("/update/{id}")
@Produces(MediaType.APPLICATION_JSON)// ww  w  . j av a  2  s .  c om
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String update(@PathParam("repositoryId") String repositoryId, @PathParam("id") String userId,
        @FormParam(FORM_USERNAME) String name, @FormParam(FORM_FIRSTNAME) String firstName,
        @FormParam(FORM_LASTNAME) String lastName, @FormParam(FORM_EMAIL) String email,
        @FormParam("addFavorites") String addFavorites, @FormParam("removeFavorites") String removeFavorites,
        @FormParam(FORM_PASSWORD) String password, @Context HttpServletRequest httpRequest) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();

    // Existing user
    User user = principalService.getUserById(repositoryId, userId);

    // Validation
    status = checkAuthorityForUser(status, errMsg, httpRequest, userId, repositoryId);
    // status = validateUser(status, errMsg, userId, name, firstName,
    // lastName);

    // Edit & Update
    if (status) {
        // Edit the user info
        // if a parameter is not input, it won't be modified.
        if (userId != null)
            user.setUserId(userId);
        if (name != null)
            user.setName(name);
        if (firstName != null)
            user.setFirstName(firstName);
        if (lastName != null)
            user.setLastName(lastName);
        if (email != null)
            user.setEmail(email);
        if (addFavorites != null) {
            try {
                JSONArray l = (JSONArray) (new JSONParser().parse(addFavorites));
                Set<String> fs = user.getFavorites();
                if (CollectionUtils.isEmpty(fs)) {
                    fs = new HashSet<String>();
                }
                fs.addAll(l);
                user.setFavorites(fs);
                System.out.println();
                // fs.addAll(l);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (removeFavorites != null) {
            try {
                JSONArray l = (JSONArray) (new JSONParser().parse(removeFavorites));
                user.getFavorites().removeAll(l);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(password)) {
            // TODO Error handling
            user = principalService.getUserById(repositoryId, userId);

            // Edit & Update
            if (status) {
                // Edit the user info
                String passwordHash = BCrypt.hashpw(password, BCrypt.gensalt());
                user.setPasswordHash(passwordHash);
                setModifiedSignature(httpRequest, user);

                try {
                    principalService.updateUser(repositoryId, user);
                } catch (Exception e) {
                    e.printStackTrace();
                    status = false;
                    addErrMsg(errMsg, ITEM_USER, ErrorCode.ERR_UPDATE);
                }
            }
        }
        setModifiedSignature(httpRequest, user);

        try {
            principalService.updateUser(repositoryId, user);
        } catch (Exception e) {
            e.printStackTrace();
            status = false;
            addErrMsg(errMsg, ITEM_USER, ErrorCode.ERR_UPDATE);
        }
    }

    makeResult(status, result, errMsg);
    return result.toJSONString();
}

From source file:eu.riscoss.rdc.RDCGithub.java

/**
 * For paginated requests/*w  ww . j  a v  a 2 s  .c  om*/
 * @param request
 * @param maxPages max pages in paginated requests
 * @param created_at_years maximum timespan for the "created at" field (used e.g. for issues). 0: no timespan
 * @return
 */
private JSONAware parsePaged(String request, int maxPages, int created_at_years) {

    JSONArray jaComplete = new JSONArray();

    char divider = '?';
    if (request.contains("?"))
        divider = '&';

    Calendar lastyear = Calendar.getInstance();//actual
    lastyear.set(Calendar.YEAR, lastyear.get(Calendar.YEAR) - created_at_years);

    try {
        for (int i = 1; i <= maxPages; i++) {

            String jsonPage = getData(repository + request + divider + "page=" + i, "");

            if (jsonPage.startsWith("WARNING")) {
                System.err.println(jsonPage); //error message - implement different handling if needed
            } else
                try {
                    JSONAware jv = (JSONAware) new JSONParser().parse(jsonPage);
                    if (jv instanceof JSONArray) {
                        JSONArray ja = (JSONArray) jv;
                        if (ja.size() == 0)
                            break;
                        jaComplete.addAll(ja);
                        //do not scan more years
                        if (created_at_years > 0) {
                            Calendar openedDate;
                            String openedAt = (String) ((JSONObject) ja.get(ja.size() - 1)).get("created_at");
                            if (openedAt != null) {
                                openedDate = DatatypeConverter.parseDateTime(openedAt);
                                //System.out.println("scan: opening date: "+openedDate.get(Calendar.YEAR)+" "+openedDate.get(Calendar.MONTH));
                                //System.out.println("scan: last    date: "+lastyear.get(Calendar.YEAR)+" "+lastyear.get(Calendar.MONTH));

                                if (openedDate.compareTo(lastyear) < 0) {
                                    System.out.println("BREAK");
                                    break;
                                }
                            }
                        }

                    }
                } catch (ParseException e) {
                    e.printStackTrace();//TODO
                }
        }

    } catch (org.apache.http.ParseException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return jaComplete;
}

From source file:com.wasteofplastic.askyblock.schematics.IslandBlock.java

/**
 * Sets this block's sign data//  w  w  w  . j  av a 2  s.c om
 * @param tileData
 */
public void setSign(Map<String, Tag> tileData) {
    signText = new ArrayList<String>();
    List<String> text = new ArrayList<String>();
    for (int i = 1; i < 5; i++) {
        String line = ((StringTag) tileData.get("Text" + String.valueOf(i))).getValue();
        // This value can actually be a string that says null sometimes.
        if (line.equalsIgnoreCase("null")) {
            line = "";
        }
        //System.out.println("DEBUG: line " + i + " = '"+ line + "' of length " + line.length());
        text.add(line);
    }

    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        public List creatArrayContainer() {
            return new LinkedList();
        }

        public Map createObjectContainer() {
            return new LinkedHashMap();
        }

    };
    // This just removes all the JSON formatting and provides the raw text
    for (int line = 0; line < 4; line++) {
        String lineText = "";
        if (!text.get(line).equals("\"\"") && !text.get(line).isEmpty()) {
            //String lineText = text.get(line).replace("{\"extra\":[\"", "").replace("\"],\"text\":\"\"}", "");
            //Bukkit.getLogger().info("DEBUG: sign text = '" + text.get(line) + "'");
            if (text.get(line).startsWith("{")) {
                // JSON string
                try {

                    Map json = (Map) parser.parse(text.get(line), containerFactory);
                    List list = (List) json.get("extra");
                    //System.out.println("DEBUG1:" + JSONValue.toJSONString(list));
                    if (list != null) {
                        Iterator iter = list.iterator();
                        while (iter.hasNext()) {
                            Object next = iter.next();
                            String format = JSONValue.toJSONString(next);
                            //System.out.println("DEBUG2:" + format);
                            // This doesn't see right, but appears to be the easiest way to identify this string as JSON...
                            if (format.startsWith("{")) {
                                // JSON string
                                Map jsonFormat = (Map) parser.parse(format, containerFactory);
                                Iterator formatIter = jsonFormat.entrySet().iterator();
                                while (formatIter.hasNext()) {
                                    Map.Entry entry = (Map.Entry) formatIter.next();
                                    //System.out.println("DEBUG3:" + entry.getKey() + "=>" + entry.getValue());
                                    String key = entry.getKey().toString();
                                    String value = entry.getValue().toString();
                                    if (key.equalsIgnoreCase("color")) {
                                        try {
                                            lineText += ChatColor.valueOf(value.toUpperCase());
                                        } catch (Exception noColor) {
                                            Bukkit.getLogger().warning("Unknown color " + value
                                                    + " in sign when pasting schematic, skipping...");
                                        }
                                    } else if (key.equalsIgnoreCase("text")) {
                                        lineText += value;
                                    } else {
                                        // Formatting - usually the value is always true, but check just in case
                                        if (key.equalsIgnoreCase("obfuscated")
                                                && value.equalsIgnoreCase("true")) {
                                            lineText += ChatColor.MAGIC;
                                        } else if (key.equalsIgnoreCase("underlined")
                                                && value.equalsIgnoreCase("true")) {
                                            lineText += ChatColor.UNDERLINE;
                                        } else {
                                            // The rest of the formats
                                            try {
                                                lineText += ChatColor.valueOf(key.toUpperCase());
                                            } catch (Exception noFormat) {
                                                // Ignore
                                                //System.out.println("DEBUG3:" + key + "=>" + value);
                                                Bukkit.getLogger().warning("Unknown format " + value
                                                        + " in sign when pasting schematic, skipping...");
                                            }
                                        }
                                    }
                                }
                            } else {
                                // This is unformatted text. It is included in "". A reset is required to clear
                                // any previous formatting
                                if (format.length() > 1) {
                                    lineText += ChatColor.RESET + format.substring(format.indexOf('"') + 1,
                                            format.lastIndexOf('"'));
                                }
                            }
                        }
                    } else {
                        // No extra tag
                        json = (Map) parser.parse(text.get(line), containerFactory);
                        String value = (String) json.get("text");
                        //System.out.println("DEBUG text only?:" + value);
                        lineText += value;
                    }
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                // This is unformatted text (not JSON). It is included in "".
                if (text.get(line).length() > 1) {
                    try {
                        lineText = text.get(line).substring(text.get(line).indexOf('"') + 1,
                                text.get(line).lastIndexOf('"'));
                    } catch (Exception e) {
                        //There may not be those "'s, so just use the raw line
                        lineText = text.get(line);
                    }
                } else {
                    // just in case it isn't - show the raw line
                    lineText = text.get(line);
                }
            }
            //Bukkit.getLogger().info("Line " + line + " is " + lineText);
        }
        signText.add(lineText);
    }
}

From source file:com.aerospike.load.AsWriterTask.java

private boolean processLine() {
    log.debug("processing  File:line " + Utils.getFileName(fileName) + this.lineNumber);
    bins = new ArrayList<Bin>();
    boolean lineProcessed = false;
    long errorTotal = 0;
    try {//from ww  w  . j av  a 2  s .  c o  m
        if (columns.size() != counters.write.colTotal) {
            if (columns.size() < counters.write.colTotal) {
                log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber
                        + " Number of column mismatch:Columns in data file is less than number of column in config file.");
            } else {
                throw new ParseException(lineNumber);
            }
        }

        //retrieve set name first
        for (ColumnDefinition metadataColumn : this.metadataMapping) {
            if (metadataColumn.staticValue
                    && metadataColumn.getBinNameHeader().equalsIgnoreCase(Constants.SET)) {
                this.set = metadataColumn.binValueHeader;
            } else {
                String metadataRawText = this.columns.get(metadataColumn.getBinValuePos());
                if (metadataColumn.getBinNameHeader().equalsIgnoreCase(Constants.SET)) {
                    if (this.set == null) {
                        this.set = metadataRawText;
                    }
                }
            }
        }
        // use set name to create key
        for (ColumnDefinition metadataColumn : this.metadataMapping) {
            if (metadataColumn.getBinNameHeader().equalsIgnoreCase(Constants.KEY)) {
                String metadataRawText = this.columns.get(metadataColumn.getBinValuePos());
                if (metadataColumn.getSrcType() == SrcColumnType.INTEGER) {
                    Long integer = Long.parseLong(metadataRawText);
                    this.key = new Key(this.nameSpace, this.set, integer);
                } else {
                    this.key = new Key(this.nameSpace, this.set, metadataRawText);
                }
            }
        }

        for (ColumnDefinition binColumn : this.binMapping) {
            Bin bin = null;

            if (!binColumn.staticName) {
                binColumn.binNameHeader = this.columns.get(binColumn.binNamePos);
            }

            if (!binColumn.staticValue) {
                String binRawText = null;
                if (binColumn.binValueHeader != null
                        && binColumn.binValueHeader.toLowerCase().equals(Constants.SYSTEM_TIME)) {
                    SimpleDateFormat sdf = new SimpleDateFormat(binColumn.getEncoding());//dd/MM/yyyy
                    Date now = new Date();
                    binRawText = sdf.format(now);
                } else {
                    binRawText = this.columns.get(binColumn.getBinValuePos());
                }

                if (binRawText.equals(""))
                    continue;

                switch (binColumn.getSrcType()) {
                case INTEGER:
                    //Server stores all integer type data in 64bit so use long
                    Long integer;
                    try {
                        integer = Long.parseLong(binRawText);
                        bin = new Bin(binColumn.getBinNameHeader(), integer);
                    } catch (Exception pi) {
                        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber
                                + " Integer/Long Parse Error:" + pi);
                    }

                    break;
                case FLOAT:

                    /**
                     * Floating type data can be stored as 8 byte byte array.
                      */
                    try {
                        float binfloat = Float.parseFloat(binRawText);
                        byte[] byteFloat = ByteBuffer.allocate(8).putFloat(binfloat).array();
                        bin = new Bin(binColumn.getBinNameHeader(), byteFloat);
                    } catch (Exception e) {
                        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber
                                + " Floating number Parse Error:" + e);
                    }
                    break;
                case STRING:
                    bin = new Bin(binColumn.getBinNameHeader(), binRawText);
                    break;
                case BLOB:
                    if (binColumn.getDstType().equals(DstColumnType.BLOB)) {
                        if (binColumn.encoding.equalsIgnoreCase(Constants.HEX_ENCODING))
                            bin = new Bin(binColumn.getBinNameHeader(), this.toByteArray(binRawText)); //TODO
                    }

                    break;
                case LIST:
                    /*
                     * Assumptions
                     * 1. Items are separated by a colon ','
                     * 2. Item value will be a string
                     * 3. List will be in double quotes
                     * 
                     * No support for nested maps or nested lists
                     * 
                     */
                    List<String> list = new ArrayList<String>();
                    String[] listValues = binRawText.split(Constants.LIST_DELEMITER, -1);
                    if (listValues.length > 0) {
                        for (String value : listValues) {
                            list.add(value.trim());
                        }
                        bin = Bin.asList(binColumn.getBinNameHeader(), list);
                    } else {
                        bin = null;
                        log.error("Error: Cannot parse to a list: " + binRawText);
                    }
                    break;
                case MAP:
                    /*
                     * Asumptions:
                     * 1. Items are separated by a colon ','
                     * 2. Name value pairs are separated by equals ':'
                     * 3. Map key is a string
                     * 4. Map value will be a string
                     * 5. Map will be in double quotes
                     * 
                     * No support for nested maps or nested lists
                     * 
                     */
                    Map<String, Object> map = new HashMap<String, Object>();
                    String[] mapValues = binRawText.split(Constants.MAP_DELEMITER, -1);
                    if (mapValues.length > 0) {
                        for (String value : mapValues) {
                            String[] kv = value.split(Constants.MAPKEY_DELEMITER);
                            if (kv.length != 2)
                                log.error("Error: Cannot parse map <k,v> using: " + kv);
                            else
                                map.put(kv[0].trim(), kv[1].trim());
                        }
                        log.debug(map.toString());
                        bin = Bin.asMap(binColumn.getBinNameHeader(), map);
                    } else {
                        bin = null;
                        log.error("Error: Cannot parse to a map: " + binRawText);
                    }
                    break;
                case JSON:
                    try {
                        log.debug(binRawText);
                        if (jsonParser == null)
                            jsonParser = new JSONParser();

                        Object obj = jsonParser.parse(binRawText);
                        if (obj instanceof JSONArray) {
                            JSONArray jsonArray = (JSONArray) obj;
                            bin = Bin.asList(binColumn.getBinNameHeader(), jsonArray);
                        } else {
                            JSONObject jsonObj = (JSONObject) obj;
                            bin = Bin.asMap(binColumn.getBinNameHeader(), jsonObj);
                        }
                    } catch (ParseException e) {
                        log.error("Failed to parse JSON", e);
                    }
                    break;
                case TIMESTAMP:
                    if (binColumn.getDstType().equals(DstColumnType.INTEGER)) {
                        DateFormat format = new SimpleDateFormat(binColumn.getEncoding());
                        try {
                            Date formatDate = format.parse(binRawText);
                            long miliSecondForDate = formatDate.getTime() - timeZoneOffset;

                            if (binColumn.getEncoding().contains(".SSS")
                                    && binColumn.binValueHeader.toLowerCase().equals(Constants.SYSTEM_TIME)) {
                                //We need time in miliseconds so no need to change it to seconds
                            } else {
                                miliSecondForDate = miliSecondForDate / 1000;
                            }
                            bin = new Bin(binColumn.getBinNameHeader(), miliSecondForDate);
                            log.trace("Date format:" + binRawText + " in seconds:" + miliSecondForDate);
                        } catch (java.text.ParseException e) {
                            e.printStackTrace();
                        }
                    } else if (binColumn.getDstType().equals(DstColumnType.STRING)) {
                        bin = new Bin(binColumn.getBinNameHeader(), binRawText);
                    }
                    break;

                default:

                }
            } else {
                bin = new Bin(binColumn.getBinNameHeader(), binColumn.getBinValueHeader());
            }

            if (bin != null) {
                bins.add(bin);
            }
        }
        lineProcessed = true;
        log.trace("Formed key and bins for line " + lineNumber + " Key: " + this.key.userKey + " Bins:"
                + this.bins.toString());
    } catch (AerospikeException ae) {
        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber
                + " Aerospike Bin processing Error:" + ae.getResultCode());
        if (log.isDebugEnabled()) {
            ae.printStackTrace();
        }
        counters.write.processingErrors.getAndIncrement();
        counters.write.recordProcessed.addAndGet(this.lineSize);
        errorTotal = (counters.write.readErrors.get() + counters.write.writeErrors.get()
                + counters.write.processingErrors.get());
        if (this.abortErrorCount != 0 && this.abortErrorCount < errorTotal) {
            System.exit(-1);
        }
    } catch (ParseException pe) {
        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber + " Parsing Error:" + pe);
        if (log.isDebugEnabled()) {
            pe.printStackTrace();
        }
        counters.write.processingErrors.getAndIncrement();
        counters.write.recordProcessed.addAndGet(this.lineSize);
        errorTotal = (counters.write.readErrors.get() + counters.write.writeErrors.get()
                + counters.write.processingErrors.get());
        if (this.abortErrorCount != 0 && this.abortErrorCount < errorTotal) {
            System.exit(-1);
        }
    } catch (Exception e) {
        log.error("File:" + Utils.getFileName(this.fileName) + " Line:" + lineNumber + " Unknown Error:" + e);
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        counters.write.processingErrors.getAndIncrement();
        counters.write.recordProcessed.addAndGet(this.lineSize);
        errorTotal = (counters.write.readErrors.get() + counters.write.writeErrors.get()
                + counters.write.processingErrors.get());
        if (this.abortErrorCount != 0 && this.abortErrorCount < errorTotal) {
            System.exit(-1);
        }
    }

    return lineProcessed;
}

From source file:hd3gtv.mydmam.db.orm.CassandraOrm.java

private Object pullColumn(ColumnList<String> columnlist, Field field) throws InvalidClassException {
    String name = field.getName();
    Class<?> fieldtype = field.getType();

    if (columnlist.getColumnByName(name) == null) {
        return null;
    }//  w w  w. j av a  2 s . c o m
    if (columnlist.getColumnByName(name).hasValue() == false) {
        return null;
    }

    if (columnlist.getColumnByName(name).getStringValue().equals(null_value)) {
        return null;
    } else if (fieldtype.isAssignableFrom(String.class)) {
        return columnlist.getColumnByName(name).getStringValue();
    } else if (fieldtype.isAssignableFrom(Byte[].class) | fieldtype.isAssignableFrom(byte[].class)) {
        return columnlist.getColumnByName(name).getByteArrayValue();
    } else if (fieldtype.isAssignableFrom(Integer.class) | fieldtype.isAssignableFrom(int.class)) {
        return columnlist.getColumnByName(name).getIntegerValue();
    } else if (fieldtype.isAssignableFrom(Long.class) | fieldtype.isAssignableFrom(long.class)) {
        return columnlist.getColumnByName(name).getLongValue();
    } else if (fieldtype.isAssignableFrom(Boolean.class) | fieldtype.isAssignableFrom(boolean.class)) {
        return columnlist.getColumnByName(name).getStringValue().equals("true");
    } else if (fieldtype.isAssignableFrom(Date.class)) {
        return columnlist.getColumnByName(name).getDateValue();
    } else if (fieldtype.isAssignableFrom(Float.class) | fieldtype.isAssignableFrom(float.class)) {
        return Float.valueOf(columnlist.getColumnByName(name).getStringValue());
    } else if (fieldtype.isAssignableFrom(Double.class) | fieldtype.isAssignableFrom(double.class)) {
        return Double.valueOf(columnlist.getColumnByName(name).getStringValue());
    } else if (fieldtype.isAssignableFrom(UUID.class)) {
        return columnlist.getColumnByName(name).getUUIDValue();
    } else if (fieldtype.isAssignableFrom(JSONObject.class)) {
        String value = "";
        try {
            Object o = fieldtype.newInstance();
            if (o instanceof JSONObject) {
                value = columnlist.getColumnByName(name).getStringValue();
                return (JSONObject) (new JSONParser()).parse(value);
            } else {
                return deserialize(columnlist.getColumnByName(name).getStringValue(), JSONObject.class);
            }
        } catch (InstantiationException e1) {
            return null;
        } catch (IllegalAccessException e1) {
            return null;
        } catch (ParseException e) {
            e.printStackTrace();
            System.err.println(value);
            return null;
        }
    } else if (fieldtype.isAssignableFrom(JSONArray.class)) {
        String value = "";
        try {
            Object o = fieldtype.newInstance();
            if (o instanceof JSONArray) {
                value = columnlist.getColumnByName(name).getStringValue();
                return (JSONArray) (new JSONParser()).parse(value);
            } else {
                return deserialize(columnlist.getColumnByName(name).getStringValue(), JSONArray.class);
            }
        } catch (InstantiationException e1) {
            return null;
        } catch (IllegalAccessException e1) {
            return null;
        } catch (ParseException e) {
            e.printStackTrace();
            System.err.println(value);
            return null;
        }
    } else if (fieldtype.isAssignableFrom(InetAddress.class)) {
        String value = columnlist.getColumnByName(name).getStringValue();
        try {
            return InetAddress.getByName(value);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            System.err.println(value);
            return null;
        }
    } else if (fieldtype.isAssignableFrom(StringBuffer.class)) {
        String value = columnlist.getColumnByName(name).getStringValue();
        return new StringBuffer(value);
    } else if (fieldtype.isAssignableFrom(Calendar.class)) {
        long value = columnlist.getColumnByName(name).getLongValue();
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(value);
        return c;
    } else if (fieldtype.isAssignableFrom(String[].class)) {
        String value = columnlist.getColumnByName(name).getStringValue();
        try {
            JSONArray ja = (JSONArray) (new JSONParser()).parse(value);
            String[] result = new String[ja.size()];
            for (int pos = 0; pos < ja.size(); pos++) {
                result[pos] = (String) ja.get(pos);
            }
            return result;
        } catch (ParseException e) {
            e.printStackTrace();
            System.err.println(value);
            return null;
        }
    } else {
        return deserialize(columnlist.getColumnByName(name).getStringValue(), fieldtype);
    }
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final void loadShops() {
    try {//from w ww .j a v  a2  s .c o  m
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONArray shopList = (JSONArray) jsonObj.get("shopsArray");

        // Make sure that our array isn't empty
        if (shopList == null) {
            Bukkit.getLogger().severe("[mcDropShop] Null shopList!");
            this.NullListException = true;
            return;
        }

        JSONObject shopObj;
        //System.out.println("[MDS DBG MSG] lS shopList.size() = "+shopList.size());
        for (int index = 0; index < shopList.size(); index++) {
            //System.out.println(index);

            shopObj = (JSONObject) (shopList.get(index));

            if (shopObj == null)
                continue; // Skip missing indices

            Holograms holo = new Holograms(this.plugin);
            holo.loadShop(shopObj, (JSONObject) jsonObj);

            Shops.shops.put(holo.shopName, holo);
        }
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in loadShops(void)");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in loadShops(void)");
        e.printStackTrace();
    }

    return;
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops delIndex(String shopName, String index, Player player) {
    if (!shops.containsKey(shopName)) {
        player.sendMessage("\u00a7eThat shop does not exist!");

        return this;
    }//from   ww w. j av  a 2  s.c o m

    try {
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONObject shopObj = (JSONObject) jsonObj.get(shopName);

        JSONArray shopItems = (JSONArray) shopObj.get("ShopItems");

        if (shopItems.size() <= Integer.parseInt(index)) {
            player.sendMessage("\u00a7eThat shop doesn't have an item at index (" + index + ")!");

            return this;
        }

        String itemName = (String) shopItems.get(Integer.parseInt(index));

        shopItems.remove(Integer.parseInt(index));

        shopObj.put("ShopItems", shopItems);

        shopObj.remove(itemName);

        jsonObj.put(shopName, shopObj);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        player.sendMessage("\u00a7aShop updated!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in delIndex()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in delIndex()");
        e.printStackTrace();
    }

    return this;
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops addBuy(String shopName, String cost, Player player) {
    try {/*from  w w w . j  ava 2 s .  c om*/
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONObject shopObj = (JSONObject) jsonObj.get(shopName);

        // Make sure the shop exists
        if (shopObj == null) {
            player.sendMessage("\u00a76That shop does not exist!");
            return this;
        }

        String newItem = player.getItemInHand().getType().name();

        Bukkit.getLogger()
                .info("Player \"" + player.getDisplayName() + "\" added " + newItem + " to shop " + shopName);

        JSONArray shopItems = (JSONArray) shopObj.get("ShopItems");

        shopItems.add(newItem + ":buy:" + player.getItemInHand().getDurability());

        shopObj.put("ShopItems", shopItems);

        JSONObject itemStub = new JSONObject();
        itemStub.put("amount", Integer.toString(player.getItemInHand().getAmount()));
        itemStub.put("price", cost);
        itemStub.put("type", "buy");
        itemStub.put("durability", "" + player.getItemInHand().getDurability());

        shopObj.put(newItem + ":buy:" + player.getItemInHand().getDurability(), itemStub);

        jsonObj.put(shopName, shopObj);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        player.sendMessage("\u00a7aShop updated!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addBuy()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addBuy()");
        e.printStackTrace();
    }

    return this;
}