private void testUmlModelToFile(IModel testModel, String filePath) {
    OutputStream os = new ByteArrayOutputStream();
    try {
      ClassUmlOutputStream uml = new ClassUmlOutputStream(os);
      uml.write(testModel);
      BufferedReader br = new BufferedReader(new FileReader(filePath));
      StringBuilder sb = new StringBuilder();
      String line = br.readLine();

      while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
      }

      // assertEquals(os.toString(), sb.toString());
      assertTrue(
          sb.toString()
              .replaceAll("\r", "")
              .replaceAll("\n", "")
              .contains(os.toString().replaceAll("\r", "").replaceAll("\n", "")));
    } catch (IOException e) {
      System.out.println("File not found: " + filePath);
      System.out.println("Printing actual output:");
      System.out.print(os.toString());
      fail("File not found");
    } catch (AssertionError e) {
      System.out.println("Test failed for file path: " + filePath);
      System.out.println("Printing actual output:");
      System.out.print(os.toString());
      fail("Test failed");
    }
  }
  @Test
  public void dataFromSeveralModulesToXmlTest()
      throws WebApplicationException, IOException, URISyntaxException {
    final NormalizedNodeContext normalizedNodeContext = prepareNormalizedNodeContext();
    final OutputStream output = new ByteArrayOutputStream();
    xmlBodyWriter.writeTo(normalizedNodeContext, null, null, null, mediaType, null, output);

    final String outputString = output.toString();
    // data
    assertTrue(
        outputString.contains(
            "<data xmlns=" + '"' + "urn:ietf:params:xml:ns:netconf:base:1.0" + '"' + '>'));
    // cont m2
    assertTrue(outputString.contains("<cont_m2 xmlns=" + '"' + "module:two" + '"' + '>'));
    assertTrue(outputString.contains("<lf1_m2>lf1 m2 value</lf1_m2>"));
    assertTrue(outputString.contains("<contB_m2></contB_m2>"));
    assertTrue(outputString.contains("</cont_m2>"));

    // cont m1
    assertTrue(outputString.contains("<cont_m1 xmlns=" + '"' + "module:one" + '"' + '>'));
    assertTrue(outputString.contains("<contB_m1></contB_m1>"));
    assertTrue(outputString.contains("<lf1_m1>lf1 m1 value</lf1_m1>"));
    assertTrue(outputString.contains("</cont_m1>"));

    // end
    assertTrue(output.toString().contains("</data>"));
  }
  public static int rebuildIndex(Map map) throws Exception {
    int ret = 0;
    shutdownServer("Rebuild index");
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);

    String[] args = {
      "--configClass",
      "org.opends.server.extensions.ConfigFileHandler",
      "--configFile",
      getOpenDJConfigFile(map),
      "--baseDN",
      (String) map.get(SetupConstants.CONFIG_VAR_ROOT_SUFFIX),
      "--rebuildAll"
    };
    OutputStream bos = new ByteArrayOutputStream();
    OutputStream boe = new ByteArrayOutputStream();
    TimeThread.start();
    ret = RebuildIndex.mainRebuildIndex(args, true, bos, boe);
    TimeThread.stop();
    String outStr = bos.toString();
    String errStr = boe.toString();
    if (errStr.length() != 0) {
      debug.error("EmbeddedOpenDS:rebuildIndex:stderr=" + errStr);
    }
    if (debug.messageEnabled()) {
      String msg = "msg=Rebuild complete.";
      int idx = outStr.indexOf(msg);
      if (idx >= 0) {
        debug.message("EmbeddedOpenDS:rebuildIndex: " + "Rebuild Status: " + outStr.substring(idx));
      }
      debug.message("EmbeddedOpenDS:rebuildIndex:Result:" + outStr);
    }
    startServer(getOpenDJBaseDir(map));
    return ret;
  }
  // Watch out: this functionality affects Drools Server
  //
  // The problem seems to be related with the CXFProducer and the async processors,
  // and it only appears when we do a lookup for different sessions.
  // Using different sessions requires that camel switch classloader to execute commands
  // in the existing sessions. That could be realted too..
  // but in Drools Camel code I don't find any problem
  // The rest endpoint is working ok
  public void testCxfSoapSessionLookup() throws Exception {

    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
    QName payloadName = new QName("http://soap.jax.drools.org", "execute", "ns1");

    body.addBodyElement(payloadName);

    String cmd = "";
    cmd += "<batch-execution lookup=\"ksession1\">\n";
    cmd += "  <insert out-identifier=\"salaboy\" disconnected=\"true\">\n";
    cmd += "      <org.drools.springframework.Person2>\n";
    cmd += "         <name>salaboy</name>\n";
    cmd += "         <age>27</age>\n";
    cmd += "      </org.drools.springframework.Person2>\n";
    cmd += "   </insert>\n";
    cmd += "   <fire-all-rules/>\n";
    cmd += "</batch-execution>\n";

    body.addTextNode(cmd);

    Object object = this.context.createProducerTemplate().requestBody("direct://http", soapMessage);

    OutputStream out = new ByteArrayOutputStream();
    out = new ByteArrayOutputStream();
    soapMessage = (SOAPMessage) object;
    soapMessage.writeTo(out);
    String response = out.toString();
    assertTrue(response.contains("fact-handle identifier=\"salaboy\""));

    SOAPMessage soapMessage2 = MessageFactory.newInstance().createMessage();
    SOAPBody body2 = soapMessage.getSOAPPart().getEnvelope().getBody();
    QName payloadName2 = new QName("http://soap.jax.drools.org", "execute", "ns1");

    body2.addBodyElement(payloadName2);

    String cmd2 = "";
    cmd2 += "<batch-execution lookup=\"ksession2\">\n";
    cmd2 += "  <insert out-identifier=\"salaboy\" disconnected=\"true\">\n";
    cmd2 += "      <org.drools.springframework.Person3>\n";
    cmd2 += "         <name>salaboy</name>\n";
    cmd2 += "         <age>27</age>\n";
    cmd2 += "      </org.drools.springframework.Person3>\n";
    cmd2 += "   </insert>\n";
    cmd2 += "   <fire-all-rules/>\n";
    cmd2 += "</batch-execution>\n";

    body2.addTextNode(cmd2);

    Object object2 =
        this.context.createProducerTemplate().requestBody("direct://http", soapMessage2);

    OutputStream out2 = new ByteArrayOutputStream();
    out2 = new ByteArrayOutputStream();
    soapMessage2 = (SOAPMessage) object2;
    soapMessage2.writeTo(out2);
    String response2 = out2.toString();
    assertTrue(response2.contains("fact-handle identifier=\"salaboy\""));
  }
  public static Document createSoapResponseDocument(
      IRuntimeContext context,
      IOutputHandler outputHandler,
      OutputStream contentStream,
      List messages) {
    Document document = createSoapDocument();
    if ((context == null) || (context.getStatus() != IRuntimeContext.RUNTIME_STATUS_SUCCESS)) {
      document
          .getRootElement()
          .element("SOAP-ENV:Body")
          .add(createSoapFaultElement(messages)); // $NON-NLS-1$
    } else {
      Element activityResponse = createActivityResponseElement();
      document.getRootElement().element("SOAP-ENV:Body").add(activityResponse); // $NON-NLS-1$

      IContentItem contentItem = outputHandler.getFeedbackContentItem();

      // hmm do we need this to be ordered?
      Set outputNames = context.getOutputNames();

      Iterator outputNameIterator = outputNames.iterator();
      while (outputNameIterator.hasNext()) {
        String outputName = (String) outputNameIterator.next();
        contentItem =
            outputHandler.getOutputContentItem(
                IOutputHandler.RESPONSE,
                IOutputHandler.CONTENT,
                context.getInstanceId(),
                "text/xml"); //$NON-NLS-1$
        if ((outputNames.size() == 1) && (contentItem != null)) {
          String mimeType = contentItem.getMimeType();
          if ((mimeType != null) && mimeType.startsWith("text/")) { // $NON-NLS-1$
            if (mimeType.equals("text/xml")) { // $NON-NLS-1$
              activityResponse.addElement(outputName).setText(contentStream.toString());
            } else if (mimeType.startsWith("text/")) { // $NON-NLS-1$
              activityResponse.addElement(outputName).addCDATA(contentStream.toString());
            }
          } else {
            Object value = context.getOutputParameter(outputName).getValue();
            if (value == null) {
              value = ""; // $NON-NLS-1$
            }
            activityResponse.add(createSoapElement(outputName, value));
          }
        } else {
          Object value = context.getOutputParameter(outputName).getValue();
          if (value == null) {
            value = ""; // $NON-NLS-1$
          }
          activityResponse.add(createSoapElement(outputName, value));
        }
      }
    }
    return document;
  }
 public void testError() throws Exception {
   runner.run(ErrorTest.class);
   assertTrue(results.toString().startsWith(convert(".E\nTime: ")));
   assertTrue(
       results
               .toString()
               .indexOf(
                   convert(
                       "\nThere was 1 failure:\n1) error(org.junit.tests.TextListenerTest$ErrorTest)\njava.lang.Exception"))
           != -1);
 }
  @Override
  public String getMappingString() throws Exception {
    // Output the mapping objects to a stream
    String result = null;
    OutputStream moStream = null;
    try {
      moStream = new ByteArrayOutputStream();
      final PrintWriter pw = new PrintWriter(moStream, true);
      final MappingOutputter outputter = new MappingOutputter();
      outputter.write(this, pw); // TODO FIX/REPLACE??? , isNewlines(), isIndent());
      pw.flush();

      result = moStream.toString();
    } catch (final Exception e) {
      throw e;
    } finally {
      if (moStream != null) {
        try {
          moStream.close();
        } catch (final IOException e1) {
          throw e1;
        }
        moStream = null;
      }
    }
    return result;
  }
 private String transformToXML(StreamSource streamSource) throws TransformerException {
   // use this later
   /**
    * SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false);
    * factory.setNamespaceAware(true);
    *
    * <p>SAXParser parser = factory.newSAXParser();
    *
    * <p>XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new
    * SimpleErrorHandler());
    *
    * <p>Builder builder = new Builder(reader); builder.build("contacts.xml");
    *
    * <p>OR
    *
    * <p>XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    * xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
    * false); Builder builder = new Builder(xmlReader); nu.xom.Document doc =
    * builder.build(fXmlFile);
    */
   OutputStream baos = new ByteArrayOutputStream();
   javaxTransformer.transform(streamSource, new StreamResult(baos));
   String ss = baos.toString();
   return ss;
 }
  /**
   * process a sample with equal content buckets to see if the partitioning of the stream works well
   */
  public void testSP_small_sample_with_proportional_huge_buffersize() throws IOException {
    int sampleSize = 5;
    // 5 * 20 == 100
    int bufferSize = 100;
    final String str =
        new StringBuilder()
            .append(StringUtils.repeat("A", 20))
            .append(StringUtils.repeat("B", 20))
            .append(StringUtils.repeat("C", 20))
            .append(StringUtils.repeat("D", 20))
            .append(StringUtils.repeat("E", 20))
            .toString();
    OutputStream out = new ByteArrayOutputStream();
    TestableRGStreamProcessor rgsp = new TestableRGStreamProcessor(sampleSize, out, bufferSize);

    assertEquals(
        "read size of `process` must match the input size",
        str.length(),
        rgsp.process(bufferedString(str)));
    assertEquals("ABCDE", out.toString());

    // each bucket contains only the same char as we repeated the string in the exact matches size
    Map<Integer, List<Character>> buckets = rgsp.getBuckets();
    assertTrue(Joiner.on("").join(buckets.get(0)).matches("^A+$"));
    assertTrue(Joiner.on("").join(buckets.get(1)).matches("^B+$"));
    assertTrue(Joiner.on("").join(buckets.get(2)).matches("^C+$"));
    assertTrue(Joiner.on("").join(buckets.get(3)).matches("^D+$"));
    assertTrue(Joiner.on("").join(buckets.get(4)).matches("^E+$"));

    // here we have less bucket content, cause our buffersize the maximum possible
    assertEquals(1, buckets.get(0).size());
  }
  /** check that the modulo parts are picked up correctly */
  public void testSP_bigger_buffer_unproportinal_size() throws IOException {
    int sampleSize = 5;
    int bufferSize = 8;
    final String str = "AABBCCDE";
    OutputStream out = new ByteArrayOutputStream();
    TestableRGStreamProcessor rgsp = new TestableRGStreamProcessor(sampleSize, out, bufferSize);

    assertEquals(
        "read size of `process` must match the input size",
        str.length(),
        rgsp.process(bufferedString(str)));
    assertEquals("ABCDE", out.toString());

    // each bucket contains only the same char as we repeated the string in the exact matches size
    Map<Integer, List<Character>> buckets = rgsp.getBuckets();
    assertTrue(Joiner.on("").join(buckets.get(0)).matches("^A+$"));
    assertTrue(Joiner.on("").join(buckets.get(1)).matches("^B+$"));
    assertTrue(Joiner.on("").join(buckets.get(2)).matches("^C+$"));
    assertTrue(Joiner.on("").join(buckets.get(3)).matches("^D+$"));
    assertTrue(Joiner.on("").join(buckets.get(4)).matches("^E+$"));

    // here we have a bigger bucket content, cause our buffersize was small
    assertEquals(1, buckets.get(0).size());
    assertEquals(1, buckets.get(1).size());
    assertEquals(1, buckets.get(2).size());
    assertEquals(1, buckets.get(3).size());
    assertEquals(1, buckets.get(4).size());
  }
  /**
   * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
   *
   * @param url
   * @return String contents of the URL
   * @should return an update rdf page for old https dev urls
   * @should return an update rdf page for old https module urls
   * @should return an update rdf page for module urls
   */
  public static String getURL(URL url) {
    InputStream in = null;
    OutputStream out = null;
    String output = "";
    try {
      in = getURLStream(url);
      if (in == null) // skip this module if updateURL is not defined
      return "";

      out = new ByteArrayOutputStream();
      OpenmrsUtil.copyFile(in, out);
      output = out.toString();
    } catch (IOException io) {
      log.warn("io while reading: " + url, io);
    } finally {
      try {
        in.close();
      } catch (Exception e) {
        /* pass */
      }
      try {
        out.close();
      } catch (Exception e) {
        /* pass */
      }
    }

    return output;
  }
