コード例 #1
1
ファイル: SearchDao.java プロジェクト: CC-Android-App/iBeebo
  public UserListBean getUserList() throws WeiboException {

    String url = WeiBoURLs.USERS_SEARCH;

    Map<String, String> map = new HashMap<String, String>();
    map.put("access_token", access_token);
    map.put("count", count);
    map.put("page", page);
    map.put("q", q);

    String jsonData = null;

    jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);

    Gson gson = new Gson();

    UserListBean value = null;
    try {
      value = gson.fromJson(jsonData, UserListBean.class);
    } catch (JsonSyntaxException e) {

      AppLoggerUtils.e(e.getMessage());
    }

    return value;
  }
コード例 #2
1
 @Nullable
 @Override
 public View onCreateView(
     LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   // Bind view with id
   View view = inflater.inflate(R.layout.detail_movie_fragment, container, false);
   titleView = (TextView) view.findViewById(R.id.title);
   releaseYearView = (TextView) view.findViewById(R.id.release_year);
   scoreView = (TextView) view.findViewById(R.id.score);
   overviewView = (TextView) view.findViewById(R.id.overview);
   imagePoster = (ImageView) view.findViewById(R.id.image);
   insertTrailerPoint = (ViewGroup) view.findViewById(R.id.insert_trailer_point);
   insertReviewPoint = (ViewGroup) view.findViewById(R.id.insert_review_point);
   trailerVideo = new ArrayList<>();
   reviewsList = new ArrayList<>();
   // Parse json movie from intent extra
   Gson gson = new Gson();
   String jsonMovie = getArguments().getString("movie");
   Movie movie = gson.fromJson(jsonMovie, Movie.class);
   // Set text and source picture.
   titleView.setText(movie.getTitle());
   releaseYearView.setText(movie.getRelease_date());
   scoreView.setText(movie.getscore() + "/10");
   String url = "http://image.tmdb.org/t/p/w185/" + movie.getimage_path();
   Picasso.with(getActivity()).load(url).into(imagePoster);
   overviewView.setText(movie.getOverview());
   // Start new thread
   FetchTrailerTask task = new FetchTrailerTask();
   task.execute(movie.getId());
   return view;
 }
コード例 #3
0
ファイル: EmbedTest.java プロジェクト: podio/podio-android
  public void testEmbedCanBeCreatedFromJson() {
    String json =
        new StringBuilder("{")
            .append("embed_height:1,")
            .append("embed_id:1,")
            .append("embed_width:1,")
            .append("description:'DESCRIPTION',")
            .append("embed_html:'EMBEDHTML',")
            .append("hostname:'HOSTNAME',")
            .append("original_url:'ORIGINALURL',")
            .append("resolved_url:'RESOLVEDURL',")
            .append("title:'TITLE',")
            .append("url:'URL'")
            .append("}")
            .toString();

    Gson gson = new Gson();
    Embed embed = gson.fromJson(json, Embed.class);

    assertNotNull(embed);
    assertEquals(1, embed.getHeight());
    assertEquals(1, embed.getId());
    assertEquals(1, embed.getWidth());
    assertEquals("DESCRIPTION", embed.getDescription());
    assertEquals("EMBEDHTML", embed.getHtml());
    assertEquals("HOSTNAME", embed.getHostName());
    assertEquals("ORIGINALURL", embed.getOriginalUrl());
    assertEquals("RESOLVEDURL", embed.getResolvedUrl());
    assertEquals("TITLE", embed.getTitle());
    assertEquals("URL", embed.getUrl());
  }
コード例 #4
0
  public void save(T media) throws IOException {

    if (!canSaveType(media.getClass())) {
      return;
    }

    String preName = media.getPreviousName();
    File f = null;

    if (fileCache.containsKey(media)) {
      f = fileCache.get(media);
    } else {
      f = generateSaveFile(media);
    }

    Gson gson =
        new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
    media.setSaved(true);
    String json = gson.toJson(media);

    BufferedWriter bfw = new BufferedWriter(new FileWriter(f));
    bfw.write(json);
    bfw.close();

    if (MediaBase.class.isAssignableFrom(media.getClass())) {
      ((MediaBase) media).save();
      System.out.println("Thumb saved");
    }

    if (preName != null && !preName.equals(media.getSaveString())) {
      deleteOldVersion(media, preName);
    }
  }
