Is it possible to extract a large file using Truezip in java? - truezip

import java.io.IOException;
import utils.myDate;
import utils.myLog;
import de.schlichtherle.truezip.file.TArchiveDetector;
import de.schlichtherle.truezip.file.TFile;
public class Main
{
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Extract(new String("C:/Documents and Settings/mitracomm/My Documents/Downloads/JAR"), new String("D:/Source/Extract Result") , "");
}
private static void Extract(String src, String dst, String incPath)
{
TFile srcFile = new TFile(src + "/" + incPath);
TFile dstFile = new TFile(dst);
try {
TFile.cp_rp(srcFile, dstFile, TArchiveDetector.ALL);
} catch (IOException e) {
myLog.add(myDate.today("yyyyMMdd") + ".log", "error", e.getMessage());
}
}
Will the above code work with a large archive? Also, how can I extract every archive in a directory without having to fill the incPath or specify archives' name? I have tried to do this but I end up with copies of all the archives from origin directory and not extracted files.

The code is principally OK, but I'ld use:
public class Main {
public static void main(String[] args) {
Extract(new String("C:/Documents and Settings/mitracomm/My Documents/Downloads/JAR"), new String("D:/Source/Extract Result") , "");
}
private static void Extract(String src, String dst, String incPath) {
TFile srcFile = new TFile(src, incPath);
TFile dstFile = new TFile(dst);
try {
TFile.cp_rp(srcFile, dstFile, TArchiveDetector.NULL);
} catch (IOException e) {
// I don't like logging for this purpose, but if you must...
myLog.add(myDate.today("yyyyMMdd") + ".log", "error", e.getMessage());
}
}
}
I'm not sure if you really want three arguments for the Extract method, though.
And finally, yes TrueZIP handles ZIP files beyond 4GB size correctly.

Related

How to choose the encode of a file created by SmbFileOutputStream?

I am using a method to create a file in a specific path in a shared folder inside my local net.
public static void stringToArquivoTextoRemoto(String path, String fileName, String content, NtlmPasswordAuthentication auth) {
String absolutePath = path + File.separator + fileName;
try {
jcifs.Config.setProperty("jcifs.smb.client.disablePlainTextPasswords", "false");
SmbFile smbFile = new SmbFile(absolutePath, auth);
SmbFileOutputStream smbFileOutputStream = new SmbFileOutputStream(smbFile);
smbFileOutputStream.write(content.getBytes());
smbFileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Now, I am trying to change the encode from "UTF-8" to "ISO-8859-1".
I already tried to put:
jcifs.Config.setProperty( "jcifs.encoding", "ISO-8859-1" );
But it didn't work.
I found a lot of information about how to change the encode using the FileOutputStream, but I found nothing about this using SmbFileOutputStream.
What do I need to do to choose the encode of a file created by SmbFileOutputStream?
This will solve the issue:
package fileWriting;
import java.io.IOException;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
public class testWriting {
public static void main(String[] args) throws IOException {
String user = "domain;username:password";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = "smb://shared/Projects/test.txt";
SmbFile sFile = new SmbFile(path, auth);
try (SmbFileOutputStream sfos = new SmbFileOutputStream(sFile)) {
String v = "Test for file writing!";
byte[] utf = v.getBytes("UTF-8");
byte[] latin1 = new String(utf, "UTF-8").getBytes("ISO-8859-1");
sfos.write(latin1,0,latin1.length );
}
}
}

how can I key rotate for google cloud storage service account?

I have written code for accessing GCS bucket to store files thru API in java which takes JSON credential file. I have created that JSON file from google console. I need to automate the JSON file or key rotation for every 90 days. How to regenerate/rotate that JSON file? I am a newbie to GCS.
import java.io.IOException;
import java.security.GeneralSecurityException;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamRequest;
import com.google.api.services.iam.v1.IamRequestInitializer;
import com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest;
public class TestServiceAccount {
public static void main(String[] args) {
// TODO Auto-generated method stub
//ServiceAccountKey key = new ServiceAccountKey();
try {
System.out.println("created");
String KEY = "AIzaSyDjHg2u4bwfvncb_YwdjJC_vUPRYLW5Sh8";
IamRequestInitializer req = new IamRequestInitializer(KEY);
HttpTransport transport;
transport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = new JacksonFactory();
Iam iam = new Iam(transport,jsonFactory,new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) {
httpRequest.setConnectTimeout(0);
httpRequest.setReadTimeout(0);
}
});
//https://iam.googleapis.com/v1/projects/newsampleproject/serviceAccounts/NewServiceAccount/keys
MyIamRequest<String> request = new MyIamRequest<String>(
iam, HttpMethods.POST, "/v1/projects/newsampleproject/serviceAccounts/NewServiceAccount/keys", String.class, String.class);
req.initialize(request);
System.out.println(req.getKey());
req.initializeJsonRequest(request);
System.out.println(req.getUserIp());
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
//req.initializeJsonRequest(request);
}
public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
});
}
}
This what I have written to call the API But i am not sure if this is the way to call it.
try this solution, it worked for me
private static void createNewKey(IamRequestInitializer req) throws IOException, GeneralSecurityException {
Iam iam = jsonAuthentication();
CreateServiceAccountKeyRequest keyRequest = new CreateServiceAccountKeyRequest();
keyRequest.setKeyAlgorithm(KEY_ALGO);
String account = SERVICE_ACCOUNT_URL + SERVICE_ACCOUNT_EMAIL;
iam.projects().serviceAccounts().keys().create(account, keyRequest);
String requestString = BASE_URL + SERVICE_ACCOUNT_EMAIL + KEY;
ServiceAccountKey result = getServiceAccountKey(req, iam, requestString);
String jsonKey = new String(result.decodePrivateKeyData());
System.out.println(jsonKey);
JsonFileUtil.createFile(JSON_KEY_FILE_NAME, jsonKey);
}
private static <T> T getServiceAccountKey(IamRequestInitializer req, Iam iam, String requestString)
throws IOException {
MyIamRequest<String> request = new MyIamRequest<String>(iam, HttpMethods.POST, requestString, String.class,
ServiceAccountKey.class);
request.setKey(API_KEY);
request.setFields(
"keyAlgorithm,name,privateKeyData,privateKeyType,publicKeyData,validAfterTime,validBeforeTime");
req.initializeJsonRequest(request);
System.out.println(request.getRequestHeaders());
return (T) request.execute();
}
If you're using a JSON credential file, you are acting as some particular service account which is a member of your project and has access to the files.
Service accounts can be programmatically controlled for exactly this sort of use case. The IAM Service Account API controls service accounts, and the two methods you want for key rotation are serviceAccount.keys.create() and serviceAccount.keys.delete().
The result of the create() call (if you pass in the private key type TYPE_GOOGLE_CREDENTIALS_FILE), will be a new, valid JSON credential file for your service account.
#user7049946
ServiceAccountKey response = getServiceAccountKey(req, iam, requestString);
CreateNewJson.createFile("NEW_JSON_KEY_FILE_NAME", new String(response.decodePrivateKeyData()));
create new class to convert that conent into new file.
public class CreateNewJson {
public static void createFile(String filename, String content) throws IOException {
FileOutputStream fileOutputStream = null;
File file;
file = new File(filename);
fileOutputStream = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}else{
file.delete();
file.createNewFile();
}
byte[] contentInBytes = content.getBytes();
fileOutputStream.write(contentInBytes);
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("File Created");
}
}

