List of usage examples for java.lang.reflect InvocationHandler InvocationHandler
InvocationHandler
From source file:org.opencms.jlan.CmsJlanRepository.java
/** * Creates a dynamic proxy for a disk interface which logs the method calls and their results.<p> * * @param impl the disk interface for which a logging proxy should be created * * @return the dynamic proxy which logs methods calls *///from w w w .ja v a2 s . co m public static DiskInterface createLoggingProxy(final DiskInterface impl) { return (DiskInterface) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { DiskInterface.class }, new InvocationHandler() { @SuppressWarnings("synthetic-access") public Object invoke(Object target, Method method, Object[] params) throws Throwable { // Just to be on the safe side performance-wise, we only log the parameters/result // if the info channel is enabled if (LOG.isInfoEnabled()) { List<String> paramStrings = new ArrayList<String>(); for (Object param : params) { paramStrings.add("" + param); } String paramsAsString = CmsStringUtil.listAsString(paramStrings, ", "); LOG.info("Call: " + method.getName() + " " + paramsAsString); } try { Object result = method.invoke(impl, params); if (LOG.isInfoEnabled()) { LOG.info("Returned from " + method.getName() + ": " + result); } return result; } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if ((cause != null) && (cause instanceof CmsSilentWrapperException)) { // not really an error LOG.info(cause.getCause().getLocalizedMessage(), cause.getCause()); } else { LOG.error(e.getLocalizedMessage(), e); } throw e.getCause(); } } }); }
From source file:org.bsc.maven.plugin.confluence.PegdownParse.java
Visitor newVisitor(final int start_indent) { final ClassLoader cl = PegdownParse.class.getClassLoader(); final InvocationHandler handler = new InvocationHandler() { int indent; {/*from www . ja va2s .c o m*/ this.indent = start_indent; } protected void visitChildren(Object proxy, Node node) { for (Node child : node.getChildren()) { child.accept((Visitor) proxy); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { for (int i = 0; i < indent; ++i) System.out.print('\t'); final Object n = args[0]; System.out.printf("[%s]", n); IfContext.iF(n, StrongEmphSuperNode.class, sesn).elseIf(n, ExpLinkNode.class, eln) .elseIf(n, AnchorLinkNode.class, aln).elseIf(n, VerbatimNode.class, vln) .elseIf(n, RefLinkNode.class, rln) ; System.out.println(); if (n instanceof Node) { ++indent; visitChildren(proxy, (Node) args[0]); --indent; } return null; } }; final Visitor proxy = (Visitor) Proxy.newProxyInstance(cl, new Class[] { Visitor.class }, handler); return proxy; }
From source file:com.github.mybatis.spring.MapperFactoryBean.java
/** * {@inheritDoc}//from ww w. j ava2 s . com */ public T getObject() throws Exception { final T mapper = getSqlSession().getMapper(this.mapperInterface); return Reflection.newProxy(this.mapperInterface, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long start = System.currentTimeMillis(); TraceContext rpc = TraceContext.get(); String parameters = getParameters(args); String iface = MapperFactoryBean.this.iface; rpc.reset().inc().setStamp(start).setIface(iface).setMethod(method.getName()) .setParameter(parameters); try { return method.invoke(mapper, args); } catch (Exception e) { rpc.setFail(true).setReason(e.getMessage()); LOG.error("{}.{}({})", iface, method.getName(), parameters, e); throw e; } finally { rpc.setCost(System.currentTimeMillis() - start); TraceRecorder.getInstance().post(rpc.copy()); } } }); }
From source file:org.pentaho.hadoop.shim.HadoopConfiguration.java
private HadoopShim getWrappedHadoopShim() { return (HadoopShim) Proxy.newProxyInstance(hadoopShim.getClass().getClassLoader(), new Class[] { HadoopShim.class }, new InvocationHandler() { @Override/* www.ja v a 2 s . c o m*/ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("submitJob")) { process((Configuration) args[0]); } return method.invoke(hadoopShim, args); } }); }
From source file:org.apache.blur.thrift.AsyncClientPool.java
/** * Gets a client instance that implements the AsyncIface interface that * connects to the given connection string. * //www . ja v a 2 s .c o m * @param <T> * @param asyncIfaceClass * the AsyncIface interface to pool. * @param connectionStr * the connection string. * @return the client instance. */ @SuppressWarnings("unchecked") public <T> T getClient(final Class<T> asyncIfaceClass, final String connectionStr) { List<Connection> connections = BlurClientManager.getConnections(connectionStr); Collections.shuffle(connections, random); // randomness ftw final Connection connection = connections.get(0); return (T) Proxy.newProxyInstance(asyncIfaceClass.getClassLoader(), new Class[] { asyncIfaceClass }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return execute(new AsyncCall(asyncIfaceClass, method, args, connection)); } }); }
From source file:org.kuali.rice.kns.web.struts.form.pojo.PojoPluginTest.java
@Test public void testUndefinedOJBClass() { final Object notAnOjbObject = new HashMap(); // stub out the persistence service PojoPropertyUtilsBean.PersistenceStructureServiceProvider.persistenceStructureService = (PersistenceStructureService) Proxy .newProxyInstance(this.getClass().getClassLoader(), new Class[] { PersistenceStructureService.class }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("listCollectionObjectTypes".equals(method.getName())) { return new HashMap(); }//from w w w .j a va 2s . co m return null; } }); assertNull(new PojoPropertyUtilsBean.PersistenceStructureServiceProvider() .getCollectionItemClass(notAnOjbObject, "abcd")); }
From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java
private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception { if (!ServletFileUpload.isMultipartContent(request)) return request; final Map<String, String> requestParams = new HashMap<String, String>(); List<FileItemStream> listFiles = new ArrayList<FileItemStream>(); // Parse the request ServletFileUpload sfu = new ServletFileUpload(); String characterEncoding = request.getCharacterEncoding(); if (characterEncoding == null) { characterEncoding = "UTF-8"; }//from ww w . ja va 2 s .com sfu.setHeaderEncoding(characterEncoding); FileItemIterator iter = sfu.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream, characterEncoding)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); final byte[] bs = os.toByteArray(); stream.close(); listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { FileItemStream.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("openStream".equals(method.getName())) { return new ByteArrayInputStream(bs); } return method.invoke(item, args); } })); } } } request.setAttribute(FileItemStream.class.getName(), listFiles); Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { HttpServletRequest.class }, new InvocationHandler() { @Override public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable { // we replace getParameter() and getParameterValues() // methods if ("getParameter".equals(arg1.getName())) { String paramName = (String) arg2[0]; return requestParams.get(paramName); } if ("getParameterValues".equals(arg1.getName())) { String paramName = (String) arg2[0]; // normalize name 'key[]' to 'key' if (paramName.endsWith("[]")) paramName = paramName.substring(0, paramName.length() - 2); if (requestParams.containsKey(paramName)) return new String[] { requestParams.get(paramName) }; // if contains key[1], key[2]... int i = 0; List<String> paramValues = new ArrayList<String>(); while (true) { String name2 = String.format("%s[%d]", paramName, i++); if (requestParams.containsKey(name2)) { paramValues.add(requestParams.get(name2)); } else { break; } } return paramValues.isEmpty() ? new String[0] : paramValues.toArray(new String[paramValues.size()]); } return arg1.invoke(request, arg2); } }); return (HttpServletRequest) proxyInstance; }
From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.HtmlReportOutput.java
/** * @see com.jaspersoft.jasperserver.api.engine.scheduling.quartz.Output#getOutput() *//* www . j a v a 2 s.c o m*/ public ReportOutput getOutput(EngineService engineService, ExecutionContext executionContext, String reportUnitURI, DataContainer htmlData, JRHyperlinkProducerFactory hyperlinkProducerFactory, RepositoryService repositoryService, JasperPrint jasperPrint, String baseFilename, Locale locale, String characterEncoding) throws JobExecutionException { try { String filename = baseFilename + ".html"; String childrenFolderName = null; if (repositoryService != null) childrenFolderName = repositoryService.getChildrenFolderName(filename); else childrenFolderName = ""; AbstractHtmlExporter exporter = null; if (isForceToUseHTMLExporter()) { // enforce to use grid-base exporter (only use for embedded report in email) exporter = new HtmlExporter(); } else { exporter = HtmlExportUtil.getHtmlExporter(getJasperReportsContext()); } exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, characterEncoding); HttpServletRequest proxy = (HttpServletRequest) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { HttpServletRequest.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; if ("getContextPath".equals(method.getName())) { result = deploymentInformation.getDeploymentURI(); } return result; } }); exporter.setParameter(new JRHtmlExporterParameter("HttpServletRequest"), proxy); boolean close = true; OutputStream htmlDataOut = htmlData.getOutputStream(); try { ReportOutput htmlOutput = new ReportOutput(htmlData, ContentResource.TYPE_HTML, filename); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, htmlDataOut); if (!childrenFolderName.equals("")) { exporter.setImageHandler(new RepoHtmlResourceHandler(htmlOutput, childrenFolderName + "/{0}")); exporter.setResourceHandler(new RepoHtmlResourceHandler(htmlOutput, null)); exporter.setFontHandler(new RepoHtmlResourceHandler(htmlOutput, childrenFolderName + "/{0}")); } else { exporter.setImageHandler(new RepoHtmlResourceHandler(htmlOutput, childrenFolderName + "{0}")); exporter.setResourceHandler(new RepoHtmlResourceHandler(htmlOutput, null)); exporter.setFontHandler(new RepoHtmlResourceHandler(htmlOutput, childrenFolderName + "{0}")); } if (hyperlinkProducerFactory != null) { exporter.setParameter(JRExporterParameter.HYPERLINK_PRODUCER_FACTORY, hyperlinkProducerFactory); } exporter.exportReport(); close = false; htmlDataOut.close(); return htmlOutput; } catch (IOException e) { throw new JSExceptionWrapper(e); } finally { if (close) { try { htmlDataOut.close(); } catch (IOException e) { log.error("Error closing stream", e); } } } } catch (JRException e) { throw new JSExceptionWrapper(e); } }
From source file:com.smartitengineering.cms.spi.impl.events.EventConsumerImpl.java
@Override public void consume(String eventContentType, String eventMessage) { BufferedReader reader = null; try {//from w w w . j a v a 2 s . c om reader = new BufferedReader(new StringReader(eventMessage)); final Type sourceType = Type.valueOf(reader.readLine()); final EventType type = EventType.valueOf(reader.readLine()); if (logger.isDebugEnabled()) { logger.debug("Event source type " + sourceType); logger.debug("Event type " + type); } final StringBuilder idStr = new StringBuilder(""); String line; do { line = reader.readLine(); if (StringUtils.isNotBlank(line)) { idStr.append(line).append('\n'); } } while (StringUtils.isNotBlank(line)); final byte[] decodedIdString = Base64.decodeBase64(idStr.toString()); final String idString = org.apache.commons.codec.binary.StringUtils.newStringUtf8(decodedIdString); if (logger.isInfoEnabled()) { logger.info("ID String from message " + idString); } switch (sourceType) { case CONTENT: { final ContentId contentId; final String[] idParams = idString.split("\n"); if (idParams.length < 3) { logger.warn( "Insufficient params for forming content id in id string. Thus ignoring the following message " + idString); return; } final byte[] contentIdBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(idParams[2]); final WorkspaceId workspaceId = SmartContentAPI.getInstance().getWorkspaceApi() .createWorkspaceId(idParams[0], idParams[1]); contentId = SmartContentAPI.getInstance().getContentLoader().createContentId(workspaceId, contentIdBytes); Content content = contentId.getContent(); if (content == null && EventType.DELETE.equals(type)) { content = (Content) Proxy.newProxyInstance(Content.class.getClassLoader(), new Class[] { Content.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getContentId")) { return contentId; } return null; } }); } if (content == null) { logger.warn("No Content for event thus ignoring it - " + idString); return; } final Event<Content> event = SmartContentAPI.getInstance().getEventRegistrar() .<Content>createEvent(type, sourceType, content); contentListener.notify(event); } break; case CONTENT_TYPE: { final ContentTypeId typeId; final String[] idParams = idString.split("\n"); if (idParams.length < 4) { logger.error( "Insufficient params for forming content type id in id string. Thus ignoring the following message " + idString); return; } final WorkspaceId workspaceId = SmartContentAPI.getInstance().getWorkspaceApi() .createWorkspaceId(idParams[0], idParams[1]); typeId = SmartContentAPI.getInstance().getContentTypeLoader().createContentTypeId(workspaceId, idParams[2], idParams[3]); ContentType contentType = typeId.getContentType(); if (contentType == null && EventType.DELETE.equals(type)) { contentType = (ContentType) Proxy.newProxyInstance(ContentType.class.getClassLoader(), new Class[] { ContentType.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getContentTypeID")) { return typeId; } return null; } }); } if (contentType == null) { logger.warn("No Content Type for event thus ignoring it - " + idString); return; } final Event<ContentType> event = SmartContentAPI.getInstance().getEventRegistrar() .<ContentType>createEvent(type, sourceType, contentType); contentTypeListener.notify(event); } break; case SEQUENCE: { final SequenceId seqId; final String[] idParams = idString.split("\n"); if (idParams.length < 3) { logger.error( "Insufficient params for forming sequence id in id string. Thus ignoring the following message " + idString); return; } final WorkspaceId workspaceId = SmartContentAPI.getInstance().getWorkspaceApi() .createWorkspaceId(idParams[0], idParams[1]); seqId = SmartContentAPI.getInstance().getWorkspaceApi().createSequenceId(workspaceId, idParams[2]); Sequence sequence = seqId.getSequence(); if (sequence == null && EventType.DELETE.equals(type)) { sequence = (Sequence) Proxy.newProxyInstance(Sequence.class.getClassLoader(), new Class[] { Sequence.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getSequenceId")) { return seqId; } return null; } }); } if (sequence == null) { logger.warn("No Sequence for event thus ignoring it - " + idString); return; } final Event<Sequence> event = SmartContentAPI.getInstance().getEventRegistrar() .<Sequence>createEvent(type, sourceType, sequence); sequenceListener.notify(event); } break; default: logger.info(new StringBuilder("Ignoring event source type ").append(sourceType).toString()); } } catch (Exception ex) { logger.warn("Could not persist content ID!", ex); throw new RuntimeException(ex); } finally { try { reader.close(); } catch (Exception ex) { logger.warn("Could not close reader!", ex); } } }
From source file:org.hyperic.hq.agent.server.CollectorThread.java
/** proxy used to intercept in order to create stats */ private Runnable getProxy(final Collector collector) { InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ((null == args || args.length == 0) && method.getName().equals("run")) { final long start = now(); Object rtn = method.invoke(collector, args); final long duration = now() - start; statsCollector.addStat(duration, COLLECTOR_THREAD_METRIC_COLLECTED_TIME); return rtn; } else { return method.invoke(collector, args); }/*from w w w . j ava 2 s. c o m*/ } }; return (Runnable) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { Runnable.class }, handler); }