protected List<ModelNode> readFile(File file, int expectedRecords) throws IOException {
   List<ModelNode> list = new ArrayList<ModelNode>();
   final BufferedReader reader = new BufferedReader(new FileReader(file));
   try {
     StringWriter writer = null;
     String line = reader.readLine();
     while (line != null) {
       if (DATE_STAMP_PATTERN.matcher(line).find()) {
         if (writer != null) {
           list.add(ModelNode.fromJSONString(writer.getBuffer().toString()));
         }
         writer = new StringWriter();
         writer.append("{");
       } else {
         if (writer != null) writer.append("\n" + line);
       }
       line = reader.readLine();
     }
     if (writer != null) {
       list.add(ModelNode.fromJSONString(writer.getBuffer().toString()));
     }
   } finally {
     IoUtils.safeClose(reader);
   }
   Assert.assertEquals(list.toString(), expectedRecords, list.size());
   return list;
 }
  @Test
  public void testJsonObjectInComplexValue() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT);
    ModelNode complexValueType = new ModelNode();
    complexValueType.get("value", DESCRIPTION).set("A  value");
    complexValueType.get("value", TYPE).set(ModelType.OBJECT);
    description.get(VALUE_TYPE).set(complexValueType);

    TypeConverter converter = getConverter(description);

    CompositeType type = assertCast(CompositeType.class, converter.getOpenType());
    Set<String> keys = type.keySet();
    Assert.assertEquals(1, keys.size());

    Assert.assertEquals(SimpleType.STRING, type.getType("value"));

    ModelNode node = new ModelNode();
    node.get("value", "long").set(1L);
    node.get("value", "string").set("test");

    CompositeData data = assertCast(CompositeData.class, converter.fromModelNode(node));
    Assert.assertEquals(type, data.getCompositeType());
    Assert.assertEquals(
        ModelNode.fromJSONString(node.toJSONString(false)), converter.toModelNode(data));
  }