Eclipse Project dependencies dont work when exported

I am currently facing following big problem:
I have a Framework-Project (maven), where a PropertyReader is included (reads "config.properties" in the same package and returns its values):
This is the Framework-Project:
public class PropertyReaderFramework {
private static Properties props;
private static void init(){
String filename = "com/ks/framework/properties/config.properties";
InputStream input = PropertyReaderFramework.class.getClassLoader()
.getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
props = null;
} else {
props = new Properties();
}
try {
props.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key){
if(props == null) init();
return props.getProperty(key);
}
public static Properties getProperties(){
if(props == null) init();
return props;
}
}
And my main-project, where I need the information of the properties-file just has one class (for demonstation):
package testmsg;
import com.ks.framework.properties.PropertyReaderFramework;
public class main {
public static void main(String[] args) throws InterruptedException {
try {
String basepath = PropertyReaderFramework.getProperty("remoteFileAccess.script.location");
System.out.println(basepath);
} catch (Exception e) {
e.printStackTrace();
} finally {
Thread.sleep(5000);
}
}
}
The funny thing is, that if I execute the main() class in eclipse, it reads the value from the properties correctly.
But when I export it as a runnable JAR, it throws me following error:
Can anyone help me to solve this problem? I cannot figure out why it behaves like that...

Can't seems to load dlls in java Web Start

