/** (内部)搜索 */ private Representation searchOrderList( String firstType, String firstValue, String secondType, String secondValue, int itemsPerPage, int pageNum, boolean isLike) { ArrayList<SLOrder> listOrders = (ArrayList<SLOrder>) orderDao.searchOrderList( firstType, firstValue, secondType, secondValue, itemsPerPage, pageNum, isLike); OrderPage orderPage = new OrderPage(itemsPerPage, pageNum); orderPage.setTheOrders(listOrders); long totalNum = orderDao.selectCount(firstType, firstValue, secondType, secondValue, isLike); if (totalNum % itemsPerPage == 0) { orderPage.setTotalPageNum((int) totalNum / itemsPerPage); } else { orderPage.setTotalPageNum((int) totalNum / itemsPerPage + 1); } JsonRepresentation ret = new JsonRepresentation(orderPage); try { ret.getJsonObject().put(RestCallInfo.REST_STATUS, RestCallStatus.success); ret.getJsonObject().put(RestCallInfo.REST_ERROR_CODE, RestCallErrorCode.no_error); } catch (JSONException e) { e.printStackTrace(); } return ret; }
@Override protected Representation post(Representation entity, Variant variant) throws ResourceException { try { JsonRepresentation represent = new JsonRepresentation(entity); JSONArray json = represent.getJsonArray(); // iterate over each password entry List<Password> passwords = new LinkedList<Password>(); int length = json.length(); AddPasswordUtil apu = new AddPasswordUtil(); for (int i = 0; i < length; i++) { JSONObject object = (JSONObject) json.get(i); String lang = object.has("lang") ? object.getString("lang") : "en"; String pwEncoded = object.getString("text"); String pw = URLDecoder.decode(pwEncoded, "UTF-8"); apu.c(pw, lang); } // add passwords to model mModelUtils.addPasswords(apu); return createSuccessRepresentation("added passwords"); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); setStatus(Status.SERVER_ERROR_INTERNAL); } return createErrorRepresentation("error while creating passwords"); }
/** * Returns the stats matching the id given in the URI * * @return JSON representation of a festivalier * @throws JSONException */ @Get("json") public Representation getFestivalierStats() throws JSONException { JSONObject festivalierObject = getEtatsToJson(festivalier); JsonRepresentation result = new JsonRepresentation(festivalierObject); result.setIndenting(true); return result; }
/** * Returns the user matching the id given in the URI * * @return JSON representation of a user stats * @throws JSONException */ @Get("json") public Representation getStats() throws JSONException { // festivalier_ is set by doInit JSONObject statsObject = toJson(festivalier_); JsonRepresentation result = new JsonRepresentation(statsObject); result.setIndenting(true); return result; }
@Put public Representation baixarConta(Representation r) throws IOException, JSONException { JsonRepresentation jsonRep = new JsonRepresentation(r); JSONObject json = jsonRep.getJsonObject(); String numeroDocumento = json.getString("numeroDocumento"); boolean result = contaDao.baixarConta(numeroDocumento); if (result == true) { return new StringRepresentation("true"); } else { return new StringRepresentation("false"); } }
@Post public StringRepresentation destroy(Representation entity) { StringRepresentation representation = null; JsonRepresentation represent; try { represent = new JsonRepresentation(entity); UserSessions sessions = UserSessions.getInstance(); User user = sessions.getUserByRequest(getRequest()); JSONObject obj = represent.getJsonObject(); ClusterDao dao = new ClusterDao(); if (user != null) { int clusterID = Integer.valueOf(obj.get("0") + ""); String pwd = obj.get("1") + ""; if (pwd.equals("")) pwd = user.getCloudSecure(); ClusterConfiguration clusterConfig = dao.findSpecificCluster(user.getId(), clusterID); if (clusterConfig != null) { ConnectionUtil.getInputStream(clusterConfig.getCloudUsername(), pwd); if (clusterConfig.getState() == ClusterConfiguration.UP) { clusterConfig.setCloudPassword(pwd); clusterConfig.setActionType(ClusterConfiguration.DESTROY_CLUSTER); clusterConfig.setCloudgeneUser(user); clusterConfig.setState(ClusterConfiguration.QUEUE); // that it doesn't appear in queue / db at the same time dao.updateCluster(clusterConfig.getPk(), 1); // add to queue ClusterQueue.getInstance().submit(clusterConfig); // add to threadpool ClusterTask task = new ClusterTask(clusterConfig); ClusterThreadPoolDelete.getInstance().runTask(task); } getResponse().setStatus(Status.SUCCESS_OK); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); getResponse().setEntity(representation); return representation; } return representation; }
private static String writeJSONInternal(JsonRepresentation representation) { String result = ""; StringWriter writer = new StringWriter(); try { representation.write(writer); result += writer.toString(); } catch (IOException e) { log.log(Level.INFO, e.getMessage(), e); } return result; }
@Put("json") public Representation putBusDriverJSON(Representation representation) { try { JsonRepresentation userRepresentation = new JsonRepresentation(representation); BusDriver busDriver = JsonHandler.fromJson(userRepresentation.getText(), BusDriver.class); // trying to add new user int result = busHelper.addBusDriver(busDriver); // checking errors if (result == BusHelper.EC_INVALID_DNI) // an user with that id exists getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT); else if (result == BusHelper.EC_INVALID_AUTH_CODE) // invalid company registry authorization code getResponse().setStatus(Status.CLIENT_ERROR_PRECONDITION_FAILED); else if (result == BusHelper.EC_BBDD_ERROR) // error in DAO getResponse().setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE); } catch (Exception ioe) { // an error occurred getResponse().setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE); } return null; }
@Post public Representation criarContaAPagar(Representation r) throws IOException, JSONException { String tipoConta = (String) getRequestAttributes().get("tipoConta"); JsonRepresentation jsonRep = new JsonRepresentation(r); JSONObject json = jsonRep.getJsonObject(); Promissoria p = new Promissoria(); String numero = json.getString("numeroDocumento"); String dataEmissao = json.getString("dataEmissao"); String dataPagamento = json.getString("dataPagamento"); String descricao = json.getString("descricao"); String fornecedor = json.getString("fornecedor"); if (tipoConta.equals("promissoria")) { p = new Promissoria(); } else { String banco = json.getString("banco"); Duplicata d = new Duplicata(); d.setBanco(BancoDePagamento.valueOf(banco)); p = d; } p.setNumeroDocumento(numero); p.setDataEmissao(dataEmissao); p.setDataPagamento(dataPagamento); p.setDescricao(descricao); p.setFornecedor(fornecedor); // p.setStatus(Status.valueOf(status)); boolean result = contaDao.cadastroConta(p); if (result == true) { return new StringRepresentation("true"); } else { return new StringRepresentation("false"); } }
/** 获取预订信息 */ @GET @Path("getorderinfo/{orderId}") @Produces("application/json") public Representation getOrderInfo(@PathParam("orderId") int orderId) { SLOrder slOrder = orderDao.getSLOrderByOrderId(orderId); if (slOrder == null) { HashMap returnInfo = new HashMap(); returnInfo.put(RestCallInfo.REST_STATUS, RestCallStatus.fail); returnInfo.put(RestCallInfo.REST_ERROR_CODE, RestCallErrorCode.no_such_order); return new JsonRepresentation(returnInfo); } slOrder.setTheBook(bookDao.queryByISBN(slOrder.getBookISBN())); slOrder.setTheUser(userDao.getSLUserByEmail(slOrder.getUserEmail())); JsonRepresentation ret = new JsonRepresentation(slOrder); try { ret.getJsonObject().put(RestCallInfo.REST_STATUS, RestCallStatus.success); ret.getJsonObject().put(RestCallInfo.REST_ERROR_CODE, RestCallErrorCode.no_error); } catch (JSONException e) { e.printStackTrace(); } return ret; }
private Map<String, Object> toMap(JsonRepresentation entity) throws BadRequestException { if (entity == null) { return Collections.emptyMap(); } try { final String jsonString = entity.getJsonObject().toString(); if (StringUtils.isNotEmpty(jsonString)) { JsonValue jsonContent = JsonValueBuilder.toJsonValue(jsonString); return jsonContent.asMap(Object.class); } return Collections.emptyMap(); } catch (JSONException e) { throw new BadRequestException(e.getMessage()); } }
@Post public Representation acceptRepresentation(Representation entity) { Representation representation = null; try { JsonRepresentation represent = new JsonRepresentation(entity); UserSessions sessions = UserSessions.getInstance(); User user = sessions.getUserByRequest(getRequest()); JSONObject obj = represent.getJsonObject(); if (user != null) { ClusterConfiguration clusterConfig = new ClusterConfiguration(); String usr = obj.get("loginUsername").toString(); String pwd = obj.get("loginPassword").toString(); String program = obj.get("program").toString(); String ssh = obj.get("key").toString(); String name = obj.get("name").toString(); String provider = obj.get("cluster").toString(); String amount = obj.get("amount").toString(); String bucket = obj.get("bucketName").toString(); String type = obj.get("type").toString(); String dirLog = "logs"; /** check credentials */ ConnectionUtil.getInputStream(usr, pwd); UserDao dao = new UserDao(); if (!obj.has("saveCre")) { user.setCloudKey(""); user.setCloudSecure(""); dao.updateCredential(user); } else { user.setCloudKey(usr); user.setCloudSecure(pwd); dao.updateCredential(user); } user.setCloudKey(usr); user.setCloudSecure(pwd); /** save ssh data */ if (ssh.equals("1")) { createKey(clusterConfig, user); } else if (ssh.equals("3")) { clusterConfig.setSshPrivate(user.getSshKey()); clusterConfig.setSshPublic(user.getSshPub()); } if (obj.has("saveSsh")) { dao.updateSSH(user); } if (obj.has("s3Export")) { clusterConfig.setS3Bucket(bucket); } /** CONFIGURE CLUSTER */ Program prog = Programs.getProgramByName(program); clusterConfig.setProgram(prog.getCluster()); Utils.checkDirAvailable(dirLog); clusterConfig.setLog(dirLog + File.separatorChar + System.currentTimeMillis() + ".txt"); clusterConfig.setCloudID(String.valueOf(System.currentTimeMillis())); clusterConfig.setName(name); clusterConfig.getProgram().setProvider(provider); clusterConfig.setCloudUsername(usr); clusterConfig.setCloudPassword(pwd); clusterConfig.setAmount(Integer.valueOf(amount)); clusterConfig.setCloudgeneUser(user); clusterConfig.setSSHAvailable(true); clusterConfig.setInstanceType(type); clusterConfig.setStartTime(System.currentTimeMillis()); clusterConfig.setActionType(ClusterConfiguration.CREATE_CLUSTER); clusterConfig.setState(ClusterConfiguration.QUEUE); /** add to queue */ ClusterQueue.getInstance().submit(clusterConfig); /** add to threadpool */ ClusterTask task = new ClusterTask(clusterConfig); ClusterThreadPoolCreate.getInstance().runTask(task); getResponse().setStatus(Status.SUCCESS_OK); } else { representation = new StringRepresentation("No user"); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); getResponse().setEntity(representation); return representation; } } catch (S3ServiceException e) { representation = new StringRepresentation("Please check your security credentials"); getResponse().setEntity(representation); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); e.printStackTrace(); return representation; } catch (Exception e) { // TODO Auto-generated catch block representation = new StringRepresentation("Error occured"); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); getResponse().setEntity(representation); e.printStackTrace(); return representation; } return representation; }
@Post("application/json") public String getList(Representation entity) { System.out.println(" --------------------------------------------------------------------- "); System.out.println("ComponentRegisteredListWebService - Starting getList"); JsonObject jsonObjectRespond = new JsonObject(); try { wsCommunicationCloudServer = (WsCommunicationCloudServer) getContext().getAttributes().get(WebServicesApplication.PLUGIN_ROOT_ATT_NAME); /* * Construct the json object */ JSONObject requestParametersJsonObject = (new JsonRepresentation(entity)).getJsonObject(); System.out.println( "ComponentRegisteredListWebService - requestParametersJsonObject = " + requestParametersJsonObject); String clientIdentityPublicKey = requestParametersJsonObject.getString(JsonAttNamesConstants.NAME_IDENTITY); DiscoveryQueryParameters discoveryQueryParameters = new DiscoveryQueryParametersCommunication() .fromJson( requestParametersJsonObject.getString(JsonAttNamesConstants.DISCOVERY_PARAM)); /* * hold the result list */ List<PlatformComponentProfile> resultList = null; if (discoveryQueryParameters.getFromOtherPlatformComponentType() == null && discoveryQueryParameters.getFromOtherNetworkServiceType() == null) { resultList = applyDiscoveryQueryParameters(discoveryQueryParameters, clientIdentityPublicKey); } else { resultList = applyDiscoveryQueryParametersFromOtherComponent( discoveryQueryParameters, clientIdentityPublicKey); } System.out.println( "ComponentRegisteredListWebService - filteredLis.size() =" + resultList.size()); /* * Convert the list to json representation */ String jsonListRepresentation = gson.toJson( resultList, new TypeToken<List<PlatformComponentProfileCommunication>>() {}.getType()); /* * Create the respond */ jsonObjectRespond.addProperty(JsonAttNamesConstants.RESULT_LIST, jsonListRepresentation); } catch (Exception e) { System.out.println("ComponentRegisteredListWebService - requested list is not available"); jsonObjectRespond.addProperty( JsonAttNamesConstants.FAILURE, "Requested list is not available"); e.printStackTrace(); } String jsonString = gson.toJson(jsonObjectRespond); JsonRepresentation jsonRepresentationRespond = new JsonRepresentation(jsonString.trim()); System.out.println( "ComponentRegisteredListWebService - jsonString.length() = " + jsonString.length()); System.out.println( "ComponentRegisteredListWebService - jsonRepresentationRespond.getSize() = " + jsonRepresentationRespond.getSize()); return jsonString; }