I have an 3 array of strings ( actually it's an ArrayList ) and I would like to create an InputStream from it, each element of the array being a line in the stream.
String[] business = ['CONSUMER', 'TELUS'];
String[] position = ['Business', 'SMB','THPS'];
String isDone = "Yes";
need to convert the above data into and pass it to InputStream so i can upload the data to ftp server
Business_Unit: 'TELUS', 'CONSUMER'
Position_Group: 'Business', 'SMB', 'THPS'
On-Cycle_Schedule: 'Yes' or 'No
ftp server method as follows
private boolean fileUpload(InputStream isUploadFile, String dirName, String fileName){
boolean storeRetVal = false;
//File submission method
return storeRetVal;
}
the above method gets called from action class
public ActionForward generatePayroll(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
SessionInfoForm _form = (SessionInfoForm) form;
String isDone = "Yes";
String[] business = request.getParameterValues("selectedBusinessValues");
String[] position = request.getParameterValues("selectedPositionValues");
String fileName = "result.csv";
InputStream isUploadFile;
fileUpload(isUploadFile, fileName);
return mapping.findForward("success");
}
You can do something like
String[] business = { "CONSUMER", "TELUS" };
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
for (String s : business) {
out.println(s);
}
InputStream in = new ByteArrayInputStream(sw.toString().getBytes());
Related
I have a method which takes the string as input, filters for specific key and value, returns the value as String output. I have a requirement to append input param to output string. The input is array int id. Here is the method code snippet:
private static String headerstomap(String headers) {
String sHeaders = headers.replace("[", "");
sHeaders = sHeaders.replace("]", "");
String res = Arrays.stream(sHeaders.split(", "))
.filter(s->s.contains("Uniquename"))
.findFirst()
.map(name->name.split(":")[1])
.orElse("Not Present");
return res;
}
Input is: [DomainValue:MYSQL,Oracle,SAP, Uniquename:jvmErrors_v1]
There is a rest API which takes the input param, gets the relevant data. Calls the above method to create a filename. The REST resource is:
public void downloadRecords(#PathVariable Long[] ids, HttpServletResponse response) throws Exception {
I need the method to return: jvmErrors_v1_1
Essentially, add an underscore at the end and append the input param.
Here is the REST resource:
public void downloadRecords(#PathVariable Long[] ids, HttpServletResponse response) throws Exception {
List<IDZip> iDZip = messageRepository.findbyId(ids);
IDZip iDZip = iDZip.get(0);
String xml = new ObjectMapper().writeValueAsString(iDZip);
String fileName = "id.zip";
String xmlname = messageController.headerstomap(iDZip.getheaders());
byte[] data = xml.getBytes();
byte[] bytes;
try (ByteOutputStream bout = new ByteOutputStream(); ZipOutputStream zout = new ZipOutputStream(bout)) {
for (Long id : ids) {
zout.setLevel(1);
ZipEntry ze = new ZipEntry(xmlname);
ze.setSize(data.length);
ze.setTime(System.currentTimeMillis());
zout.putNextEntry(ze);
zout.write(data);
zout.closeEntry();
}
bytes = bout.getBytes();
}
response.setContentType("application/zip");
response.setContentLength(bytes.length);
response.setHeader("Content-Disposition", "attachment; " + String.format("filename=" + fileName));
ServletOutputStream outputStream = response.getOutputStream();
FileCopyUtils.copy(bytes, outputStream);
outputStream.close();
}
There is IDZip class which holds getters and setters...
public String getheaders() {
return headers;
}
public void setheaders(String headers) {
this.headers = headers;
}
I will give you a gift today only if you will accept it, first debugs the process into small section system.out.println("step 1"); in each of the line then i will take it from that point
Still super new to REST, but close to finishing my first program.
I am attempting to create a CSV with the value of the POST URL Parameter being passed into it each time I POST.
Is there a way of setting my variable to be equal to my POST URL Parameter?
Code below (value is temporarily set to 10 while I figure this out):
#Path("/values")
public class values {
int totalSum = 0;
List<String> list = new ArrayList<String>();
#GET
#Produces(MediaType.TEXT_PLAIN)
public int getSum() throws IOException {
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List<String[]> read = reader.readAll();
return sum.sum(read, totalSum);
}
#POST
public String addValue() throws IOException {
int value = 10;
String valueString = Integer.toString(value);
CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv", true), ',');
String[] entries = valueString.split(",");
writer.writeNext(entries);
writer.close();
return "ok";
}
#DELETE
#Produces(MediaType.TEXT_PLAIN)
public String deleteList() throws IOException {
FileWriter fw = new FileWriter("yourfile.csv", false);
PrintWriter pw = new PrintWriter(fw, false);
pw.flush();
pw.close();
fw.close();
return "ok";
}
}
So now you need the base url, and when you add /{some_value} it gets mapped via PathVariable to String value test
Like so?
#Path("/{test}")
#POST
// Javax.ws.rs.PathParam
public String addValue(#PathParam("test") final String test) throws
// SpringFramework
//public String addValue(#PathVariable("test") final String test) throws IOException {
final String value = test;
CSVWriter writer = new CSVWriter(new FileWriter(value, true), ',');
String[] entries = valueString.split(",");
writer.writeNext(entries);
writer.close();
return "ok";
}
See link for more information
Here is code of my getStream method:
public static Twitch_Stream getStream(String channelname) {
try {
String json = API.readJsonFromUrl("https://api.twitch.tv/kraken/streams?channel=" + channelname);
Twitch_Stream stream = new Twitch_Stream();
if (json.equalsIgnoreCase("[]")) {
stream.setOnline(false);
return stream;
}
JsonArray jb = gson.fromJson(json, JsonArray.class);
if (jb.size() != 0) {
JsonObject jo = (JsonObject) jb.get(0);
stream.setOnline(true);
stream.load(jo);
}
return stream;
} catch (Exception error) {
error.printStackTrace();
}
return null;
}
and here is code of Twitch_Stream class http://pastebin.com/3RX1L1cv
When I make something like this
Twitch_Stream streamer = Twitch_API.getStream("Jankos");
Bukkit.broadcastMessage("getName " + streamer.getName());
Bukkit.broadcastMessage(streamer.isOnline() + "");
streamer.getName() return null and streamer.isOnline() returns false, even when stream is on.
Where did I make a mistake?
I don't know what problem is in your code but simple workaround would be reading content from "https://api.twitch.tv/kraken/streams/" + channel which is JSON in format:
{
"_links" : {
//links to stream and channel
},
"stream" : {
//details about current stream
}
}
Now if value of stream key is null stream is off-line. If it is not null, it is on-line.
So your code can look like
public static void main(String[] argv) throws IOException {
System.out.println(checkIfOnline("Jankos"));
System.out.println(checkIfOnline("nightblue3"));
}
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.twitch.tv/kraken/streams/" + channel;
String jsonText = readFromUrl(channerUrl);// reads text from URL
JSONObject json = new JSONObject(jsonText);
return !json.isNull("stream");
}
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
try (Stream<String> stream = new BufferedReader(new InputStreamReader(
page.openStream(), StandardCharsets.UTF_8)).lines()) {
return stream.collect(Collectors.joining(System.lineSeparator()));
}
}
I used JSONObject from org.json library. I am also using Java 8 and its streams.
If you want to use gson you can use instead something like
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.twitch.tv/kraken/streams/" + channel;
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonText).getAsJsonObject();
return !json.get("stream").isJsonNull();
}
If you don't have Java 8 you can rewrite code reading text from URL to something like
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
StringBuilder sb = new StringBuilder();
Scanner scanner = null;
try{
scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()){
sb.append(scanner.nextLine());
}
}finally{
if (scanner!=null)
scanner.close();
}
return sb.toString();
}
or from what I see you can use your API.readJsonFromUrl instead of readFromUrl.
Maybe I do not understand the servlet lifecycle very well, but this is what i want:
I want to display a page generated by a servlet let's say servlet: paginaAmd.
On this page I want to display a list of images stored in folder on web server.
The address of url of the images is something like:
/img/80-80-1-1-1-1-1-1-1-1-1
where /img/* is my servlet for displaying images.
All works well if I want to display one image at a time in browser.
But when I want to put all the list at once, the images are not displayed correctly. Sometimes are not displayed at all, sometimes are displayed in wrong position (the position does not alter in time), and sometimes are displayed only some images.
I suspect that somehow not all the doGet() methods are catched.
Can someone give me some advice?
Here are the servlet code witch is implemented by the tutorial here: http://balusc.blogspot.fr/2007/04/imageservlet.html
#WebServlet(name = "ImgDisplay", urlPatterns = {"/img/*"})
public class ImgDisplay extends HttpServlet
{
private SessionFactory sessionfactory = new AnnotationConfiguration().configure().buildSessionFactory();
private Query query;
private String mesajEroare = "";
private HttpServletRequest _request;
private HttpServletResponse _response;
private int width = 0;
private int height = 0;
private int idImagine = 0;
private int format = 0;
private String titluArticol = "";
private String numeImagine = "";
private boolean imgValida = false;
private int DEFAULT_BUFFER_SIZE = 1024 * 100;
String fileUploadPath = "";
#Override
public void init() throws ServletException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this._request = request;
this._response = response;
this.SetVariabile();
if(imgValida)
{
String nImagine = this.GetImageFromDisk();
this.DisplayImage(nImagine);
}
}
private void SetVariabile()
{
String reqUrl = _request.getRequestURL().toString();
String aUrl[] = reqUrl.split("/");
String urlImg = aUrl[aUrl.length - 1];
aUrl = urlImg.split("-");
try
{
this.width = Integer.parseInt(aUrl[0]);
this.height = Integer.parseInt(aUrl[1]);
this.idImagine = Integer.parseInt(aUrl[2]);
this.format = Integer.parseInt(aUrl[3]);
this.numeImagine = aUrl[aUrl.length - 1];
this.imgValida = true;
}
catch(Exception e)
{
this.imgValida = false;
}
}
private String GetImageFromDisk()
{
String nImagine;
//preiau imaginea
PaginiImagini pa = new PaginiImagini();
Session session;
try
{
session = sessionfactory.openSession();
session.beginTransaction();
query = session.getNamedQuery("PaginiImagini.findByImagineID");
query.setInteger("imagineID", this.idImagine);
pa = (PaginiImagini) query.uniqueResult();
session.getTransaction().commit();
session.close();
}
catch( Exception e )
{
this.mesajEroare = "Nu pot citi din baza de date!";
}
// citesc imagine de pe disk
ServletContext sctx = getServletContext();
this.fileUploadPath = sctx.getInitParameter("file-upload-path");
String pathImagine = this.fileUploadPath + "/" + Setari.pathImaginiMici;
if(this.width > Setari.wImagineMica || this.height > Setari.hImagineMica)
{
pathImagine = this.fileUploadPath + "/" + Setari.pathImaginiMari;
}
nImagine = pathImagine + "/" + pa.getNumeImaginePeDisc();
return nImagine;
}
private void DisplayImage(String imageToRead) throws FileNotFoundException, IOException
{
File image = new File(imageToRead);
String contentType = getServletContext().getMimeType(image.getName());
_response.setContentType(contentType);
_response.setHeader("Content-Length", String.valueOf(image.length()));
_response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
_response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
_response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
_response.setDateHeader("Expires", 0); // Proxies.
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try
{
// Open streams.
input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(_response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
}
finally
{
// Gently close streams.
close(output);
close(input);
}
}
/**
*
* #param resource
*/
private static void close(Closeable resource)
{
if (resource != null)
{
try
{
resource.close();
}
catch (IOException e)
{
// Do your thing with the exception. Print it, log it or mail
// it.
//e.printStackTrace();
}
}
}
}
You have serious concurrency issues in your servlet. A single instance of the servlet is used to serve all the requests to this servlet. So a servlet should be stateless. But the first thing you're doing is
this._request = request;
this._response = response;
This means that if two concurrent requests are made to the servlet, you might have the first one set these two instance variables, then the second one resetting the same instance variables. The first image would thus be sent as a response to the second request, and nothing would be sent as a response to the first request. And this is only one of the strange things that could happen. You could also have exceptions and inconsistent data.
Don't store the request and response (and any other state) in instance variables. Pass them from method to method. I've not analyzed the whole code, but the only instance field that you should have in the servlet is sessionFactory field.
I've written a transformer class that takes an HttpServletRequest and transforms it into another type that holds a pointer to the InputStream from the servlet request. (The idea is to abstract the incoming transport protocol from the request handling, so I could also write a similar transformer from FTP, for instance.)
Now I'm trying to write a unit test for this, and I'm having problems. I've managed to figure out the correct boilerplate to create a valid Multipart HTTP request (using the Spring classes MockMultipartHttpServletRequest and MockMultipartFile), but now I get a NullPointerException in the initialize() method of my UploadRequest class. I'm guessing the problem is that somehow the stream inside the MockMultipartHttpServletRequest isn't being initialized correctly, but I can't figure out what I should do differently.
Any suggestions would be gratefully accepted!
This is the stack trace:
java.lang.NullPointerException
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:976)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:886)
at java.io.InputStream.read(InputStream.java:82)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:96)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:66)
at org.apache.commons.fileupload.MultipartStream.readBodyData(MultipartStream.java:592)
at org.apache.commons.fileupload.MultipartStream.discardBodyData(MultipartStream.java:618)
at org.apache.commons.fileupload.MultipartStream.skipPreamble(MultipartStream.java:637)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:984)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:965)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.servlet.ServletFileUpload.getItemIterator(ServletFileUpload.java:148)
at com.ooyala.UploadRequest.initialize(UploadRequest.java:51)
at com.ooyala.UploadRequestTest.testCreateFromServletRequest(UploadRequestTest.java:57)
Here's an abbreviated version of my transformer class:
public class UploadRequest {
private Map<String, String> params;
private InputStream strIn;
private Logger Log = Logger.getLogger(UploadRequest.class.getName());
public UploadRequest()
{
params = new HashMap<String, String>();
}
public void initialize(HttpServletRequest sRequest,
ServletFileUpload upload)
throws IOException, FileUploadException
{
Enumeration<String> paramNames = sRequest.getParameterNames();
while (paramNames.hasMoreElements()) {
String pName = paramNames.nextElement();
params.put(pName, sRequest.getParameter(pName));
}
params.put("request_uri", sRequest.getRequestURI());
FileItemIterator iter = upload.getItemIterator(sRequest);
while (iter.hasNext()) {
FileItemStream item = iter.next();
try {
if (!item.isFormField()) {
// Skip form fields
params.put("original_file_name", item.getName());
strIn = item.openStream();
}
} catch (IOException ex) {
Log.severe("File uploading exception: " + ex.getMessage());
throw ex;
}
}
}
And here's the unit test:
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
// etc.... other imports
#RunWith(JMock.class)
public class UploadRequestTest {
private UploadRequest upRequest;
#Before
public void setUp()
{
context.setImposteriser(ClassImposteriser.INSTANCE);
upRequest = new UploadRequest();
}
#Test
public void testCreateFromServletRequest()
throws IOException, FileUploadException
{
String text_contents = "hello world";
MockMultipartHttpServletRequest sRequest =
new MockMultipartHttpServletRequest();
sRequest.setMethod("POST");
String boundary = generateBoundary();
String contentType = "multipart/form-data; boundary="+boundary;
sRequest.setContentType(contentType);
sRequest.setRequestURI("/foo");
sRequest.addParameter("test_param","test_value");
sRequest.addFile(
new MockMultipartFile("file1","test_upload.txt","text/plain",
text_contents.getBytes()));
ServletFileUpload upload = new ServletFileUpload();
assertTrue(upload.isMultipartContent(sRequest));
upRequest.initialize(sRequest, upload);
}
}
I have the same issue and I googled but no answer. I plugged in the source code from the library, You need to send content, whatever. The library might need to check if it is null in the skip method
MockMultipartHttpServletRequest request
request.setContent("whatever".getBytes());
Posted here for others
Add boundary condition
Generate contents as follows
MockMultipartHttpServletRequest request =
this.generateMockMultiPartHttpServletRequest(true);
MockMultipartFile mockMultipartFile = null;
try {
request.setContentType("multipart/form-data; boundary=-----1234");
request.setCharacterEncoding("text/plain");
String endline = "\r\n";
String bondary = "-----1234";
String textFile = this.encodeTextFile("-----1234", "\r\n", "file","test.csv",
"text/UTF-8", FileUtils.readFileToString((new File(csvFilePath)), "UTF-8"));
StringBuilder content = new StringBuilder(textFile.toString());
content.append(endline);
content.append(endline);
content.append(endline);
content.append("--");
content.append(bondary);
content.append("--");
content.append(endline);
request.setContent(content.toString().getBytes());
request.setMethod("POST");
mockMultipartFile = new MockMultipartFile("file",
FileUtils.readFileToByteArray(new File(csvFilePath)));
} catch (Exception e1) {
e1.printStackTrace();
}
request.addFile(mockMultipartFile);
Function to encode text
private String encodeTextFile(String bondary, String endline, String name,
String filename, String contentType, String content) {
final StringBuilder sb = new StringBuilder(64);
sb.append(endline);
sb.append("--");
sb.append(bondary);
sb.append(endline);
sb.append("Content-Disposition: form-data; name=\"");
sb.append(name);
sb.append("\"; filename=\"");
sb.append(filename);
sb.append("\"");
sb.append(endline);
sb.append("Content-Type: ");
sb.append(contentType);
sb.append(endline);
sb.append(endline);
sb.append(content);
return sb.toString();
}
I went through the same problem, after searching lot I got this post in which I answered with code that solved my problem.
The Shriprasad's solution works well for text file. But I had some problems with binary files.
https://stackoverflow.com/a/30541653/2762092