private SignatureData getFromCmsSignature(
      SignatureVerificationRequest signatureVerificationRequest,
      SignatureVerificationResponse response)
      throws CMSException {
    String signature = signatureVerificationRequest.getSignature();
    byte[] decoded = Base64.decode(signature);
    CMSSignedData cmsSignedData = new CMSSignedData(decoded);
    String encodedSignedData = new String((byte[]) cmsSignedData.getSignedContent().getContent());

    // Fetch information about the issuers
    List<String> certInfos = new ArrayList<String>();
    Collection certificates = cmsSignedData.getCertificates().getMatches(null);
    for (Object certificate : certificates) {
      X509CertificateHolder holder = (X509CertificateHolder) certificate;
      certInfos.add(holder.getSubject().toString());
      CertificateInfo ci = new CertificateInfo();
      ci.setSubjectDn(holder.getSubject().toString());
      ci.setValidTo(simpleDateFormat.format(holder.getNotAfter()));
      response.getCertificateInfos().getCertificateInfo().add(ci);
    }

    // Fetch timestamp
    Date signingDate = findTimestamp(cmsSignedData);
    String dateString = simpleDateFormat.format(signingDate);
    response.setSignatureDate(dateString);

    // Create the SignatureData to be verified
    SignatureData signData = new SignatureData();
    signData.setEncodedTbs(encodedSignedData);
    signData.setSignature(signature);
    ELegType clientType = new ELegType("test", "test", PkiClient.NETMAKER_NETID_4);
    signData.setClientType(clientType);
    return signData;
  }
  @GET
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  @XmlElementWrapper(name = "memorystats")
  @Path("/interval/{timeWindowsInHours}")
  public List<Memory> loadMemoryStatusInInterval(
      @PathParam("timeWindowsInHours") int timeWindowsInHours) {
    Calendar calendar = Calendar.getInstance();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    String toDate = df.format(calendar.getTime());
    calendar.add(Calendar.HOUR_OF_DAY, -timeWindowsInHours);
    String fromDate = df.format(calendar.getTime());
    Log.trace(toDate, fromDate);
    List<Memory> memorystats = null;
    try {
      IMemoryDAO mdao = DAOFactory.getInstance().getMemoryDAO();
      List<MemoryPO> memPOs = mdao.getMemoryStats(toDate, fromDate);

      memorystats = new ArrayList<Memory>();
      for (MemoryPO memPO : memPOs) {
        Memory memdto = ConverterUtils.convert(memPO);
        memorystats.add(memdto);
      }
    } catch (Exception e) {
      handleException(e);
    } finally {
      Log.exit(memorystats);
    }
    return memorystats;
  }
  @GET
  @Path("user/roles")
  @Produces("application/json")
  public Response getRolesForJAASPrincipal(
      @Context HttpServletRequest request, @QueryParam("roleCheck") String roleCheck) {
    // TODO: Why not use the identity DB right away?
    // These roles are security roles
    if (null == roleCheck)
      throw new WebApplicationException(
          new IllegalArgumentException("Missing parameter 'roleCheck'"));

    log.debug(
        "Role check user: "******", actualRoles requested: "
            + roleCheck);

    List<RoleAssignmentRef> actualRoles = new ArrayList<RoleAssignmentRef>();

    StringTokenizer tok = new StringTokenizer(roleCheck, ",");
    while (tok.hasMoreTokens()) {
      String possibleRole = tok.nextToken();
      actualRoles.add(new RoleAssignmentRef(possibleRole, request.isUserInRole(possibleRole)));
    }
    return createJsonResponse(new RoleAssignmentRefWrapper(actualRoles));
  }
Beispiel #4
0
  @Path("/writeAttribute")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response writeAttributeResponse(String input) throws Exception {

    JSONObject inputObj = new JSONObject(input);
    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class)
            .filter("client_bs_obj.device_id =", inputObj.getString("client_bs_obj.device_id"))
            .asList();

    ClientObject clientObject = clientObjects.get(0);
    resource.Object obj = clientObject.getObjectMap().get(inputObj.getInt("ObjectId"));
    obj.setPmin(inputObj.getJSONObject("value").getString("pmin"));
    obj.setPmax(inputObj.getJSONObject("value").getString("pmax"));
    obj.setLessThan(inputObj.getJSONObject("value").getString("lt"));
    obj.setGreaterThan(inputObj.getJSONObject("value").getString("gt"));
    obj.setStep(inputObj.getJSONObject("value").getString("st"));
    ds.save(clientObject);

    CountDownLatch signalRead =
        Info.getCountDownMessage(inputObj.getString("client_bs_obj.device_id"));
    signalRead.countDown();

    return Response.status(200).entity(inputObj.getString("message")).build();
  }
  /**
   * Builds the full URI path to this resource method.
   *
   * @return the full URI path to this resource method.
   */
  public String getFullpath() {
    List<String> subpaths = new ArrayList<String>();
    if (getSubpath() != null) {
      subpaths.add(0, getSubpath());
    }

    Resource parent = getParent();
    while (parent != null) {
      subpaths.add(0, parent.getPath());
      parent = parent.getParent();
    }

    StringBuilder builder = new StringBuilder();
    for (String subpath : subpaths) {
      subpath = subpath.trim();
      if (!subpath.startsWith("/")) {
        subpath = '/' + subpath;
      }
      while (subpath.endsWith("/")) {
        subpath = subpath.substring(0, subpath.length() - 1);
      }
      subpath = scrubParamNames(subpath);

      builder.append(subpath);
    }

    return builder.toString();
  }
Beispiel #6
0
  @Path("/read")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response readResponse(String input) throws Exception {
    JSONObject test = new JSONObject(input);
    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class)
            .filter("client_bs_obj.device_id =", test.getString("client_bs_obj.device_id"))
            .asList();
    Resource resourceO =
        clientObjects
            .get(0)
            .getObjectMap()
            .get(test.getInt("ObjectId"))
            .getObjInstanceMap()
            .get(test.getInt("ObjectInsId"))
            .getResourceMap()
            .get(test.getInt("resourceId"));
    ObjectMapper mapper = new ObjectMapper();
    Resource resourceN = mapper.readValue(test.getString("value"), Resource.class);

    resourceO.getValue().putAll(resourceN.getValue());

    ds.save(clientObjects.get(0));

    CountDownLatch signalRead = Info.getCountDownMessage(test.getString("client_bs_obj.device_id"));
    signalRead.countDown();

    return Response.status(200).entity("success").build();
  }
 @Path("operation")
 @POST
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public GenericServiceAPIResponseEntity createOperation(InputStream inputStream) {
   GenericServiceAPIResponseEntity response = new GenericServiceAPIResponseEntity<>();
   List<TopologyOperationEntity> operations = new LinkedList<>();
   try {
     List<TopologyOperationEntity> entities =
         (List<TopologyOperationEntity>) unmarshalOperationEntities(inputStream);
     if (entities == null) {
       throw new IllegalArgumentException("inputStream cannot convert to TopologyOperationEntity");
     }
     for (TopologyOperationEntity entity : entities) {
       String status =
           dao.loadTopologyExecutionStatus(
               entity.getSite(), entity.getApplication(), entity.getTopology());
       if (status == null) {
         throw new Exception(
             String.format(
                 "Fail to fetch the topology execution status by site=%s, application=%s, topology=%s",
                 entity.getSite(), entity.getApplication(), entity.getTopology()));
       }
       int operationsInRunning =
           dao.loadTopologyOperationsInRunning(
               entity.getSite(), entity.getApplication(), entity.getTopology());
       if (operationsInRunning != 0) {
         throw new Exception(
             operationsInRunning + "operations are running, please wait for a minute");
       }
       if (validateOperation(entity.getOperation(), status)) {
         Map<String, String> tags = entity.getTags();
         tags.put(AppManagerConstants.OPERATION_ID_TAG, UUID.randomUUID().toString());
         entity.setTags(tags);
         entity.setLastModifiedDate(System.currentTimeMillis());
         entity.setTimestamp(System.currentTimeMillis());
         operations.add(entity);
       } else {
         throw new Exception(
             String.format(
                 "%s is an invalid operation, as the topology's current status is %s",
                 entity.getOperation(), status));
       }
     }
     response = dao.createOperation(operations);
   } catch (Exception e) {
     response.setSuccess(false);
     response.setException(e);
   }
   return response;
 }
