List of usage examples for org.apache.commons.lang ArrayUtils toString
public static String toString(Object array)
Outputs an array as a String, treating null
as an empty array.
From source file:com.rb.ofbiz.test.utils.logging.LoggingCommandProcessor.java
/** * {@inheritDoc}// w ww . j a v a 2 s . c om */ public String[] getStringArray(String commandName, String[] args) { long cmdStartMillis = System.currentTimeMillis(); String[] results; try { results = this.realCommandProcessor.getStringArray(commandName, args); } catch (RuntimeException e) { doExceptionLogging(commandName, args, "", e, cmdStartMillis); throw e; } doLogging(commandName, args, LoggingCommandProcessor.SELENIUM_RC_OK_RESULT_PREFIX_WITH_COMMA + ArrayUtils.toString(results), cmdStartMillis); return results; }
From source file:com.atlassian.plugins.studio.storage.examples.it.TestSuite.java
@ToolkitTest(ignore = true) // not supported by the underlying infrastructure yet protected void constantScopeSaveDeleteForData() throws Exception { String name = getClass().getName() + "-saveDeleteCycle"; StorageFacade facade = storageService.constantNameStorage(name); facade.remove("data"); byte[] data = new byte[] { '3', 4, '7' }; stateTrue("First data access should be null", facade.getText("data") == null); facade.setData("data", data); stateTrue("data key should exist now", facade.exists("data")); stateTrue("[data]=" + ArrayUtils.toString(data), ArrayUtils.toString(facade.getText("data")).equals(ArrayUtils.toString(data))); stateTrue("delete text should work", facade.remove("data")); not("text key should NOT exist now", facade.exists("data")); }
From source file:edu.cornell.med.icb.clustering.TestQTClusterer.java
/** * This test validates that a dataset is clustered correctly using various * different values of thresholds./* ww w . j a v a2s . com*/ */ @Test public void multipleThresholds() { // raw data to test final int[] data = { 1, 2, 3, 3, 2, 1, 42, 43, 4, 6 }; // list of expected results per threshold tested @SuppressWarnings("unchecked") final List<int[]>[] expectedResults = new List[6]; // threshold = 0 ( each instance in it's own cluster ) expectedResults[0] = new ArrayList<int[]>(); // threshold = 0 expectedResults[0] = new ArrayList<int[]>(); expectedResults[0].add(new int[] { 1, 1 }); expectedResults[0].add(new int[] { 2, 2 }); expectedResults[0].add(new int[] { 3, 3 }); expectedResults[0].add(new int[] { 42 }); expectedResults[0].add(new int[] { 43 }); expectedResults[0].add(new int[] { 4 }); expectedResults[0].add(new int[] { 6 }); // threshold = 1 expectedResults[1] = new ArrayList<int[]>(); expectedResults[1].add(new int[] { 1, 1, 2, 2 }); expectedResults[1].add(new int[] { 3, 3, 4 }); expectedResults[1].add(new int[] { 42, 43 }); expectedResults[1].add(new int[] { 6 }); // threshold = 2 expectedResults[2] = new ArrayList<int[]>(); expectedResults[2].add(new int[] { 1, 1, 2, 2, 3, 3 }); expectedResults[2].add(new int[] { 42, 43 }); expectedResults[2].add(new int[] { 4, 6 }); // threshold = 3 expectedResults[3] = new ArrayList<int[]>(); expectedResults[3].add(new int[] { 1, 1, 2, 2, 3, 3, 4 }); expectedResults[3].add(new int[] { 42, 43 }); expectedResults[3].add(new int[] { 6 }); // threshold = 4 (same as 3) expectedResults[4] = new ArrayList<int[]>(expectedResults[3]); // threshold = 5 expectedResults[5] = new ArrayList<int[]>(); expectedResults[5].add(new int[] { 1, 1, 2, 2, 3, 3, 4, 6 }); expectedResults[5].add(new int[] { 42, 43 }); final Clusterer clusterer = new QTClusterer(data.length); // Distance function that returns the difference between instances final SimilarityDistanceCalculator distanceCalculator = new MaxLinkageDistanceCalculator() { public double distance(final int i, final int j) { return Math.abs(data[i] - data[j]); } }; for (int i = 0; i <= 5; i++) { final List<int[]> clusters = clusterer.cluster(distanceCalculator, i); assertNotNull("Cluster at threshold " + i, clusters); LOGGER.debug("Iterative clusters - threshold = " + i); final List<int[]> expectedCluster = expectedResults[i]; assertEquals("Number of clusters don't match at threshold = " + i, expectedCluster.size(), clusters.size()); int j = 0; for (final int[] cluster : clusters) { // convert instance indexes from the cluster to data final int[] result = new int[cluster.length]; for (int k = 0; k < result.length; k++) { result[k] = data[cluster[k]]; } LOGGER.debug(j + ":" + ArrayUtils.toString(result)); final int[] expectedResult = expectedCluster.get(j); assertArrayEquals("Cluster " + j + " with threshold " + i + " does not match expected", expectedResult, result); j++; } } }
From source file:edu.cornell.med.icb.learning.CrossValidation.java
/** * Report the area under the Receiver Operating Characteristic (ROC) curve. * See <a href="http://pages.cs.wisc.edu/~richm/programs/AUC/">http://pages.cs.wisc.edu/~richm/programs/AUC/</a> * * @param decisionValues Larger values indicate better confidence that the instance belongs to class 1. * @param labels Values of -1 or 0 indicate that the instance belongs to class 0, values of 1 indicate that the * instance belongs to class 1. * @return ROC AUC/*from w ww .j av a2 s . c om*/ */ public static double areaUnderRocCurveLOO(final double[] decisionValues, final double[] labels) { if (ArrayUtils.isEmpty(decisionValues) || ArrayUtils.isEmpty(labels)) { throw new IllegalArgumentException("There must be at least 1 label and predition." + " Predictions are empty: " + ArrayUtils.isEmpty(decisionValues) + " Labels are empty: " + ArrayUtils.isEmpty(labels)); } if (decisionValues.length != labels.length) { throw new IllegalArgumentException("number of predictions (" + decisionValues.length + ") must match number of labels (" + labels.length + ")."); } for (int i = 0; i < labels.length; i++) { // for each training example, leave it out: if (labels[i] < 0) { labels[i] = 0; } } if (LOG.isDebugEnabled()) { LOG.debug("decisions: " + ArrayUtils.toString(decisionValues)); } if (LOG.isDebugEnabled()) { LOG.debug("labels: " + ArrayUtils.toString(labels)); } final Double shortCircuitValue = areaUnderRocCurvShortCircuit(decisionValues, labels); if (shortCircuitValue != null) { return shortCircuitValue; } final RConnectionPool connectionPool = RConnectionPool.getInstance(); RConnection connection = null; try { // CALL R ROC connection = connectionPool.borrowConnection(); connection.assign("predictions", decisionValues); connection.assign("labels", labels); // library(ROCR) // predictions <- c(1,1,0,1,1,1,1) // labels <- c(1,1,1,1,1,0,1) // flabels <- factor(labels,c(0,1)) // pred.svm <- prediction(predictions, flabels) // perf.svm <- performance(pred.svm, 'auc') // attr(perf.svm,"y.values")[[1]] final StringBuilder rCommand = new StringBuilder(); rCommand.append("library(ROCR)\n"); rCommand.append("flabels <- factor(labels,c(0,1))\n"); rCommand.append("pred.svm <- prediction(predictions, labels)\n"); rCommand.append("perf.svm <- performance(pred.svm, 'auc')\n"); rCommand.append("attr(perf.svm,\"y.values\")[[1]]"); // attr(perf.rocOutAUC,"y.values")[[1]]\ final REXP expression = connection.eval(rCommand.toString()); final double valueROC_AUC = expression.asDouble(); if (LOG.isDebugEnabled()) { LOG.debug("result from R: " + valueROC_AUC); } return valueROC_AUC; } catch (Exception e) { // connection error or otherwise me LOG.warn("Cannot calculate area under the ROC curve. Make sure Rserve (R server) " + "is configured and running.", e); return Double.NaN; } finally { if (connection != null) { connectionPool.returnConnection(connection); } } }
From source file:eionet.cr.web.action.UploadCSVActionBeanTest.java
/** * Does and tests the file's "upload" step, doing it with or without overwrite, depending on the given boolean. * * @param isOverwrite Overwrite or not./*from w w w . j a va 2 s .c o m*/ * @throws Exception Any sort of error that happens. */ private void doUpload(boolean isOverwrite) throws Exception { // Prepare the servlet context mock + Stripes action bean roundtrip. MockServletContext ctx = createContextMock(); MockRoundtrip trip = new MockRoundtrip(ctx, UploadCSVActionBeanMock.class); // Prepare rich-type (e.g. file bean) request parameters. These will be picked up by MyActionBeanPropertyBinder // that has already been injected into the servlet context mock obtained above. HashMap<String, Object> richTypeRequestParams = new HashMap<String, Object>(); FileBean fileBean = new FileBean(TEST_FILE, "text/plain", TEST_FILE.getName()); richTypeRequestParams.put("fileBean", fileBean); trip.getRequest().setAttribute(RICH_TYPE_REQUEST_PARAMS_ATTR_NAME, richTypeRequestParams); // Prepare simple string-based request parameters. trip.setParameter("folderUri", TEST_FOLDER_URI); trip.setParameter("overwrite", String.valueOf(isOverwrite)); trip.setParameter("fileType", "CSV"); trip.setParameter("fileEncoding", "UTF-8"); // Execute the event. trip.execute("upload"); // Assert the returned HTTP code. UploadCSVActionBean actionBean = trip.getActionBean(UploadCSVActionBeanMock.class); MockHttpServletResponse response = (MockHttpServletResponse) actionBean.getContext().getResponse(); assertEquals(200, response.getStatus()); // Assert that the file was created in CR filestore. File storedFile = FileStore.getByUri(TEST_FILE_URI); assertNotNull("Didn't expect the stored file to be null!", storedFile); long storedFileSize = storedFile.length(); boolean flag = storedFile != null && storedFile.exists() && storedFile.isFile() && TEST_FILE_NAME.equals(storedFile.getName()); assertTrue("Expected an existing stored file with name: " + TEST_FILE_NAME, flag); assertEquals("Expected stored file size to be equal to the uploaded file size", testFileSize, storedFileSize); // Assert existence of various triples about the uploaded file and its parent folder. String[] statement1 = { TEST_FOLDER_URI, Predicates.CR_HAS_FILE, TEST_FILE_URI }; assertTrue("Expected statement: " + ArrayUtils.toString(statement1), hasResourceStatement(statement1)); boolean b = hasLiteralStatement(TEST_FILE_URI, Predicates.CR_BYTE_SIZE, String.valueOf(storedFileSize), XMLSchema.INT); assertTrue("Missing or unexpected value for " + Predicates.CR_BYTE_SIZE, b); String[] statement3 = { TEST_FILE_URI, Predicates.RDF_TYPE, Subjects.CR_TABLE_FILE }; assertTrue("Expected statement: " + ArrayUtils.toString(statement3), hasResourceStatement(statement3)); String[] statement4 = { TEST_FILE_URI, Predicates.CR_MEDIA_TYPE, "CSV" }; assertTrue("Expected statement: " + ArrayUtils.toString(statement4), hasLiteralStatement(statement4)); String[] statement5 = { TEST_FILE_URI, Predicates.CR_LAST_MODIFIED, null }; assertTrue("Expected statement: " + ArrayUtils.toString(statement5), hasLiteralStatement(statement5)); SubjectDTO testFileSubject = DAOFactory.get().getDao(HelperDAO.class).getSubject(TEST_FILE_URI); assertNotNull("Expected existing subject for " + TEST_FILE_URI, testFileSubject); ObjectDTO byteSizeLiteral = testFileSubject.getObject(Predicates.CR_BYTE_SIZE); assertNotNull("Expected a literal for " + Predicates.CR_BYTE_SIZE, byteSizeLiteral); URI datatype = byteSizeLiteral.getDatatype(); assertNotNull("Expected a datatype for the value of " + Predicates.CR_BYTE_SIZE, datatype); assertEquals("Unexpected datatype", XMLSchema.INT.stringValue(), datatype.stringValue()); }
From source file:edu.mssm.crover.tables.writers.TestLibSVMWriter.java
@Test public void testAUC() { final double[] decisions = new double[2000]; final double[] labels = new double[2000]; RandomEngine random = new MersenneTwister(21); for (int i = 0; i < decisions.length; i++) { decisions[i] = random.nextDouble() * 2 - 1; if (decisions[i] < 0) { decisions[i] = 0;//from w ww . j a va 2s. c o m } labels[i] = random.nextDouble() > 0.5 ? 1 : 0; } // System.out.println("decisions: " + ArrayUtils.toString(decisions)); // System.out.println("labels: " + ArrayUtils.toString(labels)); final double auc = LibSVMWriter.areaUnderRocCurveLOO(decisions, labels); assertEquals("random AUC must be about 0.5", 1, Math.round(auc * 2)); // almost perfect predictions: final double[] newDecisions = new double[2000]; final double[] almostPerfectLabels = new double[2000]; random = new MersenneTwister(21); for (int i = 0; i < newDecisions.length; i++) { newDecisions[i] = random.nextDouble() * 2 - 1; if (newDecisions[i] < 0) { newDecisions[i] = 0; } almostPerfectLabels[i] = newDecisions[i] > 0 ? 1 : (random.nextDouble() > 0.9 ? 1 : 0); } System.out.println("decisions: " + ArrayUtils.toString(newDecisions)); System.out.println("labels: " + ArrayUtils.toString(almostPerfectLabels)); final double almostPerfectAUC = LibSVMWriter.areaUnderRocCurveLOO(newDecisions, almostPerfectLabels); assertEquals("random AUC must be about 0.96", 96, Math.round(almostPerfectAUC * 100)); for (int i = 0; i < newDecisions.length; i++) { almostPerfectLabels[i] = newDecisions[i] > 0 ? 1 : 0; // perfect predictions. } final double perfectAUC = LibSVMWriter.areaUnderRocCurveLOO(newDecisions, almostPerfectLabels); assertEquals("Perfect AUC must be about 1.0", 100, Math.round(perfectAUC * 100)); }
From source file:it.govpay.core.utils.client.BasicClient.java
private byte[] send(boolean soap, String azione, JAXBElement<?> body, Object header, boolean isAzioneInUrl) throws ClientException { // Creazione Connessione int responseCode; HttpURLConnection connection = null; byte[] msg = null; GpContext ctx = GpThreadLocal.get(); String urlString = url.toExternalForm(); if (isAzioneInUrl) { if (!urlString.endsWith("/")) urlString = urlString.concat("/"); try {/*from w ww.j a v a2s . c o m*/ url = new URL(urlString.concat(azione)); } catch (MalformedURLException e) { throw new ClientException("Url di connessione malformata: " + urlString.concat(azione), e); } } try { Message requestMsg = new Message(); requestMsg.setType(MessageType.REQUEST_OUT); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (soap) { connection.setRequestProperty("SOAPAction", "\"" + azione + "\""); requestMsg.addHeader(new Property("SOAPAction", "\"" + azione + "\"")); } requestMsg.setContentType("text/xml"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setRequestMethod("POST"); // Imposta Contesto SSL se attivo if (sslContext != null) { HttpsURLConnection httpsConn = (HttpsURLConnection) connection; httpsConn.setSSLSocketFactory(sslContext.getSocketFactory()); HostNameVerifierDisabled disabilitato = new HostNameVerifierDisabled(); httpsConn.setHostnameVerifier(disabilitato); } // Imposta l'autenticazione HTTP Basic se attiva if (ishttpBasicEnabled) { Base64 base = new Base64(); String encoding = new String(base.encode((httpBasicUser + ":" + httpBasicPassword).getBytes())); connection.setRequestProperty("Authorization", "Basic " + encoding); requestMsg.addHeader(new Property("Authorization", "Basic " + encoding)); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (soap) { SOAPUtils.writeMessage(body, header, baos); } else { JaxbUtils.marshal(body, baos); } ctx.getIntegrationCtx().setMsg(baos.toByteArray()); invokeOutHandlers(); if (log.getLevel().isMoreSpecificThan(Level.TRACE)) { StringBuffer sb = new StringBuffer(); for (String key : connection.getRequestProperties().keySet()) { sb.append("\n\t" + key + ": " + connection.getRequestProperties().get(key)); } sb.append("\n" + new String(ctx.getIntegrationCtx().getMsg())); log.trace(sb.toString()); } requestMsg.setContent(ctx.getIntegrationCtx().getMsg()); ctx.getContext().getRequest().setOutDate(new Date()); ctx.getContext().getRequest().setOutSize(Long.valueOf(ctx.getIntegrationCtx().getMsg().length)); ctx.log(requestMsg); connection.getOutputStream().write(ctx.getIntegrationCtx().getMsg()); } catch (Exception e) { throw new ClientException(e); } try { responseCode = connection.getResponseCode(); ctx.getTransaction().getServer().setTransportCode(Integer.toString(responseCode)); } catch (Exception e) { throw new ClientException(e); } Message responseMsg = new Message(); responseMsg.setType(MessageType.RESPONSE_IN); for (String key : connection.getHeaderFields().keySet()) { if (connection.getHeaderFields().get(key) != null) { if (key == null) responseMsg .addHeader(new Property("Status-line", connection.getHeaderFields().get(key).get(0))); else if (connection.getHeaderFields().get(key).size() == 1) responseMsg.addHeader(new Property(key, connection.getHeaderFields().get(key).get(0))); else responseMsg.addHeader( new Property(key, ArrayUtils.toString(connection.getHeaderFields().get(key)))); } } try { if (responseCode < 300) { try { if (connection.getInputStream() == null) { return null; } msg = connection.getInputStream() != null ? IOUtils.toByteArray(connection.getInputStream()) : new byte[] {}; if (msg.length > 0) responseMsg.setContent(msg); return msg; } catch (Exception e) { throw new ClientException("Messaggio di risposta non valido", e); } } else { try { msg = connection.getErrorStream() != null ? IOUtils.toByteArray(connection.getErrorStream()) : new byte[] {}; responseMsg.setContent(msg); } catch (IOException e) { msg = ("Impossibile serializzare l'ErrorStream della risposta: " + e).getBytes(); } finally { log.warn("Errore nell'invocazione del Nodo dei Pagamenti [HTTP Response Code " + responseCode + "]\nRisposta: " + new String(msg)); } throw new ClientException("Ricevuto [HTTP " + responseCode + "]"); } } finally { if (responseMsg != null) { ctx.getContext().getResponse().setInDate(new Date()); ctx.getContext().getResponse().setInSize((long) responseMsg.getContent().length); ctx.log(responseMsg); } if (log.getLevel().isMoreSpecificThan(Level.TRACE) && connection != null && connection.getHeaderFields() != null) { StringBuffer sb = new StringBuffer(); for (String key : connection.getHeaderFields().keySet()) { sb.append("\n\t" + key + ": " + connection.getHeaderField(key)); } sb.append("\n" + new String(msg)); log.trace(sb.toString()); } } }
From source file:edu.cornell.med.icb.clustering.TestMCLClusterer.java
/** * This test validates that a dataset is clustered correctly using various * different values of thresholds.//from w w w. j av a 2 s.c om */ @Test public void multipleThresholds() { // raw data to test final int[] data = { 1, 2, 3, 3, 2, 1, 42, 43, 4, 6 }; // list of expected results per threshold tested @SuppressWarnings("unchecked") final List<int[]>[] expectedResults = new List[6]; // threshold = 0 ( each instance in it's own cluster ) expectedResults[0] = new ArrayList<int[]>(); // threshold = 0 expectedResults[0] = new ArrayList<int[]>(); expectedResults[0].add(new int[] { 1, 1 }); expectedResults[0].add(new int[] { 2, 2 }); expectedResults[0].add(new int[] { 3, 3 }); expectedResults[0].add(new int[] { 42 }); expectedResults[0].add(new int[] { 43 }); expectedResults[0].add(new int[] { 4 }); expectedResults[0].add(new int[] { 6 }); // threshold = 1 expectedResults[1] = new ArrayList<int[]>(); expectedResults[1].add(new int[] { 1, 2, 2, 1, 3, 3, 4 }); expectedResults[1].add(new int[] { 42, 43 }); expectedResults[1].add(new int[] { 6 }); // threshold = 2 expectedResults[2] = new ArrayList<int[]>(); expectedResults[2].add(new int[] { 1, 2, 3, 3, 2, 1, 4, 6 }); expectedResults[2].add(new int[] { 42, 43 }); final Clusterer clusterer = new MCLClusterer(data.length); // Distance function that returns the difference between instances final SimilarityDistanceCalculator distanceCalculator = new MaxLinkageDistanceCalculator() { public double distance(final int i, final int j) { return Math.abs(data[i] - data[j]); } }; for (int i = 0; i <= 2; i++) { final List<int[]> clusters = clusterer.cluster(distanceCalculator, i); assertNotNull("Cluster at threshold " + i, clusters); LOGGER.debug("Iterative clusters - threshold = " + i); final List<int[]> expectedCluster = expectedResults[i]; assertEquals("Number of clusters don't match at threshold = " + i, expectedCluster.size(), clusters.size()); int j = 0; for (final int[] cluster : clusters) { // convert instance indexes from the cluster to data final int[] result = new int[cluster.length]; for (int k = 0; k < result.length; k++) { result[k] = data[cluster[k]]; } LOGGER.debug(j + ":" + ArrayUtils.toString(result)); final int[] expectedResult = expectedCluster.get(j); assertArrayEquals("Cluster " + j + " with threshold " + i + " does not match expected", expectedResult, result); j++; } } }
From source file:gov.redhawk.ide.internal.ui.event.EventViewerLabelProvider.java
private String toString(DataType[] properties) { StringBuilder retVal = new StringBuilder(); for (DataType t : properties) { retVal.append(t.id);/* w w w . j a v a 2 s . c o m*/ retVal.append(" = "); Object value = AnyUtils.convertAny(t.value); if (value instanceof DataType[]) { retVal.append("{\n"); retVal.append(toString((DataType[]) value)); retVal.append("}"); } else if (value.getClass().isArray()) { retVal.append(ArrayUtils.toString(value)); } else { retVal.append(value); } retVal.append("\n"); } return retVal.toString(); }
From source file:edu.cornell.med.icb.clustering.TestQTClusterer.java
/** * A test that uses a clusters words of equal length together. *//*from w w w . j a v a2 s.c o m*/ @Test public void clusterWordsInAString() { final String text = "Four score and seven years ago our fathers brought forth on this" + " continent a new nation conceived in liberty and dedicated to the proposition" + " that all men are created equal"; final List<String[]> expectedResults = new ArrayList<String[]>(); expectedResults.add(new String[] { "and", "ago", "our", "new", "and", "the", "all", "men", "are" }); expectedResults.add(new String[] { "score", "seven", "years", "forth", "equal" }); expectedResults.add(new String[] { "fathers", "brought", "liberty", "created" }); expectedResults.add(new String[] { "Four", "this", "that" }); expectedResults.add(new String[] { "on", "in", "to" }); expectedResults.add(new String[] { "continent", "conceived", "dedicated" }); expectedResults.add(new String[] { "a" }); expectedResults.add(new String[] { "nation" }); expectedResults.add(new String[] { "proposition" }); // break the text up into an array of individual words final String[] words = text.split(" "); // create a distance calculator that returns the difference in size between the two words final SimilarityDistanceCalculator distanceCalculator = new MaxLinkageDistanceCalculator() { public double distance(final int i, final int j) { return Math.abs(words[i].length() - words[j].length()); } }; // and cluster the words into groups according to their size final Clusterer clusterer = new QTClusterer(words.length); final List<int[]> clusters = clusterer.cluster(distanceCalculator, 0); assertEquals("Number of clusters don't match", expectedResults.size(), clusters.size()); int j = 0; for (final int[] cluster : clusters) { // convert instance indexes from the cluster to source data final String[] result = new String[cluster.length]; for (int k = 0; k < result.length; k++) { result[k] = words[cluster[k]]; } LOGGER.debug(ArrayUtils.toString(cluster)); LOGGER.debug(ArrayUtils.toString(result)); assertArrayEquals("Cluster " + j + " does not match expected", expectedResults.get(j), result); j++; } }