I want to upload a file into bucket in Google cloud storage Api. But when i run the servelet class then it successfully deployed and it shows the output in browser like " Now see here your file content, that you have uploaded on storage..
File uploading done" .
But the problem is the servelet class will not establish the connection to Google cloud storage.And the file will not uploaded into bucket.Once check
the code and give suggestion to how to connect to bucket with this source code.
public class TestCloudStorageServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private StorageService storage = new StorageService();
private static final int BUFFER_SIZE = 1024 * 1024;
private static final Logger log = Logger.getLogger(TestCloudStorageServlet.class.getName());
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.info(this.getServletInfo()+" Servlets called....");
resp.setContentType("text/plain");
resp.getWriter().println("Now see here your file content, that you have uploaded on storage..");
ServletFileUpload upload = new ServletFileUpload();
System.out.println(upload);
FileItemIterator iter;
try {
iter = upload.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String fileName = item.getName();
String mime = item.getContentType();
storage.init(fileName, mime);
InputStream is = item.openStream();
byte[] b = new byte[BUFFER_SIZE];
int readBytes = is.read(b, 0, BUFFER_SIZE);
while (readBytes != -1) {
storage.storeFile(b, readBytes);
readBytes = is.read(b, 0, readBytes);
}
is.close();
storage.destroy();
resp.getWriter().println("File uploading done");
//resp.getWriter().println("READ:" + storage.readTextFileOnly(fileName));
log.info(this.getServletName()+" ended....");
}
}
catch (FileUploadException e) {
System.out.println("FileUploadException::"+e.getMessage());
log.severe(this.getServletName()+":FileUploadException::"+e.getMessage());
e.printStackTrace();
} catch (Exception e) {
log.severe(this.getServletName()+":Exception::"+e.getMessage());
System.out.println("Exception::"+e.getMessage());
e.printStackTrace();
}
}
my StorageService class for uploading file.
public class StorageService {
public static final String BUCKET_NAME = "mybucketname";
private FileWriteChannel writeChannel = null;
FileService fileService = FileServiceFactory.getFileService();
private OutputStream os = null;
private static final Logger log = Logger.getLogger(StorageService.class.getName());
public void init(String fileName, String mime) throws Exception {
System.out.println("Storage service:init() method: file name:"+fileName+" and mime:"+mime);
log.info("Storage service:init() method: file name:"+fileName+" and mime:"+mime);
log.info("test..");
GSFileOptionsBuilder builder = new GSFileOptionsBuilder()
.setAcl("public_read")
.setBucket(BUCKET_NAME)
.setKey(fileName)
.setMimeType(mime);
log.info("test..");
AppEngineFile writableFile = fileService.createNewGSFile(builder.build());
boolean lock = true;
writeChannel = fileService.openWriteChannel(writableFile, lock);
os = Channels.newOutputStream(writeChannel);
}
public void storeFile(byte[] b, int readSize) throws Exception {
os.write(b, 0, readSize);
os.flush();
}
public void destroy() throws Exception {
log.info("Storage service: destroy() method");
os.close();
writeChannel.closeFinally();
}
}
Related
I want to send rcon command to server using java, to do this I'm using the following library https://github.com/Kronos666/rkon-core
When i run command like this
Rcon rcon = new Rcon("127.0.0.1", 27015, "mypassword".getBytes());
// Example: On a minecraft server this will list the connected players
String result = rcon.command("list");
// Display the result in the console
System.out.println(result);
My server show response in console Gc connection established from... and so on
but in java app i have the empty result, it's not null, it's just empty
String result = rcon.command("list");
How can i take response from server using rcon protocol?
Try this:
try {
Rcon rcon = new Rcon("127.0.0.1", 27015, "mypassword".getBytes());
String result = rcon.command("list");
System.out.println(result);
} catch (AuthenticationException e) {
String result = "Authentication failed";
}
Finally I write my own implementation:
public final class RconClient implements AutoCloseable {
private static final int MAX_SIZE = 4096;
private final Socket socket;
private final RconData data;
private static final Logger LOG = LoggerFactory.getLogger(RconClient.class);
#SuppressWarnings("ConstructorShouldNotThrowExceptions")
public RconClient(final String host,
final int port,
final byte[] password) throws IOException {
this.socket = new Socket(host, port);
final RconData requst = request(new RconData(RconData.AUTH, password));
if (requst.getId() == -1) {
LOG.error("Wrong password or ip to connect to rcon");
throw new LoginException(host, port);
}
this.data = read();
}
public String command(String command) throws IOException {
command = "get5_status";
final RconData response = request(new RconData(command.getBytes()));
return new String(response.getPayload(), Charset.forName("UTF-8"));
}
public RconData request(RconData packet) throws IOException {
try {
write(packet);
return read();
} catch (final SocketException exception) {
socket.close();
throw exception;
}
}
private void write(RconData packet) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(packet.getPayload().length + 14);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(packet.getPayload().length + 10);
buffer.putInt(packet.getId());
buffer.putInt(packet.getType());
buffer.put(packet.getPayload());
buffer.put((byte)0);
buffer.put((byte)0);
socket.getOutputStream().write(buffer.array());
socket.getOutputStream().flush();
}
private RconData read() throws IOException {
byte[] packet = new byte[MAX_SIZE];
int packetSize = this.socket.getInputStream().read(packet);
ByteBuffer buffer = ByteBuffer.wrap(packet, 0, packetSize);
buffer.order(ByteOrder.LITTLE_ENDIAN);
if (buffer.remaining() < 4) {
throw new WrongPacketException();
}
int size = buffer.getInt();
if (buffer.remaining() < size) {
throw new WrongPacketException();
}
int id = buffer.getInt();
int type = buffer.getInt();
byte[] payload = new byte[size - 10];
buffer.get(payload);
buffer.get(new byte[2]);
return new RconData(id, type, payload);
}
#Override
public void close() throws IOException {
this.socket.close();
}
}
Where RconData it's simple POJO with byte[] password property,
I'm using Primefaces to upload images to tomcat
through <p:fileUpload/>
I'm uploading in this folder : C:\NEW WORK\sicweb\src\main\webapp\resources\images
But when I put my application on a server, I can't put this way. How can I select a folder through a relative path or something like that
Or put inside C:\java\apache-tomcat-8.0.32\webapps\sicweb ?
This is my class :
public class UploadLogoOrgaoControle implements Serializable {
public static String name = "";
private String caminhoCarregado = "";
private static final long serialVersionUID = 1L;
public void handleFileUpload(FileUploadEvent event) throws IOException {
String path = "C:\\NEW WORK\\sicweb\\src\\main\\webapp\\resources\\images\\";
name = event.getFile().getFileName();
File file = new File(path + name);
caminhoCarregado = "/sicweb/resources/images/" + name;
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
}
public String getCaminhoCarregado() {
return caminhoCarregado;
}
public void setCaminhoCarregado(String caminhoCarregado) {
this.caminhoCarregado = caminhoCarregado;
}
}
I encounter this exception. How can I resolve it?
m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [public javax.ws.rs.core.Response com.digit.spread.controller.VideoController.downloadVideo(java.lang.String,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.io.IOException]: java.io.FileNotFoundException: videoFile (Le fichier sp▒cifi▒ est introuvable)
Code:
#RequestMapping(value = "download.do", method = RequestMethod.GET)
public Response downloadVideo(
#RequestParam(value = "videoId", required = true) String videoId,
HttpServletRequest request, HttpServletResponse response) throws IOException {
String mail = SecurityContextHolder.getContext()
.getAuthentication().getName();
System.out.println(mail+": Download video file starts . . . videoId:"+videoId);
Video video = videoBean.getVideoObject(videoId);
InputStream videoFile = videoBean.getVideoFile(video.getFileId());
long videoFileSize =videoBean.getVideoFileSize(video.getFileId());
String range = request.getHeader("Range") ;
final int chunk_size = 1024 * 1024; // 1MB chunks
if (range == null) {
StreamingOutput streamer = new StreamingOutput() {
#Override
public void write(final OutputStream output) throws IOException, WebApplicationException {
final FileChannel inputChannel = new FileInputStream("videoFile").getChannel();
final WritableByteChannel outputChannel = Channels.newChannel(output);
try {
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
} finally {
// closing the channels
inputChannel.close();
outputChannel.close();
}
}
};
return Response.ok(streamer).header(HttpHeaders.CONTENT_LENGTH, videoFileSize).build();
}
String[] ranges = range.split("=")[1].split("-");
final int from = Integer.parseInt(ranges[0]);
/**
* Chunk media if the range upper bound is unspecified. Chrome sends "bytes=0-"
*/
int to = chunk_size + from;
if (to >= videoFileSize) {
to = (int) (videoFileSize- 1);
}
if (ranges.length == 2) {
to = Integer.parseInt(ranges[1]);
}
final String responseRange = String.format("bytes %d-%d/%d", from, to, videoFileSize);
final RandomAccessFile raf = new RandomAccessFile("videoFile", "r");
raf.seek(from);
final int len = to - from + 1;
final MediaStreamer streamer = new MediaStreamer(len, raf);
Response.ResponseBuilder res = Response.ok(streamer).status(206)
.header("Accept-Ranges", "bytes")
.header("Content-Range", responseRange)
.header(HttpHeaders.CONTENT_LENGTH, streamer.getLenth());
return Response.ok(streamer).header(HttpHeaders.CONTENT_LENGTH, videoFileSize).build();
}
I'm trying to POST an FileInputStream using Retrofit 1.9.x (I can't move to 2.0.x yet)
I've read This Post.
In that post I understood that If I use a TypedInput in my interface and implement TypedInput class wrapper that handled the stream, then it should work. It was unclear if TypedInput vs TypedOutput was the answer (TypedInput sounded the most correct, the linked retrofit documentation didn't specify as far as I could tell. Also It's all moved on to 2.0)
To proceed - I created a class
private class InputStreamMunger implements TypedInput {
private InputStream is;
private String mimeType;
private Long fileLength;
public InputStreamMunger(InputStream is, String mimeType, Long fileLength) {
this.is = is;
this.fileLength = fileLength;
this.mimeType = mimeType;
}
#Override
public String mimeType() {
return mimeType;
}
#Override
public long length() {
return fileLength;
}
#Override
public InputStream in() throws IOException {
return is;
}
}
My Interface:
#Multipart
#POST("/MrService/v1/upload/{accountId}")
Response upload(
#Path("accountId") String accountId,
#Part("file") TypedInput file);
Then I call it
FileInputStream is = new FileInputStream("src/test/java/com/me/MrService/tester.txt");
InputStreamMunger file ;
try {
file = new InputStreamMunger(is, "text/plain", is.getChannel().size());
} catch (IOException e) {
e.printStackTrace();
return;
}
Response r = client.upload("12345", file );
The error i get is:
retrofit.RetrofitError: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.me.MrService.IntegrationTestIT$InputStreamMunger and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
Does this mean that I need to create my own mapper to handle a Stream? I'm hoping that I'm just doing something wrong and that I don't need to jump through that hoop.
Thanks!
In the end I did implement the TypedOutput instead of the TypedInput.
private class InputStreamMunger implements TypedOutput {
private InputStream is;
private String mimeType;
private Long fileLength;
private String fileName;
private static final int BUFFER_SIZE = 4096;
public InputStreamMunger(InputStream is, String mimeType, Long fileLength,
String fileName) {
this.is = is;
this.fileLength = fileLength;
this.mimeType = mimeType;
this.fileName = fileName;
}
#Override
public String mimeType() {
return mimeType;
}
#Override
public long length() {
return fileLength;
}
#Override
public void writeTo(OutputStream out) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
try {
int read;
while ((read = is.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} finally {
is.close();
}
}
public String fileName() {
return fileName;
}
}
I have this action class, this class takes care of my response
Update now passing response from DownloadStatus class, but it looks like it is null
public final class DownloadStatus extends ActionSupport implements ServletRequestAware,ServletResponseAware
{
static Logger logger = Logger.getLogger(DownloadStatus.class);
private HttpServletRequest request;
private HttpServletResponse response;
private File cfile;
private String cfileFileName;
#Override
public String execute()
{
logger.debug("Inside DownloadStatus.execute method")
try {
ChainsInvoker invoker = new ChainsInvoker()
def executionResponse = invoker.invoke(request, MYChains.download, cfile, cfileFileName)
if(executionResponse == null || ErrorHandler.checkIfError(executionResponse))
{
return ERROR
}
response.setContentType("APPLICATION/xml")
logger.debug("filename: $cfileFileName")
response.addHeader("Content-Disposition", "attachment; filename=\""+cfileFileName+"\"")
response.getWriter().print(executionResponse)
logger.debug("executionResponse :" + executionResponse)
invoker.invoke(MYChains.clean)
}catch (Exception exp) {
logger.error("Exception while Creating Status ")
logger.error(exp.printStackTrace())
}
return NONE
}
#Override
public void setServletRequest(HttpServletRequest request) { this.request = request; }
#Override
public void setServletResponse(HttpServletResponse response) { this.response = response; }
public File getcfile() { cfile }
public void setcfile(File cfile) { this.cfile = cfile }
public String getcfileFileName() { cfileFileName }
public void setcfileFileName(String cfileFileName){ this.cfileFileName = cfileFileName }
}
and below class to write stream into response
class DownloadStatusResponse implements Command {
static Logger logger = Logger.getLogger(DownloadStatusResponse.class);
#Override
public boolean execute(Context ctx) throws Exception
{
logger.debug("Inside DownloadStatusResponse.execute() method")
OutputStream response = null;
if(ctx.get(ContextParams.absFileName) != null && ctx.get(ContextParams.absFileName).toString().trim().length() != 0 )
{
HttpServletResponse resp = ctx.get(ContextParams.response)
/*I am trying to get Response here*/
response=downloadStatusFile(ctx.get(ContextParams.absFileName).toString(),resp)
}
logger.debug("Response: " + response)
ctx.put(ContextParams.response,response); /*ContextParams is a enum of keywords, having response*/
return false;
}
private OutputStream downloadStatusFile(String filename,HttpServletResponse resp)
{
logger.info("Inside downloadStatusFile() method")
File fname = new File(filename)
if(!fname.exists())
{
logger.info("$filename does not exists")
return null
}
else
{
resp.setContentType("APPLICATION/xml")
/*Exception: cannot setContentType on null object*/
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"")
FileInputStream istr = new FileInputStream(fname)
OutputStream ostr = resp.getOutputStream()
/*I need to use resp.getOutputStream() for ostr*/
int curByte=-1;
while( (curByte=istr.read()) !=-1)
ostr.write(curByte)
ostr.flush();
}
return ostr
}
}
My question is how can ostr be returned to the response in DownloadStatus class?
Update (working test servlet)
I have this below servlet which does the job of getting file content into a stream and giving it back to the HttpServletResponse, but i want to use it in above code
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String fileName = req.getParameter("zipFile");
if(fileName == null) return;
File fname = new File(fileName);
System.out.println("filename");
if(!fname.exists()) {System.out.println("Does not exists"); return;}
FileInputStream istr = null;
OutputStream ostr = null;
//resp.setContentType("application/x-download");
resp.setContentType("APPLICATION/ZIP");
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"");
System.out.println(fname.getName());
try {
istr = new FileInputStream(fname);
ostr = resp.getOutputStream();
int curByte=-1;
while( (curByte=istr.read()) !=-1)
ostr.write(curByte);
ostr.flush();
} catch(Exception ex){
ex.printStackTrace(System.out);
} finally{
try {
if(istr!=null) istr.close();
if(ostr!=null) ostr.close();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
try {
resp.flushBuffer();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}
As far as I understand all you require is how to download a file using Struts2.
You need something like this is your struts.xml file
<action name="downloadfile" class="DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="document.pdf"</param>
<param name="bufferSize">1024</param>
</result>
</action>
Code:
public class DownloadAction extends ActionSupport {
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String execute() throws FileNotFoundException {
String filePath = ServletActionContext.getServletContext().getRealPath("/uploads");
File f = new File(filePath + "/nn.pdf");
System.out.println(f.exists());
inputStream = new FileInputStream(f);
return SUCCESS;
}
}