コード例 #5
0
    @Override
    public JsonElement serialize(
        OutputDataRaw cellRaw, Type typeOfSrc, JsonSerializationContext context) {
      final JsonObject jsonObject = new JsonObject();

      if (cellRaw.png != null) {
        jsonObject.addProperty("image/png", cellRaw.png);
      }
      if (cellRaw.html != null) {
        final JsonElement html = gson.toJsonTree(cellRaw.html);
        jsonObject.add("text/html", html);
      }
      if (cellRaw.svg != null) {
        final JsonElement svg = gson.toJsonTree(cellRaw.svg);
        jsonObject.add("image/svg+xml", svg);
      }
      if (cellRaw.jpeg != null) {
        final JsonElement jpeg = gson.toJsonTree(cellRaw.jpeg);
        jsonObject.add("image/jpeg", jpeg);
      }
      if (cellRaw.latex != null) {
        final JsonElement latex = gson.toJsonTree(cellRaw.latex);
        jsonObject.add("text/latex", latex);
      }
      if (cellRaw.text != null) {
        final JsonElement text = gson.toJsonTree(cellRaw.text);
        jsonObject.add("text/plain", text);
      }

      return jsonObject;
    }
コード例 #6
0
ファイル: Miner.java プロジェクト: arjun-v/WekaLearner
  public static void main(String[] args) {

    try {

      InputStream stream =
          Thread.currentThread()
              .getContextClassLoader()
              .getResourceAsStream("miningResources/config.json");

      Gson gson = new GsonBuilder().create();
      String jsonString = new String(IOUtils.readFully(stream, -1, false));
      stream.close();
      JsonParser parser = new JsonParser();
      JsonArray Jarray = parser.parse(jsonString).getAsJsonArray();
      List<MineSettings> settings = new ArrayList<MineSettings>();

      for (JsonElement obj : Jarray) {
        MineSettings cse = gson.fromJson(obj, MineSettings.class);
        settings.add(cse);
      }

      AprioriAssociationRules apriori = new AprioriAssociationRules();
      apriori.build(settings.get(0).getFILE(), settings.get(0).getOPTIONS());

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #7
0
  @Override
  public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {
      ActividadDao oActividadDAO = new ActividadDao(Conexion.getConection());
      ActividadBean oActividad = new ActividadBean();
      Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
      String jason = request.getParameter("json");
      jason = EncodingUtil.decodeURIComponent(jason);
      oActividad = gson.fromJson(jason, oActividad.getClass());
      Map<String, String> data = new HashMap<>();
      if (oActividad != null) {
        oActividadDAO.set(oActividad);
        data.put("status", "200");
        data.put("message", Integer.toString(oActividad.getId()));
      } else {
        data.put("status", "error");
        data.put("message", "error");
      }
      String resultado = gson.toJson(data);
      return resultado;
    } catch (Exception e) {
      throw new ServletException("ActividadSaveJson: View Error: " + e.getMessage());
    }
  }
  @Override
  public boolean parse(
      @NonNull String line,
      @NonNull OutputLineReader reader,
      @NonNull List<Message> messages,
      @NonNull ILogger logger)
      throws ParsingFailedException {
    Matcher m = MSG_PATTERN.matcher(line);
    if (!m.matches()) {
      return false;
    }
    String json = m.group(1);
    if (json.trim().isEmpty()) {
      return false;
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    MessageJsonSerializer.registerTypeAdapters(gsonBuilder);
    Gson gson = gsonBuilder.create();
    try {
      Message msg = gson.fromJson(json, Message.class);
      messages.add(msg);
      return true;
    } catch (JsonParseException e) {
      throw new ParsingFailedException(e);
    }
  }
コード例 #9
0
 @RequestMapping(path = "health", method = RequestMethod.GET)
 public String health() {
   Gson gson = new GsonBuilder().create();
   JsonObject jsonObject = new JsonObject();
   jsonObject.add("status", new JsonPrimitive("healthy"));
   return gson.toJson(jsonObject);
 }
コード例 #10
0
  @POST()
  @Path("New")
  public Response New(
      String siteInfo,
      @Context HttpServletResponse servletResponse,
      @Context SecurityContext context) {
    if (!context.isUserInRole(Roles.REG_USER)) {
      return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build();
    }

    Response response;

    try {
      Gson gson = new Gson();
      String json = siteInfo.split("=")[1];
      Site site = gson.fromJson(json, Site.class);
      SitesController.getInstance().NewSite(site);

      response = Response.status(200).entity(GeoRedConstants.SITE_SUCCESSFULY_ADDED).build();
    } catch (Exception e) {
      response = Response.status(500).entity(e.getMessage()).build();
    }

    return response;
  }
コード例 #11
0
 @Override
 public String render(Object model) {
   if (model instanceof Response) {
     return gson.toJson(new HashMap<>());
   }
   return gson.toJson(model);
 }
コード例 #12
0
  // crear comentario. recibe un Comment.
  @POST()
  @Path("Comments/New")
  public Response CommentsNew(
      String commentInfo,
      @Context HttpServletResponse servletResponse,
      @Context SecurityContext context) {
    // si no es un usuario registrado, devolver error 500 de acceso denegado
    if (!context.isUserInRole(Roles.REG_USER)) {
      return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build();
    }

    // crear comentario
    try {
      Gson gson = new Gson();
      commentInfo = commentInfo.split("=")[1];
      Comment comment = gson.fromJson(commentInfo, Comment.class);
      SitesController.getInstance().newComment(comment);

      return Response.status(200).entity(GeoRedConstants.COMMENT_SUCCESSFULY_ADDED).build();
    }

    // si salta una excepción, devolver error
    catch (Exception ex) {
      return Response.status(500).entity(ex.getMessage()).build();
    }
  }
コード例 #13
0
  // obtener datos de una visita.
  // recibe un String con el id, y devuelve un Site.
  @GET()
  @Produces("text/plain")
  @Path("GetById")
  public Response GetById(
      @QueryParam("siteId") String siteId,
      @Context HttpServletResponse servletResponse,
      @Context SecurityContext context) {
    if (!context.isUserInRole(Roles.REG_USER)) {
      return Response.status(500).entity(GeoRedConstants.ACCESS_DENIED).build();
    }

    // obtener visita
    try {
      Gson gson = new Gson();

      Site site = SitesController.getInstance().getById(siteId);

      return Response.status(200).entity(gson.toJson(site)).build();
    }

    // si salta una excepción, devolver error
    catch (Exception ex) {
      return Response.status(500).entity(ex.getMessage()).build();
    }
  }
コード例 #14
0
 /**
  * 删除用户
  *
  * @param request
  * @param response
  */
 @RequestMapping("/user_del")
 public void delUser(HttpServletRequest request, HttpServletResponse response) {
   Map<String, Object> resMap = new HashMap<String, Object>();
   String ids = request.getParameter("ids");
   logger.debug("ids:" + ids);
   List<Integer> paramList = new ArrayList<Integer>();
   if (StringUtils.isNoneBlank(ids)) {
     String[] s_array = ids.split(",", -1);
     if (s_array != null && s_array.length > 0) {
       for (String item : s_array) {
         paramList.add(new Integer(item));
       }
       Integer[] i_array = new Integer[paramList.size()];
       for (int i = 0; i < paramList.size(); i++) {
         i_array[i] = paramList.get(i);
       }
       userService.delUserById(i_array);
       resMap.put("msg", "ok");
     } else {
       resMap.put("msg", "error");
     }
   }
   try {
     response.setCharacterEncoding("utf-8");
     response.setHeader("Content-type", "text/html;charset=UTF-8");
     PrintWriter out = response.getWriter();
     Gson gson = new Gson();
     logger.debug("json输出:" + gson.toJson(resMap));
     out.println(gson.toJson(resMap));
     out.flush();
     out.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #15
0
  public static void main(String[] args) throws IOException {

    Verzeichnisdienst v = Verzeichnisdienst.init();

    //		URL yahoo = new URL("http://vs-docker.informatik.haw-hamburg.de/ports/8053/services/1");
    //
    //		URLConnection uc = yahoo.openConnection();
    //		uc.setRequestProperty("Authorization", "Basic YWJvNDc2OkRFMTAwNnN1ODc=");
    //
    //		InputStream content = (InputStream) uc.getInputStream();
    //		BufferedReader in = new BufferedReader(new InputStreamReader(content));
    //
    //		String line;
    //		while ((line = in.readLine()) != null) {
    //			System.out.println(line);
    //		}
    //
    //		in.close();

    System.out.println(v.getServices());

    VerzeichnisdienstInterface verzeichnisdienst =
        ServiceGenerator.createService(VerzeichnisdienstInterface.class);

    Gson gson = new Gson();
    String json = gson.toJson(verzeichnisdienst.holeService().execute().body());
    System.out.println(json);
  }
コード例 #16
0
 public static void addTask(Task task) {
   Gson gson = new Gson();
   JsonHttpRequest request = new JsonHttpRequest(serverUrl, tasksPath, gson.toJson(task), "POST");
   request.addHeaderParameter(authorizationHeaderName, Util.base64Header);
   request.addHeaderParameter("Content-Type", "application/json");
   request.execute();
 }
コード例 #17
0
  @POST
  @Path("{token}")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public String gerarToken(@PathParam("token") Long id, String json) {
    String retorno = BLANK_RETURN;
    Token token = null;
    try {
      Usuario usuario = usuarioSevice.findByCodigo(id);
      if (usuario != null) {
        token = tokenGeneratorService.findByUsuarioId(id);

        Gson gson = new GsonBuilder().setExclusionStrategies(new TokenExclusionStrategy()).create();

        if (token != null) {
          retorno = gson.toJson(token);
        } else {
          JSONObject jsonObject = new JSONObject(json);
          configurarUsuario(usuario, jsonObject);

          token = tokenGeneratorService.create(usuario);
          retorno = gson.toJson(token);
        }
      } else {
        // TODO Saber qual a mensagem enviar para o cliente
      }
    } catch (ServiceException e) {
      // TODO Saber qual mensagem passar para o usuário
    } catch (Exception e) {
      // TODO Saber qual mensagem passar para o usuário
    }
    return retorno;
  }
コード例 #18
0
  public static void sendBuyRequest(String monsterName) throws Exception {
    Gson gson = new Gson(); // Gson object for deserialization of the response
    URL url = new URL("http://193.60.15.159:8080/MMG6Main/BuyServlet");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    /*
     * POST request details
     */
    writer.write("name=" + monsterName);
    writer.flush();
    String line; // Response in text
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
      Monster monster = gson.fromJson(line, Monster.class);
      System.out.println(monster.getAggression());
      PersistManager persistIt = new PersistManager();
      persistIt.init();
      persistIt.create(monster);
      // Add Monster to the user who sent the request
    }

    writer.close();
    reader.close();
  }
コード例 #19
0
 // 进行json解析
 private void analyzeJson(String json) {
   if (!TextUtils.isEmpty(json)) {
     String[] cir_arr_one = json.split("\\(");
     String cir_one = cir_arr_one[1];
     String[] cir_arr_two = cir_one.split("\\)");
     String cir_two = cir_arr_two[0];
     if ("null".equals(cir_two)) {
       // 标明 已经全部加载完
       // 证明已经到了最后一页
       isLastPage = true;
       ToastAlone.show(R.string.load_all_data);
       Log.i("cxm", "the last one");
       return;
     } else {
       Gson gson = new Gson();
       List<StoryBean> storyBeans =
           gson.fromJson(cir_two, new TypeToken<List<StoryBean>>() {}.getType());
       if (storyBeans != null) {
         if (mStartNum == 20) {
           mStoryAdapter.setData(storyBeans);
         } else {
           mStoryAdapter.addData(storyBeans);
         }
       }
     }
   }
 }
コード例 #20
0
  /* Sharepoint pilotProject json data creation */
  public void publishMetaData() throws PhrescoException {

    ProjectInfo info = new ProjectInfo();
    info.setName("PilotSharePoint");
    info.setCode("PHR_PilotSharePoint");
    info.setDescription("");
    info.setApplication("apptype-webapp");

    Technology tech = new Technology();
    tech.setId("tech-sharepoint");
    tech.setName("Sharepoint");

    tech.setFrameworks(null);

    info.setTechnology(tech);
    info.setPilotProjectUrls(new String[] {"/pilots/tech-sharepoint/0.1/tech-sharepoint-0.1.zip"});
    Gson gson = new Gson();

    String json = gson.toJson(info);
    try {
      FileWriter write = new FileWriter("sharepointJson.pilots");
      write.write(json);
      write.close();
      ArtifactInfo aInfo =
          new ArtifactInfo(
              PilotProjectManager.PILOT_GROUP, TechnologyTypes.SHAREPOINT, "", "pilots", "0.1");
      File artifact = new File("sharepointJson.pilots");
      repManager.addArtifact(aInfo, artifact);

    } catch (IOException e) {
      throw new PhrescoException(e);
    }
  }
コード例 #21
0
ファイル: WebUtils.java プロジェクト: liuqinggang/neixunutil
 /**
  * 验证项目是否ok
  *
  * @param contextPath 项目路径
  */
 public static boolean isdomainok(String contextPath, String securityKey, String domiankey) {
   try {
     if (contextPath.indexOf("127.0.") > -1 || contextPath.indexOf("192.168.") > -1) {
       return true;
     }
     String dedomaininfo = PurseSecurityUtils.decryption(domiankey, securityKey);
     Gson gson = new Gson();
     JsonParser jsonParser = new JsonParser();
     JsonObject jsonObject = jsonParser.parse(dedomaininfo).getAsJsonObject();
     Map<String, String> map =
         gson.fromJson(jsonObject, new TypeToken<Map<String, String>>() {}.getType());
     String domain = map.get("domain");
     if (contextPath.indexOf(domain) < 0) {
       System.exit(2);
       return false;
     }
     String dt = map.get("dt");
     if (com.yizhilu.os.core.util.StringUtils.isNotEmpty(dt)) {
       Date t = DateUtils.toDate(dt, "yyyy-MM-dd");
       if (t.compareTo(new Date()) < 0) {
         System.exit(3);
         return false;
       }
     }
     return true;
   } catch (Exception e) {
     return false;
   }
 }
コード例 #22
0
 /** 获取TOKEN,一天最多获取200次,需要所有用户共享值 */
 public String GetToken() {
   String requestUrl =
       tokenUrl + "?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
   TenpayHttpClient httpClient = new TenpayHttpClient();
   httpClient.setReqContent(requestUrl);
   if (httpClient.call()) {
     String res = httpClient.getResContent();
     Gson gson = new Gson();
     TreeMap map = gson.fromJson(res, TreeMap.class);
     // 在有效期内直接返回access_token
     if (map.containsKey("access_token")) {
       String s = map.get("access_token").toString();
     }
     // 如果请求成功
     if (null != map) {
       try {
         if (map.containsKey("access_token")) {
           Token = map.get("access_token").toString();
           return this.Token;
         }
       } catch (Exception e) {
         // 获取token失败
         System.out.println("失败:" + map.get("errmsg"));
       }
     }
   }
   return "";
 }
コード例 #23
0
    @Override
    public CellOutputRaw deserialize(
        JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
      final JsonObject object = json.getAsJsonObject();
      final CellOutputRaw cellOutputRaw = new CellOutputRaw();
      final JsonElement ename = object.get("ename");
      if (ename != null) {
        cellOutputRaw.ename = ename.getAsString();
      }
      final JsonElement name = object.get("name");
      if (name != null) {
        cellOutputRaw.name = name.getAsString();
      }
      final JsonElement evalue = object.get("evalue");
      if (evalue != null) {
        cellOutputRaw.evalue = evalue.getAsString();
      }
      final JsonElement data = object.get("data");
      if (data != null) {
        cellOutputRaw.data = gson.fromJson(data, OutputDataRaw.class);
      }

      final JsonElement count = object.get("execution_count");
      if (count != null) {
        cellOutputRaw.execution_count = count.getAsInt();
      }
      final JsonElement outputType = object.get("output_type");
      if (outputType != null) {
        cellOutputRaw.output_type = outputType.getAsString();
      }
      final JsonElement png = object.get("png");
      if (png != null) {
        cellOutputRaw.png = png.getAsString();
      }
      final JsonElement stream = object.get("stream");
      if (stream != null) {
        cellOutputRaw.stream = stream.getAsString();
      }
      final JsonElement jpeg = object.get("jpeg");
      if (jpeg != null) {
        cellOutputRaw.jpeg = jpeg.getAsString();
      }

      cellOutputRaw.html = getStringOrArray("html", object);
      cellOutputRaw.latex = getStringOrArray("latex", object);
      cellOutputRaw.svg = getStringOrArray("svg", object);
      final JsonElement promptNumber = object.get("prompt_number");
      if (promptNumber != null) {
        cellOutputRaw.prompt_number = promptNumber.getAsInt();
      }
      cellOutputRaw.text = getStringOrArray("text", object);
      cellOutputRaw.traceback = getStringOrArray("traceback", object);
      final JsonElement metadata = object.get("metadata");
      if (metadata != null) {
        cellOutputRaw.metadata = gson.fromJson(metadata, Map.class);
      }

      return cellOutputRaw;
    }
コード例 #24
0
  /** 实时获取token,并更新到application中 */
  public String getTokenReal() {
    String requestUrl =
        tokenUrl + "?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
    try {
      // 发送请求,返回json
      TenpayHttpClient httpClient = new TenpayHttpClient();
      httpClient.setReqContent(requestUrl);
      String resContent = "";
      if (httpClient.callHttpPost(requestUrl, "")) {
        resContent = httpClient.getResContent();
        Gson gson = new Gson();
        Map<String, String> map =
            gson.fromJson(resContent, new TypeToken<Map<String, String>>() {}.getType());
        // 判断返回是否含有access_token
        if (map.containsKey("access_token")) {
          // 更新application值
          Token = map.get("access_token");
        } else {
          System.out.println("get token err ,info =" + map.get("errmsg"));
        }
        System.out.println("res json=" + resContent);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return Token;
  }
コード例 #25
0
  public T load(File f) throws IOException, JsonSyntaxException {

    if (!f.isFile()) {
      return null;
    }

    T doc = null;
    BufferedReader reader = new BufferedReader(new FileReader(f));

    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
      sb.append(line);
    }
    reader.close();

    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    doc = (T) gson.fromJson(sb.toString(), myClass);
    fileCache.put(doc, f);
    doc.setSaved(true);
    doc.getInternalID();
    addMedia(doc);
    System.out.println("Loaded: " + doc.getSaveString() + " " + doc.getClass().getSimpleName());

    if (MediaBase.class.isAssignableFrom(doc.getClass())) {
      ((MediaBase) doc).load();
    }

    return doc;
  }
コード例 #26
0
 /**
  * 获取答题卡
  *
  * @param histId
  * @return
  */
 @RequestMapping(value = "admin/exam/get-answersheet/{histId}", method = RequestMethod.GET)
 public @ResponseBody AnswerSheet getAnswerSheet(@PathVariable("histId") int histId) {
   ExamHistory history = examService.getUserExamHistListByHistId(histId);
   Gson gson = new Gson();
   AnswerSheet answerSheet = gson.fromJson(history.getAnswerSheet(), AnswerSheet.class);
   return answerSheet;
 }
コード例 #27
0
ファイル: VNFDescriptor.java プロジェクト: T-NOVA/NFS
 public boolean setJsonImageProperty(String imageName, String md5Sum, String imageType) {
   boolean result = false;
   Gson gson = new Gson();
   JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
   JsonArray vduList = jsonElement.getAsJsonObject().getAsJsonArray(VirtualDeploymentUnit.VDU);
   for (JsonElement vduElement : vduList) {
     JsonElement imageElement = vduElement.getAsJsonObject().get(VirtualDeploymentUnit.VM_IMAGE);
     if (imageElement == null) continue;
     String image = imageElement.getAsString();
     if (image == null || image.isEmpty()) continue;
     if (image.endsWith("/files/" + imageName)) {
       if (md5Sum == null || md5Sum.isEmpty()) {
         vduElement.getAsJsonObject().remove(VirtualDeploymentUnit.VM_IMAGE_MD5);
       } else {
         vduElement.getAsJsonObject().addProperty(VirtualDeploymentUnit.VM_IMAGE_MD5, md5Sum);
       }
       if (imageType == null || imageType.isEmpty()) {
         vduElement.getAsJsonObject().remove(VirtualDeploymentUnit.VM_IMAGE_FORMAT);
       } else {
         vduElement
             .getAsJsonObject()
             .addProperty(VirtualDeploymentUnit.VM_IMAGE_FORMAT, imageType);
       }
       result = true;
     }
   }
   if (result) {
     json = gson.toJson(jsonElement);
     vnfd = gson.fromJson(json, VNFD.class);
   }
   return result;
 }
コード例 #28
0
ファイル: WsChatServer.java プロジェクト: kc87/WebChatSB
  @OnMessage
  public void onTextMsg(String jsonStr) {
    Gson gson = new GsonBuilder().serializeNulls().create();

    try {
      jsonStr = jsonStr.trim();
      LOG.debug("Rcv.:" + jsonStr + " from: " + thisSession.getId());
      Message clientMsg = gson.fromJson(jsonStr, Message.class);

      if (clientMsg.TYPE.equals("PING")) {
        sendPong();
      }

      if (clientMsg.TYPE.equals("JOIN")) {
        joinChat();
      }

      if (clientMsg.TYPE.equals("CHAT")) {
        handleChat(clientMsg);
      }

    } catch (JsonSyntaxException e) {
      LOG.error("@OnMessage: " + e);
    }
  }
コード例 #29
0
 /** Play Monument Handler for the server */
 @Override
 public void handle(HttpExchange exchange) throws IOException {
   exchange.getResponseHeaders().set("Content-type", "application/json");
   try {
     int gameID = checkCookie(exchange);
     if (gameID == -1) {
       System.err.print("\nInvalid Cookie. Thowing Error");
       throw new Exception("INVALID COOKIE!");
     }
     Gson gson = new Gson();
     StringWriter writer = new StringWriter();
     IOUtils.copy(exchange.getRequestBody(), writer);
     shared.communication.toServer.moves.Monument_ move =
         gson.fromJson(writer.toString(), Monument_.class);
     server.commands.Monument command = new server.commands.Monument(gameID);
     command.setParams(move);
     command.execute(server);
     this.addCommand(command, gameID);
     exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
     OutputStreamWriter output = new OutputStreamWriter(exchange.getResponseBody());
     output.write(server.getModel(gameID));
     output.flush();
     exchange.getResponseBody().close();
     exchange.close();
   } catch (Exception e) {
     exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, -1);
     exchange.getResponseBody().close();
     exchange.close();
   }
 }
コード例 #30
0
  /**
   * Save state.
   *
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public default void SaveState() throws IOException {

    final Gson newGsonWriter = new Gson();
    final String stringFileinJSON = newGsonWriter.toJson(this);
    final String path = GetFolder() + "\\" + GetName() + "_" + GetID() + ".txt";
    Files.write(Paths.get(path), stringFileinJSON.getBytes());
  }