I'll preface this by saying "I have no idea what I'm doing" with java, let alone ehcache, but I'm trying to learn.
That said, I have this code I've written that ran fine until I added the ehcache stuff. I had been simply writing to and reading from files, which worked fine but slow, so I'm trying to speed things up by using cache instead.
When I run my program, I get the following error, and I don't understand what it's telling me is wrong:
Exception in thread "Connect thread - [6, 5]."
java.lang.NoClassDefFoundError: org.ehcache.CacheManagerBuilder
at com.ibm.tpf.internal.ZSTATEngine.doFilter(ZSTATEngine.java:24)
at com.ibm.tpf.etos.filter.FilterFramework.filterMessage(FilterFramework.java:229)
at com.ibm.tpf.etos.api.APIFramework.addMessage(APIFramework.java:304)
at com.ibm.tpf.etos.comm.ETOSConnection.addMessage(ETOSConnection.java:765)
at com.ibm.tpf.etos.comm.ETOSModel._connect(ETOSModel.java:528)
at com.ibm.tpf.etos.comm.ETOSModel$ConnectThread.run(ETOSModel.java:706)
Caused by: java.lang.NoClassDefFoundError:
org.ehcache.CacheMangerBuilder
at java.net.URLClassLoader.findClass(URLClassLoader.java:496)
at java.lang.ClassLoader.loadClass(ClassLoader.java:631)
at java.lang.ClassLoader.loadClass(ClassLoader.java:597)
... 6 more
I tried to mimic the cache code found on the ehcache 3.0 documentation page... but I must've done something horribly wrong. Anyone mind taking a look?
package com.ibm.tpf.internal;
import java.awt.Color;
import java.io.File;
import org.ehcache.*;
import org.ehcache.config.CacheConfigurationBuilder;
import com.ibm.tpf.etos.TPFFilter.*;
import com.ibm.tpf.etos.api.*;
import com.ibm.tpf.etos.filter.*;
public class ZSTATEngine implements ETOSFilterEngine {
FilterFramework fw = null;
String[] names = null;
public ZSTATEngine(FilterFramework filFW, String[] parms) {
super();
this.fw = filFW;
}
public MessageBlock doFilter(MessageBlock msgBlock) throws FilterRuntimeException {
File file = new File("{path omitted}\\FILTER.DAT");
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("csmpCache",CacheConfigurationBuilder.newCacheConfigurationBuilder().buildConfig(Long.class, String.class)).build(false);
cacheManager.init();
Cache<Long, String> csmpCache = cacheManager.getCache("csmpCache", Long.class, String.class);
if(msgBlock.getMsgID().equals("CSMP0097I")) {
csmpCache.put(1L, msgBlock.getMsg()); /* 1L is a key */
msgBlock.setSuppressed(TernarySwitch.ON);
}
else {
if(msgBlock.getFlag() == Constants.ETOS_ONE_MSG || msgBlock.getFlag() == Constants.ETOS_START_MSG) {
if(file.exists() && file.isFile()) {
String csmpValue = csmpCache.get(1L);
MessageBlock mbCSMP = new MessageBlock(csmpValue, Constants.ETOS_ONE_MSG);
mbCSMP.setForeground(Color.BLUE);
msgBlock.setForeground(Color.BLUE);
fw.addFilteredMessage(mbCSMP);
}
}
}
cacheManager.close();
return msgBlock; /* whatever gets returned is what the system prints */
}
private Color ColorStringInterpreter(String colorMsg) throws FilterRuntimeException {
if (colorMsg.toUpperCase().startsWith("TOS")) { /* if it starts with TOS, then we're using color names */
String[] colorParts = colorMsg.split("_",2);
String colorTxt = colorParts[1].toString().trim();
if (colorTxt.toUpperCase() != "NONE") {
Color finalColor = Colors.fromString(colorTxt);
return finalColor;
}
}
else {
String[] colorParts = colorMsg.split("_",3); /* otherwise we're using RGB values */
String sRed = colorParts[0].toString().trim();
String sGreen = colorParts[1].toString().trim();
String sBlue = colorParts[2].toString().trim();
int iRed = Integer.parseInt(sRed);
int iGreen = Integer.parseInt(sGreen);
int iBlue = Integer.parseInt(sBlue);
Color finalColor = new Color (iRed, iGreen, iBlue);
return finalColor;
}
return null;
}
public String getName() {
return null;
}
public void modifyState(Object[] newParams) throws FilterConfigurationException, FilterRuntimeException {
}
public boolean isActive() {
return false;
}
public void shutdown() {
}
}
Thank you for your time
Related
I have a sub-method that builds my FtpInboundFileSynchronizer object. (from a factory object generated out of scope)
private FtpInboundFileSynchronizer createFtpInboundFileSynchronizer(SessionFactory<FTPFile> factory) {
var synchronizer = new FtpInboundFileSynchronizer(factory);
CompositeFileListFilter filter = new CompositeFileListFilter<>();
filter.addFilter(new FtpSimplePatternFileListFilter("filename1.txt"));
filter.addFilter(new FtpSimplePatternFileListFilter("filename2.txt"));
synchronizer.setFilter(filter);
synchronizer.setRemoteDirectory(ftpConfiguration.getPath());
synchronizer.setDeleteRemoteFiles(false);
return synchronizer;
}
However, in this case, I get no files. If I remove one of the FTPSimplePAtternFileListFilter instances, it correctly retrieves that one filename from the FTP server.
The aim is to only download a predefined list of full file names, so both name and extension.
I cannot seem to wrap my head around how to do this. Anyone able to help?
import java.util.Arrays;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.integration.file.filters.AbstractDirectoryAwareFileListFilter;
import org.springframework.util.AntPathMatcher;
/**
* Filter to accept specific file name list.
*/
public class MultiPatternFileListFilter extends AbstractDirectoryAwareFileListFilter<FTPFile> {
private final AntPathMatcher matcher = new AntPathMatcher();
private String[] patterns;
public MultiPatternFileListFilter(String... patterns) {
this.patterns = patterns;
}
#Override
public boolean accept(FTPFile file) {
return alwaysAccept(file) || (file != null && this.matchesAnyPattern(file));
}
#Override
protected boolean isDirectory(FTPFile file) {
return false;
}
protected String getFilename(FTPFile file) {
return (file != null) ? file.getName() : null;
}
private boolean matchesAnyPattern(FTPFile file) {
return Arrays.stream(patterns).anyMatch(pattern -> this.matcher.match(pattern, this.getFilename(file)));
}
}
This solved my problem.
I have been struggling with getting this test to work for awhile, the relevant code executes fine in production my assumption is that it has some additional configuration, lots of searching seems to be related specifically to email handling and additional libraries, I don't want to include anything else, what am I missing to link DataHandler to a relevant way of handling "text/plain" ?
Expected result: DataHandler allows me to stream the input "Value" back into a result.
Reproduce issue with this code:
import java.io.IOException;
import java.io.InputStream;
import javax.activation.CommandInfo;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DataHandlerTest {
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public void test() throws IOException {
printDefaultCommandMap();
DataHandler dh = new DataHandler("Value", "text/plain");
System.out.println("DataHandler commands:");
printDataHandlerCommands(dh);
dh.setCommandMap(CommandMap.getDefaultCommandMap());
System.out.println("DataHandler commands:");
printDataHandlerCommands(dh);
final InputStream in = dh.getInputStream();
String result = new String(IOUtils.toByteArray(in));
System.out.println("Returned String: " + result);
}
private void printDataHandlerCommands(DataHandler dh) {
CommandInfo[] infos = dh.getAllCommands();
printCommands(infos);
}
private void printDefaultCommandMap() {
CommandMap currentMap = CommandMap.getDefaultCommandMap();
String[] mimeTypes = currentMap.getMimeTypes();
System.out.println("Found " + mimeTypes.length + " MIME types.");
for (String mimeType : mimeTypes) {
System.out.println("Commands for: " + mimeType);
printCommands(currentMap.getAllCommands(mimeType));
}
}
private void printCommands(CommandInfo[] infos) {
for (CommandInfo info : infos) {
System.out.println(" Command Class: " +info.getCommandClass());
System.out.println(" Command Name: " + info.getCommandName());
}
}
}
Exception:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME
type text/plain at
javax.activation.DataHandler.getInputStream(DataHandler.java:249)
Help much appreciated, I hope this is a well formed question!
========================
Update 25th February
I have found if i know I stored a String in DataHandler, then I can cast the result to String and return the object that was stored, example:
#Test
public void testGetWithoutStream() throws IOException {
String inputString = "Value";
DataHandler dh = new DataHandler(inputString, "text/plain");
String rawResult = (String) dh.getContent();
assertEquals(inputString, rawResult);
}
But the code under test uses an InputStream, so my 'real' tests still fail when executed locally.
Continuing my investigation and still hoping for someone's assistance/guidance on this one...
Answering my own question for anyone's future reference.
All credit goes to: https://community.oracle.com/thread/1675030?start=0
The principle here is that you need to provide DataHandler a factory that contains a DataContentHandler that will behave as you would like it to for your MIME type, setting this is via a static method that seems to affect all DataHandler instances.
I declared a new class (SystemDataHandlerConfigurator), which has a single public method that creates my factory and provides it the static DataHandler.setDataContentHandlerFactory() function.
My tests now work correctly if I do this before they run:
SystemDataHandlerConfigurator configurator = new SystemDataHandlerConfigurator();
configurator.setupCustomDataContentHandlers();
SystemDataHandlerConfigurator
import java.io.IOException;
import javax.activation.*;
public class SystemDataHandlerConfigurator {
public void setupCustomDataContentHandlers() {
DataHandler.setDataContentHandlerFactory(new CustomDCHFactory());
}
private class CustomDCHFactory implements DataContentHandlerFactory {
#Override
public DataContentHandler createDataContentHandler(String mimeType) {
return new BinaryDataHandler();
}
}
private class BinaryDataHandler implements DataContentHandler {
/** Creates a new instance of BinaryDataHandler */
public BinaryDataHandler() {
}
/** This is the key, it just returns the data uninterpreted. */
public Object getContent(javax.activation.DataSource dataSource) throws java.io.IOException {
return dataSource.getInputStream();
}
public Object getTransferData(java.awt.datatransfer.DataFlavor dataFlavor,
javax.activation.DataSource dataSource)
throws java.awt.datatransfer.UnsupportedFlavorException,
java.io.IOException {
return null;
}
public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors() {
return new java.awt.datatransfer.DataFlavor[0];
}
public void writeTo(Object obj, String mimeType, java.io.OutputStream outputStream)
throws java.io.IOException {
if (mimeType == "text/plain") {
byte[] stringByte = (byte[]) ((String) obj).getBytes("UTF-8");
outputStream.write(stringByte);
}
else {
throw new IOException("Unsupported Data Type: " + mimeType);
}
}
}
}
Is it possible to determine, what client libs have been loaded prior to a component?
We are running multiple site backed by different Javascript frameworks. In order to run a single component across the board, it's not sufficient to just use
<cq:includeClientLib categories="blah"/>
We need to identify the respective framework (i.e. AngularJS, Vanilla, jQuery, blah) in order to facilitate the integration.
We are looking for a decent server side solution.
I haven't actually done this, but it would presumably be possible if you are buffering your output to clone the JspWriter buffer or examine it to see what it already contains. That sounds ugly to me, though. But this is decompiled code for how the cq:includeClientLib tag adds libraries to the output, which may show you how you can read back what was previously written:
package com.adobe.granite.ui.tags;
import com.day.cq.widget.HtmlLibraryManager;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.scripting.jsp.util.TagUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IncludeClientLibraryTag extends TagSupport {
private static final long serialVersionUID = -3068291967085012331L;
private static final Logger log = LoggerFactory.getLogger(IncludeClientLibraryTag.class);
private String categories;
private String js;
private String css;
private String theme;
private Boolean themed;
public IncludeClientLibraryTag() {
}
public void setPageContext(PageContext pageContext) {
super.setPageContext(pageContext);
this.categories = null;
this.js = null;
this.css = null;
this.theme = null;
this.themed = null;
}
public void setCategories(String categories) {
this.categories = categories;
}
public void setJs(String js) {
this.js = js;
}
public void setCss(String css) {
this.css = css;
}
public void setTheme(String theme) {
this.theme = theme;
}
public void setThemed(boolean themed) {
this.themed = Boolean.valueOf(themed);
}
public int doEndTag() throws JspException {
SlingHttpServletRequest request = TagUtil.getRequest(this.pageContext);
HtmlLibraryManager libManager = this.getHtmlLibraryManager(request);
if(libManager == null) {
log.warn("<ui:includeClientLib>: Could not retrieve HtmlLibraryManager service, skipping inclusion.");
return 6;
} else {
JspWriter out = this.pageContext.getOut();
try {
if(this.categories != null) {
libManager.writeIncludes(request, out, toArray(this.categories));
} else if(this.theme != null) {
libManager.writeThemeInclude(request, out, toArray(this.theme));
} else if(this.js != null) {
if(this.themed != null) {
libManager.writeJsInclude(request, out, this.themed.booleanValue(), toArray(this.js));
} else {
libManager.writeJsInclude(request, out, toArray(this.js));
}
} else if(this.css != null) {
if(this.themed != null) {
libManager.writeCssInclude(request, out, this.themed.booleanValue(), toArray(this.css));
} else {
libManager.writeCssInclude(request, out, toArray(this.css));
}
}
return 6;
} catch (IOException var6) {
String libs = this.categories != null?"categories: " + this.categories:(this.theme != null?"theme: " + this.theme:(this.js != null?"js: " + this.js:(this.css != null?"css: " + this.css:"")));
throw new JspException("Could not include client library: " + libs, var6);
}
}
}
private HtmlLibraryManager getHtmlLibraryManager(ServletRequest request) {
SlingBindings bindings = (SlingBindings)request.getAttribute(SlingBindings.class.getName());
return (HtmlLibraryManager)bindings.getSling().getService(HtmlLibraryManager.class);
}
private static String[] toArray(String commaSeparatedList) {
if(commaSeparatedList == null) {
return new String[0];
} else {
String[] split = commaSeparatedList.split(",");
for(int i = 0; i < split.length; ++i) {
split[i] = split[i].trim();
}
return split;
}
}
}
I think the best solution may be to use the client library dependencies or embed attributes in your library, though, or let the client-side JavaScript test if a library is present (ex. test if the jQuery object is undefined) and then take appropriate action. In other words, let the client side determine the final rendering based on what libraries exist on in the client. It sounds like this may not be possible for your situation, though.
dependencies: This is a list of other client library categories on
which this library folder depends. For example, given two
cq:ClientLibraryFolder nodes F and G, if a file in F requires another
file in G in order to function properly, then at least one of the
categories of G should be among the dependencies of F.
embed: Used to > embed code from other libraries. If node F embeds nodes G and H, the
resulting HTML will be a concetration of content from nodes G and H.
I'm trying to create a phonegap plugin for an android device, sadly my Java is terrible.
I have a simple helloworld project i'm working in to try and get this going.
I've created a plugin which loads fine and works ( just a simple return string example )
From this i then have tried to add my native library code.
public class Medida extends CordovaPlugin
{
static {
System.loadLibrary("finger");
}
public native static int SFM_Init(byte[] dev);
The error message i keep encountering is:
10-28 15:23:03.207: W/dalvikvm(11618): No implementation found for native Lorg/apache/cordova/plugin/Medida;.SFM_Init ([B)I
Now - I'm taking the libfinger.so file from a full JAVA android project and trying to wrap it into a phonegap plugin (why? Because i can code phonegap, but no java).
The files are all been placed in the correct locations
the libfinger.so file is in the libs/ folder
So my question is - what else do i need to add-in or do to get the JAVA plugin to work with the libfinger.so - so i can call all the clases etc..
Thanks for looking - spents days trying to find out, but there is not much info on calling loadlibrary for plugins which i understand.
John
Main java class
package org.apache.cordova.plugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class Medida extends CordovaPlugin{
static {
System.loadLibrary("finger");
}
public native static int SFM_Init(byte[] dev);
static final String LOG_TAG = "Medida.Java: ";
int fd = 0;
String retval = null;
int[] nQuality = {0};
int[] nBufferSize = {0};
private final String retSuccess = "OK";
public static final int REFRESH = 1;
public static final int ERROR = 0;
private Thread thread = null;
private int peripheral_fd = 1;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("dave")) {
String message = args.getString(0);
this.dave("Medida CALLING DAVE " + message, callbackContext);
return true;
}
else if (action.equals("scanfinger_getID")){
this.scanfinger_getID( args, callbackContext);
return true;
}
return false;
}
private void dave(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(" --- Medida FROM DAVE: " + message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
private void scanfinger_getID(JSONArray args, CallbackContext callbackContext) throws JSONException {
String message = args.getString(0);
JSONObject object = new JSONObject(message);
String id = object.getString("id");
String dev = "/dev/ttySAC3";
byte[] devName = dev.getBytes();
fd = SFM_Init(devName);
callbackContext.success("Got to scanfinger_getID: " + id);
}
}
Try to define the method as a class method (taken from here):
public class Medida extends CordovaPlugin {
static {
System.loadLibrary("finger");
}
public native int SFM_Init(byte[] dev);
}
EDIT
From the error it seems that there is no method called SFM_Init in the native library, try to list the exported methods and see the exact definition: How do I list the symbols in a .so file
i'd like to implement a index on a custom asset made for my project called "projet", i've already developped this class : (based on the liferay's bookmark indexer )
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import javax.portlet.PortletURL;
import org.apache.log4j.Logger;
import com.liferay.portal.kernel.search.BaseIndexer;
import com.liferay.portal.kernel.search.BooleanQuery;
import com.liferay.portal.kernel.search.Document;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.SearchContext;
import com.liferay.portal.kernel.search.SearchEngineUtil;
import com.liferay.portal.kernel.search.Summary;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.model.Group;
import com.liferay.portal.service.ClassNameLocalServiceUtil;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.util.PortletKeys;
public class ProjetIndexer extends BaseIndexer {
private static Logger LOGGER = Logger.getLogger(ProjetIndexer.class);
public static final String[] CLASS_NAMES = { Projet.class.getName() };
public String[] getClassNames() {
return CLASS_NAMES;
}
public String getPortletId() {
return Long.toString(ClassNameLocalServiceUtil.getClassNameId(Projet.class)) ;
}
#Override
protected void doDelete(Object obj) throws Exception {
LOGGER.info("doDelete");
Projet entry = (Projet) obj;
deleteDocument(entry.getCompanyId(), entry.getPrimaryKey());
}
#Override
protected Document doGetDocument(Object obj) throws Exception {
LOGGER.info("doGetDocument");
Projet entry = (Projet) obj;
Document document = getBaseModelDocument(getPortletId(), entry);
document.addText(Field.DESCRIPTION, "test123");
document.addText(Field.TITLE, "test123");
document.addKeyword(Field.TYPE, entry.getType());
document.addKeyword(Field.COMPANY_ID, entry.getCompanyId());
//what else ??
return document;
}
#Override
protected Summary doGetSummary(Document document, Locale locale,
String snippet, PortletURL portletURL) throws Exception {
LOGGER.info("doGetSummary");
String title = document.get(Field.TITLE);
String url = document.get(Field.URL);
String entryId = document.get(Field.ENTRY_CLASS_PK);
// portletURL.setParameter("struts_action",
// "/bookmarks/view_entry");TODO
portletURL.setParameter("entryId", entryId);
return new Summary(title, url, portletURL);
}
#Override
protected void doReindex(Object obj) throws Exception {
LOGGER.info("doReindex");
Projet entry = (Projet) obj;
Document document = getDocument(entry);
SearchEngineUtil.updateDocument(entry.getCompanyId(), document);
}
#Override
protected void doReindex(String className, long classPK) throws Exception {
LOGGER.info("doReindex");
Projet entry = ProjetLocalServiceUtil.getProjet(classPK);
doReindex(entry);
}
#Override
protected void doReindex(String[] ids) throws Exception {
long companyId = GetterUtil.getLong(ids[0]);
LOGGER.info("doReindex");
// reindexFolders(companyId);
reindexRoot(companyId);
}
#Override
protected String getPortletId(SearchContext searchContext) {
return getPortletId();
}
protected void reindexRoot(long companyId) throws Exception {
LOGGER.info("reindexRoot");
int groupCount = GroupLocalServiceUtil.getCompanyGroupsCount(companyId);
int groupPages = groupCount / Indexer.DEFAULT_INTERVAL;
for (int i = 0; i <= groupPages; i++) {
int groupStart = (i * Indexer.DEFAULT_INTERVAL);
int groupEnd = groupStart + Indexer.DEFAULT_INTERVAL;
reindexRoot(companyId, groupStart, groupEnd);
}
}
protected void reindexRoot(long companyId, int groupStart, int groupEnd)
throws Exception {
LOGGER.info("reindexRoot");
List<Group> groups = GroupLocalServiceUtil.getCompanyGroups(companyId,
groupStart, groupEnd);
for (Group group : groups) {
long groupId = group.getGroupId();
// long folderId =
// BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID;
int entryCount = ProjetLocalServiceUtil.getEntriesCount(groupId);
int entryPages = entryCount / Indexer.DEFAULT_INTERVAL;
for (int i = 0; i <= entryPages; i++) {
int entryStart = (i * Indexer.DEFAULT_INTERVAL);
int entryEnd = entryStart + Indexer.DEFAULT_INTERVAL;
reindexEntries(companyId, groupId, entryStart, entryEnd);
}
}
}
protected void reindexEntries(long companyId, long groupId, int entryStart,
int entryEnd) throws Exception {
LOGGER.info("reindexEntries");
List<Projet> entries = ProjetLocalServiceUtil.getEntries(groupId,
entryStart, entryEnd);
if (entries.isEmpty()) {
return;
}
Collection<Document> documents = new ArrayList<Document>();
for (Projet entry : entries) {
Document document = getDocument(entry);
documents.add(document);
}
SearchEngineUtil.updateDocuments(companyId, documents);
}
}
and this is my liferay portlet.xml:
<indexer-class>path package .ProjetIndexer</indexer-class>
but it doesnt work. search portlet (bundled with liferay 6.0) does not retrieve my custom asset
any ideas? thank
My issue is solved by deleting data under /data/lucent/ Maybe my tests deleloppment was corrupted I've changed the method doGetDocument too, making sure that no empty field is set in the map. many thanks for your cooperation