FileUpload: Get the full path of the CSV file - sql

I'm working on a project or I want to upload an Excel CSV file that contains data from a table that I have in the database using the query LOAD DATA LOCAL, I test the query using the full path of the file with its path (example C: //../file.csv) directly in the query it works without problem, I wanted to work with the library primefaces p: fileUpload and when I choose a file CSV from my desktop or from another directory on my pc, it only returns the name of the file I selected and not the full path of the hit I have an error:
org.hibernate.exception.GenericJDBCException: could not execute statement
java.io.FileNotFoundException: extraction1.csv (The specified file can not be found)
Forced because there is not the full path of the file with the name of the folder, what I want is to return the name of the file with its root files from where I have selected so that my request can to execute correctly, as to show on the code below I wish that the path where the file is located when I select also be returned with the name of the file in question, and thanks.
prelevServ.importToDB("C:\\Users\\helyoubi\\Desktop\\Japon 2\\"+fichierUpload.getFileName());
My JSF form:
<h:form enctype="multipart/form-data">
    <p:growl id="messages" showDetail="true" />
<p:fileUpload label="Choisir" value="#{importFichier.fichierUpload}" mode="simple" skinSimple="true"/>
<p:separator/>
<p:commandButton value="Envoyer" ajax="false" action="#importFichier.importation}" />
</h:form>
My managedBean formula:
#ManagedBean
public class ImportFichier implements Serializable{
     
    /**
     *
     */
    private static final long serialVersionUID = 1L;
 
    private UploadedFile fichierUpload;
     
    private PrelevementServices prelevServ = new PrelevementServicesImpl();
     
 
     
    public UploadedFile getFichierUpload() {
        return fichierUpload;
    }
 
 
 
 
    public void setFichierUpload(UploadedFile fichierUpload) {
        this.fichierUpload = fichierUpload;
    }
 
 
 
 
    public void importation() {
 
        if(fichierUpload.getFileName()!= null) {
         
            //prelevServ.importToDB("C:\\Users\\helyoubi\\Desktop\\Japon 2\\"+fichierUpload.getFileName());
             
            prelevServ.importToDB(fichierUpload.getFileName());
             
            FacesMessage message = new FacesMessage("Succesful", fichierUpload.getFileName()+ " is uploaded.");
             
            FacesContext.getCurrentInstance().addMessage(null, message);
             
        }else {
             
            FacesMessage message = new FacesMessage("Le chemin du fichier : "+fichierUpload.getFileName()+" est introuvable");
             
            FacesContext.getCurrentInstance().addMessage(null, message);
             
        }
         
     
        System.out.println("CSV added to your the DB Table");
         
    }
     
     
 
}
My request :
#Override
    public void importToDB(String cheminFichier) {
         
        session.beginTransaction();
         
        session.createSQLQuery("LOAD DATA LOCAL INFILE :filename INTO TABLE Prelevement_saisons FIELDS TERMINATED BY ',' ENCLOSED BY '\"'(espece,saison,departement,commune,code,attributions,realisations)").setString("filename", cheminFichier).executeUpdate();
         
        session.getTransaction().commit();
         
    }

Try sending .getPath():
prelevServ.importToDB(fichierUpload.getPath());

Related

Export all jobs from jenkins including run history

Ideally I need a script that outputs the following information in a CSV format that's easy to import into Excel:
job name,number of times run in last year,number of times run overall,last run status
For that job, output no individual run details.
Tried this on my Jenkins:
List Jenkins job build detials for last one year along with the user who triggered the build.
but got an error:
java.lang.NullPointerException: Cannot invoke method getShortDescription() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
Any idea what in the Groovy needs changing? or is there a better solution?
Thanks all!
Thanks to #daggett and #ian . Both worked.
I went with IANS :
def jobNamePattern ='.*'   // adjust to folder/job regex as needed
def daysBack = 365   // adjust to how many days back to report on
def timeToDays = 24*60*60*1000  // converts msec to daysprintln "Job Name: ( # builds: last ${daysBack} days / overall )  Last Status\n   Number | Trigger | Status | Date | Duration\n"Jenkins.instance.allItems.findAll() {
  it instanceof Job && it.fullName.matches(jobNamePattern)
}.each { job ->
  builds = job.getBuilds().byTimestamp(System.currentTimeMillis() - daysBack*timeToDays, System.currentTimeMillis())
  println job.fullName + ' ( ' + builds.size() + ' / ' + job.builds.size() + ' )  ' + job.getLastBuild()?.result
  
  // individual build details
  builds.each { build ->
    println '   ' + build.number + ' | ' + build.getCauses()[0]?.getShortDescription() + ' | ' + build.result + ' | ' + build.getTimestampString2() + ' | ' + build.getDurationString()
  }
}
return