Beispiel #3
0
    private ToStateTransitions load(
        LoginData loginData, ProjectGroupConfig boardConfig, Issue issue, String toState)
        throws IOException {
      final UriBuilder builder =
          UriBuilder.fromUri(boardConfig.getJiraUrl())
              .path("rest")
              .path("api")
              .path("2")
              .path("issue")
              .path(issue.getKey())
              .path("transitions")
              .queryParam("issueIdOrKey", issue.getKey());
      final WebTarget target = loginData.getClient().target(builder);
      final Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get();

      if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
        throw new IOException(
            "Error looking up the transitions for issue "
                + issue.getKey()
                + ": "
                + response.readEntity(String.class));
      }
      Map<String, Transition> states = new HashMap<>();
      ModelNode modelNode = ModelNode.fromJSONString(response.readEntity(String.class));
      for (ModelNode transitionNode : modelNode.get("transitions").asList()) {
        Transition transition =
            new Transition(transitionNode.get("id").asInt(), transitionNode.get("name").asString());
        states.put(transition.toState, transition);
      }
      ToStateTransitions toStateTransitions = new ToStateTransitions(issue.getState(), states);
      return toStateTransitions;
    }
  @Test
  public void testJsonObjectInList() throws Exception {
    ModelNode description = createDescription(ModelType.LIST, ModelType.OBJECT);

    TypeConverter converter = getConverter(description);

    ArrayType<String> arrayType = assertCast(ArrayType.class, converter.getOpenType());
    Assert.assertEquals(
        SimpleType.STRING, assertCast(SimpleType.class, arrayType.getElementOpenType()));

    ModelNode list = new ModelNode();
    ModelNode value1 = new ModelNode();
    value1.get("long").set(5L);
    value1.get("string").set("Value");
    value1.get("a", "b").set(true);
    value1.get("c", "d").set(40);
    list.add(value1);
    ModelNode value2 = new ModelNode();
    value2.get("long").set(10L);
    list.add(value2);

    String json1 = value1.toJSONString(false);
    String json2 = value2.toJSONString(false);
    String[] data = assertCast(String[].class, converter.fromModelNode(list));
    Assert.assertEquals(2, data.length);
    Assert.assertEquals(json1, data[0]);
    Assert.assertEquals(json2, data[1]);

    Assert.assertEquals(
        ModelNode.fromJSONString(list.toJSONString(false)), converter.toModelNode(data));
  }
 @Override
 public void setEnvVars(Collection<IEnvironmentVariable> envVars) {
   if (envVars == null) return;
   String[] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV);
   ModelNode envNode = getNode().get(path);
   envNode.clear();
   envVars.forEach(v -> envNode.add(ModelNode.fromJSONString(v.toJson())));
 }
  @Override
  public void setBuildStrategy(IBuildStrategy strategy) {
    // Remove other strategies if already set?
    switch (strategy.getType()) {
      case BuildStrategyType.CUSTOM:
        if (!(strategy instanceof ICustomBuildStrategy)) {
          throw new IllegalArgumentException(
              "IBuildStrategy of type Custom does not implement ICustomBuildStrategy");
        }
        ICustomBuildStrategy custom = (ICustomBuildStrategy) strategy;
        if (custom.getImage() != null) {
          set(BUILDCONFIG_CUSTOM_IMAGE, custom.getImage().toString());
        }
        set(BUILDCONFIG_CUSTOM_EXPOSEDOCKERSOCKET, custom.exposeDockerSocket());
        if (custom.getEnvironmentVariables() != null) {
          setEnvMap(BUILDCONFIG_CUSTOM_ENV, custom.getEnvironmentVariables());
        }
        break;
      case BuildStrategyType.STI:
        if (!(strategy instanceof ISTIBuildStrategy)) {
          throw new IllegalArgumentException(
              "IBuildStrategy of type Custom does not implement ISTIBuildStrategy");
        }
        ISTIBuildStrategy sti = (ISTIBuildStrategy) strategy;
        if (sti.getImage() != null) {
          set(BUILDCONFIG_STI_IMAGE, sti.getImage().toString());
        }
        if (sti.getScriptsLocation() != null) {
          set(BUILDCONFIG_STI_SCRIPTS, sti.getScriptsLocation());
        }
        set(BUILDCONFIG_STI_INCREMENTAL, sti.incremental());
        if (sti.getEnvironmentVariables() != null) {
          setEnvMap(BUILDCONFIG_STI_ENV, sti.getEnvironmentVariables());
        }
        break;
      case BuildStrategyType.SOURCE:
        ISourceBuildStrategy source = (ISourceBuildStrategy) strategy;
        get(SOURCE_STRATEGY).set(ModelNode.fromJSONString(source.toString()));
        break;
      case BuildStrategyType.DOCKER:
        if (!(strategy instanceof IDockerBuildStrategy)) {
          throw new IllegalArgumentException(
              "IBuildStrategy of type Custom does not implement IDockerBuildStrategy");
        }
        IDockerBuildStrategy docker = (IDockerBuildStrategy) strategy;
        if (docker.getBaseImage() != null) {
          set(BUILDCONFIG_DOCKER_BASEIMAGE, docker.getBaseImage().toString());
        }
        if (docker.getContextDir() != null) {
          set(BUILDCONFIG_DOCKER_CONTEXTDIR, docker.getContextDir());
        }
        set(BUILDCONFIG_DOCKER_NOCACHE, docker.isNoCache());
        break;
    }

    set(BUILDCONFIG_TYPE, strategy.getType());
  }
 @Before
 public void setUp() {
   client = mock(IClient.class);
   ModelNode node = ModelNode.fromJSONString(sample.getContentAsString());
   pv =
       new PersistentVolume(
           node,
           client,
           ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PERSISTENT_VOLUME));
 }
 @Before
 public void setUp() {
   IClient client = mock(IClient.class);
   ModelNode node = ModelNode.fromJSONString(Samples.V1_PROJECT_REQUEST.getContentAsString());
   request =
       new OpenshiftProjectRequest(
           node,
           client,
           ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PROJECT_REQUEST));
 }
  @Test
  public void testUndefinedTypeEmptyConverter() {
    TypeConverter converter = getConverter(new ModelNode());
    Assert.assertEquals(SimpleType.STRING, converter.getOpenType());

    ModelNode node = new ModelNode();
    node.get("abc");
    node.get("def");
    node.protect();

    String json = assertCast(String.class, converter.fromModelNode(node));
    Assert.assertEquals(node.resolve(), ModelNode.fromJSONString(json));
    Assert.assertEquals(json, assertCast(String.class, converter.fromModelNode(node)));
    assertToArray(converter, json);
  }
  @Test
  public void testUndefinedTypeExpressionConverter() throws Exception {
    ModelNode description = new ModelNode();
    description.get(EXPRESSIONS_ALLOWED).set(true);
    TypeConverter converter = getConverter(description);

    ModelNode node = new ModelNode();
    node.get("abc").setExpression("${this.should.not.exist.!!!!!:10}");
    node.get("def").setExpression("${this.should.not.exist.!!!!!:false}");
    node.protect();

    String json = assertCast(String.class, converter.fromModelNode(node));
    Assert.assertEquals(node, ModelNode.fromJSONString(json));
    assertToArray(converter, json, null);
  }
  @Test
  public void testCompareWithMultipleHistoryEntries() {
    ModelNode history = root.get("history");
    List<ModelNode> entries =
        history
            .asList()
            .stream()
            .map(n -> ModelNode.fromJSONString(n.get("v1Compatibility").asString()))
            .collect(Collectors.toList());
    entries.sort(comparator);

    ModelNode last = entries.get(entries.size() - 1);
    assertEquals(
        "Exp. to retrieve the 'newest' entry with a non-null parent",
        "5f162644b2633962f753b9a09c7783d342c8aaebccaf6270fde68404d2af7a8c",
        last.get("id").asString());
  }
  @Test
  public void testUndefinedTypeConverter() {
    TypeConverter converter = getConverter(new ModelNode());
    Assert.assertEquals(SimpleType.STRING, converter.getOpenType());

    ModelNode node = new ModelNode();
    // BES 2013/01/10 This uses BigInteger; I'm not sure why. But use a value > Long.MAX_VALUE
    // so the json parser won't convert it down to a long or int resulting in a different value
    // See AS7-4913
    // Likely BigInteger was used *because of* the problem discussed in AS7-4913
    node.get("abc").set(new BigInteger(String.valueOf(Long.MAX_VALUE) + "0"));
    node.get("def").set(false);
    node.protect();

    String json = assertCast(String.class, converter.fromModelNode(node));
    Assert.assertEquals(node, ModelNode.fromJSONString(json));
    Assert.assertEquals(json, assertCast(String.class, converter.fromModelNode(node)));
    assertToArray(converter, json);
  }
  @Test
  public void testJsonObject() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT);

    TypeConverter converter = getConverter(description);

    Assert.assertEquals(SimpleType.STRING, converter.getOpenType());

    ModelNode node = new ModelNode();
    node.get("long").set(5L);
    node.get("string").set("Value");
    node.get("a", "b").set(true);
    node.get("c", "d").set(40);

    String json = node.toJSONString(false);
    String data = assertCast(String.class, converter.fromModelNode(node));
    Assert.assertEquals(json, data);

    Assert.assertEquals(ModelNode.fromJSONString(json), converter.toModelNode(data));
  }
  @Override
  public void executeRuntimeStep(OperationContext context, ModelNode operation)
      throws OperationFailedException {
    final String attributeName = operation.require(ModelDescriptionConstants.NAME).asString();

    PathAddress pathAddress =
        PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
    String addressName = pathAddress.getElement(pathAddress.size() - 2).getValue();
    String roleName = pathAddress.getLastElement().getValue();

    final ServiceName serviceName =
        MessagingServices.getActiveMQServiceName(
            PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
    ServiceController<?> service = context.getServiceRegistry(false).getService(serviceName);
    ActiveMQServer server = ActiveMQServer.class.cast(service.getValue());
    AddressControl control =
        AddressControl.class.cast(
            server.getManagementService().getResource(ResourceNames.CORE_ADDRESS + addressName));

    if (control == null) {
      PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
      throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
    }

    try {
      String rolesAsJSON = control.getRolesAsJSON();
      ModelNode res = ModelNode.fromJSONString(rolesAsJSON);
      ModelNode roles = ManagementUtil.convertSecurityRole(res);
      ModelNode matchedRole = findRole(roleName, roles);
      if (matchedRole == null || !matchedRole.hasDefined(attributeName)) {
        throw MessagingLogger.ROOT_LOGGER.unsupportedAttribute(attributeName);
      }
      boolean value = matchedRole.get(attributeName).asBoolean();
      context.getResult().set(value);
    } catch (Exception e) {
      context.getFailureDescription().set(e.getLocalizedMessage());
    }
  }
 private ModelNode parseResponse(HttpResponse response, boolean encoded) {
   try {
     String content = EntityUtils.toString(response.getEntity());
     int status = response.getStatusLine().getStatusCode();
     ModelNode modelResponse;
     if (status == HttpStatus.SC_OK) {
       if (encoded) {
         modelResponse = ModelNode.fromBase64(new ByteArrayInputStream(content.getBytes()));
         Assert.assertTrue(
             response.getFirstHeader("Content-Type").getValue().contains(DMR_ENCODED));
       } else {
         modelResponse = ModelNode.fromJSONString(content);
       }
     } else {
       modelResponse = new ModelNode();
       modelResponse.get(OUTCOME).set(FAILED);
       modelResponse.get(FAILURE_DESCRIPTION).set(content);
     }
     return modelResponse;
   } catch (IOException e) {
     throw new RuntimeException("Unable to read response content as String");
   }
 }
 @Before
 public void setUp() throws Exception {
   root = ModelNode.fromJSONString(Samples.V1_DOCKER_IMAGE_MANIFEST.getContentAsString());
 }