@Override public void processProperty( ISchemaType type, ISchemaProperty prop, ISerializationNode childNode, Set<String> processedTypes) { if (this.structureType == StructureType.COLLECTION) { int l = this.array.length(); for (int i = 0; i < l; i++) { JSONObject item; try { item = (JSONObject) this.array.get(i); appendProperty(item, type, prop, childNode); } catch (JSONException e) { e.printStackTrace(); } } } else if (this.structureType == StructureType.MAP) { try { for (Iterator<?> iter = this.object.keys(); iter.hasNext(); ) { String key = iter.next().toString(); JSONObject value = this.object.getJSONObject(key); appendProperty(value, type, prop, childNode); } } catch (JSONException e) { e.printStackTrace(); } } else { appendProperty(this.object, type, prop, childNode); } }
@PostConstruct public void listarGrupos() { JSONArray lista = null; try { JSONObject respuesta = new IGrupo().listarGrupos(sesion.getTokenId()); lista = respuesta.getJSONArray("lista"); listaGrupos.clear(); if (lista != null) { int len = lista.length(); for (int i = 0; i < len; i++) { try { JSONObject ob = lista.getJSONObject(i); JSONObject ob2 = ob.getJSONObject("grupo"); listaGrupos.add(ob2.getString("nombre")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { listaGrupos.clear(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@SuppressWarnings("deprecation") @GET @Path("/list/") @Produces("application/json") public JSONArray doGet(@QueryParam("ids") String paramIds) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); String[] ids = paramIds.split(","); JSONArray jsonMovies = new JSONArray(); for (String id : ids) { Entity movieEntity; JSONObject movieToAdd = null; Query query = new Query("Movie").addFilter("redboxid", Query.FilterOperator.EQUAL, id); List<Entity> movieEntitiesArray = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5)); if (movieEntitiesArray.size() == 0) { // need to get the movie from the Redbox and then add to db movieEntity = getRedboxInfoAndAdd(); } else { movieEntity = movieEntitiesArray.get(0); } try { // todo put the movie properties here movieToAdd.put("title", movieEntity.getProperty("title")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return jsonMovies; }
@Override public Contact checkIFPhoneNumberIsAContactOfUser(JSONObject data) { em = PersistenceManager.getEntityManagerFactory().createEntityManager(); String phone = ""; int userId = 0; try { phone = data.getString("phone"); userId = data.getInt("userId"); } catch (JSONException e) { e.printStackTrace(); } try { return (Contact) em.createQuery( "SELECT c FROM Contact c WHERE c.phone = '" + phone + "' AND c.user_owner.id = " + userId) .getSingleResult(); } catch (NoResultException e) { return null; } }
@POST @Path("/addNewParentTestField") @Produces("text/plain") @Consumes(MediaType.APPLICATION_JSON) public String addNewParentField(JSONObject obj) { try { JSONArray data = obj.getJSONArray("parentfileds"); Set<ParentTestFields> ParentFieldList = new HashSet<ParentTestFields>(); for (int curr = 0; curr < data.length(); curr++) { ParentTestFields pf = new ParentTestFields(); pf.setParentField_IDName("PF"); pf.setParent_FieldName(data.getJSONObject(curr).getString("parent_FieldName")); // pf.setfTest_RangeID(testFieldsRangeDBDriver.getTestFieldRangeByID(Integer.parseInt(data.getJSONObject(curr).getString("fTest_RangeID")))); pf.setfTest_NameID( testNamesDBDriver.getTestNameByID( Integer.parseInt(data.getJSONObject(curr).getString("fTest_NameID")))); ParentFieldList.add(pf); } for (ParentTestFields pf : ParentFieldList) { parentfieldDBDriver.addNewParentTestField(pf); } } catch (JSONException e) { e.printStackTrace(); return null; } catch (Exception e) { System.out.println(e.getMessage()); return null; } return "TRUE"; }
/** * Get the URL of the file to download. This has not been modified from the original version. * * <p>For more information, please see: <a href= * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features"> * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting- * portal-help#features</a> * * <p>Original code can be accessed at: <a href= * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip"> * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a> * * @see #login(String, String) * @see org.collegeboard.scoredwnld.client.FileInfo * @author CollegeBoard * @param accessToken Access token obtained from {@link #login(String, String)} * @param filePath File to download * @return FileInfo descriptor of file to download */ private FileInfo getFileUrlByToken(String accessToken, String filePath) { Client client = getClient(); WebResource webResource = client.resource( scoredwnldUrlRoot + "/pascoredwnld/file?tok=" + accessToken + "&filename=" + filePath); ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } try { JSONObject json = new JSONObject(response.getEntity(String.class)); FileInfo fileInfo = new FileInfo(); fileInfo.setFileName(filePath); fileInfo.setFileUrl(String.valueOf(json.get("fileUrl"))); return fileInfo; } catch (ClientHandlerException e) { log("Error: " + e.getMessage()); e.printStackTrace(); } catch (UniformInterfaceException e) { log("Error: " + e.getMessage()); e.printStackTrace(); } catch (JSONException e) { log("Error: " + e.getMessage()); e.printStackTrace(); } return null; }
private ComboAvailableList() { this.playerCombos = new HashMap<>(); try { JSONObject configs = new JSONObject(FilesTools.readFile(ConfigPath.comboAvailableList)); Iterator iterator = configs.keys(); while (iterator.hasNext()) { String name = (String) iterator.next(); EGameObject player = EGameObject.getEnumByValue(name); if (player != EGameObject.NULL) { this.playerCombos.put(player, new ArrayList<>()); JSONArray combos = configs.getJSONArray(name); for (int i = 0; i < combos.length(); ++i) { this.playerCombos .get(player) .add( new Pair<>( combos.getJSONObject(i).getString("name"), combos.getJSONObject(i).getString("combo"))); } } } } catch (JSONException e) { e.printStackTrace(); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Long id = Long.valueOf(request.getParameter("id")); Contact contact = contactService.getById(id); HttpSession session = request.getSession(); if (contact != null) { contactService.remove(id); try { conversationService.removeConversationByUserAndContact( new JSONObject() .put("userId", ((User) session.getAttribute("user")).getId()) .put("phoneNumber", contact.getPhone())); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/auth/contact"); } else { session.setAttribute(Alert.PRMTR_ERROR, "The contact doesn't exist !"); request.setAttribute("pageTitle", "Contacts"); request.getRequestDispatcher("/auth/contact.jsp").forward(request, response); } }
@GET @Path("/registerCoupons/{id}&{couponcode}&{allocated}&{used}/") @Produces(MediaType.APPLICATION_JSON) public JSONObject registerCoupons( @PathParam("id") String id, @PathParam("couponcode") String couponcode, @PathParam("allocated") String allocated, @PathParam("used") String used) { JSONObject res = new JSONObject(); System.out.println("Inside registerCoupons "); Registration registration = new Registration(); int response = registration.registerCoupons(id, couponcode, allocated, used); try { if (response == 0) { res.append("result", "200"); res.append("response", "Successfully Registered"); } else { res.append("result", "400"); res.append("response", "Not Registered"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; }
public void registrarUsuario(ActionEvent ae) { try { JSONObject respuesta = new IUsuario() .registrarUsuario( sesion.getTokenId(), sesion.getMail(), nombre, apellido, telefono, interno, contrasena); String status = respuesta.getString("status"); if (status.equals("2")) { sesion.setNuevoUsuario(false); } System.out.println(sesion.isNuevoUsuario()); String mensaje = respuesta.getString("mensaje"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(mensaje, null)); } catch (JSONException e) { e.printStackTrace(); System.out.println("ERROR JSOOOOOOOOOOOON"); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String conversationId = request.getParameter("id"); try { List<SMS> sms = smsService.getAllSMSByConversation( new JSONObject().put("conversationId", conversationId)); request.setAttribute("sms", sms); Conversation conversation = conversationService.getConversationById( new JSONObject().put("conversationId", Integer.parseInt(conversationId))); request.setAttribute("conversationNumber", conversation.getContactName()); Contact contact = contactService.getContactByPhoneAndUser( new JSONObject() .put("phone", conversation.getContactName()) .put("userId", ((User) request.getSession().getAttribute("user")).getId())); if (contact != null) conversation.setContactName(contact.getFirstName() + " " + contact.getLastName()); request.setAttribute("conversation", conversation); } catch (JSONException e) { e.printStackTrace(); } request.setAttribute("pageTitle", "Conversation"); request.getRequestDispatcher("/auth/conversation.jsp").forward(request, response); }
public List<NombreMail> listarAdministradores() { JSONObject respuesta = new IGrupo().listarAdministradores(sesion.getTokenId()); JSONArray admins = null; listaAdministradores.clear(); try { admins = respuesta.getJSONArray("lista"); if (admins != null) { for (int i = 0; i < admins.length(); i++) { JSONObject ob = admins.getJSONObject(i); NombreMail b = new NombreMail(); b.setMail(ob.getString("correo")); b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido")); listaAdministradores.add(b); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listaAdministradores; }
@POST @Consumes(MediaType.APPLICATION_JSON) public Response saveListItem(InputStream incomingData) { StringBuilder listBuilder = new StringBuilder(); try { BufferedReader in = new BufferedReader(new InputStreamReader(incomingData)); String line = null; while ((line = in.readLine()) != null) { listBuilder.append(line); } } catch (Exception e) { System.out.println("Error Parsing: - "); } try { JSONObject json = new JSONObject(listBuilder.toString()); Iterator<String> iterator = json.keys(); if (list == null) { list = new ArrayList<ListItem>(); } ListItem item = new ListItem( (String) json.get(iterator.next()), (String) json.get(iterator.next()), (Boolean) json.get(iterator.next())); list.add(item); } catch (JSONException e) { e.printStackTrace(); return Response.status(500).entity(listBuilder.toString()).build(); } // return HTTP response 200 in case of success return Response.status(200).entity(listBuilder.toString()).build(); }
private void appendProperty( JSONObject item, ISchemaType type, ISchemaProperty prop, ISerializationNode childNode) { Node n = (Node) childNode; ISchemaType propType = prop.getType(); String propName = type.getQualifiedPropertyName(prop); try { if (prop.isAttribute()) { propName = "@" + propName; if (prop.getStructureType() == StructureType.MAP) { IMapSchemaProperty mapProp = (IMapSchemaProperty) prop; Object defaultValue = DefaultValueFactory.getDefaultValue(mapProp.getValueType()); item.put(propName + "_1", defaultValue + "_1"); item.put(propName + "_2", defaultValue + "_2"); } else { Object defaultValue = DefaultValueFactory.getDefaultValue(propType); item.put(propName, defaultValue); } } else if (prop.getStructureType() == StructureType.COLLECTION) { item.put(propName, n.array); } else if (propType == null || propType.isComplex()) { item.put(propName, n.object); } else { Object defaultValue = DefaultValueFactory.getDefaultValue(prop); if (item != null) item.put(propName, defaultValue); } } catch (JSONException e) { e.printStackTrace(); } }
/** * **************************************************************** * * <p>REGISTRATION URL FOR VARIOUS USERS 1. Kandy Details 2. Rewards * * <p>**************************************************************** */ @GET @Path("/registerKandy/{id}&{username}&{password}&{key}&{provider}&{uid}/") @Produces(MediaType.APPLICATION_JSON) public JSONObject registerEndUser( @PathParam("id") String id, @PathParam("username") String username, @PathParam("password") String password, @PathParam("key") String key, @PathParam("provider") String provider, @PathParam("uid") String uid) { JSONObject res = new JSONObject(); System.out.println("Inside registerKandy Helper"); Registration registration = new Registration(); int response = registration.registerKandy(id, username, password, key, provider, uid); try { if (response == 0) { res.append("result", "200"); res.append("response", "Successfully Registered"); } else { res.append("result", "400"); res.append("response", "Not Registered"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; }
public void guardarCambiosGrupo() { JSONArray lista = new JSONArray(); for (int i = 0; i < listaTecnicosGrupo.size(); i++) { lista.put(listaTecnicosGrupo.get(i).getMail()); } JSONObject respuesta = new IGrupo() .modificiarGrupo( sesion.getTokenId(), grupoSeleccionado, nuevoNombreGrupo, lista, parsearMail(nuevoAdministrador)); try { FacesMessage msg; if (respuesta.getInt("status") == 2) { msg = new FacesMessage("Grupo modificado con exito", ""); listarGrupos(); } else msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al modificar grupo.", ""); FacesContext.getCurrentInstance().addMessage(null, msg); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@PUT @Consumes(MediaType.APPLICATION_JSON) public Response addUpdateListItem(InputStream incomingData) { StringBuilder listBuilder = new StringBuilder(); try { BufferedReader in = new BufferedReader(new InputStreamReader(incomingData)); String line = null; while ((line = in.readLine()) != null) { listBuilder.append(line); } } catch (Exception e) { System.out.println("Error Parsing :- "); } try { JSONObject json = new JSONObject(listBuilder.toString()); Iterator<String> iterator = json.keys(); ListItem item = new ListItem( (String) json.get(iterator.next()), (String) json.get(iterator.next()), Boolean.parseBoolean((String) json.get(iterator.next()))); int index = list.indexOf(item); item = list.get(index); list.remove(index); item.setTitle((String) json.get(iterator.next())); item.setBody((String) json.get(iterator.next())); list.add(index, item); } catch (JSONException e) { e.printStackTrace(); } // return HTTP response 200 in case of success return Response.status(200).entity(listBuilder.toString()).build(); }
public void refreshPhotonInfo() { if (isPhotonActive) { System.out.println(this.port + ": Updating photon"); String photonJson = requestSender.findSpark(); try { photon = new JSONObject(photonJson); } catch (JSONException e) { e.printStackTrace(); } } }
public Node(ISchemaType type, ISchemaProperty prop) { this.structureType = prop != null ? prop.getStructureType() : type.getParentStructureType(); if (structureType == StructureType.COLLECTION) { this.array = new JSONArray(); if (type.isComplex()) { array.put(new JSONObject()); array.put(new JSONObject()); } else { Object defaultValue = prop != null ? DefaultValueFactory.getDefaultValue(prop) : DefaultValueFactory.getDefaultValue(type); array.put(defaultValue); array.put(defaultValue); } } else if (structureType == StructureType.MAP) { this.object = new JSONObject(); ISchemaType keyType = SimpleType.STRING; ISchemaType valueType = new TypeModelImpl("Object", "java.lang.Object", null, StructureType.COMMON); if (prop != null && prop instanceof IMapSchemaProperty) { keyType = ((IMapSchemaProperty) prop).getKeyType(); valueType = ((IMapSchemaProperty) prop).getValueType(); if (!keyType.getClassName().equals(SimpleType.STRING.getClassName())) { StringBuilder bld = new StringBuilder("Invalid map key type. Only String is available as key type."); if (type != null) { bld.append(" Type: " + type.getClassQualifiedName()); } if (prop != null) { bld.append(" Property: " + prop.getName()); } throw new IllegalArgumentException(bld.toString()); } } String key = DefaultValueFactory.getDefaultValue(keyType).toString(); try { if (valueType.isComplex()) { this.object.put(key + "_1", new JSONObject()); this.object.put(key + "_2", new JSONObject()); } else { Object defaultValue = DefaultValueFactory.getDefaultValue(valueType); this.object.put(key + "_1", defaultValue); this.object.put(key + "_2", defaultValue); } } catch (JSONException e) { e.printStackTrace(); } } else if (type.isComplex()) { this.object = new JSONObject(); } }
private List<String> mapTagsField(String tags) { List<String> result = new ArrayList<String>(); if (StringUtil.isNotEmpty(tags)) { try { JSONArray jsArr = new JSONArray(tags); for (int i = 0; i < jsArr.length(); i++) { result.add(jsArr.getString(i)); } } catch (JSONException e) { e.printStackTrace(); } } return result; }
public void cargarDatosGrupo() { JSONObject respuesta = new IGrupo().listarMiembrosDeGrupo(sesion.getTokenId(), grupoSeleccionado); JSONObject respuesta2 = new IGrupo().tecnicosFueraDelGrupo(sesion.getTokenId(), grupoSeleccionado); try { if (respuesta.has("jefe")) { JSONObject objetoJefe = respuesta.getJSONObject("jefe"); nuevoAdministrador = objetoJefe.getString("nombre") + " " + objetoJefe.getString("apellido"); if (!objetoJefe.getString("nombre").equals("")) nuevoAdministrador = nuevoAdministrador + " - "; nuevoAdministrador = nuevoAdministrador + objetoJefe.getString("correo"); } else nuevoAdministrador = "No tiene administrador."; listaTecnicosGrupo.clear(); JSONArray objetoIntegantes = respuesta.getJSONArray("grupo"); if (objetoIntegantes != null) { for (int i = 0; i < objetoIntegantes.length(); i++) { JSONObject ob = objetoIntegantes.getJSONObject(i); NombreMail b = new NombreMail(); b.setMail(ob.getString("correo")); b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido")); listaTecnicosGrupo.add(b); } } listaRestoTecnicos.clear(); JSONArray objetoTecnicos = respuesta2.getJSONArray("Tecnicos"); if (objetoTecnicos != null) { for (int i = 0; i < objetoTecnicos.length(); i++) { JSONObject ob = objetoTecnicos.getJSONObject(i); NombreMail b = new NombreMail(); b.setMail(ob.getString("correo")); b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido")); listaRestoTecnicos.add(b); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
{ ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); JourneyPattern jp = new JourneyPattern(); ObjectReference objectRef = new ObjectReference(jp); objectRef.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = null; try { res = new JSONObject(text); Assert.assertEquals( res.getString("type"), TYPE.journey_pattern, "wrong object reference type"); Assert.assertEquals(res.getString("id"), jp.getObjectId(), "wrong object referenced id"); } catch (JSONException e) { e.printStackTrace(); } }
// Finds the responsible node for the photon and updates it and the successor of it public void findResponsibleNode() { String photonJson = requestSender.findSpark(); try { JSONObject temp = new JSONObject(photonJson); JSONObject temp2 = temp.getJSONObject("coreInfo"); String deviceID = temp2.getString("deviceID"); int convertedID = Key.generate16BitsKey(deviceID); NodeInfo responsible = findSuccessor(convertedID); // NodeInfo resposibleSuccessor = requestSender.getNodeSuccessor(responsible); requestSender.updatePhoton(responsible); // requestSender.updatePhoton(resposibleSuccessor); System.out.println("PhotonID: " + convertedID); System.out.println("Responsible is:\n" + responsible.getID()); } catch (JSONException e) { e.printStackTrace(); } }
// Updates the photon of this node @PUT @Path("/update-photon/") public Response updatePhoton(NodeInfo target) { String photonJson = requestSender.findSpark(); try { photon = new JSONObject(photonJson); JSONObject coreInfo = photon.getJSONObject("coreInfo"); String deviceID = coreInfo.getString("deviceID"); photonId = Key.generate16BitsKey(deviceID); System.out.println("deviceID returned: " + deviceID); System.out.println("deviceID int returned: " + photonId); isPhotonActive = true; createPhotonUpdateTimer(); } catch (JSONException e) { e.printStackTrace(); } // System.out.println("Spark returned:\n" + photonJson); return Response.status(200).entity(photon).build(); }
@Override public String encodeData(Map<String, String> files) { JSONObject root = new JSONObject(); String result = ""; try { root.put("description", "Multiverse-Core Debug Info"); root.put("public", !this.isPrivate); JSONObject fileList = new JSONObject(); for (Map.Entry<String, String> entry : files.entrySet()) { JSONObject fileObject = new JSONObject(); fileObject.put("content", entry.getValue()); fileList.put(entry.getKey(), fileObject); } root.put("files", fileList); result = root.toString(); } catch (JSONException e) { e.printStackTrace(); } return result; }
/** * Executes the call to the REST Service and processes the response. * * @return The service response. */ public UserInfoResponse exec() { // Prepare request parameters initClientRequest(); clientRequest.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); clientRequest.setHttpMethod(getHttpMethod()); if (getRequest().getAuthorizationMethod() == null || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD) { if (StringUtils.isNotBlank(getRequest().getAccessToken())) { clientRequest.header("Authorization", "Bearer " + getRequest().getAccessToken()); } } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) { if (StringUtils.isNotBlank(getRequest().getAccessToken())) { clientRequest.formParameter("access_token", getRequest().getAccessToken()); } } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) { if (StringUtils.isNotBlank(getRequest().getAccessToken())) { clientRequest.queryParameter("access_token", getRequest().getAccessToken()); } } // Call REST Service and handle response try { if (getRequest().getAuthorizationMethod() == null || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD || getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) { clientResponse = clientRequest.get(String.class); } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) { clientResponse = clientRequest.post(String.class); } int status = clientResponse.getStatus(); setResponse(new UserInfoResponse(status)); String entity = clientResponse.getEntity(String.class); getResponse().setEntity(entity); getResponse().setHeaders(clientResponse.getHeaders()); if (StringUtils.isNotBlank(entity)) { List<String> contentType = clientResponse.getHeaders().get("Content-Type"); if (contentType != null && contentType.contains("application/jwt")) { String[] jwtParts = entity.split("\\."); if (jwtParts.length == 5) { byte[] sharedSymmetricKey = sharedKey != null ? sharedKey.getBytes(Util.UTF8_STRING_ENCODING) : null; Jwe jwe = Jwe.parse(entity, rsaPrivateKey, sharedSymmetricKey); getResponse().setClaims(jwe.getClaims().toMap()); } else { Jwt jwt = Jwt.parse(entity); JwsValidator jwtValidator = new JwsValidator(jwt, sharedKey, jwksUri, null); if (jwtValidator.validateSignature()) { getResponse().setClaims(jwt.getClaims().toMap()); } } } else { try { JSONObject jsonObj = new JSONObject(entity); if (jsonObj.has("error")) { getResponse() .setErrorType(UserInfoErrorResponseType.fromString(jsonObj.getString("error"))); jsonObj.remove("error"); } if (jsonObj.has("error_description")) { getResponse().setErrorDescription(jsonObj.getString("error_description")); jsonObj.remove("error_description"); } if (jsonObj.has("error_uri")) { getResponse().setErrorUri(jsonObj.getString("error_uri")); jsonObj.remove("error_uri"); } for (Iterator<String> iterator = jsonObj.keys(); iterator.hasNext(); ) { String key = iterator.next(); List<String> values = new ArrayList<String>(); JSONArray jsonArray = jsonObj.optJSONArray(key); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { String value = jsonArray.optString(i); if (value != null) { values.add(value); } } } else { String value = jsonObj.optString(key); if (value != null) { values.add(value); } } getResponse().getClaims().put(key, values); } } catch (JSONException e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } finally { closeConnection(); } return getResponse(); }
@GET @Path("/get/{context}/{formId}") @Produces(MediaType.APPLICATION_JSON) public String getNextForm( @PathParam("context") String context, @PathParam("formId") long formId) { JSONObject newContext = null; JSONObject form = null; String nextFormId = String.valueOf(formId); if (formId == -2) { // Chamada Ass�ncrona AssyncClick2Call sC2c = null; try { newContext = new JSONObject(context); String destino = newContext.getString("_TransferDestino"); if (destino.startsWith("41")) { destino = destino.substring(2); } sC2c = new AssyncClick2Call("0" + destino, newContext.getString("_TransferVDN"), "1-xxxxx"); sC2c.start(); } catch (Exception e) { e.printStackTrace(); } } else { // getNextForm try { newContext = new JSONObject(context); if (formId == -1) { Stack<String> stack = new Stack<String>(); if (!newContext.isNull("_FlowInternalStack")) { String[] list = (newContext.get("_FlowInternalStack").toString().split("_")); for (String string : list) { stack.add(string); } } nextFormId = stack.pop(); System.out.println("*****************: " + nextFormId); String ret = "i"; for (String string : stack) { ret += "_" + string; } ret = ret.replace("i_", ""); newContext.put("_FlowInternalStack", ret); } Client client = Client.create(); WebResource webResource = client.resource("http://vmdwin062:8080/ims-tool-manager/nextform/nextformid"); JSONObject object = new JSONObject(); object.put("context", context); object.put("nextId", formId); ClientResponse response = webResource.type("application/json").post(ClientResponse.class, object.toString()); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } form = new JSONObject(response.getEntity(String.class)); newContext = new JSONObject(form.get("jsonContexto").toString()); while (form.get("formtype").equals(9) || (form.get("formtype").equals(1) && form.getJSONObject("announce").get("nextForm").equals(-1))) { System.out.println("FlowInternal or Return"); if (form.get("formtype").equals(9)) { Stack<String> stack = new Stack<String>(); if (!newContext.isNull("_FlowInternalStack")) { String[] list = (newContext.get("_FlowInternalStack").toString().split("_")); for (String string : list) { stack.add(string); } } System.out.println(">>> " + form.getJSONObject("flow").getString("nextForm")); stack.add(form.getJSONObject("flow").getString("nextForm")); String ret = "i"; for (String string : stack) { ret += "_" + string; } ret = ret.replace("i_", ""); newContext.put("_FlowInternalStack", ret); object = new JSONObject(); object.put("context", newContext.toString()); object.put("nextId", form.getJSONObject("flow").get("flowFirstForm").toString()); response = webResource.type("application/json").post(ClientResponse.class, object.toString()); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } form = new JSONObject(response.getEntity(String.class)); newContext = new JSONObject(form.get("jsonContexto").toString()); System.out.println(">>> id=9 : " + form.toString()); System.out.println(" Context: " + newContext.toString()); } else { Stack<String> stack = new Stack<String>(); if (!newContext.isNull("_FlowInternalStack")) { String[] list = (newContext.get("_FlowInternalStack").toString().split("_")); for (String string : list) { stack.add(string); } } nextFormId = stack.pop(); System.out.println("*****************: " + nextFormId); String ret = "i"; for (String string : stack) { ret += "_" + string; } ret = ret.replace("i_", ""); newContext.put("_FlowInternalStack", ret); object = new JSONObject(); object.put("context", newContext.toString()); object.put("nextId", nextFormId); response = webResource.type("application/json").post(ClientResponse.class, object.toString()); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } form = new JSONObject(response.getEntity(String.class)); newContext = new JSONObject(form.get("jsonContexto").toString()); System.out.println(">>> id=0 : " + form.toString()); System.out.println(" Context: " + newContext.toString()); } } } catch (Exception e) { e.printStackTrace(); } } // Constroi JSON de resposta JSONObject jInteraction = null; try { jInteraction = new JSONObject(); jInteraction.put("context", newContext); jInteraction.put("form", form); } catch (JSONException e) { e.printStackTrace(); } System.out.println(" "); return jInteraction.toString(); }
/* * public ArrayList<com.application.baatna.bean.User> usersToBeRated(int * userId) { * * Session session=null; * ArrayList<com.application.baatna.bean.User>users=null; try { session = * DBUtil.getSessionFactory().openSession(); Transaction transaction = * session.beginTransaction(); * * users= new ArrayList<com.application.baatna.bean.User>(); String sql = * "SELECT * FROM USER WHERE USERID IN (SELECT USER_TWO_ID FROM USERWISH WHERE USERID= :userId AND WISH_STATUS= :status)" * ; SQLQuery query = session.createSQLQuery(sql); * query.addEntity(com.application.baatna.bean.User.class); * query.setParameter("userId", userId); query.setParameter("status", * CommonLib.STATUS_ACCEPTED); * * * java.util.List results = (java.util.List) query.list(); UserDAO dao= new * UserDAO(); for (Iterator iterator = ((java.util.List) * results).iterator(); iterator.hasNext();) { * users.add((com.application.baatna.bean.User)iterator.next()); } * * String sql2= * "SELECT * FROM USER WHERE USERID IN (SELECT USERID FROM USERWISH WHERE USER_TWO_ID= :userIdone AND WISH_STATUS= :statusone)" * ; SQLQuery query2=session.createSQLQuery(sql2); * query2.addEntity(com.application.baatna.bean.User.class); * query2.setParameter("userIdone",userId); * query2.setParameter("statusone",CommonLib.STATUS_ACCEPTED); * * java.util.List results2=(java.util.List)query2.list(); for (Iterator * iterator = ((java.util.List) results2).iterator(); iterator.hasNext();) { * users.add((com.application.baatna.bean.User)iterator.next()); } * transaction.commit(); session.close(); }catch (HibernateException e) { * System.out.println(e.getMessage()); System.out.println("error"); } * finally { if (session != null && session.isOpen()) session.close(); } * * return users; } */ public JSONArray usersToBeRated(int userId) { Session session = null; JSONArray usersJson = new JSONArray(); ArrayList<com.application.baatna.bean.User> users = null; try { session = DBUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); { String sql = "SELECT * FROM USERWISH WHERE USERID=:userId AND WISH_STATUS= :status AND U1RATEDU2= :zero_rating"; SQLQuery query = session.createSQLQuery(sql); query.addEntity(com.application.baatna.bean.UserWish.class); query.setParameter("userId", userId); query.setParameter("status", CommonLib.STATUS_FULLFILLED); query.setParameter("zero_rating", 0); java.util.List results = (java.util.List) query.list(); for (Iterator iterator = ((java.util.List) results).iterator(); iterator.hasNext(); ) { User user = null; Wish wish = null; UserWish userWish = (UserWish) iterator.next(); String sql2 = "SELECT * FROM USER WHERE USERID= :userId"; SQLQuery query2 = session.createSQLQuery(sql2); query2.addEntity(User.class); query2.setParameter("userId", userWish.getUserTwoId()); java.util.List results2 = (java.util.List) query2.list(); for (Iterator iterator2 = ((java.util.List) results2).iterator(); iterator2.hasNext(); ) { user = (User) iterator2.next(); break; } String sql3 = "SELECT * FROM WISH WHERE USERID= :userId AND WISHID= :wishId"; SQLQuery query3 = session.createSQLQuery(sql3); query3.addEntity(Wish.class); query3.setParameter("userId", userWish.getUserId()); query3.setParameter("wishId", userWish.getWishId()); java.util.List results3 = (java.util.List) query3.list(); for (Iterator iterator3 = ((java.util.List) results3).iterator(); iterator3.hasNext(); ) { wish = (Wish) iterator3.next(); break; } try { if (user != null && wish != null) { JSONObject userWishJson = JsonUtil.getUserWishJson(user, wish); usersJson.put(userWishJson); } } catch (JSONException e) { e.printStackTrace(); } } } { String sql = "SELECT * FROM USERWISH WHERE USER_TWO_ID=:userId AND WISH_STATUS= :status AND U2RATEDU1= :zero_rating"; SQLQuery query = session.createSQLQuery(sql); query.addEntity(com.application.baatna.bean.UserWish.class); query.setParameter("userId", userId); query.setParameter("status", CommonLib.STATUS_FULLFILLED); query.setParameter("zero_rating", 0); java.util.List results = (java.util.List) query.list(); for (Iterator iterator = ((java.util.List) results).iterator(); iterator.hasNext(); ) { User user = null; Wish wish = null; UserWish userWish = (UserWish) iterator.next(); String sql2 = "SELECT * FROM USER WHERE USERID= :userId"; SQLQuery query2 = session.createSQLQuery(sql2); query2.addEntity(User.class); query2.setParameter("userId", userWish.getUserId()); java.util.List results2 = (java.util.List) query2.list(); for (Iterator iterator2 = ((java.util.List) results2).iterator(); iterator2.hasNext(); ) { user = (User) iterator2.next(); break; } String sql3 = "SELECT * FROM WISH WHERE USERID= :userId AND WISHID= :wishId"; SQLQuery query3 = session.createSQLQuery(sql3); query3.addEntity(Wish.class); query3.setParameter("userId", userWish.getUserId()); query3.setParameter("wishId", userWish.getWishId()); java.util.List results3 = (java.util.List) query3.list(); for (Iterator iterator3 = ((java.util.List) results3).iterator(); iterator3.hasNext(); ) { wish = (Wish) iterator3.next(); break; } try { if (user != null && wish != null) { JSONObject userWishJson = JsonUtil.getUserWishJson(user, wish); usersJson.put(userWishJson); } } catch (JSONException e) { e.printStackTrace(); } } } } catch (HibernateException e) { System.out.println(e.getMessage()); System.out.println("error"); e.printStackTrace(); } finally { if (session != null && session.isOpen()) session.close(); } return usersJson; }
/** * Throttled controller that executes php function via rest http request, sends list invitation * emails to a given list. Executed by jsp job handler */ @Override public void execute(JobExecutionContext context) throws JobExecutionException { sentLog = new JSONArray(); JSONArray contactListSent; String rawJSONArray; int limit = 100; int offset = 0; int pageCounter = 1; int increment = limit; ; JobDataMap dataMap = context.getJobDetail().getJobDataMap(); taskID = dataMap.getString("taskID"); String userID = dataMap.getString("userid"); String contactListID = dataMap.getString("contactListID"); String contactListLink = Constants.DATABASE_BASE_URL + "/" + Constants.DATABASE_CONTACT_LISTS + "/" + contactListID; try { CouchUtilities.setTaskAsOpen(taskID); // System.out.println("uid: " + userID + " clid: " + contactListID); Thread.sleep(1000); int contactCount = CouchUtilities.getContactCountForContactList(userID, contactListID); double totalPages = Math.ceil((double) contactCount / (double) limit); // Set the contact list status as running JSONObject taskinfo = CouchUtilities.getTaskInfo(taskID); do { contactListSent = new JSONArray(); rawJSONArray = new String(); taskinfo.put("offset", offset); taskinfo.put("limit", limit); // CouchUtilities.setContactListRunningStatus(true, contactListLink); // Set the task status as in progress in task.json String strTaskInfo = taskinfo.toString(); // System.out.println("TaskINFO: " + strTaskInfo); String URL = UpdentityConstants.REST_URL + "?action=send_optin_emails&uid=" + userID + "&clid=" + contactListID; CouchConnect request = new CouchConnect(URL); // EXECUTE BULK SEND try { Thread.sleep(250); // wait 1/4 of a sec for added stability rawJSONArray = request.post(strTaskInfo); /* debug code for dev * File file1 = new File("/usr/share/nginx/www/log/optin_java.log"); FileWriter writer1; writer1 = new FileWriter(file1, true); PrintWriter printer1 = new PrintWriter(writer1); printer1.append("Pass "+pageCounter+"\n"); printer1.close();*/ } catch (Exception e) { try { // localhost// File file = new // File("/home/samuel/workspace/tmp/optin_java_exception.log"); // Beta// File file = new File("/usr/share/nginx/www/log/optin_java_exception.log"); File file = new File("/usr/share/nginx/log/optin_java_exception.log"); // enterprise FileWriter writer; writer = new FileWriter(file, true); PrintWriter printer = new PrintWriter(writer); printer.append(e.getMessage() + "\n StackTrace:\n" + e.getStackTrace() + "\n---------"); printer.close(); Thread.sleep(3000); rawJSONArray = request.post(strTaskInfo); contactListSent.add(rawJSONArray); } catch (Exception e1) { logger.error(ExceptionUtils.getStackTrace(e1)); } } offset += increment; limit += increment; pageCounter += 1; contactListSent.add(rawJSONArray); sentLog.addAll(contactListSent.getJSONArray(0)); } while (pageCounter <= totalPages); // System.out.println("threads: " + (pageCounter - 1)); taskinfo.put("log", sentLog); saveSentLogToTask(taskinfo); CouchUtilities.setTaskAsClosed(taskID); String UserInfoURL = UpdentityConstants.REST_URL + "?action=get_user&uid=" + userID; CouchConnect userRequest = new CouchConnect(UserInfoURL); JSONObject userData = JSONObject.fromObject(userRequest.get()); // System.out.println(userData); String user_nicename = userData.getString("first_name") + " " + userData.getString("last_name"); String title = "Opt-in messages sent"; String txtMessage = "Hi, " + user_nicename + ",\n\n Your opt-in email task has finished running!\n\n"; String message = "<p>Hi " + user_nicename + ",</p>\n"; message += "<h3 style='color:#707070;margin:20px 0px 20px 0px'>Your opt-in email task has finished running!</h3>"; UserDao.sendEmailNotification( userID, "Your opt-in invites have been sent!", txtMessage, EmailTemplates.getStandardTemplate(title, message), UpdentityUtil.isProductionServer()); } catch (MalformedURLException e) { try { CouchUtilities.setTaskAsFailed(taskID); } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e1) { e1.printStackTrace(); } e.printStackTrace(); } catch (IOException e) { try { CouchUtilities.setTaskAsFailed(taskID); } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e1) { e1.printStackTrace(); } e.printStackTrace(); } catch (Exception e) { try { CouchUtilities.setTaskAsFailed(taskID); } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { // Set the contact list status as not running CouchUtilities.removeTaskFromContactListQueue(taskID, contactListLink); // Suggest garbage collection Utilities.collectGarbage(); // Get the next task in queue, if any taskID = SchedularUtilities.getNextTaskInQueue(contactListID); if (!taskID.equals("")) { SchedularUtilities schedulerUtils = new SchedularUtilities(); schedulerUtils.defineJob(taskID); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (SchedulerException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }
/** * Calculates walksheds for a given location, based on time given to walk and the walk speed. * * <p>Depending on the value for the "output" parameter (i.e. "POINTS", "SHED" or "EDGES"), a * different type of GeoJSON geometry is returned. If a SHED is requested, then a ConcaveHull of * the EDGES/roads is returned. If that fails, a ConvexHull will be returned. * * <p>The ConcaveHull parameter is set to 0.005 degrees. The offroad walkspeed is assumed to be * 0.83333 m/sec (= 3km/h) until a road is hit. * * <p>Note that the set of EDGES/roads returned as well as POINTS returned may contain duplicates. * If POINTS are requested, then not the end-points are returned at which the max time is reached, * but instead all the graph nodes/crossings that are within the time limits. * * <p>In case there is no road near by within the given time, then a circle for the walktime limit * is created and returned for the SHED parameter. Otherwise the edge with the direction towards * the closest road. Note that the circle is calculated in Euclidian 2D coordinates, and * distortions towards an ellipse will appear if it is transformed/projected to the user location. * * <p>An example request may look like this: * localhost:8080/otp-rest-servlet/ws/iso?layers=traveltime&styles=mask&batch=true&fromPlace=51.040193121307176 * %2C-114.04471635818481&toPlace * =51.09098935%2C-113.95179705&time=2012-06-06T08%3A00%3A00&mode=WALK&maxWalkDistance=10000&walkSpeed=1.38&walkTime=10.7&output=EDGES * Though the first parameters (i) layer, (ii) styles and (iii) batch could be discarded. * * @param walkmins Maximum number of minutes to walk. * @param output Can be set to "POINTS", "SHED" or "EDGES" to return different types of GeoJSON * geometry. SHED returns a ConcaveHull or ConvexHull of the edges/roads. POINTS returns all * graph nodes that are within the time limit. * @return a JSON document containing geometries (either points, lineStrings or a polygon). * @throws Exception * @author sstein---geo.uzh.ch */ @GET @Produces({MediaType.APPLICATION_JSON}) public String getIsochrone( @QueryParam("walkTime") @DefaultValue("15") double walkmins, @QueryParam("output") @DefaultValue("POINTS") String output) throws Exception { this.debugGeoms = new ArrayList(); this.tooFastTraversedEdgeGeoms = new ArrayList(); RoutingRequest sptRequestA = buildRequest(0); String from = sptRequestA.getFrom().toString(); int pos = 1; float lat = 0; float lon = 0; for (String s : from.split(",")) { if (s.isEmpty()) { // no location Response.status(Status.BAD_REQUEST).entity("no position").build(); return null; } try { float num = Float.parseFloat(s); if (pos == 1) { lat = num; } if (pos == 2) { lon = num; } } catch (Exception e) { throw new WebApplicationException( Response.status(Status.BAD_REQUEST) .entity( "Could not parse position string to number. Require numerical lat & long coords.") .build()); } pos++; } GeometryFactory gf = new GeometryFactory(); Coordinate dropPoint = new Coordinate(lon, lat); int walkInMin = (int) Math.floor(walkmins); double walkInSec = walkmins * 60; LOG.debug( "given travel time: " + walkInMin + " mins + " + (walkInSec - (60 * walkInMin)) + " sec"); // restrict the evaluated SPT size to 30mins for requests with walking < 30min // if larger walking times are requested we adjust the evaluated // graph dynamically by 1.3 * min -> this should save processing time if (walkInMin < 30) { sptRequestA.worstTime = sptRequestA.dateTime + (30 * 60); } else { sptRequestA.worstTime = sptRequestA.dateTime + Math.round(walkInMin * 1.3 * 60); } // set the switch-time for shed/area calculation, i.e. to decide if the hull is calculated based // on points or on edges TraverseModeSet modes = sptRequestA.modes; LOG.debug("mode(s): " + modes); if ((modes.contains(TraverseMode.TRANSIT)) || (modes.contains(TraverseMode.BUSISH)) || (modes.contains(TraverseMode.TRAINISH))) { shedCalcMethodSwitchTimeInSec = 60 * 20; // 20min (use 20min for transit, since buses may not come all the time) } else if (modes.contains(TraverseMode.CAR)) { shedCalcMethodSwitchTimeInSec = 60 * 10; // 10min } else if (modes.contains(TraverseMode.BICYCLE)) { shedCalcMethodSwitchTimeInSec = 60 * 10; // 10min } else { shedCalcMethodSwitchTimeInSec = 60 * 20; // 20min } // set the maxUserSpeed, which is used later to check for u-type streets/crescents when // calculating sub-edges; // Note, that the car speed depends on the edge itself, so this value may be replaced later this.usesCar = false; int numberOfModes = modes.getModes().size(); if (numberOfModes == 1) { if (modes.getWalk()) { this.maxUserSpeed = sptRequestA.getWalkSpeed(); } else if (modes.getBicycle()) { this.maxUserSpeed = sptRequestA.getBikeSpeed(); } else if (modes.getDriving()) { this.maxUserSpeed = sptRequestA.getCarSpeed(); this.usesCar = true; } } else { // for all other cases (multiple-modes) // sstein: I thought I may set it to 36.111 m/sec = 130 km/h, // but maybe it is better to assume walk speed for transit, i.e. treat it like if the // person gets off the bus on the last crossing and walks the "last mile". this.maxUserSpeed = sptRequestA.getWalkSpeed(); } if (doSpeedTest) { LOG.debug("performing angle and speed based test to detect u-shapes"); } else { LOG.debug("performing only angle based test to detect u-shapes"); } // TODO: OTP prefers to snap to car-roads/ways, which is not so nice, when walking, // and a footpath is closer by. So far there is no option to switch that off // create the ShortestPathTree try { sptRequestA.setRoutingContext(graphService.getGraph()); } catch (Exception e) { // if we get an exception here, and in particular a VertexNotFoundException, // then it is likely that we chose a (transit) mode without having that (transit) modes data LOG.debug("cannot set RoutingContext: " + e.toString()); LOG.debug("cannot set RoutingContext: setting mode=WALK"); sptRequestA.setMode(TraverseMode.WALK); // fall back to walk mode sptRequestA.setRoutingContext(graphService.getGraph()); } ShortestPathTree sptA = sptService.getShortestPathTree(sptRequestA); StreetLocation origin = (StreetLocation) sptRequestA.rctx.fromVertex; sptRequestA.cleanup(); // remove inserted points // create a LineString for display Coordinate pathToStreetCoords[] = new Coordinate[2]; pathToStreetCoords[0] = dropPoint; pathToStreetCoords[1] = origin.getCoordinate(); LineString pathToStreet = gf.createLineString(pathToStreetCoords); // get distance between origin and drop point for time correction double distanceToRoad = this.distanceLibrary.distance(origin.getY(), origin.getX(), dropPoint.y, dropPoint.x); long offRoadTimeCorrection = (long) (distanceToRoad / this.offRoadWalkspeed); // // --- filter the states --- // Set<Coordinate> visitedCoords = new HashSet<Coordinate>(); ArrayList<Edge> allConnectingEdges = new ArrayList<Edge>(); Coordinate coords[] = null; long maxTime = (long) walkInSec - offRoadTimeCorrection; // System.out.println("Reducing walktime from: " + (int)(walkmins * 60) + "sec to " + maxTime + // "sec due to initial walk of " + distanceToRoad // + "m"); // if the initial walk is already to long, there is no need to parse... if (maxTime <= 0) { noRoadNearBy = true; long timeToWalk = (long) walkInSec; long timeBetweenStates = offRoadTimeCorrection; long timeMissing = timeToWalk; double fraction = (double) timeMissing / (double) timeBetweenStates; pathToStreet = getSubLineString(pathToStreet, fraction); LOG.debug( "no street found within giving travel time (for off-road walkspeed: {} m/sec)", this.offRoadWalkspeed); } else { noRoadNearBy = false; Map<ReversibleLineStringWrapper, Edge> connectingEdgesMap = Maps.newHashMap(); for (State state : sptA.getAllStates()) { long et = state.getElapsedTimeSeconds(); if (et <= maxTime) { // -- filter points, as the same coordinate may be passed several times due to the graph // structure // in a Calgary suburb family homes neighborhood with a 15min walkshed it filtered about // 250 points away (while 145 were finally displayed) if (visitedCoords.contains(state.getVertex().getCoordinate())) { continue; } else { visitedCoords.add(state.getVertex().getCoordinate()); } // -- get all Edges needed later for the edge representation // and to calculate an edge-based walkshed // Note, it can happen that we get a null geometry here, e.g. for hop-edges! Collection<Edge> vertexEdgesIn = state.getVertex().getIncoming(); for (Iterator<Edge> iterator = vertexEdgesIn.iterator(); iterator.hasNext(); ) { Edge edge = (Edge) iterator.next(); Geometry edgeGeom = edge.getGeometry(); if (edgeGeom != null) { // make sure we get only real edges if (edgeGeom instanceof LineString) { // allConnectingEdges.add(edge); // instead of this, use a map now, so we don't have // similar edge many times connectingEdgesMap.put( new ReversibleLineStringWrapper((LineString) edgeGeom), edge); } } } Collection<Edge> vertexEdgesOut = state.getVertex().getOutgoing(); for (Iterator<Edge> iterator = vertexEdgesOut.iterator(); iterator.hasNext(); ) { Edge edge = (Edge) iterator.next(); Geometry edgeGeom = edge.getGeometry(); if (edgeGeom != null) { if (edgeGeom instanceof LineString) { // allConnectingEdges.add(edge); // instead of this, use a map now, so we don't // similar edge many times connectingEdgesMap.put( new ReversibleLineStringWrapper((LineString) edgeGeom), edge); } } } } // end : if(et < maxTime) } // -- // points from list to array, for later coords = new Coordinate[visitedCoords.size()]; int i = 0; for (Coordinate c : visitedCoords) coords[i++] = c; // connection edges from Map to List allConnectingEdges.clear(); for (Edge tedge : connectingEdgesMap.values()) allConnectingEdges.add(tedge); } StringWriter sw = new StringWriter(); GeoJSONBuilder json = new GeoJSONBuilder(sw); // // -- create the different outputs --- // try { if (output.equals(IsoChrone.RESULT_TYPE_POINTS)) { // in case there was no road we create a circle and // and return those points if (noRoadNearBy) { Geometry circleShape = createCirle(dropPoint, pathToStreet); coords = circleShape.getCoordinates(); } // -- the states/nodes with time elapsed <= X min. LOG.debug("write multipoint geom with {} points", coords.length); json.writeGeom(gf.createMultiPoint(coords)); LOG.debug("done"); } else if (output.equals(IsoChrone.RESULT_TYPE_SHED)) { Geometry geomsArray[] = null; // in case there was no road we create a circle if (noRoadNearBy) { Geometry circleShape = createCirle(dropPoint, pathToStreet); json.writeGeom(circleShape); } else { if (maxTime > shedCalcMethodSwitchTimeInSec) { // eg., walkshed > 20 min // -- create a point-based walkshed // less exact and should be used for large walksheds with many edges LOG.debug("create point-based shed (not from edges)"); geomsArray = new Geometry[coords.length]; for (int j = 0; j < geomsArray.length; j++) { geomsArray[j] = gf.createPoint(coords[j]); } } else { // -- create an edge-based walkshed // it is more exact and should be used for short walks LOG.debug("create edge-based shed (not from points)"); Map<ReversibleLineStringWrapper, LineString> walkShedEdges = Maps.newHashMap(); // add the walk from the pushpin to closest street point walkShedEdges.put(new ReversibleLineStringWrapper(pathToStreet), pathToStreet); // get the edges and edge parts within time limits ArrayList<LineString> withinTimeEdges = this.getLinesAndSubEdgesWithinMaxTime( maxTime, allConnectingEdges, sptA, angleLimitForUShapeDetection, distanceToleranceForUShapeDetection, maxUserSpeed, usesCar, doSpeedTest); for (LineString ls : withinTimeEdges) { walkShedEdges.put(new ReversibleLineStringWrapper(ls), ls); } geomsArray = new Geometry[walkShedEdges.size()]; int k = 0; for (LineString ls : walkShedEdges.values()) geomsArray[k++] = ls; } // end if-else: maxTime condition GeometryCollection gc = gf.createGeometryCollection(geomsArray); // create the concave hull, but in case it fails we just return the convex hull Geometry outputHull = null; LOG.debug( "create concave hull from {} geoms with edge length limit of about {} m (distance on meridian)", geomsArray.length, concaveHullAlpha * 111132); // 1deg at Latitude phi = 45deg is about 111.132km // (see wikipedia: // http://en.wikipedia.org/wiki/Latitude#The_length_of_a_degree_of_latitude) try { ConcaveHull hull = new ConcaveHull(gc, concaveHullAlpha); outputHull = hull.getConcaveHull(); } catch (Exception e) { outputHull = gc.convexHull(); LOG.debug("Could not generate ConcaveHull for WalkShed, using ConvexHull instead."); } LOG.debug("write shed geom"); json.writeGeom(outputHull); LOG.debug("done"); } } else if (output.equals(IsoChrone.RESULT_TYPE_EDGES)) { // in case there was no road we return only the suggested path to the street if (noRoadNearBy) { json.writeGeom(pathToStreet); } else { // -- if we would use only the edges from the paths to the origin we will miss // some edges that will be never on the shortest path (e.g. loops/crescents). // However, we can retrieve all edges by checking the times for each // edge end-point Map<ReversibleLineStringWrapper, LineString> walkShedEdges = Maps.newHashMap(); // add the walk from the pushpin to closest street point walkShedEdges.put(new ReversibleLineStringWrapper(pathToStreet), pathToStreet); // get the edges and edge parts within time limits ArrayList<LineString> withinTimeEdges = this.getLinesAndSubEdgesWithinMaxTime( maxTime, allConnectingEdges, sptA, angleLimitForUShapeDetection, distanceToleranceForUShapeDetection, maxUserSpeed, usesCar, doSpeedTest); for (LineString ls : withinTimeEdges) { walkShedEdges.put(new ReversibleLineStringWrapper(ls), ls); } Geometry mls = null; LineString edges[] = new LineString[walkShedEdges.size()]; int k = 0; for (LineString ls : walkShedEdges.values()) edges[k++] = ls; LOG.debug("create multilinestring from {} geoms", edges.length); mls = gf.createMultiLineString(edges); LOG.debug("write geom"); json.writeGeom(mls); LOG.debug("done"); } } else if (output.equals("DEBUGEDGES")) { // -- for debugging, i.e. display of detected u-shapes/crescents ArrayList<LineString> withinTimeEdges = this.getLinesAndSubEdgesWithinMaxTime( maxTime, allConnectingEdges, sptA, angleLimitForUShapeDetection, distanceToleranceForUShapeDetection, maxUserSpeed, usesCar, doSpeedTest); if (this.showTooFastEdgesAsDebugGeomsANDnotUShapes) { LOG.debug("displaying edges that are traversed too fast"); this.debugGeoms = this.tooFastTraversedEdgeGeoms; } else { LOG.debug("displaying detected u-shaped roads/crescents"); } LineString edges[] = new LineString[this.debugGeoms.size()]; int k = 0; for (Iterator iterator = debugGeoms.iterator(); iterator.hasNext(); ) { LineString ls = (LineString) iterator.next(); edges[k] = ls; k++; } Geometry mls = gf.createMultiLineString(edges); LOG.debug("write debug geom"); json.writeGeom(mls); LOG.debug("done"); } } catch (org.codehaus.jettison.json.JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sw.toString(); }