@Test
 public void getOptimalGatewayNodeIPInvalidPool() throws Exception {
   try {
     vr.getOptimalGatewayNodeInfo("nonExistentGatewayPool", null, (short) 1);
     fail();
   } catch (IllegalArgumentException e) {
     assertEquals(IllegalArgumentException.class, e.getClass());
   }
 }
 @Test
 public void testAddGatewayNodeInvalidPool() throws Exception {
   try {
     vr.addGatewayPoolNode("nonExistentGatewayPool", "10.0.0.1");
     fail();
   } catch (IllegalArgumentException e) {
     assertEquals(IllegalArgumentException.class, e.getClass());
   }
 }
 @Test
 public void testInvalidObjs() {
   for (Triplet<HBRecord, String, Class<? extends IllegalArgumentException>> p :
       TestObjects.invalidObjs) {
     HBRecord record = p.getValue0();
     String errorMessage =
         "An object with " + p.getValue1() + " should've thrown an " + p.getValue2().getName();
     try {
       hbMapper.writeValueAsResult(record);
       fail(errorMessage + " while converting bean to Result\nFailing object = " + record);
     } catch (IllegalArgumentException ex) {
       assertEquals("Mismatch in type of exception thrown", p.getValue2(), ex.getClass());
     }
     try {
       hbMapper.writeValueAsPut(record);
       fail(errorMessage + " while converting bean to Put\nFailing object = " + record);
     } catch (IllegalArgumentException ex) {
       assertEquals("Mismatch in type of exception thrown", p.getValue2(), ex.getClass());
     }
   }
 }
示例#4
0
  @Test
  public void test_cause_faultcodeAsNULL_severity_locale_messageargs_constructor() {
    IFaultCode expectedFaultCode = FaultCode.UNKNOWN;
    IllegalArgumentException expectedCause = new IllegalArgumentException();
    ISeverity expectedSeverity = CustomSeverity.DISASTER;
    UncheckedException e =
        new UncheckedException(expectedCause, null, expectedSeverity, Locale.FRENCH, "sangeeth");

    AssertEx.assertException(
        expectedCause,
        null,
        expectedFaultCode,
        Locale.FRENCH, // expectedLocale
        expectedCause.getClass().getName(), // expectedMessage
        expectedSeverity, // expectedSeverity
        e); // actualException
  }
 @Override
 protected String doInBackground(Boolean... params) {
   Integer redLevel = uiMan.getRed();
   Integer greenLevel = uiMan.getGreen();
   Integer blueLevel = uiMan.getBlue();
   Integer trans = uiMan.getTransition();
   Integer time = uiMan.getTime();
   if (!params[0]) trans = -1;
   Log.d(
       "LightRequest",
       String.format(
           "R:%d, G:%d, B:%d, Trans:%d, Time:%d", redLevel, greenLevel, blueLevel, trans, time));
   try {
     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost(serviceURI);
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
     nameValuePairs.add(new BasicNameValuePair("r", redLevel.toString()));
     nameValuePairs.add(new BasicNameValuePair("g", greenLevel.toString()));
     nameValuePairs.add(new BasicNameValuePair("b", blueLevel.toString()));
     nameValuePairs.add(new BasicNameValuePair("trans", trans.toString()));
     nameValuePairs.add(new BasicNameValuePair("time", time.toString()));
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity entity = response.getEntity();
     if (entity != null) {
       InputStream instream = entity.getContent();
       StringBuilder sb = new StringBuilder();
       String line;
       BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
       while ((line = reader.readLine()) != null) {
         sb.append(line).append("\n");
       }
       String result = sb.toString();
       return result;
     }
   } catch (ClientProtocolException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   } catch (IOException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   } catch (IllegalArgumentException e) {
     Log.e(e.getClass().toString(), e.getMessage());
   } catch (Exception e) {
     Log.e(e.getClass().toString(), e.getMessage());
   }
   return "null";
 }
  @Test
  public void should_create_exception_model_from_non_business_exception() {

    // Arrange
    IllegalArgumentException exception = buildIllegalArgException();
    ExceptionModel.Builder builder = new ExceptionModel.Builder("foo", exception);
    builder
        .withHelpLink("http://help")
        .withHttpCode(500, "desc")
        .withPath("/api/v1/resource")
        .withSessionId("abcd1234");

    // Act
    ExceptionModel model = builder.build();

    // Assert
    assertNotNull(model);
    assertEquals("foo", model.getApplicationName());
    assertNotNull(model.getDateTime());
    assertEquals(exception.getMessage(), model.getMessage());
    assertEquals(exception.getClass().getName(), model.getExceptionClass());
    assertEquals("/api/v1/resource", model.getPath());
    assertEquals("abcd1234", model.getSessionId());
    assertEquals("http://help", model.getHelpLink());
    assertEquals(500, model.getHttpStatusCode());
    assertEquals("desc", model.getHttpStatusDescription());
    assertNotNull(model.getDateTime());
    assertEquals("exception-core-model", model.getMetadata());
    assertFalse(model.getExceptionChain().isEmpty());
    assertNotNull(model.getExceptionId());
    assertEquals(
        model.getExceptionChain().get(0).getCorrelationId(),
        "d99306bc-4b04-4a34-b7e7-f5554383f570");
    assertEquals(
        model.getExceptionChain().get(0).getMessage(),
        "Something went wrong here is the exception Id d99306bc-4b04-4a34-b7e7-f5554383f570");
  }