Exemple #12
0
  /**
   * Hoitaa tiedostojen kopioimisen
   *
   * @param lahde kopioitavan tiedsoton sijainti
   * @param maaranpaa minne kopioitava tiedosto tallennetaan
   */
  public void kopioiKuvaUlosJarResourcesTiedostosta(String lahde, String maaranpaa) {
    File kohdeTiedosto = new File(maaranpaa);
    if (kohdeTiedosto.exists()) {
      System.out.println("Tiedosto " + kohdeTiedosto.getPath() + " on jo tallennettuna");
    } else {

      try {
        OutputStream ulosTallennus;
        try (InputStream sisaanVirta = this.getClass().getResourceAsStream(lahde)) {
          ulosTallennus = new FileOutputStream(kohdeTiedosto);
          byte[] buf = new byte[1024];
          int len;
          while ((len = sisaanVirta.read(buf)) > 0) {
            ulosTallennus.write(buf, 0, len);
          }
        }
        System.out.println("Tiedosto " + ulosTallennus.toString());
        ulosTallennus.close();
        System.out.print(" tallennettu");
      } catch (FileNotFoundException ex) {
        TyokaluPakki.popUpViesti(
            "Json tiedostoa ei saatu siirrettyä ulos jar tiedostosta. Kokeile siirrää Jar tiedosto henkilökohtaiseen kansioon ja avaa uudelleen",
            "Json tiedoston siirto");
      } catch (IOException e) {
        TyokaluPakki.popUpViesti(
            "Json tiedostoa ei saatu siirrettyä ulos jar tiedostosta. Kokeile siirrää Jar tiedosto henkilökohtaiseen kansioon ja avaa uudelleen",
            "Json tiedoston siirto");
      }
    }
  }
  @Test
  public void testSerialize() throws Exception {
    byte[] bodyBytes = "{'test': 'this is a value'}".getBytes();
    InputStream body = new ByteArrayInputStream(bodyBytes);
    HttpResponse response =
        HttpResponse.status(HttpStatus.OK)
            .header("Some-Special-Header", "test")
            .header("Content-Type", "application/json")
            .body(body);

    OutputStream os = new ByteArrayOutputStream();
    responseSerializer.serialize(response, os);

    String expected =
        "HTTP/1\\.1 200 OK\\r\\n"
            + "content-type: application/json\\r\\n"
            + "some-special-header: test\\r\\n"
            + "Date: .*\\r\\n"
            + "Content-Length: "
            + bodyBytes.length
            + "\\r\\n"
            + "\\r\\n"
            + "\\{'test': 'this is a value'\\}";

    Assert.assertTrue(os.toString().matches(expected));
  }
 @RequestMapping(value = "/detailXTestSC", method = RequestMethod.POST)
 public @ResponseBody String detailXTestSC(@RequestBody String xTestName) {
   logger.info("DetailXTestSC " + xTestName);
   String xTestSCPath = null;
   for (String xTestSCName : resultList) {
     if (xTestSCName.indexOf(xTestName) >= 0) {
       xTestSCPath = xTestSCName;
       break;
     }
   }
   OutputStream contentStream = p4ConnectionService.detailXTestSC(xTestSCPath);
   // File file=new
   // File("C:\\Dev\\Perforce\\depot\\Platform\\tools\\xTest\\xDB10\\src\\com\\emc\\xtest\\suite\\lib\\xdb10\\qa\\xplore\\XPloreQueryPerfSC.java");
   // FileInputStream fis =null;
   // OutputStream contentStream =null;
   // try {
   // fis = new FileInputStream(file);
   // contentStream = new ByteArrayOutputStream();
   // byte[] buff = new byte[32 * 1024];
   // int len;
   // while ((len = fis.read(buff)) > 0){
   // contentStream.write(buff, 0, len);
   // }
   // fis.close();
   // contentStream.close();
   // } catch (FileNotFoundException e) {
   // // TODO Auto-generated catch block
   // e.printStackTrace();
   // } catch (IOException e) {
   // // TODO Auto-generated catch block
   // e.printStackTrace();
   // }
   return contentStream.toString();
 }