Beispiel #8
0
 @GET
 @Path("/vinesDescribed")
 @Produces(MediaType.APPLICATION_JSON)
 public List<Vine> getAllVineDescribed() {
   logger.info("ServiceVineDescribed contains " + serviceVineDescribed.getSize() + " units.");
   List<VineDescribed> vinesDescribed = serviceVineDescribed.getVineDescribeds();
   List<Vine> vines = new ArrayList<Vine>();
   if (vinesDescribed == null) {
     return null;
   }
   for (int i = 0; i < vinesDescribed.size(); i++) {
     vines.add(vinesDescribed.get(i).getVine());
   }
   return vines;
 }
  @GET
  @Path("user/{actorId}/actors")
  @Produces("application/json")
  public Response getAvailableActors(@PathParam("actorId") String actorId) {
    Set<String> users = new HashSet<String>();
    List<String> groups = getUserManagement().getGroupsForActor(actorId);
    for (String group : groups) {
      List<String> actors = getUserManagement().getActorsForGroup(group);
      users.addAll(actors);
    }

    List<String> availableActors = new ArrayList<String>();
    availableActors.addAll(users);
    availableActors.addAll(groups);
    return createJsonResponse(availableActors);
  }
  @GET
  @Path("/types/{type}")
  public List<Long> getTypes(@PathParam("type") String type) {

    List<Long> matchingTransactions = new ArrayList<>();
    getDatabase()
        .values()
        .stream()
        .forEach(
            item -> {
              if (item.getType().equals(type)) {
                matchingTransactions.add(item.getTransactionId());
              }
            });

    return matchingTransactions;
  }
Beispiel #11
0
 @GET
 @Path("/process")
 @Produces(MediaType.APPLICATION_JSON)
 public List<Descriptor> processAllVines() {
   List<Vine> vines = vineRepository.findAllNotDescribedOrderedById();
   for (int i = 0; i < vines.size(); i++) {
     try {
       Descriptor descriptor = new Descriptor(vines.get(i));
       serviceDescriptor.save(descriptor);
       serviceVineDescribed.addVineDescribed(new VineDescribed(descriptor));
       logger.info("ServiceVineDescribed contains " + serviceVineDescribed.getSize() + " units.");
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return descriptorRepository.findAllOrderedByVineID();
 }
 @GET
 @Path("{warName}")
 public Response deploymentState(@PathParam("warName") String warName) throws Exception {
   DeploymentCheckRequest request = new DeploymentCheckRequest();
   request.setWarName(warName);
   Message<DeploymentCheckRequest> msg =
       new Message<DeploymentCheckRequest>(DeploymentCheckCommandAction.COMMAND_ACTION, request);
   checkResponse.resetAll();
   sender.sendMessage(msg, null);
   Map<ChannelMember, DeploymentCheckResponse> responses =
       new HashMap<ChannelMember, DeploymentCheckResponse>();
   int timeout = 240;
   while (timeout-- > 0) {
     Thread.sleep(500l);
     boolean foundAll = true;
     for (ChannelMember mem : members) {
       Message<DeploymentCheckResponse> memResponse = checkResponse.getResponse(mem);
       if (memResponse != null) {
         responses.put(mem, memResponse.getBody());
       } else {
         foundAll = false;
       }
     }
     if (foundAll) {
       break;
     }
   }
   if (responses.size() == members.size()) {
     Set<ChannelMember> membersInError = new HashSet<ChannelMember>();
     boolean combinedState = true;
     boolean anyStarted = false;
     for (ChannelMember mem : responses.keySet()) {
       DeploymentCheckResponse response = responses.get(mem);
       if (response.getError() != null) {
         combinedState = false;
         membersInError.add(mem);
       } else {
         combinedState = combinedState && response.isFinished();
       }
       if (response.isStarted()) {
         anyStarted = true;
       }
     }
     Map<String, Object> responseObj = new LinkedHashMap<String, Object>();
     responseObj.put("finished", combinedState);
     responseObj.put("started", anyStarted);
     if (membersInError.size() > 0) {
       Set<String> inError = new TreeSet<String>();
       responseObj.put("errors", inError);
       for (ChannelMember mem : membersInError) {
         inError.add(mem.getAddress().toString() + (mem.isCoordinator() ? ":coord" : ""));
       }
     }
     return Response.ok(new Gson().toJson(responseObj)).build();
   }
   return Response.status(Response.Status.NOT_FOUND).build();
 }
 @Path("/my/course/{id}")
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public StreamingOutput getMyCourseSignups(@PathParam("id") String courseId) {
   checkAuthenticated();
   final List<CourseSignup> signups = courseService.getMySignups(null);
   final List<CourseSignup> courseSignups = new ArrayList<CourseSignup>();
   for (CourseSignup signup : signups) {
     if (courseId.equals(signup.getGroup().getCourseId())) {
       courseSignups.add(signup);
     }
   }
   return new StreamingOutput() {
     public void write(OutputStream output) throws IOException, WebApplicationException {
       objectMapper
           .typedWriter(TypeFactory.collectionType(List.class, CourseSignup.class))
           .writeValue(output, courseSignups);
     }
   };
 }
Beispiel #14
0
  @Path("/discover/{ObjID}/{ObjInsId}/{resourceId}")
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public Response sendDiscover(
      @PathParam("ObjID") String objectId,
      @PathParam("ObjInsId") String objectInstanceId,
      @PathParam("resourceId") String resourceID,
      @QueryParam("ep") String endPoint)
      throws Exception {
    String directory =
        "{\"operation\":\"discover\""
            + ","
            + "\""
            + "directory\":"
            + "\""
            + objectId
            + "/"
            + objectInstanceId
            + "/"
            + resourceID
            + "\"}";
    Info.setInfo(endPoint, directory);
    CountDownLatch signal = Info.getCountDown(endPoint);
    if (signal == null) {
      return Response.status(200).entity("Devices not registerd yet").build();
    }
    signal.countDown();

    CountDownLatch signalRead = new CountDownLatch(1);
    Info.setCountDownLatchMessageMap(endPoint, signalRead);
    signalRead.await();

    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class).filter("client_bs_obj.device_id =", endPoint).asList();
    resource.Object obj = clientObjects.get(0).getObjectMap().get(Integer.parseInt(objectId));
    String message = "discover success! " + "pmin:" + obj.getPmin() + " pmax:" + obj.getPmax();

    return Response.status(200).entity(message).build();
  }
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response invoices(@Context HttpServletRequest request) throws SQLException, IOException {
    authService.guardAuthenticatedUser(request);

    try (Connection c = dataSource.getConnection()) {
      List<UUID> ids = registrationsSqlMapper.all(c).map(x -> x.fst());
      List<RegistrationsSqlMapper.Registration> all = Option.somes(ids.traverseIO(ioify(c)).run());
      JsonRootNode overview =
          object(
              field(
                  "received",
                  array(
                      all.filter(x -> x.tuple.state == RegistrationState.RECEIVED)
                          .map(RegistrationsRestService::json))),
              field(
                  "invoicing",
                  array(
                      all.filter(x -> x.tuple.state == RegistrationState.INVOICING)
                          .map(RegistrationsRestService::json))),
              field(
                  "paid",
                  array(
                      all.filter(x -> x.tuple.state == RegistrationState.PAID)
                          .map(RegistrationsRestService::json))));
      return Response.ok(ArgoUtils.format(overview)).build();
    }
  }
Beispiel #16
0
  @Path("/create")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response createResponse(String input) throws Exception {

    JSONObject inputObj = new JSONObject(input);
    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class)
            .filter("client_bs_obj.device_id =", inputObj.getString("client_bs_obj.device_id"))
            .asList();

    ClientObject clientObject = clientObjects.get(0);
    Map<Integer, ObjInstance> objInstanceMap =
        clientObject.getObjectMap().get(inputObj.getInt("ObjectId")).getObjInstanceMap();
    Map<Integer, Resource> resourceMap =
        objInstanceMap.get(inputObj.getInt("ObjectInsId")).getResourceMap();
    ObjInstance objInstance = new ObjInstance();
    objInstance.setObjInstance_id(inputObj.getInt("ObjectInsId") + 1);
    Resource resource = new Resource();
    resource.setRecourse_id(0);
    resource.setName(inputObj.getString("value"));
    Map<Integer, Resource> resourceMapNew = objInstance.getResourceMap();
    resourceMapNew.put(0, resource);
    objInstanceMap.put(objInstance.getObjInstance_id(), objInstance);

    // Map<Integer,Resource> resourceMap = objInstanceMap.get(ObjectInsId).getResourceMap();

    ds.save(clientObject);

    CountDownLatch signalRead =
        Info.getCountDownMessage(inputObj.getString("client_bs_obj.device_id"));
    signalRead.countDown();

    return Response.status(200).entity(inputObj.getString("message")).build();
  }