How to send Ionic push notifications using Parse-Server?

I want to send push notifications from my ionic app to app now I wrote parse cloud code and  normal typescript but both are not working, actually m requirement is sending push notification to all devices and also specific device,please review my code below and help me 
my cloud code
Parse.Cloud.define("send", (request) => {
enter code here
    return Parse.Push.send({
        channels: ["News"],
        data: {
            title: "Hello from the Cloud Code",
            alert: "Back4App rocks!",
        }
    }, { useMasterKey: true });
});
typescript code
calling cloud code
Parse.Cloud.run('send').then(function (ratings) { debugger console.log("updated"); // result should be 'Update object successfully' }).catch((error) => { console.log(error) console.log("fail") });
You should add a query parameter. That way the push knows which user to send the push too.
You don't need the query parameter for channels. Do your installation have the channel?
Feel free to open an issue on the JS SDK.

Load file into textarea from uploaded files in primefaces

I would like to display text file into textarea in primefaces.
Following user define steps are:
Click on Upload control (user can upload multiple files)
I am fetching all uploaded files and displaying file name in radio button
From radio buttons, User will select one of the file and that file
will load into textarea.
While performing 3rd steps, I am getting following error
java.io.FileNotFoundException: C:\Users\UserName\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\ProjectDummy\upload_d8a75697_ad88_43fe_acd8_8133bf93d727_00000017.tmp (The system cannot find the file specified)
javax.servlet.ServletException: java.io.FileNotFoundException: C:\Users\UserName\Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\ProjectDummy\upload_d8a75697_ad88_43fe_acd8_8133bf93d727_00000017.tmp (The system cannot find the file specified)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Following is the code:
Xhtml code:
<h:form method="POST" enctype="multipart/form-data"
prependId="false">
<p:growl id="messages" showDetail="true" />
<p:panelGrid columns="1">
<p:fileUpload
fileUploadListener="#{backingBean.handleFileUpload}"
mode="advanced" update="messages,console" auto="true"
multiple="true" />
<br />
<br />
<p:selectOneRadio id="console" value="#{backingBean.fileName}"
layout="grid" columns="1">
<f:selectItems value="#{backingBean.fileNames}" var="f"
itemLabel="#{fileName}" itemValue="#{fileName}" />
</p:selectOneRadio>
<p:commandButton value="Load" action="#{backingBean.loadFile}"
ajax="false" update="txtInput" process="#all" style="width:80px"></p:commandButton>
<br />
<br />
<p:inputTextarea id="txtInput" value="#{backingBean.fileText}"
rows="10" cols="50">
</p:inputTextarea>
</p:panelGrid>
</h:form>
BackingBean.java
public void handleFileUpload(FileUploadEvent event) throws IOException, NotSerializableException {
li = new ArrayList<UploadedFile>();
li.add(event.getFile());
setLi(li);
ListIterator<UploadedFile> list = li.listIterator();
while (list.hasNext()) {
String str = event.getFile().getFileName();
System.out.println(str);
++count;
fileNames.add(str);
fileList.add(event.getFile());
list.next();
}
}
public void loadFile() throws IOException, NotSerializableException {
String filenameRadio = getFileName();
for (int i = 0; i < count; i++) {
String fileS = fileList.get(i).getFileName();
if (fileS.equalsIgnoreCase(filenameRadio)) {
setUploadedFile(fileList.get(i));
InputStream is = getUploadedFile().getInputstream();
int read = 0;
byte[] bytes = new byte[(int) fileList.get(i).getSize()];
String s1;
while ((read = is.read(bytes)) != -1) {
s1 = new String(fileList.get(i).getContents());
setFileText(s1);
System.out.println(getFileText());
}
is.close();
}
}
}
Could help me to solve this error ?

Why NoPointerExcepeion when decompression by apache compress?

click and see The NoPointerExcepeion
I generate tar.gz files and send 2 others 4 decompress, but their progrem has error above(their progrem was not created by me), only one file has that error.
But when using command 'tar -xzvf ***' on my computer and their computer, no problem occured...
So I want 2 know what was wrong in my progrem below:
public static void archive(ArrayList<File> files, File destFile) throws Exception {
TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(destFile));
taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
for (File file : files) {
//LOG.info("file Name: "+file.getName());
archiveFile(file, taos, "");
}
}
private static void archiveFile(File file, TarArchiveOutputStream taos, String dir) throws Exception {
TarArchiveEntry entry = new TarArchiveEntry(dir + file.getName());
entry.setSize(file.length());
taos.putArchiveEntry(entry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
taos.write(data, 0, count);
}
bis.close();
taos.closeArchiveEntry();
}
The stack trace looks like a bug in Apache Commons Compress https://issues.apache.org/jira/browse/COMPRESS-223 that has been fixed with version 1.7 (released almost three years ago).

ASP MVC 2 Uploading file to database (blob)

I am trying to upload a file via a form and then save in in SQL as a blob.
I already have my form working fine, my database is fully able to take the blob and I have a controller that take the file, saves it in a local directory:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(int id, HttpPostedFileBase uploadFile)
{
//allowed types
string typesNonFormatted = "text/plain,application/msword,application/pdf,image/jpeg,image/png,image/gif";
string[] types = typesNonFormatted.Split(',');
//
//Starting security check
//checking file size
if (uploadFile.ContentLength == 0 && uploadFile.ContentLength > 10000000)
ViewData["StatusMsg"] = "Could not upload: File too big (max size 10mb) or error while transfering the file.";
//checking file type
else if(types.Contains(uploadFile.ContentType) == false)
ViewData["StatusMsg"] = "Could not upload: Illigal file type!<br/> Allowed types: images, Ms Word documents, PDF, plain text files.";
//Passed all security checks
else
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName)); //generating path
uploadFile.SaveAs(filePath); //saving file to final destination
ViewData["StatusMsg"] = "Uploaded: " + uploadFile.FileName + " (" + Convert.ToDecimal(uploadFile.ContentLength) / 1000 + " kb)";
//saving file to database
//
//MISSING
}
return View("FileUpload", null);
}
Now all I am missing is putting the file in the database. I could not find anything on the subject... I found some way to do it in a regular website but nothing in MVC2.
Any kind of help would be welcome!
Thank you.
This could help: http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/
Since you have HttpPostedFileBase in your controllers method, all you need to do is:
int length = uploadFile.ContentLength;
byte[] tempImage = new byte[length];
myDBObject.ContentType = uploadFile.ContentType;
uploadFile.InputStream.Read(tempImage, 0, length);
myDBObject.ActualImage = tempImage ;
HttpPostedFileBase has a InputStream property
Hope this helps.
Alright thanks to kheit, I finaly got it working. Here's the final solution, it might help someone out there.
This script method takes all the file from a directory and upload them to the database:
//upload all file from a directory to the database as blob
public void UploadFilesToDB(long UniqueId)
{
//directory path
string fileUnformatedPath = "../Uploads/" + UniqueId; //setting final path with unique id
//getting all files in directory ( if any)
string[] FileList = System.IO.Directory.GetFiles(HttpContext.Server.MapPath(fileUnformatedPath));
//for each file in direcotry
foreach (var file in FileList)
{
//extracting file from directory
System.IO.FileStream CurFile = System.IO.File.Open(file, System.IO.FileMode.Open);
long fileLenght = CurFile.Length;
//converting file to a byte array (byte[])
byte[] tempFile = new byte[fileLenght];
CurFile.Read(tempFile, 0, Convert.ToInt32(fileLenght));
//creating new attachment
IW_Attachment CurAttachment = new IW_Attachment();
CurAttachment.attachment_blob = tempFile; //setting actual file
string[] filedirlist = CurFile.Name.Split('\\');//setting file name
CurAttachment.attachment_name = filedirlist.ElementAt(filedirlist.Count() - 1);//setting file name
//uploadind attachment to database
SubmissionRepository.CreateAttachment(CurAttachment);
//deleting current file fromd directory
CurFile.Flush();
System.IO.File.Delete(file);
CurFile.Close();
}
//deleting directory , it should be empty by now
System.IO.Directory.Delete(HttpContext.Server.MapPath(fileUnformatedPath));
}
(By the way IW_Attachment is the name of one of my database table)