Exemple #15
0
    private JSONObject reformLastestTrafficData(String sensorURL, JSONArray filterArr) {
      JSONObject result = new JSONObject();
      try {
        SensorManager sensorManager = new SensorManager();
        Sensor sensor = sensorManager.getSpecifiedSensorWithSensorId(sensorURL);
        if (sensor == null) return result;
        Observation obs = sensorManager.getNewestObservationForOneSensor(sensorURL);

        JSONObject metaJson = new JSONObject();
        metaJson.put("name", sensor.getName());
        metaJson.put("source", sensor.getSource());
        metaJson.put("sourceType", sensor.getSourceType());
        metaJson.put("city", sensor.getPlace().getCity());
        metaJson.put("country", sensor.getPlace().getCountry());

        OutputStream out = null;
        out = DatabaseUtilities.getNewestSensorData(sensorURL);
        JSONObject json = (JSONObject) JSONSerializer.toJSON(out.toString());
        json.put("updated", DateUtil.date2StandardString(new Date()));
        json.put("ntriples", JSONUtil.JSONToNTriple(json.getJSONObject("results")));
        json.put("error", "false");
        json.put("meta", metaJson);

        System.out.println(json);
        result = json;
      } catch (Exception e) {
        e.printStackTrace();
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("error", "true");
        jsonResult.put("ntriples", "");
        result = jsonResult;
      }
      return result;
    }
 public String getWrittenMessage() {
   if (os != null) {
     return os.toString();
   } else {
     return null;
   }
 }
  public boolean load(String location) {
    try {
      String query = URLEncoder.encode(location, "utf-8");
      Log.d("OUT", "query: " + query);
      URL url =
          new URL("http://api.openweathermap.org/data/2.5/forecast?q=" + query + "&mode=json");
      URLConnection connection = url.openConnection();
      connection.connect();
      InputStream input = new BufferedInputStream(url.openStream());
      OutputStream output = new ByteArrayOutputStream();
      byte data[] = new byte[1024];
      int count;

      while ((count = input.read(data)) != -1) {
        output.write(data, 0, count);
      }
      rawString = output.toString();
      response = new JSONObject(rawString);
      if (response.getString("cod").equals("200")) {
        list = response.getJSONArray("list");
        return true;
      }
    } catch (Exception e) {
    }
    return false;
  }
  @Test
  public void testFindAndCountMaxSmall() {
    int[] intArray = {2, 5, 3, 2, 7, 4, 7, 2, 4};
    new FindAndCountMax().findAndCountMax(intArray);

    assertEquals("Max value is: 7\r\nIt occurs 2 times\r\n", outputStream.toString());
  }