Beispiel #17
0
  @Path("/delete")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.TEXT_PLAIN)
  public Response deleteResponse(String input) throws Exception {
    JSONObject inputObj = new JSONObject(input);
    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class)
            .filter("client_bs_obj.device_id =", inputObj.getString("client_bs_obj.device_id"))
            .asList();

    ClientObject clientObject = clientObjects.get(0);
    Map<Integer, ObjInstance> objInstanceMap =
        clientObject.getObjectMap().get(inputObj.getInt("ObjectId")).getObjInstanceMap();
    objInstanceMap.remove(inputObj.getInt("ObjectInsId"));
    ds.save(clientObject);

    CountDownLatch signalRead =
        Info.getCountDownMessage(inputObj.getString("client_bs_obj.device_id"));
    signalRead.countDown();

    return Response.status(200).entity(inputObj.getString("message")).build();
  }
  private void writeMethodImpl(JMethod method) throws UnableToCompleteException {
    boolean returnRequest = false;
    if (method.getReturnType() != JPrimitiveType.VOID) {
      if (!method.getReturnType().getQualifiedSourceName().equals(Request.class.getName())
          && !method
              .getReturnType()
              .getQualifiedSourceName()
              .equals(JsonpRequest.class.getName())) {
        getLogger()
            .log(
                ERROR,
                "Invalid rest method. Method must have void, Request or JsonpRequest return types: "
                    + method.getReadableDeclaration());
        throw new UnableToCompleteException();
      } else {
        returnRequest = true;
      }
    }

    Json jsonAnnotation = source.getAnnotation(Json.class);
    final Style classStyle = jsonAnnotation != null ? jsonAnnotation.style() : Style.DEFAULT;

    Options classOptions = source.getAnnotation(Options.class);
    Options options = method.getAnnotation(Options.class);

    p(method.getReadableDeclaration(false, false, false, false, true) + " {").i(1);
    {
      String restMethod = getRestMethod(method);
      LinkedList<JParameter> args =
          new LinkedList<JParameter>(Arrays.asList(method.getParameters()));

      // the last arg should be the callback.
      if (args.isEmpty()) {
        getLogger()
            .log(
                ERROR,
                "Invalid rest method. Method must declare at least a callback argument: "
                    + method.getReadableDeclaration());
        throw new UnableToCompleteException();
      }
      JParameter callbackArg = args.removeLast();
      JClassType callbackType = callbackArg.getType().isClassOrInterface();
      JClassType methodCallbackType = METHOD_CALLBACK_TYPE;
      if (callbackType == null || !callbackType.isAssignableTo(methodCallbackType)) {
        getLogger()
            .log(
                ERROR,
                "Invalid rest method. Last argument must be a "
                    + methodCallbackType.getName()
                    + " type: "
                    + method.getReadableDeclaration());
        throw new UnableToCompleteException();
      }
      JClassType resultType = getCallbackTypeGenericClass(callbackType);

      String pathExpression = null;
      Path pathAnnotation = method.getAnnotation(Path.class);
      if (pathAnnotation != null) {
        pathExpression = wrap(pathAnnotation.value());
      }

      JParameter contentArg = null;
      HashMap<String, JParameter> queryParams = new HashMap<String, JParameter>();
      HashMap<String, JParameter> formParams = new HashMap<String, JParameter>();
      HashMap<String, JParameter> headerParams = new HashMap<String, JParameter>();

      for (JParameter arg : args) {
        PathParam paramPath = arg.getAnnotation(PathParam.class);
        if (paramPath != null) {
          if (pathExpression == null) {
            getLogger()
                .log(
                    ERROR,
                    "Invalid rest method.  Invalid @PathParam annotation. Method is missing the @Path annotation: "
                        + method.getReadableDeclaration());
            throw new UnableToCompleteException();
          }
          pathExpression = pathExpression(pathExpression, arg, paramPath);
          // .replaceAll(Pattern.quote("{" + paramPath.value() + "}"),
          // "\"+com.google.gwt.http.client.URL.encodePathSegment(" + toStringExpression(arg) +
          // ")+\"");
          if (arg.getAnnotation(Attribute.class) != null) {
            // allow part of the arg-object participate in as PathParam and the object goes over the
            // wire
            contentArg = arg;
          }
          continue;
        }

        QueryParam queryParam = arg.getAnnotation(QueryParam.class);
        if (queryParam != null) {
          queryParams.put(queryParam.value(), arg);
          continue;
        }

        FormParam formParam = arg.getAnnotation(FormParam.class);
        if (formParam != null) {
          formParams.put(formParam.value(), arg);
          continue;
        }

        HeaderParam headerParam = arg.getAnnotation(HeaderParam.class);
        if (headerParam != null) {
          headerParams.put(headerParam.value(), arg);
          continue;
        }

        if (!formParams.isEmpty()) {
          getLogger()
              .log(
                  ERROR,
                  "You can not have both @FormParam parameters and a content parameter: "
                      + method.getReadableDeclaration());
          throw new UnableToCompleteException();
        }

        if (contentArg != null) {
          getLogger()
              .log(
                  ERROR,
                  "Invalid rest method. Only one content parameter is supported: "
                      + method.getReadableDeclaration());
          throw new UnableToCompleteException();
        }
        contentArg = arg;
      }

      String acceptTypeBuiltIn = null;
      if (callbackType.equals(TEXT_CALLBACK_TYPE)) {
        acceptTypeBuiltIn = "CONTENT_TYPE_TEXT";
      } else if (callbackType.equals(JSON_CALLBACK_TYPE)) {
        acceptTypeBuiltIn = "CONTENT_TYPE_JSON";
      } else if (callbackType.isAssignableTo(OVERLAY_CALLBACK_TYPE)) {
        acceptTypeBuiltIn = "CONTENT_TYPE_JSON";
      } else if (callbackType.equals(XML_CALLBACK_TYPE)) {
        acceptTypeBuiltIn = "CONTENT_TYPE_XML";
      }

      p("final " + METHOD_CLASS + " __method =");

      p("getResource()");
      if (pathExpression != null) {
        p(".resolve(" + pathExpression + ")");
      }
      for (Map.Entry<String, JParameter> entry : queryParams.entrySet()) {
        String expr = entry.getValue().getName();
        JClassType type = entry.getValue().getType().isClassOrInterface();
        if (type != null && isQueryParamListType(type)) {
          p(
              ".addQueryParams("
                  + wrap(entry.getKey())
                  + ", "
                  + toIteratedStringExpression(entry.getValue())
                  + ")");
        } else {
          p(
              ".addQueryParam("
                  + wrap(entry.getKey())
                  + ", "
                  + toStringExpression(entry.getValue().getType(), expr)
                  + ")");
        }
      }
      // example: .get()
      p("." + restMethod + "();");

      // Handle JSONP specific configuration...
      JSONP jsonpAnnotation = method.getAnnotation(JSONP.class);

      final boolean isJsonp = restMethod.equals(METHOD_JSONP) && jsonpAnnotation != null;
      if (isJsonp) {
        if (returnRequest
            && !method
                .getReturnType()
                .getQualifiedSourceName()
                .equals(JsonpRequest.class.getName())) {
          getLogger()
              .log(
                  ERROR,
                  "Invalid rest method. JSONP method must have void or JsonpRequest return types: "
                      + method.getReadableDeclaration());
          throw new UnableToCompleteException();
        }
        if (jsonpAnnotation.callbackParam().length() > 0) {
          p(
              "(("
                  + JSONP_METHOD_CLASS
                  + ")__method).callbackParam("
                  + wrap(jsonpAnnotation.callbackParam())
                  + ");");
        }
        if (jsonpAnnotation.failureCallbackParam().length() > 0) {
          p(
              "(("
                  + JSONP_METHOD_CLASS
                  + ")__method).failureCallbackParam("
                  + wrap(jsonpAnnotation.failureCallbackParam())
                  + ");");
        }
      } else {
        if (returnRequest
            && !method.getReturnType().getQualifiedSourceName().equals(Request.class.getName())) {
          getLogger()
              .log(
                  ERROR,
                  "Invalid rest method. Non JSONP method must have void or Request return types: "
                      + method.getReadableDeclaration());
          throw new UnableToCompleteException();
        }
      }

      // configure the dispatcher
      if (options != null && options.dispatcher() != Dispatcher.class) {
        // use the dispatcher configured for the method.
        p("__method.setDispatcher(" + options.dispatcher().getName() + ".INSTANCE);");
      } else {
        // use the default dispatcher configured for the service..
        p("__method.setDispatcher(this.dispatcher);");
      }

      // configure the expected statuses..
      if (options != null && options.expect().length != 0) {
        // Using method level defined expected status
        p("__method.expect(" + join(options.expect(), ", ") + ");");
      } else if (classOptions != null && classOptions.expect().length != 0) {
        // Using class level defined expected status
        p("__method.expect(" + join(classOptions.expect(), ", ") + ");");
      }

      // configure the timeout
      if (options != null && options.timeout() >= 0) {
        // Using method level defined value
        p("__method.timeout(" + options.timeout() + ");");
      } else if (classOptions != null && classOptions.timeout() >= 0) {
        // Using class level defined value
        p("__method.timeout(" + classOptions.timeout() + ");");
      }

      if (jsonpAnnotation == null) {
        Produces producesAnnotation = findAnnotationOnMethodOrEnclosingType(method, Produces.class);
        if (producesAnnotation != null) {
          p(
              "__method.header("
                  + RESOURCE_CLASS
                  + ".HEADER_ACCEPT, "
                  + wrap(producesAnnotation.value()[0])
                  + ");");
        } else {
          // set the default accept header....
          if (acceptTypeBuiltIn != null) {
            p(
                "__method.header("
                    + RESOURCE_CLASS
                    + ".HEADER_ACCEPT, "
                    + RESOURCE_CLASS
                    + "."
                    + acceptTypeBuiltIn
                    + ");");
          } else {
            p(
                "__method.header("
                    + RESOURCE_CLASS
                    + ".HEADER_ACCEPT, "
                    + RESOURCE_CLASS
                    + ".CONTENT_TYPE_JSON);");
          }
        }

        Consumes consumesAnnotation = findAnnotationOnMethodOrEnclosingType(method, Consumes.class);
        if (consumesAnnotation != null) {
          p(
              "__method.header("
                  + RESOURCE_CLASS
                  + ".HEADER_CONTENT_TYPE, "
                  + wrap(consumesAnnotation.value()[0])
                  + ");");
        }

        // and set the explicit headers now (could override the accept header)
        for (Map.Entry<String, JParameter> entry : headerParams.entrySet()) {
          String expr = entry.getValue().getName();
          p(
              "__method.header("
                  + wrap(entry.getKey())
                  + ", "
                  + toStringExpression(entry.getValue().getType(), expr)
                  + ");");
        }
      }

      if (!formParams.isEmpty()) {
        p(FORM_POST_CONTENT_CLASS + " __formPostContent = new " + FORM_POST_CONTENT_CLASS + "();");

        for (Map.Entry<String, JParameter> entry : formParams.entrySet()) {
          p(
              "__formPostContent.addParameter("
                  + wrap(entry.getKey())
                  + ", "
                  + toFormStringExpression(entry.getValue(), classStyle)
                  + ");");
        }

        p("__method.form(__formPostContent.getTextContent());");
      }

      if (contentArg != null) {
        if (contentArg.getType() == STRING_TYPE) {
          p("__method.text(" + contentArg.getName() + ");");
        } else if (contentArg.getType() == JSON_VALUE_TYPE) {
          p("__method.json(" + contentArg.getName() + ");");
        } else if (contentArg.getType().isClass() != null
            && isOverlayArrayType(contentArg.getType().isClass())) {
          p("__method.json(new " + JSON_ARRAY_CLASS + "(" + contentArg.getName() + "));");
        } else if (contentArg.getType().isClass() != null
            && contentArg.getType().isClass().isAssignableTo(OVERLAY_VALUE_TYPE)) {
          p("__method.json(new " + JSON_OBJECT_CLASS + "(" + contentArg.getName() + "));");
        } else if (contentArg.getType() == DOCUMENT_TYPE) {
          p("__method.xml(" + contentArg.getName() + ");");
        } else {
          JClassType contentClass = contentArg.getType().isClass();
          if (contentClass == null) {
            contentClass = contentArg.getType().isClassOrInterface();
            if (!locator.isCollectionType(contentClass)) {
              getLogger().log(ERROR, "Content argument must be a class.");
              throw new UnableToCompleteException();
            }
          }

          jsonAnnotation = contentArg.getAnnotation(Json.class);
          Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;

          // example:
          // .json(Listings$_Generated_JsonEncoder_$.INSTANCE.encode(arg0)
          // )
          p(
              "__method.json("
                  + locator.encodeExpression(contentClass, contentArg.getName(), style)
                  + ");");
        }
      }

      List<AnnotationResolver> annotationResolvers = getAnnotationResolvers(context, getLogger());
      getLogger()
          .log(
              TreeLogger.DEBUG,
              "found " + annotationResolvers.size() + " additional AnnotationResolvers");

      for (AnnotationResolver a : annotationResolvers) {
        getLogger()
            .log(
                TreeLogger.DEBUG,
                "("
                    + a.getClass().getName()
                    + ") resolve `"
                    + source.getName()
                    + "#"
                    + method.getName()
                    + "´ ...");
        final Map<String, String[]> addDataParams =
            a.resolveAnnotation(getLogger(), source, method, restMethod);

        if (addDataParams != null) {
          for (String s : addDataParams.keySet()) {
            final StringBuilder sb = new StringBuilder();
            final List<String> classList = Arrays.asList(addDataParams.get(s));

            sb.append("[");
            for (int i = 0; i < classList.size(); ++i) {
              sb.append("\\\"").append(classList.get(i)).append("\\\"");

              if ((i + 1) < classList.size()) {
                sb.append(",");
              }
            }
            sb.append("]");

            getLogger()
                .log(TreeLogger.DEBUG, "add call with (\"" + s + "\", \"" + sb.toString() + "\")");
            p("__method.addData(\"" + s + "\", \"" + sb.toString() + "\");");
          }
        }
      }

      if (acceptTypeBuiltIn != null) {
        // TODO: shouldn't we also have a cach in here?
        p(returnRequest(returnRequest, isJsonp) + "__method.send(" + callbackArg.getName() + ");");
      } else if (isJsonp) {
        p(returnRequest(returnRequest, isJsonp)
                + "(("
                + JSONP_METHOD_CLASS
                + ")__method).send(new "
                + ABSTRACT_ASYNC_CALLBACK_CLASS
                + "<"
                + resultType.getParameterizedQualifiedSourceName()
                + ">(("
                + JSONP_METHOD_CLASS
                + ")__method, "
                + callbackArg.getName()
                + ") {")
            .i(1);
        {
          p("protected "
                  + resultType.getParameterizedQualifiedSourceName()
                  + " parseResult("
                  + JSON_VALUE_CLASS
                  + " result) throws Exception {")
              .i(1);
          {
            if (resultType.getParameterizedQualifiedSourceName().equals("java.lang.Void")) {
              p("return (java.lang.Void) null;");
            } else {
              p("try {").i(1);
              {
                if (resultType.isAssignableTo(locator.LIST_TYPE)) {
                  p("result = new " + JSON_ARRAY_CLASS + "(result.getJavaScriptObject());");
                }
                jsonAnnotation = method.getAnnotation(Json.class);
                Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;
                p("return " + locator.decodeExpression(resultType, "result", style) + ";");
              }
              i(-1).p("} catch (Throwable __e) {").i(1);
              {
                p(
                    "throw new "
                        + RESPONSE_FORMAT_EXCEPTION_CLASS
                        + "(\"Response was NOT a valid JSON document\", __e);");
              }
              i(-1).p("}");
            }
          }
          i(-1).p("}");
        }
        i(-1).p("});");
      } else {
        p("try {").i(1);
        {
          p(returnRequest(returnRequest, isJsonp)
                  + "__method.send(new "
                  + ABSTRACT_REQUEST_CALLBACK_CLASS
                  + "<"
                  + resultType.getParameterizedQualifiedSourceName()
                  + ">(__method, "
                  + callbackArg.getName()
                  + ") {")
              .i(1);
          {
            p("protected "
                    + resultType.getParameterizedQualifiedSourceName()
                    + " parseResult() throws Exception {")
                .i(1);
            {
              if (resultType.getParameterizedQualifiedSourceName().equals("java.lang.Void")) {
                p("return (java.lang.Void) null;");
              } else {
                p("try {").i(1);
                {
                  jsonAnnotation = method.getAnnotation(Json.class);
                  Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;
                  p(
                      "return "
                          + locator.decodeExpression(
                              resultType,
                              JSON_PARSER_CLASS + ".parse(__method.getResponse().getText())",
                              style)
                          + ";");
                }
                i(-1).p("} catch (Throwable __e) {").i(1);
                {
                  p(
                      "throw new "
                          + RESPONSE_FORMAT_EXCEPTION_CLASS
                          + "(\"Response was NOT a valid JSON document\", __e);");
                }
                i(-1).p("}");
              }
            }
            i(-1).p("}");
          }
          i(-1).p("});");
        }
        i(-1).p("} catch (" + REQUEST_EXCEPTION_CLASS + " __e) {").i(1);
        {
          p(callbackArg.getName() + ".onFailure(__method,__e);");
          if (returnRequest) {
            p("return null;");
          }
        }
        i(-1).p("}");
      }
    }
    i(-1).p("}");
  }
  // Annotation interface
  public Annotation process(
      String text,
      double confidence,
      int support,
      String ontologyTypesString,
      String sparqlQuery,
      boolean blacklist,
      boolean coreferenceResolution,
      Spotter spotter,
      ParagraphDisambiguatorJ disambiguator)
      throws SearchException, ItemNotFoundException, InputException, SpottingException {

    Annotation annotation = new Annotation(text);
    List<Spot> spots = new LinkedList<Spot>();

    Text textObject = new Text(text);
    textObject.setFeature(new Score("confidence", confidence));

    if (Server.getTokenizer() != null) Server.getTokenizer().tokenizeMaybe(textObject);

    List<SurfaceFormOccurrence> entityMentions = spotter.extract(textObject);
    if (entityMentions.size() == 0) return annotation; // nothing to disambiguate
    Paragraph paragraph = Factory.paragraph().fromJ(entityMentions);
    LOG.info(String.format("Spotted %d entity mentions.", entityMentions.size()));

    Map<SurfaceFormOccurrence, List<DBpediaResourceOccurrence>> entityCandidates =
        disambiguator.bestK(paragraph, k);
    LOG.info(
        String.format(
            "Disambiguated %d candidates with %s.", entityCandidates.size(), disambiguator.name()));

    Enumeration.Value listColor =
        blacklist ? FilterPolicy$.MODULE$.Blacklist() : FilterPolicy$.MODULE$.Whitelist();

    /*The previous addition of filter to the Candidates requests (which has usability questioned) produce the error described at issue #136.
      To solve it, this feature for this argument (Candidates) is disabled, setting coreferenceResolution to false ever. Ignoring the user's configuration.
    */
    Boolean unableCoreferenceResolution = false;
    FilterElement filter =
        new OccsFilter(
            confidence,
            support,
            ontologyTypesString,
            sparqlQuery,
            blacklist,
            unableCoreferenceResolution,
            Server.getSimilarityThresholds(),
            Server.getSparqlExecute());

    Map<SurfaceFormOccurrence, List<DBpediaResourceOccurrence>> filteredEntityCandidates =
        new HashMap<SurfaceFormOccurrence, List<DBpediaResourceOccurrence>>();
    ;

    for (Map.Entry<SurfaceFormOccurrence, List<DBpediaResourceOccurrence>> entry :
        entityCandidates.entrySet()) {
      List<DBpediaResourceOccurrence> result =
          filter.accept(new FilterOccsImpl(), entry.getValue());

      if (!result.isEmpty()) filteredEntityCandidates.put(entry.getKey(), result);
    }

    for (SurfaceFormOccurrence sfOcc : filteredEntityCandidates.keySet()) {
      Spot spot = Spot.getInstance(sfOcc);
      List<Resource> resources = new LinkedList<Resource>();
      for (DBpediaResourceOccurrence occ : filteredEntityCandidates.get(sfOcc)) {
        Resource resource = Resource.getInstance(occ);
        resources.add(resource);
      }
      spot.setResources(resources);
      spots.add(spot);
    }
    annotation.setSpots(spots);
    return annotation;
  }
  /** TODO Does not do any filtering at the moment!!! */
  public Annotation process(
      String text,
      double confidence,
      int support,
      List<OntologyType> ontologyTypes,
      String sparqlQuery,
      boolean blacklist,
      boolean coreferenceResolution,
      Spotter spotter,
      ParagraphDisambiguatorJ disambiguator)
      throws SearchException, ItemNotFoundException, InputException, SpottingException {

    Annotation annotation = new Annotation(text);
    List<Spot> spots = new LinkedList<Spot>();

    Text textObject = new Text(text);

    if (Server.getTokenizer() != null) Server.getTokenizer().tokenizeMaybe(textObject);

    List<SurfaceFormOccurrence> entityMentions = spotter.extract(textObject);
    if (entityMentions.size() == 0) return annotation; // nothing to di
    // sambiguate
    Paragraph paragraph = Factory.paragraph().fromJ(entityMentions);
    LOG.info(String.format("Spotted %d entity mentions.", entityMentions.size()));

    Map<SurfaceFormOccurrence, List<DBpediaResourceOccurrence>> entityCandidates =
        disambiguator.bestK(paragraph, k);
    LOG.info(
        String.format(
            "Disambiguated %d candidates with %s.", entityCandidates.size(), disambiguator.name()));

    Enumeration.Value listColor =
        blacklist ? FilterPolicy$.MODULE$.Blacklist() : FilterPolicy$.MODULE$.Whitelist();

    Map<SurfaceFormOccurrence, List<DBpediaResourceOccurrence>> filteredEntityCandidates =
        entityCandidates;

    if (Server.getCombinedFilters() != null) {
      CombineAllAnnotationFilters filters = Server.getCombinedFilters();
      filteredEntityCandidates =
          filters.filter(
              entityCandidates,
              confidence,
              support,
              ontologyTypes,
              sparqlQuery,
              listColor,
              coreferenceResolution);
    }

    for (SurfaceFormOccurrence sfOcc : filteredEntityCandidates.keySet()) {
      Spot spot = Spot.getInstance(sfOcc);
      List<Resource> resources = new LinkedList<Resource>();
      for (DBpediaResourceOccurrence occ : filteredEntityCandidates.get(sfOcc)) {
        Resource resource = Resource.getInstance(occ);
        resources.add(resource);
      }
      spot.setResources(resources);
      spots.add(spot);
    }
    annotation.setSpots(spots);
    return annotation;
  }
  public Annotation getAnnotation(
      String text,
      double confidence,
      int support,
      String ontologyTypesString,
      String sparqlQuery,
      String policy,
      boolean coreferenceResolution,
      String spotterName,
      String disambiguatorName,
      String clientIp)
      throws SearchException, InputException, ItemNotFoundException, SpottingException,
          MalformedURLException, BoilerpipeProcessingException {

    LOG.info("******************************** Parameters ********************************");
    // announceAPI();

    boolean blacklist = false;
    if (policy.trim().equalsIgnoreCase("blacklist")) {
      blacklist = true;
      policy = "blacklist";
    } else {
      policy = "whitelist";
    }
    LOG.info("client ip: " + clientIp);
    LOG.info("text to be processed: " + text);
    LOG.info("text length in chars: " + text.length());
    LOG.info("confidence: " + String.valueOf(confidence));
    LOG.info("support: " + String.valueOf(support));
    LOG.info("types: " + ontologyTypesString);
    LOG.info("sparqlQuery: " + sparqlQuery);
    LOG.info("policy: " + policy);
    LOG.info("coreferenceResolution: " + String.valueOf(coreferenceResolution));
    LOG.info("spotter: " + spotterName);
    LOG.info("disambiguator: " + disambiguatorName);

    /* Validating parameters */

    if (text.trim().equals("")) {
      throw new InputException("No text was specified in the &text parameter.");
    }

    List<OntologyType> ontologyTypes = new ArrayList<OntologyType>();
    String types[] = ontologyTypesString.trim().split(",");
    for (String t : types) {
      if (!t.trim().equals("")) ontologyTypes.add(Factory.ontologyType().fromQName(t.trim()));
      // LOG.info("type:"+t.trim());
    }

    /* Setting defaults */
    if (Server.getTokenizer() == null
        && disambiguatorName == SpotlightConfiguration.DisambiguationPolicy.Default.name()
        && text.length() > 1200) {
      disambiguatorName = SpotlightConfiguration.DisambiguationPolicy.Document.name();
      LOG.info(
          String.format(
              "Text length: %d. Using %s to disambiguate.", text.length(), disambiguatorName));
    }

    Spotter spotter = Server.getSpotter(spotterName);
    ParagraphDisambiguatorJ disambiguator = Server.getDisambiguator(disambiguatorName);

    /* Running Annotation */

    Annotation annotation =
        process(
            text,
            confidence,
            support,
            ontologyTypes,
            sparqlQuery,
            blacklist,
            coreferenceResolution,
            spotter,
            disambiguator);

    LOG.debug("Shown: " + annotation.toXML());
    LOG.debug("****************************************************************");

    return annotation;
  }