I'm having a huge problem with my java webstart application, I have tries a lot of solutions, but none seems to work correctly in th end.
I need to write a webstart applet to load basic hardware info about the client computer to check if my client can connect on our systems and use the software four our courses. I use Sigar to load the CPU and Memory information and then use JNI to load a custom c++ script that check the graphic card name (This one works perfectly).
I've put all my dlls in src/resources folder to load them in the jar, I also use what we call here "engines" which are classed that do specified operations (In our case, Jni Engine, Config Engine and Data Engine (Code below)), I'm new to webstart so I'm not sure if this concept works well with library loading.
I've tries to add the dlls in a jar as a library in Netbeans, I've tried to add the dlls in the jnlp, but each run recreates it and I can't add them with project properties, finnaly, I've built my Data Engine in a way that should load the dlls in the java temp directory in case they are not there, but Sigar still don't want to work. I've also put my dll in the java.library.path correctly cofigured (As it works in local).
It work when I run my main class locally (With right click-run), but when I click the run button to load the webstart, it crashes with this error message (it happens in ConfigEngine as it extends SigarBase) :
JNLPClassLoader: Finding library sigar-amd64-winnt.dll.dll
no sigar-amd64-winnt.dll in java.library.path
org.hyperic.sigar.SigarException: no sigar-amd64-winnt.dll in java.library.path
Here's the code :
JNi Engine (Loads the c++ code for the graphic card)
package Engine;
public class JniEngine
{
static private final String nomLibJni = "JniEngine";
static private final String nomLibJni64 = "JniEngine_x64";
static
{
if (System.getProperty("os.arch").contains("86"))
{
System.loadLibrary(nomLibJni);
}
else
{
System.loadLibrary(nomLibJni64);
}
}
public native String getInfoGPU() throws Error;
}
ConfigEngine
package Engine;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.cmd.SigarCommandBase;
public class ConfigEngine extends SigarCommandBase
{
private final String nomOsAcceptes = "Windows";
static
{
DataEngine data;
}
public ConfigEngine()
{
super();
}
#Override
public void output(String[] args) throws SigarException
{
}
public HashMap<String, String> getMap() throws SigarException, SocketException
{
HashMap<String, String> hmConfig = new HashMap<>();
loadInfoCpu(hmConfig);
loadInfoRam(hmConfig);
loadInfoOs(hmConfig);
loadInfoNet(hmConfig);
loadInfoGpu(hmConfig);
return hmConfig;
}
private void loadInfoCpu(HashMap<String,String> Hashmap) throws SigarException
{
org.hyperic.sigar.CpuInfo[] configCpu = this.sigar.getCpuInfoList();
org.hyperic.sigar.CpuInfo infoCpu = configCpu[0];
long cacheSize = infoCpu.getCacheSize();
Hashmap.put("Builder", infoCpu.getVendor());
Hashmap.put("Model" , infoCpu.getModel());
Hashmap.put("Mhz", String.valueOf(infoCpu.getMhz()));
Hashmap.put("Cpus nbr", String.valueOf(infoCpu.getTotalCores()));
if ((infoCpu.getTotalCores() != infoCpu.getTotalSockets()) ||
(infoCpu.getCoresPerSocket() > infoCpu.getTotalCores()))
{
Hashmap.put("Cpus", String.valueOf(infoCpu.getTotalSockets()));
Hashmap.put("Core", String.valueOf(infoCpu.getCoresPerSocket()));
}
if (cacheSize != Sigar.FIELD_NOTIMPL) {
Hashmap.put("Cache", String.valueOf(cacheSize));
}
}
private void loadInfoRam(HashMap<String,String> Hashmap) throws SigarException
{
org.hyperic.sigar.Mem mem = this.sigar.getMem();
Hashmap.put("RAM" , String.valueOf(mem.getRam()));
Hashmap.put("Memoery", String.valueOf(mem.getTotal()));
Hashmap.put("Free", String.valueOf(mem.getUsed()));
}
private void loadInfoOs(HashMap<String,String> Hashmap) throws SigarException
{
Hashmap.put("OS", System.getProperty("os.name"));
Hashmap.put("Version", System.getProperty("os.version"));
Hashmap.put("Arch", System.getProperty("os.arch"));
}
private void loadInfoNet(HashMap<String,String> Hashmap) throws SocketException
{
List<NetworkInterface> interfaces = Collections.
list(NetworkInterface.getNetworkInterfaces());
int i = 1;
for (NetworkInterface net : interfaces)
{
if (!net.isVirtual() && net.isUp())
{
Hashmap.put("Port Name " + String.valueOf(i), net.getDisplayName());
}
i++;
}
}
private void loadInfoGpu(HashMap<String,String> Hashmap) throws SocketException
{
if (System.getProperty("os.name").contains(nomOsAcceptes))
{
JniEngine Jni = new JniEngine();
Hashmap.put("VGA", Jni.getInfoGPU());
}
}
}
Finally my Data Engine which tries to load all the dlls and change the library path (Most of it is temporary as it is patches on patches)
package Engine;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class DataEngine
{
static private final String nomLibSigar = "sigar-x86-winnt";
static private final String nomLibSigar64 = "sigar-amd64-winnt";
static private final String nomLibJni = "JniEngine";
static private final String nomLibJni64 = "JniEngine_x64";
static private final String NomJar86 = "lib_config_x86";
static private final String nomJar64 = "lib_config_x64";
static private final String path = "Resources\\";
static
{
try
{
if (System.getProperty("os.arch").contains("86"))
{
System.loadLibrary(nomLibJni);
System.loadLibrary(nomLibSigar);
}
else
{
System.loadLibrary(nomLibJni64);
System.loadLibrary(nomLibSigar64);
}
}
catch (UnsatisfiedLinkError ex)
{
loadJniFromJar();
loadSigarFromJar();
}
}
public static void loadSigarFromJar()
{
try
{
File dll;
InputStream is;
if (System.getProperty("os.arch").contains("86"))
{
is = DataEngine.class.getResourceAsStream(
path + nomLibSigar + ".dll");
dll = File.createTempFile(path + nomLibSigar, ".dll");
}
else
{
is = DataEngine.class.getResourceAsStream(
path + nomLibSigar64 + ".dll");
dll = File.createTempFile(path + nomLibSigar64, ".dll");
}
FileOutputStream fos = new FileOutputStream(dll);
byte[] array = new byte[1024];
for (int i = is.read(array);
i != -1;
i = is.read(array))
{
fos.write(array, 0, i);
}
fos.close();
is.close();
System.load(dll.getAbsolutePath());
System.setProperty("java.library.path", dll.getAbsolutePath());
}
catch (Throwable e)
{
}
}
public static void loadJniFromJar()
{
try
{
File dll;
InputStream is;
if (System.getProperty("os.arch").contains("86"))
{
is = DataEngine.class.getResourceAsStream(
path + nomLibJni + ".dll");
dll = File.createTempFile(path + nomLibJni, ".dll");
}
else
{
is = DataEngine.class.getResourceAsStream(
path + nomLibJni64 + ".dll");
dll = File.createTempFile(path + nomLibJni64, ".dll");
}
FileOutputStream fos = new FileOutputStream(dll);
byte[] array = new byte[1024];
for (int i = is.read(array);
i != -1;
i = is.read(array))
{
fos.write(array, 0, i);
}
fos.close();
is.close();
System.load(dll.getAbsolutePath());
}
catch (Throwable e)
{
}
}
}
I also have some problem with my main class (NetBeans don't want my JAppletForm to be the main class of my project, but I'll probably recreate the project anyway since the hundreds of patches I tries have corrupted the build. My main class simply load the HashMap with GetMap of ConfigEngine and show it in the console if local or in the JAppletForm if it runs with webstart.
Its a pretty big problem so I'll update my question with all the info you'll need if asked.

How to change the default folder for uploading file in jboss

I am trying to upload a file, I am trying to change the default location of the uploaded file. How to change this please suggest ?
package Controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import requests.Connect;
import display.DisplayLog;
/** * Servlet implementation class ControlServlet
*/
public class ControlServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
boolean result;
private boolean isMultipart;
private String filePath;
private int maxFileSize = 1000 * 1024;
private int maxMemSize = 1000 * 1024;
private File file ;
public ControlServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session=request.getSession();
String userName = request.getParameter("username");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("audio/mpeg3;audio/x-mpeg-3;video/mpeg;video/x-mpeg;text/xml");
PrintWriter out = response.getWriter( );
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
String root = getServletContext().getRealPath("/");
root = "F/images";
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(" Prashant File Upload Location is ");
// System.out.println(uploadedFile.getAbsolutePath());
System.out.println("fileName is " +fileName);
System.out.println("root is " + root);
System.out.println("path is " + path);
if(fileName!="")
{
item.write(uploadedFile);
System.out.println(" Prashant File Upload Location 2 is ");
System.out.println(uploadedFile.getAbsolutePath());
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
out.println(uploadedFile.getAbsolutePath());
out.println("<h1>File Uploaded Successfully....:-)</h1>");
System.out.println("file not found");
}
}
else
{
String abc = item.getString();
}
}
} catch (FileUploadException e) {
out.println(e);
} catch (Exception e) {
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
System.out.println("print this Prashant" + userName);
session.setAttribute("username",userName);
request.setAttribute("username","prashant");
// RequestDispatcher myDispatch = request.getRequestDispatcher("Index.jsp");
//myDispatch.forward(request, response);
}
}
I am getting this as default folder F:\jboss-4.2.3.GA-jdk6\jboss-4.2.3.GA\bin\ please help i am new to this
Your problem is here:
String root = getServletContext().getRealPath("/");
you are setting the upload path to the containers path, not a default path but the place where the server started from. You can make the upload path anything you want it to be, it depends on your needs and configuration.
You could create a system property with the directory of your choice, you could set it as a dynamic property in a JBoss configuration file (not sure what that would be for JBoss4).