Exemple #19
0
 @Then("^I should see the printed output$")
 public void I_should_see_printed_output(String text) throws IOException {
   String actual = outputStream.toString().replace(System.getProperty("line.separator"), "");
   String expected = text.replace(System.getProperty("line.separator"), "");
   assertEquals("The printed output is wrong.", expected, actual);
   outputStream.close();
 }
  @Override
  public Scenario parse(InputStream inputStream)
      throws IOException, SAXException, ParserConfigurationException {

    OutputStream output = new ByteArrayOutputStream();
    JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).prettyPrint(false).build();

    try {

      /* Create source (XML). */
      XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(inputStream);
      // XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
      // Source source = new StAXSource(reader);

      /* Create result (JSON). */
      XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
      // XMLStreamWriter writer = new JsonXMLOutputFactory(config).createXMLStreamWriter(output);
      // Result result = new StAXResult(writer);

      /*
       * Copy events from reader to writer.
       */
      writer.add(reader);

      /* Copy source to result via "identity transform". */
      // TransformerFactory.newInstance().newTransformer().transform(source, result);
    } catch (XMLStreamException e) {
      e.printStackTrace();
    } finally {

      /* As per StAX specification, XMLStreamReader/Writer.close()
      doesn't close
      the underlying stream. */
      output.close();
      inputStream.close();
    }

    /*
    try {
        json = xmlToJson(inputStream);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String jsonString = json.toString();

    System.out.println(jsonString);

    GenericDocument genericDocument = new GenericDocument();
    genericDocument.setJson(jsonString);
    */

    GenericDocument genericDocument = new GenericDocument();
    String json = output.toString();

    genericDocument.setJson(json);

    return genericDocument;
  }
  // Util: get String type of ExceptionStackTrace
  public static String getExceptionStackTrace(Exception exception) {
    java.io.OutputStream out = new java.io.ByteArrayOutputStream();

    java.io.PrintStream ps = new java.io.PrintStream(out, true);
    exception.printStackTrace(ps);
    String str = out.toString();
    return str;
  }