Beispiel #22
0
  private static Map<String, Object> makeClientData(
      final PwmApplication pwmApplication,
      final PwmSession pwmSession,
      final HttpServletRequest request,
      final HttpServletResponse response,
      final String pageUrl)
      throws ChaiUnavailableException, PwmUnrecoverableException {
    final Configuration config = pwmApplication.getConfig();
    final TreeMap<String, Object> settingMap = new TreeMap<>();
    settingMap.put(
        "client.ajaxTypingTimeout",
        Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_TIMEOUT)));
    settingMap.put(
        "client.ajaxTypingWait",
        Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_WAIT)));
    settingMap.put(
        "client.activityMaxEpsRate",
        Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_ACTIVITY_MAX_EPS_RATE)));
    settingMap.put(
        "client.js.enableHtml5Dialog",
        Boolean.parseBoolean(config.readAppProperty(AppProperty.CLIENT_JS_ENABLE_HTML5DIALOG)));
    settingMap.put(
        "client.pwShowRevertTimeout",
        Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_PW_SHOW_REVERT_TIMEOUT)));
    settingMap.put(
        "enableIdleTimeout", config.readSettingAsBoolean(PwmSetting.DISPLAY_IDLE_TIMEOUT));
    settingMap.put(
        "pageLeaveNotice", config.readSettingAsLong(PwmSetting.SECURITY_PAGE_LEAVE_NOTICE_TIMEOUT));
    settingMap.put(
        "setting-showHidePasswordFields",
        pwmApplication
            .getConfig()
            .readSettingAsBoolean(
                password.pwm.config.PwmSetting.DISPLAY_SHOW_HIDE_PASSWORD_FIELDS));
    settingMap.put("setting-displayEula", PwmConstants.ENABLE_EULA_DISPLAY);
    settingMap.put(
        "setting-showStrengthMeter",
        config.readSettingAsBoolean(PwmSetting.PASSWORD_SHOW_STRENGTH_METER));

    {
      long idleSeconds = config.readSettingAsLong(PwmSetting.IDLE_TIMEOUT_SECONDS);
      if (pageUrl == null || pageUrl.isEmpty()) {
        LOGGER.warn(pwmSession, "request to /client data did not incliude pageUrl");
      } else {
        try {
          final PwmURL pwmURL = new PwmURL(new URI(pageUrl), request.getContextPath());
          final TimeDuration maxIdleTime =
              IdleTimeoutCalculator.idleTimeoutForRequest(pwmURL, pwmApplication, pwmSession);
          idleSeconds = maxIdleTime.getTotalSeconds();
        } catch (Exception e) {
          LOGGER.error(
              pwmSession, "error determining idle timeout time for request: " + e.getMessage());
        }
      }
      settingMap.put("MaxInactiveInterval", idleSeconds);
    }
    settingMap.put("paramName.locale", config.readAppProperty(AppProperty.HTTP_PARAM_NAME_LOCALE));
    settingMap.put("startupTime", pwmApplication.getStartupTime());
    settingMap.put("applicationMode", pwmApplication.getApplicationMode());

    final String contextPath = request.getContextPath();
    settingMap.put("url-context", contextPath);
    settingMap.put(
        "url-logout", contextPath + PwmServletDefinition.Logout.servletUrl() + "?idle=true");
    settingMap.put("url-command", contextPath + PwmServletDefinition.Command.servletUrl());
    settingMap.put(
        "url-resources",
        contextPath
            + "/public/resources"
            + pwmApplication.getResourceServletService().getResourceNonce());
    settingMap.put("url-restservice", contextPath + "/public/rest");

    {
      String passwordGuideText =
          pwmApplication
              .getConfig()
              .readSettingAsLocalizedString(
                  PwmSetting.DISPLAY_PASSWORD_GUIDE_TEXT,
                  pwmSession.getSessionStateBean().getLocale());
      final MacroMachine macroMachine =
          pwmSession.getSessionManager().getMacroMachine(pwmApplication);
      passwordGuideText = macroMachine.expandMacros(passwordGuideText);
      settingMap.put("passwordGuideText", passwordGuideText);
    }

    {
      final List<String> formTypeOptions = new ArrayList<>();
      for (final FormConfiguration.Type type : FormConfiguration.Type.values()) {
        formTypeOptions.add(type.toString());
      }
      settingMap.put("formTypeOptions", formTypeOptions);
    }

    {
      final List<String> actionTypeOptions = new ArrayList<>();
      for (final ActionConfiguration.Type type : ActionConfiguration.Type.values()) {
        actionTypeOptions.add(type.toString());
      }
      settingMap.put("actionTypeOptions", actionTypeOptions);
    }

    {
      final List<String> epsTypes = new ArrayList<>();
      for (final Statistic.EpsType loopEpsType : Statistic.EpsType.values()) {
        epsTypes.add(loopEpsType.toString());
      }
      settingMap.put("epsTypes", epsTypes);
    }

    {
      final List<String> epsDurations = new ArrayList<>();
      for (final Statistic.EpsDuration loopEpsDuration : Statistic.EpsDuration.values()) {
        epsDurations.add(loopEpsDuration.toString());
      }
      settingMap.put("epsDurations", epsDurations);
    }

    {
      final Map<String, String> localeInfo = new TreeMap<>();
      final Map<String, String> localeDisplayNames = new TreeMap<>();
      final Map<String, String> localeFlags = new TreeMap<>();

      for (final Locale locale : pwmApplication.getConfig().getKnownLocales()) {
        final String flagCode = pwmApplication.getConfig().getKnownLocaleFlagMap().get(locale);
        localeFlags.put(locale.toString(), flagCode);
        localeInfo.put(
            locale.toString(), locale.getDisplayName() + " - " + locale.getDisplayLanguage(locale));
        localeDisplayNames.put(locale.toString(), locale.getDisplayLanguage());
      }

      settingMap.put("localeInfo", localeInfo);
      settingMap.put("localeDisplayNames", localeDisplayNames);
      settingMap.put("localeFlags", localeFlags);
      settingMap.put("defaultLocale", PwmConstants.DEFAULT_LOCALE.toString());
    }

    if (pwmApplication
            .getConfig()
            .readSettingAsEnum(PwmSetting.LDAP_SELECTABLE_CONTEXT_MODE, SelectableContextMode.class)
        != SelectableContextMode.NONE) {
      final Map<String, Map<String, String>> ldapProfiles = new LinkedHashMap<>();
      for (final String ldapProfile : pwmApplication.getConfig().getLdapProfiles().keySet()) {
        final Map<String, String> contexts =
            pwmApplication.getConfig().getLdapProfiles().get(ldapProfile).getLoginContexts();
        ldapProfiles.put(ldapProfile, contexts);
      }
      settingMap.put("ldapProfiles", ldapProfiles);
    }

    return settingMap;
  }
  public ResourceMethod(MethodDeclaration delegate, Resource parent) {
    super(delegate);

    Set<String> httpMethods = new TreeSet<String>();
    Collection<AnnotationMirror> mirrors = delegate.getAnnotationMirrors();
    for (AnnotationMirror mirror : mirrors) {
      AnnotationTypeDeclaration annotationDeclaration = mirror.getAnnotationType().getDeclaration();
      HttpMethod httpMethodInfo = annotationDeclaration.getAnnotation(HttpMethod.class);
      if (httpMethodInfo != null) {
        // request method designator found.
        httpMethods.add(httpMethodInfo.value());
      }
    }

    if (httpMethods.isEmpty()) {
      throw new IllegalStateException(
          "A resource method must specify an HTTP method by using a request method designator annotation.");
    }

    this.httpMethods = httpMethods;

    Set<String> consumes;
    Consumes consumesInfo = delegate.getAnnotation(Consumes.class);
    if (consumesInfo != null) {
      consumes = new TreeSet<String>(Arrays.asList(JAXRSUtils.value(consumesInfo)));
    } else {
      consumes = new TreeSet<String>(parent.getConsumesMime());
    }
    this.consumesMime = consumes;

    Set<String> produces;
    Produces producesInfo = delegate.getAnnotation(Produces.class);
    if (producesInfo != null) {
      produces = new TreeSet<String>(Arrays.asList(JAXRSUtils.value(producesInfo)));
    } else {
      produces = new TreeSet<String>(parent.getProducesMime());
    }
    this.producesMime = produces;

    String subpath = null;
    Path pathInfo = delegate.getAnnotation(Path.class);
    if (pathInfo != null) {
      subpath = pathInfo.value();
    }

    ResourceEntityParameter entityParameter;
    List<ResourceEntityParameter> declaredEntityParameters =
        new ArrayList<ResourceEntityParameter>();
    List<ResourceParameter> resourceParameters;
    ResourceRepresentationMetadata outputPayload;
    ResourceMethodSignature signatureOverride =
        delegate.getAnnotation(ResourceMethodSignature.class);
    if (signatureOverride == null) {
      entityParameter = null;
      resourceParameters = new ArrayList<ResourceParameter>();
      // if we're not overriding the signature, assume we use the real method signature.
      for (ParameterDeclaration parameterDeclaration : getParameters()) {
        if (ResourceParameter.isResourceParameter(parameterDeclaration)) {
          resourceParameters.add(new ResourceParameter(parameterDeclaration));
        } else if (ResourceParameter.isFormBeanParameter(parameterDeclaration)) {
          resourceParameters.addAll(ResourceParameter.getFormBeanParameters(parameterDeclaration));
        } else if (parameterDeclaration.getAnnotation(Context.class) == null) {
          entityParameter = new ResourceEntityParameter(this, parameterDeclaration);
          declaredEntityParameters.add(entityParameter);
        }
      }

      DecoratedTypeMirror returnTypeMirror;
      TypeHint hintInfo = getAnnotation(TypeHint.class);
      if (hintInfo != null) {
        try {
          Class hint = hintInfo.value();
          AnnotationProcessorEnvironment env = net.sf.jelly.apt.Context.getCurrentEnvironment();
          if (TypeHint.NO_CONTENT.class.equals(hint)) {
            returnTypeMirror =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(env.getTypeUtils().getVoidType());
          } else {
            String hintName = hint.getName();

            if (TypeHint.NONE.class.equals(hint)) {
              hintName = hintInfo.qualifiedName();
            }

            if (!"##NONE".equals(hintName)) {
              TypeDeclaration type = env.getTypeDeclaration(hintName);
              returnTypeMirror =
                  (DecoratedTypeMirror)
                      TypeMirrorDecorator.decorate(env.getTypeUtils().getDeclaredType(type));
            } else {
              returnTypeMirror = (DecoratedTypeMirror) getReturnType();
            }
          }
        } catch (MirroredTypeException e) {
          returnTypeMirror = (DecoratedTypeMirror) TypeMirrorDecorator.decorate(e.getTypeMirror());
        }
        returnTypeMirror.setDocComment(((DecoratedTypeMirror) getReturnType()).getDocComment());
      } else {
        returnTypeMirror = (DecoratedTypeMirror) getReturnType();

        if (getJavaDoc().get("returnWrapped")
            != null) { // support jax-doclets. see http://jira.codehaus.org/browse/ENUNCIATE-690
          String fqn = getJavaDoc().get("returnWrapped").get(0);
          AnnotationProcessorEnvironment env = net.sf.jelly.apt.Context.getCurrentEnvironment();
          TypeDeclaration type = env.getTypeDeclaration(fqn);
          if (type != null) {
            returnTypeMirror =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(env.getTypeUtils().getDeclaredType(type));
          }
        }

        // in the case where the return type is com.sun.jersey.api.JResponse,
        // we can use the type argument to get the entity type
        if (returnTypeMirror.isClass()
            && returnTypeMirror.isInstanceOf("com.sun.jersey.api.JResponse")) {
          DecoratedClassType jresponse = (DecoratedClassType) returnTypeMirror;
          if (!jresponse.getActualTypeArguments().isEmpty()) {
            DecoratedTypeMirror responseType =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(
                        jresponse.getActualTypeArguments().iterator().next());
            if (responseType.isDeclared()) {
              responseType.setDocComment(returnTypeMirror.getDocComment());
              returnTypeMirror = responseType;
            }
          }
        }
      }

      outputPayload =
          returnTypeMirror.isVoid() ? null : new ResourceRepresentationMetadata(returnTypeMirror);
    } else {
      entityParameter = loadEntityParameter(signatureOverride);
      declaredEntityParameters.add(entityParameter);
      resourceParameters = loadResourceParameters(signatureOverride);
      outputPayload = loadOutputPayload(signatureOverride);
    }

    JavaDoc.JavaDocTagList doclets =
        getJavaDoc()
            .get(
                "RequestHeader"); // support jax-doclets. see
                                  // http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        resourceParameters.add(
            new ExplicitResourceParameter(this, doc, header, ResourceParameterType.HEADER));
      }
    }

    ArrayList<ResponseCode> statusCodes = new ArrayList<ResponseCode>();
    ArrayList<ResponseCode> warnings = new ArrayList<ResponseCode>();
    StatusCodes codes = getAnnotation(StatusCodes.class);
    if (codes != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : codes.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        statusCodes.add(rc);
      }
    }

    doclets =
        getJavaDoc()
            .get("HTTP"); // support jax-doclets. see http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        try {
          ResponseCode rc = new ResponseCode();
          rc.setCode(Integer.parseInt(code));
          rc.setCondition(doc);
          statusCodes.add(rc);
        } catch (NumberFormatException e) {
          // fall through...
        }
      }
    }

    Warnings warningInfo = getAnnotation(Warnings.class);
    if (warningInfo != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : warningInfo.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        warnings.add(rc);
      }
    }

    codes = parent.getAnnotation(StatusCodes.class);
    if (codes != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : codes.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        statusCodes.add(rc);
      }
    }

    warningInfo = parent.getAnnotation(Warnings.class);
    if (warningInfo != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : warningInfo.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        warnings.add(rc);
      }
    }

    ResponseHeaders responseHeaders = parent.getAnnotation(ResponseHeaders.class);
    if (responseHeaders != null) {
      for (ResponseHeader header : responseHeaders.value()) {
        this.responseHeaders.put(header.name(), header.description());
      }
    }

    responseHeaders = getAnnotation(ResponseHeaders.class);
    if (responseHeaders != null) {
      for (ResponseHeader header : responseHeaders.value()) {
        this.responseHeaders.put(header.name(), header.description());
      }
    }

    doclets =
        getJavaDoc()
            .get(
                "ResponseHeader"); // support jax-doclets. see
                                   // http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        this.responseHeaders.put(header, doc);
      }
    }

    this.entityParameter = entityParameter;
    this.resourceParameters = resourceParameters;
    this.subpath = subpath;
    this.parent = parent;
    this.statusCodes = statusCodes;
    this.warnings = warnings;
    this.representationMetadata = outputPayload;
    this.declaredEntityParameters = declaredEntityParameters;
  }