示例#7
0
  @RolesAllowed(Roles.OWNER)
  @POST
  @Path("/{stream_name}.zip")
  @Consumes("application/zip")
  @ApiOperation(value = "Load zip file to a stream.", notes = "TBD")
  @ApiResponses(value = {@ApiResponse(code = 500, message = "Interval Server Error")})
  public ResponseMsg doPostStreamZip(
      @PathParam("stream_name") String streamName,
      @ApiParam(
              name = "str_tuple",
              value =
                  "<pre>Usage: attach a zip file containing a single file with the following content:\n"
                      + "timestamp, 1st_channel, 2nd_channel, 3rd_channel, ..\n"
                      + "timestamp, 1st_channel, 2nd_channel, 3rd_channel, ..\n"
                      + ".\n"
                      + ".\n"
                      + "\n"
                      + "e.g.,\n"
                      + "2013-01-01 09:20:12.12345, 12.4, 1.2, 5.5\n"
                      + "2013-01-01 09:20:13.12345, 11.4, 3.2, 1.5\n"
                      + "2013-01-01 09:20:14.12345, 10.4, 4.2, 7.5\n"
                      + "</pre>")
          byte[] data)
      throws JsonProcessingException {

    // check if report generation is ongoing.
    synchronized (CreateReportRunnable.reportLock) {
      File lockFile = new File(CreateReportRunnable.REPORT_LOCK_FILE);
      if (lockFile.exists()) {
        throw WebExceptionBuilder.buildBadRequest("Report creation job is running..");
      }
    }

    // Create temporary file
    DataOutputStream os = null;
    File file = null;
    String zipFileName = null;
    String unzipFolderName = null;
    try {
      unzipFolderName = TEMP_ZIP_FILE_PREFIX + newUUIDString();
      zipFileName = unzipFolderName + ".zip";
      file = new File(zipFileName);
      if (file.exists()) {
        file.delete();
      }
      file.createNewFile();

      os = new DataOutputStream(new FileOutputStream(file));
      os.write(data);
    } catch (IOException e) {
      deleteTempZipFiles(zipFileName, unzipFolderName);
      throw WebExceptionBuilder.buildInternalServerError(e);
    } finally {
      try {
        if (os != null) os.close();
      } catch (IOException e) {
        throw WebExceptionBuilder.buildInternalServerError(e);
      }
    }

    // Unzip the file.
    String unzippedFileName = null;
    try {
      unzippedFileName = unzip(zipFileName, unzipFolderName);
    } catch (IOException | UnsupportedOperationException e) {
      deleteTempZipFiles(zipFileName, unzipFolderName);
      throw WebExceptionBuilder.buildInternalServerError(e);
    }

    // Check unzipped filename
    if (unzippedFileName == null) {
      deleteTempZipFiles(zipFileName, unzipFolderName);
      throw WebExceptionBuilder.buildBadRequest("Problem with Zip file.");
    }

    // Read the file into memory.
    String unzippedData = null;
    try {
      unzippedData = readEntireFile(unzippedFileName);
    } catch (IOException e) {
      deleteTempZipFiles(zipFileName, unzipFolderName);
      throw WebExceptionBuilder.buildInternalServerError(e);
    }

    if (unzippedData.length() <= 0) {
      deleteTempZipFiles(zipFileName, unzipFolderName);
      throw WebExceptionBuilder.buildBadRequest("Empty data.");
    }

    // Pass unzipped data to database
    String ownerName = securityContext.getUserPrincipal().getName();
    StreamDatabaseDriver db = null;
    try {
      db = DatabaseConnector.getStreamDatabase();
      db.bulkLoad(ownerName, streamName, unzippedData);
    } catch (SQLException
        | IOException
        | ClassNotFoundException
        | NamingException
        | NoSuchAlgorithmException e) {
      throw WebExceptionBuilder.buildInternalServerError(e);
    } catch (IllegalArgumentException e) {
      throw WebExceptionBuilder.buildBadRequest(
          e.getClass().getSimpleName() + ": " + e.getMessage());
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }

      deleteTempZipFiles(zipFileName, unzipFolderName);
    }

    return new ResponseMsg("Successfully completed zip bulkloading.");
  }
 @Test
 public void testInvalidClasses() {
   Set<String> exceptionMessages = new HashSet<String>();
   for (Triplet<HBRecord, String, Class<? extends IllegalArgumentException>> p :
       invalidRecordsAndErrorMessages) {
     HBRecord record = p.getValue0();
     Class recordClass = record.getClass();
     assertFalse(
         "Object mapper couldn't detect invalidity of class " + recordClass.getName(),
         hbMapper.isValid(recordClass));
     String errorMessage =
         p.getValue1()
             + " ("
             + recordClass.getName()
             + ") should have thrown an "
             + IllegalArgumentException.class.getName();
     String exMsgObjToResult = null,
         exMsgObjToPut = null,
         exMsgResultToObj = null,
         exMsgPutToObj = null;
     try {
       hbMapper.writeValueAsResult(record);
       fail(errorMessage + " while converting bean to Result");
     } catch (IllegalArgumentException ex) {
       assertEquals(
           "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
           p.getValue2(),
           ex.getClass());
       exMsgObjToResult = ex.getMessage();
     }
     try {
       hbMapper.writeValueAsPut(record);
       fail(errorMessage + " while converting bean to Put");
     } catch (IllegalArgumentException ex) {
       assertEquals(
           "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
           p.getValue2(),
           ex.getClass());
       exMsgObjToPut = ex.getMessage();
     }
     try {
       hbMapper.readValue(someResult, recordClass);
       fail(errorMessage + " while converting Result to bean");
     } catch (IllegalArgumentException ex) {
       assertEquals(
           "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
           p.getValue2(),
           ex.getClass());
       exMsgResultToObj = ex.getMessage();
     }
     try {
       hbMapper.readValue(
           new ImmutableBytesWritable(someResult.getRow()), someResult, recordClass);
       fail(errorMessage + " while converting Result to bean");
     } catch (IllegalArgumentException ex) {
       assertEquals(
           "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
           p.getValue2(),
           ex.getClass());
     }
     try {
       hbMapper.readValue(somePut, recordClass);
       fail(errorMessage + " while converting Put to bean");
     } catch (IllegalArgumentException ex) {
       assertEquals(
           "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
           p.getValue2(),
           ex.getClass());
       exMsgPutToObj = ex.getMessage();
     }
     try {
       hbMapper.readValue(new ImmutableBytesWritable(somePut.getRow()), somePut, recordClass);
       fail(errorMessage + " while converting row key and Put combo to bean");
     } catch (IllegalArgumentException ex) {
       assertEquals("Mismatch in type of exception thrown", p.getValue2(), ex.getClass());
     }
     assertEquals(
         "Validation for 'conversion to Result' and 'conversion to Put' differ in code path",
         exMsgObjToResult,
         exMsgObjToPut);
     assertEquals(
         "Validation for 'conversion from Result' and 'conversion from Put' differ in code path",
         exMsgResultToObj,
         exMsgPutToObj);
     assertEquals(
         "Validation for 'conversion from bean' and 'conversion to bean' differ in code path",
         exMsgObjToResult,
         exMsgResultToObj);
     System.out.printf(
         "%s threw below Exception as expected:\n%s\n%n", p.getValue1(), exMsgObjToResult);
     if (!exceptionMessages.add(exMsgObjToPut)) {
       fail("Same error message for different invalid inputs");
     }
   }
 }
