Esempio n. 1
0
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response importVine(Vine vine) {
    Response.ResponseBuilder builder = null;

    try {
      // Verify and save
      serviceVin.save(vine);

      // Create an "ok" response
      builder = Response.ok();
    } catch (ConstraintViolationException ce) {
      // Handle bean validation issues
      builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
      // Handle the unique constrain violation
      Map<String, String> responseObj = new HashMap<String, String>();
      responseObj.put("email", "Email taken");
      builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
      // Handle generic exceptions
      Map<String, String> responseObj = new HashMap<String, String>();
      responseObj.put("error", e.getMessage());
      builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }

    return builder.build();
  }
Esempio n. 2
0
  @Path("/advance/{id}")
  @GET
  @Produces("text/html")
  public Response advanceGet(@PathParam("id") final String encoded) {

    String[] params = courseService.getCourseSignupFromEncrypted(encoded);
    if (log.isDebugEnabled()) {
      for (int i = 0; i < params.length; i++) {
        log.debug("decoded parameter [" + params[i] + "]");
      }
    }
    String signupId = params[0];
    // This is the status that is being advanced to.
    String emailStatus = params[1];
    Status status = toStatus(emailStatus);
    CourseSignup signup = courseService.getCourseSignupAnyway(signupId);
    Map<String, Object> model = new HashMap<>();
    model.put("signup", signup);
    model.put("encoded", encoded);

    // Check that the status we're trying to advance to is valid
    if (!statusProgression.next(signup.getStatus()).contains(status)) {
      model.put("errors", Collections.singletonList("The signup has already been dealt with."));
    } else {
      // We only put the status in if we're happy for it to be changed.
      model.put("status", emailStatus);
    }

    addStandardAttributes(model);

    return Response.ok(new Viewable("/static/advance", model)).build();
  }
Esempio n. 3
0
 @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();
 }
  // Seeded Local Database
  public static Map<Long, Transaction> getDatabase() {
    database.put(1L, new Transaction(0.12, "car", 1, 2));
    database.put(2L, new Transaction(10.23, "ship", 2, 1));
    database.put(3L, new Transaction(200.34, "car", 3, 2));
    database.put(4L, new Transaction(4000.45, "house", 4, 6));
    database.put(5L, new Transaction(80000.56, "Shopping", 5));
    database.put(6L, new Transaction(160000.67, "house", 6, 3));

    return database;
  }
Esempio n. 5
0
  @Path("/advance/{id}")
  @POST
  @Produces("text/html")
  public Response advancePost(
      @PathParam("id") final String encoded, @FormParam("formStatus") final String formStatus) {

    if (null == encoded) {
      return Response.noContent().build();
    }
    String[] params = courseService.getCourseSignupFromEncrypted(encoded);

    String signupId = params[0];
    Status status = toStatus(params[1]);
    String placementId = params[2];

    CourseSignup signup = courseService.getCourseSignupAnyway(signupId);
    if (null == signup) {
      return Response.noContent().build();
    }
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("signup", signup);
    if (!statusProgression.next(signup.getStatus()).contains(status)) {
      model.put("errors", Collections.singletonList("The signup has already been dealt with."));
    } else {
      try {
        switch (formStatus.toLowerCase()) {
          case "accept":
            courseService.accept(signupId, true, placementId);
            break;
          case "approve":
            courseService.approve(signupId, true, placementId);
            break;
          case "confirm":
            courseService.confirm(signupId, true, placementId);
            break;
          case "reject":
            courseService.reject(signupId, true, placementId);
            break;
          default:
            throw new IllegalStateException("No mapping for action of: " + formStatus);
        }
      } catch (IllegalStateException ise) {
        model.put("errors", Collections.singletonList(ise.getMessage()));
      }
    }

    addStandardAttributes(model);
    return Response.ok(new Viewable("/static/ok", model)).build();
  }
Esempio n. 6
0
  private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) {
    logger.fine("Validation completed. violations found: " + violations.size());

    Map<String, String> responseObj = new HashMap<String, String>();

    for (ConstraintViolation<?> violation : violations) {
      responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
    }

    return Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
  }
    public T execute(String coloExpr, String type, String name) {
      Set<String> colos = getColosFromExpression(coloExpr, type, name);

      Map<String, T> results = new HashMap<String, T>();
      for (String colo : colos) {
        try {
          T resultHolder = doExecute(colo);
          results.put(colo, resultHolder);
        } catch (FalconException e) {
          results.put(
              colo,
              getResultInstance(
                  APIResult.Status.FAILED, e.getClass().getName() + "::" + e.getMessage()));
        }
      }
      T finalResult = consolidateResult(results, clazz);
      if (finalResult.getStatus() != APIResult.Status.SUCCEEDED) {
        throw FalconWebException.newException(finalResult, Response.Status.BAD_REQUEST);
      } else {
        return finalResult;
      }
    }
 @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;
 }
Esempio n. 9
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();
  }
Esempio n. 10
0
 @GET
 @Path("/{sampleId}/annotate")
 @Consumes(MediaType.APPLICATION_JSON)
 @ApiOperation(value = "annotate sample", position = 5)
 public Response annotateSampleGET(
     @ApiParam(value = "sampleId", required = true) @PathParam("sampleId") int sampleId,
     @ApiParam(value = "Annotation set name. Must be unique", required = true)
         @QueryParam("annotateSetName")
         String annotateSetName,
     @ApiParam(value = "variableSetId", required = true) @QueryParam("variableSetId")
         int variableSetId) {
   try {
     QueryResult<VariableSet> variableSetResult =
         catalogManager.getVariableSet(variableSetId, null, sessionId);
     if (variableSetResult.getResult().isEmpty()) {
       return createErrorResponse("sample - annotate", "VariableSet not find.");
     }
     Map<String, Object> annotations = new HashMap<>();
     variableSetResult
         .getResult()
         .get(0)
         .getVariables()
         .stream()
         .filter(variable -> params.containsKey(variable.getId()))
         .forEach(
             variable -> {
               annotations.put(variable.getId(), params.getFirst(variable.getId()));
             });
     QueryResult<AnnotationSet> queryResult =
         catalogManager.annotateSample(
             sampleId, annotateSetName, variableSetId, annotations, queryOptions, sessionId);
     return createOkResponse(queryResult);
   } catch (Exception e) {
     return createErrorResponse(e);
   }
 }
 private void initializeFor(String colo) throws FalconException {
   processInstanceManagerChannels.put(colo, ChannelFactory.get("ProcessInstanceManager", colo));
 }
Esempio n. 12
0
 /**
  * This just adds the standard skin values that are needed when rendering a page.
  *
  * @param model The model to add the values to.
  */
 public void addStandardAttributes(Map<String, Object> model) {
   model.put("skinRepo", serverConfigurationService.getString("skin.repo", "/library/skin"));
   model.put("skinDefault", serverConfigurationService.getString("skin.default", "default"));
   model.put("skinPrefix", serverConfigurationService.getString("portal.neoprefix", ""));
 }
Esempio n. 13
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;
  }