Beispiel #24
0
  @Path("/read/{ObjID}/{ObjInsId}/{resourceId}")
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response sendRead(
      @PathParam("ObjID") Integer objectId,
      @PathParam("ObjInsId") Integer objectInstanceId,
      @PathParam("resourceId") Integer resourceID,
      @QueryParam("ep") String endPoint)
      throws Exception {
    String directory =
        "{"
            + "\"operation\":\"read\""
            + ","
            + "\""
            + "directory\":"
            + "\""
            + objectId
            + "/"
            + objectInstanceId
            + "/"
            + resourceID
            + "\"}";
    Info.setInfo(endPoint, directory);
    CountDownLatch signal = Info.getCountDown(endPoint);
    if (signal == null) {
      return Response.status(200).entity("Devices not registerd yet").build();
    }
    signal.countDown();

    CountDownLatch signalRead = new CountDownLatch(1);
    Info.setCountDownLatchMessageMap(endPoint, signalRead);
    signalRead.await();

    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class).filter("client_bs_obj.device_id =", endPoint).asList();

    JSONArray jsonArray = new JSONArray();
    if (objectInstanceId == 0) {

      Map<Date, Double> hashMap;
      hashMap =
          clientObjects
              .get(0)
              .getObjectMap()
              .get(objectId)
              .getObjInstanceMap()
              .get(objectInstanceId)
              .getResourceMap()
              .get(resourceID)
              .getValue();
      Map<Date, Double> sortedMap = new TreeMap<Date, Double>(hashMap);

      Iterator it = sortedMap.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        JSONArray jsonArray1 = new JSONArray();
        Date date = (Date) pair.getKey();
        jsonArray1.put(date.getTime()).put(pair.getValue());
        jsonArray.put(jsonArray1);
        it.remove(); // avoids a ConcurrentModificationException
      }
    } else if (objectInstanceId == 1) {

      Map<Date, Integer> hashMap;
      hashMap =
          clientObjects
              .get(0)
              .getObjectMap()
              .get(objectId)
              .getObjInstanceMap()
              .get(objectInstanceId)
              .getResourceMap()
              .get(resourceID)
              .getMvalue();
      Map<Date, Integer> sortedMap = new TreeMap<Date, Integer>(hashMap);
      Iterator it = sortedMap.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        JSONArray jsonArray1 = new JSONArray();
        Date date = (Date) pair.getKey();

        jsonArray1.put(date.getTime()).put(pair.getValue());
        jsonArray.put(jsonArray1);
        it.remove(); // avoids a ConcurrentModificationException
      }
    }

    return Response.status(200).entity(jsonArray.toString()).build();
  }