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:it.govpay.web.handler.MessageLoggingHandlerUtils.java
@SuppressWarnings("unchecked") public static boolean logToSystemOut(SOAPMessageContext smc, String tipoServizio, int versioneServizio, Logger log) {/*from w ww . j a va 2 s . c om*/ Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); GpContext ctx = null; Message msg = new Message(); SOAPMessage message = smc.getMessage(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); msg.setContent(baos.toByteArray()); } catch (Exception e) { log.error("Exception in handler: " + e); } Map<String, List<String>> httpHeaders = null; if (outboundProperty.booleanValue()) { ctx = GpThreadLocal.get(); httpHeaders = (Map<String, List<String>>) smc.get(MessageContext.HTTP_RESPONSE_HEADERS); msg.setType(MessageType.RESPONSE_OUT); ctx.getContext().getResponse().setOutDate(new Date()); ctx.getContext().getResponse().setOutSize(Long.valueOf(baos.size())); } else { try { ctx = new GpContext(smc, tipoServizio, versioneServizio); ThreadContext.put("op", ctx.getTransactionId()); GpThreadLocal.set(ctx); } catch (Exception e) { log.error(e.getMessage(), e); return false; } httpHeaders = (Map<String, List<String>>) smc.get(MessageContext.HTTP_REQUEST_HEADERS); msg.setType(MessageType.REQUEST_IN); msg.setContentType(((HttpServletRequest) smc.get(MessageContext.SERVLET_REQUEST)).getContentType()); ctx.getContext().getRequest().setInDate(new Date()); ctx.getContext().getRequest().setInSize(Long.valueOf(baos.size())); } if (httpHeaders != null) { for (String key : httpHeaders.keySet()) { if (httpHeaders.get(key) != null) { if (key == null) msg.addHeader(new Property("Status-line", httpHeaders.get(key).get(0))); else if (httpHeaders.get(key).size() == 1) msg.addHeader(new Property(key, httpHeaders.get(key).get(0))); else msg.addHeader(new Property(key, ArrayUtils.toString(httpHeaders.get(key)))); } } } ctx.log(msg); return true; }
From source file:com.usefullc.platform.common.log.LogHandlerInterceptor.java
@Override public void beforeHandler(ActionHandler actionHandler) { if (!this.monitor) { // ? return;/*from w w w . j a v a 2 s . c om*/ } Long userId = OnlineUserManager.getUserId(); if (userId == null) { // return; } HttpServletRequest request = actionHandler.getRequest(); String url = request.getRequestURI(); // ? if (!logInfoRemoteService.canRecord(url)) { return; } // LogInfoDto domain = new LogInfoDto(); domain.setRequestUrl(url); // ?? String cnName = OnlineUserManager.getCnName(); domain.setUserName(cnName); String remoteAddr = request.getRemoteAddr(); domain.setRemoteAddr(remoteAddr); // request headers JSONObject jsonObj = new JSONObject(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerValues = request.getHeaders(headerName); StringBuilder sb = new StringBuilder(); while (headerValues.hasMoreElements()) { sb.append(headerValues.nextElement()); sb.append(","); } if (sb.length() > 0) { sb.substring(0, sb.length() - 1); } jsonObj.put(headerName, sb.toString()); } domain.setRequestHeader(jsonObj.toString()); // request data jsonObj = new JSONObject(); Map<String, String[]> paramMap = request.getParameterMap(); if (MapUtils.isNotEmpty(paramMap)) { Set<Entry<String, String[]>> set = paramMap.entrySet(); for (Entry<String, String[]> entry : set) { String key = entry.getKey(); String value = ArrayUtils.toString(entry.getValue()); jsonObj.put(key, value); } } domain.setRequestData(jsonObj.toString()); threadLocal.set(domain); }
From source file:mitm.common.mail.MailUtilsTest.java
@Test public void testSaveNewMessage() throws IOException, MessagingException { File outputFile = File.createTempFile("mailUtilsTest", ".eml"); outputFile.deleteOnExit();// ww w . j a va2 s. c o m MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") }); message.addRecipients(RecipientType.TO, "recipient@example.com"); message.setContent("test body", "text/plain"); message.saveChanges(); MailUtils.writeMessage(message, new FileOutputStream(outputFile)); MimeMessage loadedMessage = MailUtils.loadMessage(outputFile); String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO)); assertEquals("{recipient@example.com}", recipients); String from = ArrayUtils.toString(loadedMessage.getFrom()); assertEquals("{test@example.com}", from); }
From source file:gda.device.enumpositioner.EpicsValve.java
@Override public void rawAsynchronousMoveTo(Object position) throws DeviceException { try {/*from w w w.j a va 2 s.c o m*/ // check top ensure a correct string has been supplied if (positions.contains(position.toString())) { controller.caput(currentPositionChnl, position.toString(), channelManager); return; } // if get here then wrong position name supplied throw new DeviceException(getName() + ": demand position " + position.toString() + " not acceptable. Should be one of: " + ArrayUtils.toString(positions)); } catch (Throwable th) { throw new DeviceException("failed to move to" + position.toString(), th); } }
From source file:com.taobao.itest.listener.ITestSpringContextListener.java
private String[] retrieveLocations(Class<?> clazz) { Class<ITestSpringContext> annotationType = ITestSpringContext.class; @SuppressWarnings("rawtypes") List<Class> classesAnnotationDeclared = AnnotationUtil.findClassesAnnotationDeclaredWith(clazz, annotationType);//from www. j ava2 s . c o m List<String> locationsList = new ArrayList<String>(); for (Class<?> classAnnotationDeclared : classesAnnotationDeclared) { ITestSpringContext iTestSpringContext = classAnnotationDeclared.getAnnotation(annotationType); String[] value = iTestSpringContext.value(); String[] locations = iTestSpringContext.locations(); if (!ArrayUtils.isEmpty(value) && !ArrayUtils.isEmpty(locations)) { String msg = String.format( "Test class [%s] has been configured with @ITestSpringContext' 'value' [%s] and 'locations' [%s] attributes. Use one or the other, but not both.", classAnnotationDeclared, ArrayUtils.toString(value), ArrayUtils.toString(locations)); throw new RuntimeException(msg); } else if (!ArrayUtils.isEmpty(value)) { locations = value; } if (locations != null) { locationsList.addAll(0, Arrays.<String>asList(locations)); } if (!iTestSpringContext.inheritLocations()) { break; } } return locationsList.toArray(new String[locationsList.size()]); }
From source file:edu.cornell.med.icb.R.RUtils.java
/** * Can be used to start a rserve instance. * @param threadPool The ExecutorService used to start the Rserve process * @param rServeCommand Full path to command used to start Rserve process * @param host Host where the command should be sent * @param port Port number where the command should be sent * @param username Username to send to the server if authentication is required * @param password Password to send to the server if authentication is required * @return The return value from the Rserve instance *///from w w w .ja va 2 s . c o m static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host, final int port, final String username, final String password) { if (LOG.isInfoEnabled()) { LOG.info("Attempting to start Rserve on " + host + ":" + port); } return threadPool.submit(new Callable<Integer>() { public Integer call() throws IOException { final List<String> commands = new ArrayList<String>(); // if the host is not local, use ssh to exec the command if (!"localhost".equals(host) && !"127.0.0.1".equals(host) && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) { commands.add("ssh"); commands.add(host); } // TODO - this will fail when spaces are in the the path to the executable CollectionUtils.addAll(commands, rServeCommand.split(" ")); commands.add("--RS-port"); commands.add(Integer.toString(port)); final String[] command = commands.toArray(new String[commands.size()]); LOG.debug(ArrayUtils.toString(commands)); final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); final Process process = builder.start(); BufferedReader br = null; try { final InputStream is = process.getInputStream(); final InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { if (LOG.isDebugEnabled()) { LOG.debug(host + ":" + port + "> " + line); } } process.waitFor(); if (LOG.isInfoEnabled()) { LOG.info("Rserve on " + host + ":" + port + " terminated"); } } catch (InterruptedException e) { LOG.error("Interrupted!", e); process.destroy(); Thread.currentThread().interrupt(); } finally { IOUtils.closeQuietly(br); } final int exitValue = process.exitValue(); if (LOG.isInfoEnabled()) { LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue); } return exitValue; } }); }
From source file:com.laxser.blitz.web.impl.module.ModuleAppContext.java
/** ?messageSourceRose? */ public static void registerMessageSourceIfNecessary(BeanDefinitionRegistry registry, String[] messageBaseNames) { if (!ArrayUtils.contains(registry.getBeanDefinitionNames(), MESSAGE_SOURCE_BEAN_NAME)) { logger.debug("registerMessageSource " + ArrayUtils.toString(messageBaseNames)); GenericBeanDefinition messageSource = new GenericBeanDefinition(); messageSource.setBeanClass(ReloadableResourceBundleMessageSource.class); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("useCodeAsDefaultMessage", true); propertyValues.addPropertyValue("defaultEncoding", "UTF-8"); // propertiesUTF-8?ISO-9959-1 propertyValues.addPropertyValue("cacheSeconds", 60); // hardcode! 60 propertyValues.addPropertyValue("basenames", messageBaseNames); messageSource.setPropertyValues(propertyValues); registry.registerBeanDefinition(MESSAGE_SOURCE_BEAN_NAME, messageSource); }/* w ww.ja v a 2s . c om*/ }
From source file:com.jaspersoft.jasperserver.repository.test.RepositoryServiceDependentResourcesTest.java
@Test public void shouldFindFirstFiveDependantReportsForDataSource() { assertNotNull("RepositoryService service is not wired.", getRepositoryService()); assertNotNull("SearchCriteriaFactory service is not wired.", searchCriteriaFactory); String uri = "/datasources/JServerJNDIDS"; List<ResourceLookup> resources = getRepositoryService().getDependentResources(null, uri, searchCriteriaFactory, 0, 5); assertEquals("Should find 5 dependant resources.", 5, resources.size()); assertEquals("All resources should be lookup's.", 5, CollectionUtils.countMatches(resources, PredicateUtils.instanceofPredicate(ResourceLookup.class))); String sortOrder = ArrayUtils.toString( CollectionUtils.collect(resources, TransformerUtils.invokerTransformer("getURIString")).toArray()); assertEquals("Resources should be sorted in order.", expectedOrderForTopFive, sortOrder); }
From source file:ch.ledcom.maven.sitespeed.analyzer.SiteSpeedAnalyzer.java
public Document analyze(URL url) throws IOException, JDOMException, InterruptedException { InputStream in = null;/*from w ww.j av a 2 s. co m*/ boolean threw = true; try { log.info("Starting analysis of [" + url.toExternalForm() + "]"); List<String> command = constructCommand(url); logCommand(command); ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(); Process p = pb.start(); // FIXME: we need to filter the InputStream as it seems we can get // content outside of the XML document (see sitespeed.io) in = p.getInputStream(); byte[] result = IOUtils.toByteArray(in); log.info("Result of analysis:" + ArrayUtils.toString(result)); Document doc = docBuilder.get().build(new ByteArrayInputStream(result)); log.info(XmlPrettyPrinter.prettyPrint(doc)); int status = p.waitFor(); if (status != 0) { throw new RuntimeException("PhantomJS returned with status [" + status + "]"); } threw = false; return doc; } finally { Closeables.close(in, threw); } }
From source file:com.athena.chameleon.engine.policy.Policy.java
@Override public String toString() { StringBuilder sb = new StringBuilder("unzipDir : ").append(unzipDir).append("\n") .append("defaultEncoding : ").append(defaultEncoding).append("\n") .append("enEncoding : " + enEncoding).append("\n").append("suffix : ") .append(ArrayUtils.toString(suffix)).append("\n").append("webSphere : ") .append(ArrayUtils.toString(webSphere)).append("\n").append("weblogic : ") .append(ArrayUtils.toString(weblogic)).append("\n").append("jeus : ") .append(ArrayUtils.toString(jeus)).append("others : ").append(ArrayUtils.toString(others)) .append("\n").append("pattern : ").append(pattern.toString()).append("etcPattern : ") .append(etcPattern.toString()); return sb.toString(); }