I am using below java class which uses sardine , i am getting only resources or zip files list in the directory, what should i use to download zip files?
package com.download;
import java.util.List;
import org.mule.api.MuleEventContext;
import org.mule.api.lifecycle.Callable;
import com.github.sardine.DavResource;
import com.github.sardine.Sardine;
import com.github.sardine.SardineFactory;
public class filesdownload implements Callable{
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
Sardine sardine = SardineFactory.begin("***","***");
List<DavResource> resources = sardine.list("http://hfus.com/vsd");
for (DavResource res : resources)
{
System.out.println(res);
}
return sardine;
}
You need to use sardine.get() method. Method documentation
Don't forget to use absolute path to your file. For example: http://hfus.com/vsd/file.zip.
Code sample:
package com.download;
import java.util.List;
import org.mule.api.MuleEventContext;
import org.mule.api.lifecycle.Callable;
import com.github.sardine.DavResource;
import com.github.sardine.Sardine;
import com.github.sardine.SardineFactory;
//TODO: add missing imports
public class filesdownload implements Callable{
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
Sardine sardine = SardineFactory.begin("***","***");
List<DavResource> resources = sardine.list(serverUrl()+"/vsd");
for (DavResource res : resources) {
if(res.getName().endsWith(".zip")) {
downloadFile(res);
}
}
return sardine;
}
private void downloadFile(DavResource resource) {
try {
InputStream in = sardine.get(serverUrl()+resource.getPath());
// TODO: handle same file name in subdirectories
OutputStream out = new FileOutputStream(resource.getName());
IOUtils.copy(in, out);
in.close();
out.close();
} catch(IOException ex) {
// TODO: handle exception
}
}
private String serverUrl() {
return "http://hfus.com";
}
}
Related
Ideally in Java, but perhaps in C#, I'm looking to programmatically copy a directory of files & folders into the clipboard, and allow the user to manually paste these through Windows Explorer (Ctr+V etc) onto their Android device, via Windows Explorer.
So the code below is from the following question and is what I've tried so far:-
https://stackoverflow.com/a/31798747/6120066
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CopyFile {
public static void main(String[] args) throws InterruptedException {
File file = new File("C:\\blabla.txt");
List listOfFiles = new ArrayList();
listOfFiles.add(file);
FileTransferable ft = new FileTransferable(listOfFiles);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ft, new ClipboardOwner() {
#Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("Lost ownership");
}
});
System.out.println("WAITING");
Thread.sleep(2 * 60 * 1000);
}
public static class FileTransferable implements Transferable {
private List listOfFiles;
public FileTransferable(List listOfFiles) {
this.listOfFiles = listOfFiles;
}
#Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.javaFileListFlavor};
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.javaFileListFlavor.equals(flavor);
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return listOfFiles;
}
}
}
I've managed to copy files and paste them manually to another location on my laptop's disk, but it doesn't work when I try pasting to the Android device. However if I manually copy a file/folder in Explorer, I can paste it onto the Android device fine.
Any ideas? Do I need to use more native stuff? That is why I tagged with C# also.
I am trying to integrate XLLoop from a servlet and trying to run in via HTTP protocol. Below is my code:
XlloopServlet.java
#WebServlet(value = "/FunctionServer", name = "FunctionServer", asyncSupported = true)
public class XlloopServlet extends FunctionServlet {
private static final long serialVersionUID = -3845895326255874126L;
#Override
public void init(final ServletConfig config) throws ServletException {
// Create a function information handler to register our functions
FunctionInformationHandler infoHandler = new FunctionInformationHandler();
// Create a reflection function handler and add the required methods
FunctionHandler handler = new FunctionHandler();
infoHandler.add(handler.getFunctions());
// Set the handlers
CompositeFunctionHandler compositeHandler = new CompositeFunctionHandler();
compositeHandler.add(handler);
compositeHandler.add(infoHandler);
// Setting the function handler in the parent servlet
setHandler(compositeHandler);
}
and my FunctionHandler class which registers the functions:
public class FunctionHandler implements IFunctionHandler, FunctionProvider {
private ReflectFunctionHandler rfh;
public FunctionHandler() {
// Create a reflection function handler and add the Math methods
rfh = new ReflectFunctionHandler();
rfh.addMethods("Math.", Math.class);
rfh.addMethods("Math.", Maths.class);
rfh.addMethods("CSV.", CSV.class);
rfh.addMethods("Reflect.", Reflect.class);
}
#Override
public XLoper execute(IFunctionContext arg0, String arg1, XLoper[] arg2) throws RequestException {
return rfh.execute(arg0, arg1, arg2);
}
#Override
public boolean hasFunction(String arg0) {
return rfh.hasFunction(arg0);
}
#Override
public FunctionInformation[] getFunctions() {
return rfh.getFunctions();
}
public ReflectFunctionHandler getReflectFunctionHandler() {
return rfh;
}
}
My XLLoop ini file is as below:
protocol=http
url=http://localhost:8080/MyApp/FunctionServer
Now, when I try to call a function from my excel, I get a call in the servlet class and everything executes, but functions are not getting executed on the excel file.
Anyone having any idea about how to integrate XLLoop plugin on a webserver like tomcat?
I've just implemented this with JAX-RS and a bit of Spring. I use a REST endpoint to populate the xlloop.ini file with the correct server host/port for the running service and then package up my xlsb, xll and ini file in a zip for clients to download. It's not particularly pretty at the moment but the web.xml and Startup snippets are below.
The thing I haven't spent time on yet is memory management. If a lot of users load a lot of data, I'll need to periodically clean that up, so beware of idle session threads!
Web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>com.myapp.web.excel.XLLoopStartup</listener-class>
</listener>
XLLoopStartup.java
public class XLLoopStartup implements ServletContextListener {
public static XLLoopStartup INSTANCE;
private FunctionServer fs;
#Inject
private SomeInjectionThing usefulSpringStuff;
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
#Override
public void contextInitialized(ServletContextEvent sce) {
INSTANCE = this;
// Initialize my Spring stuff
if (sce != null){
WebApplicationContextUtils//
.getRequiredWebApplicationContext(sce.getServletContext())//
.getAutowireCapableBeanFactory()//
.autowireBean(this);
}
Executors.newSingleThreadExecutor().execute(new Runnable() {
#Override
public void run() {
registerConverters();
fs = new FunctionServer(Integer.parseInt(System.getProperty("port.tomcat.xlloop", "10606")));
ReflectFunctionHandler rfh = new ReflectFunctionHandler();
rfh.addMethods(ExcelTrades.CATEGORY, ExcelTrades.class);
rfh.addMethods(ExcelUtils.CATEGORY, ExcelUtils.class);
rfh.addMethods(ExcelPositions.CATEGORY, ExcelPositions.class);
rfh.addMethods(ExcelProducts.CATEGORY, ExcelProducts.class);
// Create a function information handler to register our functions
FunctionInformationHandler firh = new FunctionInformationHandler();
firh.add(rfh.getFunctions());
// Set the handlers
CompositeFunctionHandler cfh = new CompositeFunctionHandler();
cfh.add(rfh);
cfh.add(firh);
DebugFunctionHandler debugFunctionHandler = new DebugFunctionHandler(cfh);
fs.setFunctionHandler(new SecureFunctionHandler(debugFunctionHandler));
try {
fs.run();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
// For quick testing
public static void main(String[] args) {
new XLLoopStartup().contextInitialized(null);
}
// Function classes can statically access this instance and get spring things from it
public SomeInjectionThing getThing() {
return usefulSpringStuff;
}
}
ExcelService.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.io.IOUtils;
import io.swagger.annotations.Api;
#Api("excel")
#Path("/excel")
public class ExcelService {
#Context
UriInfo uri;
#GET
#Path("/download")
#Produces({ MediaType.APPLICATION_OCTET_STREAM })
public Response download() {
StringWriter sw = new StringWriter();
// Create an INI file. We should probably store all default settings in a file and just add the server info to
// it.
sw.write("server=");
sw.write(uri.getBaseUri().getHost());
sw.write(":");
sw.write(System.getProperty("port.tomcat.xlloop", "10605"));
String inifile = sw.toString();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
// Add the ini file to the zip
ZipEntry entry = new ZipEntry("xlloop.ini");
zos.putNextEntry(entry);
zos.write(inifile.getBytes());
zos.closeEntry();
// Add the Excel files
writeFileFromClasspath(zos, "xlloop.xll");
// This is my custom Excel macro sheet with other useful functions for user authentication etc.
writeFileFromClasspath(zos, "xlloop.xlsb");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return Response.ok(new ByteArrayInputStream(baos.toByteArray()))
.header("Content-Disposition", "attachment; filename=xlloop.zip").build();
}
private void writeFileFromClasspath(ZipOutputStream zos, String filename) throws IOException {
ZipEntry xlFileEntry = new ZipEntry(filename);
zos.putNextEntry(xlFileEntry);
zos.write(IOUtils.toByteArray(ExcelService.class.getClassLoader().getResourceAsStream(filename)));
zos.closeEntry();
}
}
Is there any way to map a image file using a spring controller? In my spring application, I want store the images in the directory src/main/resources (i'm using maven) and access them with a method like this:
#RequestMapping(value="image/{theString}")
public ModelAndView image(#PathVariable String theString) {
return new ModelAndView('what should be placed here?');
}
the string theString it's the image name (without extension). With this approach, I should be able to access my images this way:
/webapp/controller_mapping/image/image_name
Anyone can point a direction to do that?
You can return HttpEntity<byte[]>. Construct new instance providing image byte array and necessary headers like content length and mime type then return it from your method. Image bytes can be obtained using classloader getResourceAsStream method.
This works for me. It could use some cleaning up but it works. The ServiceException is just a simple base exception.
Good Luck!
package com.dhargis.example;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/image")
public class ImageController {
private static final Logger log = Logger.getLogger(ImageController.class);
private String filestore = "C:\\Users\\dhargis";
//produces = "application/octet-stream"
#RequestMapping(value = "/{filename:.+}", method = RequestMethod.GET)
public void get( #PathVariable String filename,
HttpServletRequest request,
HttpServletResponse response) {
log.info("Getting file " + filename);
try {
byte[] content = null;
File store = new File(filestore);
if( store.exists() ){
File file = new File(store.getPath()+File.separator+filename);
if( file.exists() ){
content = FileUtils.readFileToByteArray(file);
} else {
throw new ServiceException("File does not exist");
}
} else {
throw new ServiceException("Report store is required");
}
ServletOutputStream out = response.getOutputStream();
out.write(content);
out.flush();
out.close();
} catch (ServiceException e) {
log.error("Error on get", e);
} catch (IOException e) {
log.error("Error on get", e);
}
}
}
<!-- begin snippet: js hide: false -->
I'm trying to convert the below velocity macro into a velocity Java directive, as I need to add some bells and whistles around the rendering logic:
#macro(renderModules $modules)
#if($modules)
#foreach($module in $modules)
#if(${module.template})
#set($moduleData = $module.data)
#parse("${module.template}.vm")
#end
#end
#end
#end
My equivalent Java Directive:
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.ASTBlock;
import org.apache.velocity.runtime.parser.node.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class RenderModulesDirective extends Directive {
private static final Logger LOGGER = LoggerFactory.getLogger(RenderModulesDirective.class);
#Override
public String getName() {
return "renderModules";
}
#Override
public int getType() {
return LINE;
}
#Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
for(int i=0; i<node.jjtGetNumChildren(); i++) {
Node modulesNode = node.jjtGetChild(i);
if (modulesNode != null) {
if(!(modulesNode instanceof ASTBlock)) {
if(i == 0) {
// This should be the list of modules
List<Module> modules = (List<Module>) modulesNode.value(context);
if(modules != null) {
for (Module module : modules) {
context.put("moduleData", module.getData());
String templateName = module.getTemplate() + ".vm";
try {
// ??? How to parse the template here ???
} catch(Exception e) {
LOGGER.error("Encountered an error while rendering the Module {}", module, e);
}
}
break;
}
}
}
}
}
return true;
}
}
So, I'm stuck at the point where I need the Java equivalent of the #parse("<template_name>.vm") call. Is this the right approach? Would it help to instead extend from the Parse directive?
I believe
Template template = Velocity.getTemplate("path/to/template.vm");
template.merge(context, writer);
will accomplish what you're looking to do.
If you have access to RuntimeServices you could call createNewParser() and then call parse(Reader reader, String templateName) inside of the parser, the SimpleNode that comes out has a render() method which I think is what you're looking fo
hello:
I'm writing code in java for nutch(open source search engine) to remove the movments from arabic words in the indexer.
I don't know what is the error in it.
Tthis is the code:
package com.mycompany.nutch.indexing;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.indexer.IndexingException;
import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.parse.getData().parse.getData();
public class InvalidUrlIndexFilter implements IndexingFilter {
private static final Logger LOGGER =
Logger.getLogger(InvalidUrlIndexFilter.class);
private Configuration conf;
public void addIndexBackendOptions(Configuration conf) {
// NOOP
return;
}
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
CrawlDatum datum, Inlinks inlinks) throws IndexingException {
if (url == null) {
return null;
}
char[] parse.getData() = input.trim().toCharArray();
for(int p=0;p<parse.getData().length;p++)
if(!(parse.getData()[p]=='َ'||parse.getData()[p]=='ً'||parse.getData()[p]=='ُ'||parse.getData()[p]=='ِ'||parse.getData()[p]=='ٍ'||parse.getData()[p]=='ٌ' ||parse.getData()[p]=='ّ'||parse.getData()[p]=='ْ' ||parse.getData()[p]=='"' ))
new String.append(parse.getData()[p]);
return doc;
}
public Configuration getConf() {
return conf;
}
public void setConf(Configuration conf) {
this.conf = conf;
}
}
I think that the error is in using parse.getdata() but I don't know what I should use instead of it?
The line
char[] parse.getData() = input.trim().toCharArray();
will give you a compile error because the left hand side is not a variable. Please replace parse.getData() by a unique variable name (e.g. parsedData) in this line and the following lines.
Second the import of
import org.apache.nutch.parse.getData().parse.getData();
will also fail. Looks a lot like a text replace issue.