示例#9
0
  /**
   * Setup parameter accordnig to ZkParameter annotation.
   *
   * @param <T> type of field.
   * @param annot the annotation with parameter definition
   * @param field the field to set
   * @param clazz class of the field and parameter
   */
  protected static <T> void setupZkParameter(
      ZkParameter annot,
      String paramName,
      Class<T> clazz,
      Field field,
      Method method,
      Object instance) {
    T result = null;

    Map[] paramMaps =
        new Map[] {
          Executions.getCurrent().getArg(),
          Executions.getCurrent().getAttributes(),
          Executions.getCurrent().getParameterMap()
        };

    Map paramMap = paramMaps[0];
    for (Map map : paramMaps) {
      if (map.containsKey(paramName)) {
        paramMap = map;
        break;
      }
    }

    try {
      if (annot.required()) result = ZKHelper.getRequiredParameter(paramMap, paramName, clazz);
      else if (!paramMap.containsKey(paramName)) return; // optional parameter doesn't do anything
      else result = ZKHelper.getOptionalParameter(paramMap, paramName, clazz, null);
    } catch (IllegalArgumentException ex) {
      throw new IllegalArgumentException(
          "@ZkParameter(name='"
              + paramName
              + "', "
              + "required="
              + (annot.required() ? "true" : "false")
              + ", "
              + "createIfNull="
              + (annot.createIfNull() ? "true" : "false")
              + "): "
              + ex.getLocalizedMessage());
    }

    if (result == null && annot.createIfNull())
      try {
        result = (T) clazz.newInstance();
      } catch (InstantiationException ex) {
        throw new InstantiationError(
            "@ZkParameter(name='"
                + paramName
                + "', "
                + "required="
                + (annot.required() ? "true" : "false")
                + ", "
                + "createIfNull="
                + (annot.createIfNull() ? "true" : "false")
                + ") - Parameter is null, unable to create new object with error: "
                + ex.getLocalizedMessage());
      } catch (IllegalAccessException ex) {
        throw new InstantiationError(
            "@ZkParameter(name='"
                + paramName
                + "', "
                + "required="
                + (annot.required() ? "true" : "false")
                + ", "
                + "createIfNull="
                + (annot.createIfNull() ? "true" : "false")
                + ") - Parameter is null, unable to create new object, no public default constructor: "
                + ex.getLocalizedMessage());
      }

    if (field != null)
      try {
        field.setAccessible(true);
        field.set(instance, result);
        field.setAccessible(false);
      } catch (IllegalArgumentException ex) {
        throw new IllegalArgumentException(
            "@ZkParameter(name='"
                + paramName
                + "', "
                + "required="
                + (annot.required() ? "true" : "false")
                + ", "
                + "createIfNull="
                + (annot.createIfNull() ? "true" : "false")
                + ") - Unable to set new value of field to '"
                + result
                + "': "
                + ex.getLocalizedMessage(),
            ex);
      } catch (IllegalAccessException ex) {
        throw SystemException.Aide.wrap(ex);
      }
    if (method != null)
      try {
        method.setAccessible(true);
        method.invoke(instance, new Object[] {result});
        method.setAccessible(false);
      } catch (IllegalAccessException ex) {
        throw SystemException.Aide.wrap(ex);
      } catch (IllegalArgumentException ex) {
        throw new IllegalArgumentException(
            "@ZkParameter(name='"
                + paramName
                + "', "
                + "required="
                + (annot.required() ? "true" : "false")
                + ", "
                + "createIfNull="
                + (annot.createIfNull() ? "true" : "false")
                + ") - Unable to set new value of method to '"
                + result
                + "': "
                + ex.getClass()
                + " - "
                + ex.getLocalizedMessage(),
            ex);
      } catch (InvocationTargetException ex) {
        throw new IllegalArgumentException(
            "@ZkParameter(name='"
                + paramName
                + "', "
                + "required="
                + (annot.required() ? "true" : "false")
                + ", "
                + "createIfNull="
                + (annot.createIfNull() ? "true" : "false")
                + ") - Unable to set new value of method to '"
                + result
                + "', error in method invocation: "
                + ex.getClass()
                + " - "
                + (ex.getTargetException() == null
                    ? ex.getLocalizedMessage()
                    : ex.getTargetException().getLocalizedMessage()),
            ex);
      }
  }
 @ExceptionHandler
 @ResponseBody
 public String handleException(IllegalArgumentException ex) {
   return ClassUtils.getShortName(ex.getClass());
 }