Exemple #22
0
 /**
  * Converts the message implementation into a String representation
  *
  * @return String representation of the message
  * @throws Exception Implemetation may throw an endpoint specific exception
  */
 public byte[] getPayloadAsBytes() throws Exception {
   if (out instanceof ByteArrayOutputStream) {
     return ((ByteArrayOutputStream) out).toByteArray();
   } else {
     logger.warn("Attempting to get the bytes of a non-ByteArray output stream");
     return StringMessageUtils.getBytes(out.toString());
   }
 }
Exemple #23
0
 /**
  * Converts the message implementation into a String representation
  *
  * @param encoding The encoding to use when transforming the message (if necessary). The parameter
  *     is used when converting from a byte array
  * @return String representation of the message payload
  * @throws Exception Implementation may throw an endpoint specific exception
  */
 public String getPayloadAsString(String encoding) throws Exception {
   if (out instanceof ByteArrayOutputStream) {
     return StringMessageUtils.getString(((ByteArrayOutputStream) out).toByteArray(), encoding);
   } else {
     logger.warn("Attempting to get the String contents of a non-ByteArray output stream");
     return out.toString();
   }
 }
  @Override
  public CompoundStatus checkTargetTTsSuccess(
      String opType, String[] affectedTTs, int totalTargetEnabled, HadoopCluster cluster) {
    CompoundStatus status = new CompoundStatus("checkTargetTTsSuccess");

    String scriptFileName = CHECK_SCRIPT_FILE_NAME;
    String scriptRemoteFilePath = DEFAULT_SCRIPT_DEST_PATH + scriptFileName;
    String listRemoteFilePath = null;
    String opDesc = "checkTargetTTsSuccess";

    _log.log(Level.INFO, "AffectedTTs:");
    for (String tt : affectedTTs) {
      _log.log(Level.INFO, tt);
    }
    HadoopConnection connection = getConnectionForCluster(cluster);
    setErrorParamsForCommand(opDesc, scriptRemoteFilePath, listRemoteFilePath);

    int rc = -1;
    int iterations = 0;
    do {
      if (iterations > 0) {
        _log.log(Level.INFO, "Target TTs not yet achieved...checking again - " + iterations);
      }

      OutputStream out = new ByteArrayOutputStream();
      rc =
          executeScriptWithCopyRetryOnFailure(
              connection,
              scriptFileName,
              new String[] {"" + totalTargetEnabled, connection.getHadoopHome()},
              out);
      try {
        out.flush();
      } catch (IOException e) {
        String errorMsg = "Unexpected exception in SSH OutputStream ";
        _log.log(Level.WARNING, errorMsg, e);
        status.registerTaskFailed(false, errorMsg + e.getMessage());
      }

      // _log.log(Level.INFO, "Output from SSH script execution:\n"+out.toString());

      /* Convert to String array and "nullify" last element (which happens to be "@@@..." or empty line) */
      String[] allActiveTTs = out.toString().split("\n");
      allActiveTTs[allActiveTTs.length - 1] = null;

      if (checkOpSuccess(opType, affectedTTs, allActiveTTs)) {
        _log.log(Level.INFO, "All selected TTs correctly %sed", opType.toLowerCase());
        rc = SUCCESS;
        break;
      }
      // TODO: out.close()?

    } while ((rc == ERROR_FEWER_TTS || rc == ERROR_EXCESS_TTS)
        && (++iterations <= MAX_CHECK_RETRY_ITERATIONS));

    status.addStatus(_errorCodes.interpretErrorCode(_log, rc, _errorParamValues));
    return status;
  }
  /**
   * Navigate based on a form. Complete and post the form.
   *
   * @param form The form to be posted.
   * @param submit The submit button on the form to simulate clicking.
   */
  public final void navigate(final Form form, final Input submit) {

    try {
      EncogLogging.log(EncogLogging.LEVEL_INFO, "Posting a form");

      InputStream is;
      URLConnection connection = null;
      OutputStream os;
      URL targetURL;

      if (form.getMethod() == Form.Method.GET) {
        os = new ByteArrayOutputStream();
      } else {

        connection = form.getAction().getUrl().openConnection();
        os = connection.getOutputStream();
      }

      // add the parameters if present
      final FormUtility formData = new FormUtility(os, null);
      for (final DocumentRange dr : form.getElements()) {
        if (dr instanceof FormElement) {
          final FormElement element = (FormElement) dr;
          if ((element == submit) || element.isAutoSend()) {
            final String name = element.getName();
            String value = element.getValue();
            if (name != null) {
              if (value == null) {
                value = "";
              }
              formData.add(name, value);
            }
          }
        }
      }

      // now execute the command
      if (form.getMethod() == Form.Method.GET) {
        String action = form.getAction().getUrl().toString();
        os.close();
        action += "?";
        action += os.toString();
        targetURL = new URL(action);
        connection = targetURL.openConnection();
        is = connection.getInputStream();
      } else {
        targetURL = form.getAction().getUrl();
        os.close();
        is = connection.getInputStream();
      }

      navigate(targetURL, is);
      is.close();
    } catch (final IOException e) {
      throw new BrowseError(e);
    }
  }
 public String executeToString(AddressQuery addressQuery) throws AddressParserException {
   if (addressQuery == null) {
     throw new AddressParserException("Can not stream a null Adsress query to string");
   }
   String url = getUrl(addressQuery);
   OutputStream outputStream = new ByteArrayOutputStream();
   getRestClient().get(url, outputStream, OutputFormat.JSON);
   return outputStream.toString();
 }
 @Test
 public void testDecorateLogger() throws IOException {
   OutputStream mpos = wrapper.decorateLogger(build, logger);
   mpos.write("devpass is a password in testdb\n".getBytes());
   mpos.write("dbuser is a userId in testdb\n".getBytes());
   String result = logger.toString();
   System.out.println(result);
   assertFalse("devpass should not be in output", result.contains("devpass"));
   assertTrue("dbuser should be in output", result.contains("dbuser"));
 }
  @Test
  public void testFindAndCountMaxMedium() {
    int[] intArray = {
      28, 53, 2, 59, 20, 41, 44, 60, 40, 22, 90, 92, 31, 23, 53, 62, 31, 53, 26, 7, 4, 32, 63, 53,
      22, 75, 78, 2, 3, 6, 15, 35, 4, 7, 88, 93, 25, 4, 75, 8, 29, 11, 1, 53
    };
    new FindAndCountMax().findAndCountMax(intArray);

    assertEquals("Max value is: 93\r\nIt occurs 1 times\r\n", outputStream.toString());
  }
  private String getJson(final String xmlPath) throws Exception {
    final String uri = "choice-case-test:cont";
    final NormalizedNodeContext testNN =
        TestRestconfUtils.loadNormalizedContextFromXmlFile(xmlPath, uri);

    final OutputStream output = new ByteArrayOutputStream();
    jsonBodyWriter.writeTo(testNN, null, null, null, mediaType, null, output);

    return output.toString();
  }
  public boolean updateMobileDevice(
      String serialNumber,
      String deviceName,
      String assetTag,
      String building,
      String room,
      String department) {
    boolean success = false;
    MobileDeviceMatch match = findMobileDevice(serialNumber);
    if (match != null) {
      // TODO: urlencode string
      String id = match.id;
      MobileDevice device = getMobileDevice(id);
      if (device != null) {
        String updateUrlString = jssServerUrl + MOBILE_DEVICES_API_PATH + "/id/" + id;
        GenericUrl updateUrl = new GenericUrl(updateUrlString);
        int status = 500;
        try {
          device.general.deviceName = deviceName;
          device.general.assetTag = assetTag;

          if (building != null && !building.isEmpty()) {
            device.location.building = building;
          }
          if (room != null && !room.isEmpty()) {
            device.location.room = room;
          }
          if (department != null && !department.isEmpty()) {
            device.location.department = department;
          }

          XmlHttpContent content = new XmlHttpContent(nsdict, "mobile_device", device);
          if (debug) {
            OutputStream out = new ByteArrayOutputStream();
            content.writeTo(out);
            System.out.println("content " + out.toString());
          }

          // JSS REST API - use PUT method to update existing object
          HttpRequest updateRequest = factory.buildPutRequest(updateUrl, content);
          HttpResponse updateResponse = updateRequest.execute();
          status = updateResponse.getStatusCode();
          if (status < 400) {
            success = true;
          }
        } catch (Exception ex1) {
          System.out.println("Exception! " + ex1.getMessage());
        }
        if (debug) {
          System.out.println("update " + id + ", status " + String.valueOf(status));
        }
      }
    }
    return success;
  }