@Test
  public void testGetCodenvyPropertiesShouldReturnErrorResponse() throws Exception {
    doThrow(new IOException("error")).when(configManager).loadInstalledCodenvyConfig();

    Response response = service.getCodenvyProperties();
    assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
  }
  @Test
  public void testGetInstalledVersionsShouldReturnErrorStatus() throws Exception {
    doThrow(new IOException("error")).when(mockFacade).getInstalledVersions();

    Response result = service.getInstalledVersions();
    assertEquals(result.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
  }
  @Test
  public void testGetStoragePropertiesShouldReturnErrorResponse() throws Exception {
    doThrow(new IOException("error")).when(mockFacade).loadStorageProperties();

    Response response = service.getStorageProperties();
    assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
  }
  @Test
  public void testGetUpdatesShouldReturnErrorStatus() throws Exception {
    doThrow(new IOException("error")).when(mockFacade).getAllUpdates(any(Artifact.class));

    Response result = service.getUpdates();
    assertEquals(result.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
  }
 private void setHttpStatus(Throwable ex, GenericException exception) {
   if (ex instanceof WebApplicationException) {
     exception.setStatus(((WebApplicationException) ex).getResponse().getStatus());
   } else {
     exception.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
   }
 }
  @Test
  public void testGetNodeConfigError() throws IOException {
    doThrow(new RuntimeException("error")).when(configManager).detectInstallationType();

    Response result = service.getNodesList();
    assertEquals(result.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    assertEquals(result.getEntity().toString(), "{message=error}");
  }
 /**
  * A test case for predicting with a dataset incompatible with the trained dataset in terms of
  * number of features
  *
  * @throws MLHttpClientException
  * @throws JSONException
  */
 private void testPredictDiabetesInvalidNumberOfFeatures()
     throws MLHttpClientException, JSONException {
   String payload = "[[1,89,66,23,94,28.1,0.167],[2,197,70,45,543,30.5,0.158]]";
   response = mlHttpclient.doHttpPost("/api/models/" + modelId + "/predict", payload);
   assertEquals(
       "Unexpected response received",
       Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
       response.getStatusLine().getStatusCode());
 }
 @Override
 public Response toResponse(E exception) {
   if (getStatus().getStatusCode() >= Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
     log.error("System error {}: {}", getStatus(), exception.getClass().getName(), exception);
   return Response.status(getStatus())
       .type("application/x-protobuf+json")
       .entity(getErrorDto(exception))
       .build();
 }
  @Test
  public void testGetUpdateInfoShouldReturnErrorResponse() throws Exception {
    doReturn(artifact).when(service).createArtifact(artifact.getName());
    doReturn(InstallType.SINGLE_SERVER).when(configManager).detectInstallationType();
    doThrow(new IOException("error"))
        .when(mockFacade)
        .getUpdateInfo(artifact, InstallType.SINGLE_SERVER);

    Response response = service.getUpdateInfo();
    assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
  }
 /**
  * Retrieves the list of tasks.
  *
  * <p>The list includes only the tasks associated to the user.
  *
  * @return The task collection
  */
 @GET
 @Produces(Constants.INDIGOMIMETYPE)
 public final TaskList listTasks() {
   TaskList tasks;
   try {
     tasks = new TaskList(retrieveTaskList());
   } catch (RuntimeException re) {
     getResponse().setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
     throw re;
   }
   return tasks;
 }
  @Test
  public void testLoginToSaasWhenNullAccountReference() throws Exception {
    Credentials testSaasUsernameAndPassword =
        Commons.createDtoFromJson(TEST_CREDENTIALS_JSON, Credentials.class);

    doReturn(new DtoServerImpls.TokenImpl().withValue(TEST_ACCESS_TOKEN))
        .when(mockFacade)
        .loginToCodenvySaaS(testSaasUsernameAndPassword);
    doReturn(null).when(mockFacade).getAccountWhereUserIsOwner(null, TEST_ACCESS_TOKEN);

    Response response = service.loginToCodenvySaaS(testSaasUsernameAndPassword);
    assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
  }
 @Test
 public void testValidationGroupsException() {
   final Response resp =
       resources
           .client()
           .target("/person/blah/validation-groups-exception")
           .request()
           .post(Entity.json("{}"));
   assertThat(resp.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
   assertThat(resp.readEntity(String.class))
       .isEqualTo(
           "{\"code\":500,\"message\":\"Parameters must have the same"
               + " validation groups in validationGroupsException\"}");
 }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    response.setContentType("text/html");

    try {

      String url = Config.get().getMotdUrl();

      // no MOTD URL : use local file
      if (url == null || url.trim().length() == 0) {

        File f = new File(this.getServletContext().getRealPath(motdFileName));
        long ft = f.lastModified();
        if (ft != lastModified) {
          lastModified = ft;
          try {
            fileContent = FileUtils.readFileToString(f);
          } catch (IOException e) {
            LOGGER.debug("Failed to read MOTD file", e);
            response.getWriter().write("");
            return;
          }
        }
        response.getWriter().write(fileContent);

      } else {
        HttpClient httpclient = new DefaultHttpClient();

        try {
          HttpGet httpget = new HttpGet(url);

          ResponseHandler<String> responseHandler = new BasicResponseHandler();
          String responseBody = httpclient.execute(httpget, responseHandler);
          response.setStatus(Response.Status.OK.getStatusCode());
          response.getWriter().write(responseBody);
        } catch (Exception e) {
          response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
          response.getWriter().write("Server error");
        } finally {
          httpclient.getConnectionManager().shutdown();
        }
      }

    } catch (IOException e) {
      LOGGER.debug("Failed to provide MOTD file", e);
    }
  }
 @Path("device/stats/{deviceId}")
 @GET
 @Consumes("application/json")
 @Produces("application/json")
 public Response getVirtualFirealarmStats(
     @PathParam("deviceId") String deviceId,
     @QueryParam("from") long from,
     @QueryParam("to") long to) {
   String fromDate = String.valueOf(from);
   String toDate = String.valueOf(to);
   String query =
       "deviceId:"
           + deviceId
           + " AND deviceType:"
           + VirtualFireAlarmConstants.DEVICE_TYPE
           + " AND time : ["
           + fromDate
           + " TO "
           + toDate
           + "]";
   String sensorTableName = VirtualFireAlarmConstants.TEMPERATURE_EVENT_TABLE;
   try {
     if (!APIUtil.getDeviceAccessAuthorizationService()
         .isUserAuthorized(
             new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
             DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
       return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
     }
     List<SortByField> sortByFields = new ArrayList<>();
     SortByField sortByField = new SortByField("time", SORT.ASC, false);
     sortByFields.add(sortByField);
     List<SensorRecord> sensorRecords =
         APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
     return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
   } catch (AnalyticsException e) {
     String errorMsg =
         "Error on retrieving stats on table " + sensorTableName + " with query " + query;
     log.error(errorMsg);
     return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
         .entity(errorMsg)
         .build();
   } catch (DeviceAccessAuthorizationException e) {
     log.error(e.getErrorMessage(), e);
     return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
   }
 }
  @Path("/Client/{cid}")
  @GET
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response getAssociatedPersons(
      @HeaderParam("Authorization") String authorization, @PathParam("cid") String cid)
      throws Exception {
    clientService = ClientService.instance();

    Response authorizationResponse = processAuthorization(authorization);
    if (authorizationResponse != null) {
      return authorizationResponse;
    }

    try {

      log.info("getting the client");
      OxAuthClient client = clientService.getClientByInum(cid);

      if (client == null) {
        // sets HTTP status code 404 Not Found
        return getErrorResponse(
            "Resource " + cid + " not found", Response.Status.NOT_FOUND.getStatusCode());
      }

      log.info("mapping client attributes");
      ClientAssociation clientAssociation = MapperUtil.map(client, null);
      log.info("getting URL");
      URI location = new URI("/ClientAssociation/Client/" + cid);
      log.info("returning response");
      return Response.ok(clientAssociation).location(location).build();

    } catch (EntryPersistenceException ex) {
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Resource " + cid + " not found", Response.Status.NOT_FOUND.getStatusCode());
    } catch (Exception ex) {
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Unexpected processing error, please check the input parameters",
          Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }
  }
  @Path("/User/{uid}")
  @GET
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response getAssociatedClients(
      @HeaderParam("Authorization") String authorization, @PathParam("uid") String uid)
      throws Exception {

    personService = PersonService.instance();

    Response authorizationResponse = processAuthorization(authorization);
    if (authorizationResponse != null) {
      return authorizationResponse;
    }

    try {

      GluuCustomPerson gluuPerson = personService.getPersonByInum(uid);
      if (gluuPerson == null) {
        // sets HTTP status code 404 Not Found
        return getErrorResponse(
            "Resource " + uid + " not found", Response.Status.NOT_FOUND.getStatusCode());
      }

      PersonAssociation personAssociation = MapperUtil.map(gluuPerson, null);

      URI location = new URI("/ClientAssociation/User/" + uid);

      return Response.ok(personAssociation).location(location).build();
    } catch (EntryPersistenceException ex) {
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Resource " + uid + " not found", Response.Status.NOT_FOUND.getStatusCode());
    } catch (Exception ex) {
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Unexpected processing error, please check the input parameters",
          Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }
  }
  @PUT
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response deleteAssociation(
      @HeaderParam("Authorization") String authorization, PersonAssociation personAssociation)
      throws Exception {

    personService = PersonService.instance();
    clientService = ClientService.instance();

    Response authorizationResponse = processAuthorization(authorization);
    if (authorizationResponse != null) {
      return authorizationResponse;
    }

    try {
      log.info("Creating an instance of GluuCustomPerson");
      GluuCustomPerson person =
          personService.getPersonByInum(personAssociation.getUserAssociation().replaceAll(" ", ""));
      log.info("getting a list of clientDNs");
      List<String> listClientDNs = new ArrayList<String>();

      boolean isACDNsEmpty = person.getAssociatedClient() == null;

      if (!isACDNsEmpty) {
        for (String dn : person.getAssociatedClient()) {
          log.info("isACDNsEmpty = false");
          if (dn != null && !dn.equalsIgnoreCase("")) {
            listClientDNs.add(dn.replaceAll(" ", ""));
          }
        }
      }

      log.info("getting a list of clean clients");

      List<String> cleanPACDNs = new ArrayList<String>();
      for (String dn : personAssociation.getEntryAssociations()) {
        if (dn != null && !dn.equalsIgnoreCase("")) {
          cleanPACDNs.add(dn);
        }
      }

      log.info("removing clientdns");

      for (String clientdn : cleanPACDNs) {

        if (listClientDNs.contains(clientdn)) {
          listClientDNs.remove(clientdn);
        }
      }

      log.info("geting a cleanlist");

      List<String> cleanList = new ArrayList<String>();
      for (String cDn : listClientDNs) {
        if (cDn != null && !cDn.equalsIgnoreCase("")) {
          cleanList.add(cDn);
        }
      }
      log.info("setting AssociatedClientDNs");
      if (cleanList.size() < 1) {
        person.setAssociatedClient(null);
      } else {
        person.setAssociatedClient(cleanList);
      }

      log.info("Updating person");

      personService.updatePerson(person);

      log.info("deleting user dn from clients");

      List<String> EntryAssociations = new ArrayList<String>();

      for (String dn : personAssociation.getEntryAssociations()) {
        if (dn != null && !dn.equalsIgnoreCase("")) {
          EntryAssociations.add(dn.replaceAll(" ", ""));
        }
      }

      for (String clientDn : EntryAssociations) {
        log.info("getting a client");

        OxAuthCustomClient client =
            clientService.getClientByAttributeCustom(
                applicationConfiguration.getClientAssociationAttribute(),
                clientDn.replaceAll(" ", ""));
        // String[] personDNS =
        // client.getAttributes("associatedPersonDN");
        log.info("checking if the associatedPerson is empty");
        log.info("client dn : ", client.getDn());
        boolean isAPDNsEmpty = client.getAttributes("associatedPerson") == null;
        log.info("new ArrayList");
        List<String> list = new ArrayList<String>();
        if (!isAPDNsEmpty) {
          log.info("!isAPDNsEmpty");
          // list =
          // Arrays.asList(client.getAttributes("associatedPersonDN"));
          for (int i = 0; i < client.getAttributes("associatedPerson").length; i++) {
            if (client.getAttributes("associatedPerson")[i] != null
                && !client.getAttributes("associatedPerson")[i].equalsIgnoreCase("")) {
              list.add(client.getAttributes("associatedPerson")[i]);
            }
          }
          /*
           * for(String dn : client.getAssociatedPersonDNs()){ if(dn
           * != null && !dn.equalsIgnoreCase("")){list.add(dn);} }
           */
        }
        log.info("getting personDN");
        String personInum = personAssociation.getUserAssociation().replaceAll(" ", "");

        if (list.contains(personInum)) {
          log.info("removing person's dn");
          list.remove(personInum);
        }

        log.info("Creating a clean list");

        List<String> cleanPersonList = new ArrayList<String>();
        for (String cDn : list) {
          if (cDn != null && cDn.equalsIgnoreCase("")) {
            cleanPersonList.add(cDn);
          }
        }
        log.info("Setting AssociatedPersonDNs");
        if (cleanPersonList.size() < 1) {
          String[] nullArray = null;
          client.setAttribute("associatedPerson", nullArray);
        } else {
          String[] arrayPersonDns = new String[cleanPersonList.size()];
          for (int i = 0; i < cleanPersonList.size(); i++) {
            arrayPersonDns[i] = cleanPersonList.get(i);
          }
          client.setAttribute("associatedPerson", arrayPersonDns);
        }
        clientService.updateCustomClient(client);
      }
      log.info("returning result;");

      return Response.ok().build();
    } catch (Exception ex) {
      log.info("Exception: ", ex);
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Unexpected processing error, please check the input parameters",
          Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }
  }
  @Path("/Associate/")
  @POST
  @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response createAssociation(
      @HeaderParam("Authorization") String authorization, PersonAssociation personAssociation)
      throws Exception {

    personService = PersonService.instance();
    clientService = ClientService.instance();

    Response authorizationResponse = processAuthorization(authorization);
    if (authorizationResponse != null) {
      return authorizationResponse;
    }

    try {
      log.info("creating an instance of gluuCustomperson");
      GluuCustomPerson person =
          personService.getPersonByInum(personAssociation.getUserAssociation().replaceAll(" ", ""));

      log.info("setting AssociatedClientDNs");
      List<String> cleanCDNList = new ArrayList<String>();
      for (String dn : personAssociation.getEntryAssociations()) {
        cleanCDNList.add(dn.replaceAll(" ", ""));
      }

      person.setAssociatedClient(cleanCDNList);

      log.info("updating person");

      personService.updatePerson(person);

      log.info("setting user in clients");
      for (String clientDn : personAssociation.getEntryAssociations()) {
        log.info("getting a client");
        OxAuthCustomClient client =
            clientService.getClientByAttributeCustom(
                applicationConfiguration.getClientAssociationAttribute(),
                clientDn.replaceAll(" ", ""));

        log.info("the inum of the client ", client.getInum());

        log.info("checking if the list is empty");
        boolean isAPDNsEmpty = client.getAttributes("associatedPerson") == null;

        log.info("instantiating a new arraylist");

        List<String> listOfpersons = new ArrayList<String>();
        log.info("getting AssociatedPersonDN");
        if (!isAPDNsEmpty) {
          listOfpersons = new ArrayList(Arrays.asList(client.getAttributes("associatedPerson")));
          /*
           * for(String dn :
           * client.getAttributes("associatedPersonDN")){ if(dn !=
           * null && !dn.equalsIgnoreCase("")){listOfpersons.add(dn);}
           * }
           */

        }
        log.info("getting persons dn");
        String personInum = personAssociation.getUserAssociation().replaceAll(" ", "");

        if (isAPDNsEmpty || !listOfpersons.contains(personInum)) {
          log.info("adding person");
          listOfpersons.add(personInum);
        }

        String[] arrayOfpersons = new String[listOfpersons.size()];
        for (int i = 0; i < listOfpersons.size(); i++) {
          arrayOfpersons[i] = listOfpersons.get(i);
        }
        log.info("setting list of AssociatedPersonDns");
        client.setAttribute("associatedPerson", arrayOfpersons);
        log.info("Updating client");
        clientService.updateCustomClient(client);
      }

      String uri = "/ClientAssociation/Associate/" + person.getInum();
      log.info("returning response");
      return Response.created(URI.create(uri)).entity(personAssociation).build();

    } catch (Exception ex) {
      log.error("Failed to add Association", ex);
      // log.info("Failed to add Association" , ex);
      return getErrorResponse(
          "Unexpected processing error, please check the input parameters",
          Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }
  }
Beispiel #19
0
    public String requestString(
        int timeout, String url, String method, Object body, Pair<String, ?>... parameters)
        throws IOException, ServerException, ForbiddenException, NotFoundException,
            UnauthorizedException, ConflictException {
      final String authToken = getAuthenticationToken();
      if ((parameters != null && parameters.length > 0) || authToken != null) {
        final UriBuilder ub = UriBuilder.fromUri(url);
        // remove sensitive information from url.
        ub.replaceQueryParam("token", null);

        if (parameters != null && parameters.length > 0) {
          for (Pair<String, ?> parameter : parameters) {
            String name = URLEncoder.encode(parameter.first, "UTF-8");
            String value =
                parameter.second == null
                    ? null
                    : URLEncoder.encode(String.valueOf(parameter.second), "UTF-8");
            ub.replaceQueryParam(name, value);
          }
        }
        url = ub.build().toString();
      }
      final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
      conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
      conn.setReadTimeout(timeout > 0 ? timeout : 60000);
      try {
        conn.setRequestMethod(method);
        // drop a hint for server side that we want to receive application/json
        conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        if (authToken != null) {
          conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
        }
        if (body != null) {
          conn.addRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
          conn.setDoOutput(true);

          if (HttpMethod.DELETE.equals(
              method)) { // to avoid jdk bug described here
                         // http://bugs.java.com/view_bug.do?bug_id=7157360
            conn.setRequestMethod(HttpMethod.POST);
            conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
          }

          try (OutputStream output = conn.getOutputStream()) {
            output.write(DtoFactory.getInstance().toJson(body).getBytes());
          }
        }

        final int responseCode = conn.getResponseCode();
        if ((responseCode / 100) != 2) {
          InputStream in = conn.getErrorStream();
          if (in == null) {
            in = conn.getInputStream();
          }
          final String str;
          try (Reader reader = new InputStreamReader(in)) {
            str = CharStreams.toString(reader);
          }
          final String contentType = conn.getContentType();
          if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
            final ServiceError serviceError =
                DtoFactory.getInstance().createDtoFromJson(str, ServiceError.class);
            if (serviceError.getMessage() != null) {
              if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
                throw new ForbiddenException(serviceError);
              } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
                throw new NotFoundException(serviceError);
              } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
                throw new UnauthorizedException(serviceError);
              } else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
                throw new ConflictException(serviceError);
              } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
                throw new ServerException(serviceError);
              }
              throw new ServerException(serviceError);
            }
          }
          // Can't parse content as json or content has format other we expect for error.
          throw new IOException(
              String.format(
                  "Failed access: %s, method: %s, response code: %d, message: %s",
                  UriBuilder.fromUri(url).replaceQuery("token").build(),
                  method,
                  responseCode,
                  str));
        }
        final String contentType = conn.getContentType();
        if (!(contentType == null || contentType.startsWith(MediaType.APPLICATION_JSON))) {
          throw new IOException(conn.getResponseMessage());
        }

        try (Reader reader = new InputStreamReader(conn.getInputStream())) {
          return CharStreams.toString(reader);
        }
      } finally {
        conn.disconnect();
      }
    }
 private void assertErrorResponse(Response result) {
   assertEquals(result.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
 }