Issue with storing image files for profile pictures - java

I'm doing a coursework project for university and I'm in charge of getting the profile system functioning. Our lecturer has given us some sample code to get a file-upload working which I'm going to use for the user's profile picture however even though my code looks to be very similar I just can't seem to get it working. The issue is that the file won't actually create and save in my project, yet the code my lecturer gave me does!
Here is the code the lecturer gave me:
NewsStory newsstory = new NewsStory();
newsstory.uniqueid = "story_"+System.currentTimeMillis();
newsstory.dateItWasPublished = System.currentTimeMillis();
newsstory.title = toProcess.params.get("title");
newsstory.description = toProcess.params.get("description");
newsstory.journalists.add(toProcess.params.get("journalist"));
newsstory.filepathToImage = toProcess.params.get("fileupload");
File uploaded = new File(newsstory.filepathToImage);
int ind = newsstory.filepathToImage.lastIndexOf('.');
String extension = newsstory.filepathToImage.substring(ind);
uploaded.renameTo(new File("httpdocs/"+newsstory.uniqueid+extension));
newsstory.filepathToImage = newsstory.uniqueid+extension;
//At this point you would normally add the newsstory to the database
MVMap<String, NewsStory> newsStories = db.s.openMap("NewsStories");
newsStories.put(newsstory.uniqueid, newsstory);
This basically takes in a String from a fileupload paramater passed in through a form and runs the code below. Here is my code:
user.userEmail = toProcess.params.get("email");
user.profilePicturePath = toProcess.params.get("filepath");
System.out.println(user.profilePicturePath);
File uploaded = new File(user.profilePicturePath);
int ind = user.profilePicturePath.lastIndexOf('.');
String extension = user.profilePicturePath.substring(ind);
uploaded.renameTo(new File("httpdocs/"+user.username+"ProfilePicture"+extension));
user.profilePicturePath = user.username+"ProfilePicture"+extension;
System.out.println(user.profilePicturePath);
users.put(user.username, user);
db.commit();
Does anyone know why I might be having this issue?

Related

Create BE Initiative, BE Feature and CPM Feature using Rally Rest Client in Java

We are trying to automate the project migration from one Rally workspace to other. Everything seems to work fine like we are able to migrate project and related releases/iterations/userstories/tasks from one workspace to another workspace.
But while trying to migrate BE Initiative/BE Feature/CPM Feature we are getting some exception related to Null Pointer exception but the error we are getting in Response doesn't seem to give much info.
A sample of code is -
String oldProjectObjectId = "12345";
String newProjectObjectId = "67890";
String oldRallyWorkspaceObjectId = "32145";
String newRallyWorkspaceObjectId = "67894";
QueryResponse beInitiativeResponse = queryRally("portfolioitem/beinitiative", "/project/"+this.oldProjectObjectId, "/workspace/"+this.oldRallyWorkspaceObjectId);
int beInitiativeCount = beInitiativeResponse.getTotalResultCount();
if(beInitiativeCount >0){
JsonArray initiativeArray = beInitiativeResponse.getResults();
for(int i=0; i< initiativeArray.size();i++){
JsonObject beInitiativeObject = initiativeArray.get(i).getAsJsonObject();
String oldBeInitiativeObjectId = beInitiativeObject.get("ObjectID").getAsString();
String oldBeInitiativeName = beInitiativeObject.get("_refObjectName").getAsString();
String owner = getObjectId(beInitiativeObject, "Owner");
JsonObject BeInitiativeCreateObject = getJsonObject(oldBeInitiativeName, "/project/"+this.newProjectObjectId, "/workspace/"+this.newRallyWorkspaceObjectId, owner);
CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/beinitiative", BeInitiativeCreateObject);
if(beInitiativeCreateResponse.wasSuccessful()){
String newBeInitiativeObjectId = beInitiativeCreateResponse.getObject().get("ObjectID").getAsString();
String mapKey = oldBeInitiativeObjectId;
String mapValue= newBeInitiativeObjectId;
this.beInitiativesHashMap.put(mapKey, mapValue);
}
else{
String[] errorList;
errorList = beInitiativeCreateResponse.getErrors();
for (int j = 0; j < errorList.length; j++) {
System.out.println(errorList[j]);
}
}
}
}
queryRally and createInRally functions use Rally rest client to fetch and create the required projects and associated attributes like releases, iterations etc.
After executing CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/beinitiative", BeInitiativeCreateObject); when it's trying to execute if(beInitiativeCreateResponse.wasSuccessful()) it is instead going to else block and thus printing the below mentioned error.
An unexpected error has occurred.We have recorded this error and will begin to investigate it. In the meantime, if you would like to speak with our Support Team, please reference the information below:java.lang.NullPointerException2017-12-05 11:01 AM PST America/Los_Angeles
But the important point that is when trying to migrate projects and it's related attributes like release/iterations etc. withing same Rally workspace the above piece of code works just fine.
Update1:
While analysing the issue I made the following observations -
The workspace in which I am trying to create the BeInitiative doesn't have BEinitiative, Be Feature, CPM Feature options in Portfolio items dropdown. Rather it has Theme, Initiative and Feature options in it.
Therefore, I think I was getting the previouly mentioned error. Now I made the following changes to the code.
CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/theme", themeCreateObject);
So now instead of creating the BEInitiative I am trying to create the theme only in new workspace but getting the following error -
Requested type name \"/portfolioitem/theme\" is unknown.
The object that i am passing to CreateResponse function is -
{"Name":"xyz","Project":"/project/1804","Workspace":"/workspace/139"}
Also code for createInRally function is as mentioned below -
public CreateResponse createInRally( String query, JsonObject object) throws IOException{
CreateRequest createRequest = new CreateRequest(query, object);
CreateResponse createResponse = restApi.create(createRequest);
return createResponse;
}
The Unknown Type error was occurring as a result of not passing the workspace's object id in which we were trying to create the portfolio item.
So after modifying the createInRally function to include the workspace object id we were able to create the initiative portfolio item.
The modified createInRally function is as shown below-
CreateRequest createRequest = new CreateRequest(query, object);
createRequest.addParam("workspace", "/workspace/1333333333");
CreateResponse createResponse = restApi.create(createRequest);
return createResponse;
So this is definitely an error in the web services api. You should never get 500 responses with an unhandled nullpointer. My initial guess is that when you're creating your new object some field on it is still referencing an object in the old workspace, and when we try to correctly hook up all the associations it fails to read one of those objects in the new workspace. Can you provide some more information about what your actual object you're sending to create looks like? Specifically what object relationships are you including (that may not be valid in the new workspace)?

Open graph fetching meta data

I am using open graph library to fetch the metadata from url.
I am getting the title and description from url link which follow og tag rules. How to get metadata from url link which don't follow og tag.
my simple code :
OpenGraph data = new OpenGraph(url, true);
response.setDescription(data.getContent("description"));
response.setMetaDataImage(data.getContent("image"));
response.setTitle(data.getContent("title"));
response.setMetaDataUrl(data.getContent("url"));
Data fetch is null.
I think you're talking about this library. If so, the boolean in the constructor serves the purpose:
public OpenGraph(String url, boolean ignoreSpecErrors) {
...
}
The way I use this library to fetch, for example, images is as follows:
OpenGraph og = new OpenGraph(url, true);
MetaElement[] imageElements = og.getProperties("image");
Perhaps you are just using the wrong getter? If the page has og tags, this snippet should work!
I had similar issues with opengraph-java (ie. getting null response).
I tried the example in the docs, but the response was null
OpenGraph movie = new OpenGraph("http://www.rottentomatoes.com/m/back_to_the_future/", true);
System.out.println("movie = " + movie)); // movie = null
Trying the false option for ignoreSpecErrors throws an exception java.lang.Exception: Does not conform to Open Graph protocol
So I made a library called ogmapper that's a little more flexible.
DefaultOgMapper ogMapper = new JsoupOgMapperFactory().build();
OgTags ogTags = ogMapper.process(new URL("http://www.rottentomatoes.com/m/back_to_the_future/"));
System.out.println("title = " + ogTags.getTitle()); // title = Back to the Future (1985)
Hopefully this is helpful!

JavaScript Error in BIRT

I have been assigned to clean up a project for a client that uses BIRT reporting. I have fixed most of the issues but I still have one report that is not working and is returning an error. The error is:
Row (id = 1467):
+ There are errors evaluating script "var fileName = row["Attached_File"];
params["HyperlinkParameter"].value = ImageDecoder.decodeDocs(row["Ecrash_Attach"],fileName);":
Wrapped java.lang.NullPointerException (/report/body/table[#id="61"]/detail/row[#id="70"]/cell[#id="71"]/grid[#id="1460"]/row[#id="1462"]/cell[#id="1463"]/table[#id="1464"]/detail/row[#id="1467"]/method[#name="onCreate"]#2)
I can post the full stack trace if someone wants it but for now I will omit it since it is very long.
Here is the source of the decodeDocs method:
public static String decodeDocs(byte[] source, String fileName) {
String randName = "";
byte[] docSource = null;
if ( Base64.isArrayByteBase64(source) ){
docSource = Base64.decodeBase64(source);
}
documentZipPath = writeByteStreamToFile(source);
randName = writeByteStreamToFile(docSource, fileName);
return randName;
}
I am pretty well lost on this one. The error looks to be telling me there is an error on line two of the script which is:
var fileName = row["Attached_File"];
params["HyperlinkParameter"].value = ImageDecoder.decodeDocs(row["Ecrash_Attach"],fileName);
This is written in the OnCreate method of the report. Any help, even clues would be greatly appreciated. If you would like to see the report just ask and I will post the xml for it.
A common mistake I make in BIRT is to access the value of a null report parameter.
In your case, could params["HyperlinkParameter"] be null?

Issue while adding attachment to QC Test Case using Com4j API

I am trying to add attachment to QC Test LAB Test Case run from my Java code using Com4J API. I was able to create a successful run, however while adding attachments below code is throwing invalid parameter for "IAttachment attach = attachfac.addItem(null).queryInterface(IAttachment.class);". In this case additem is expecting Java Item Object. I also tried to pass addItem(""), but then attach.Type(1) is failing with reason:- Attachment Type cannot be changed. Could anyone please help me with this:
IBaseFactory obj2 = testset.tsTestFactory().queryInterface(IBaseFactory.class);
IList tstestlist = obj2.newList("");
for(Com4jObject obj3:tstestlist){
ITSTest tstest = obj3.queryInterface(ITSTest.class);
if(tstest.name().contentEquals("[1]TC1")){
System.out.println("TC found");
IRunFactory runfactory = tstest.runFactory().queryInterface(IRunFactory.class);
IRun run=runfactory.addItem("RunNew").queryInterface(IRun.class);
run.status("Passed");
IAttachmentFactory attachfac = run.attachments().queryInterface(IAttachmentFactory.class);
IAttachment attach = attachfac.addItem("").queryInterface(IAttachment.class);
attach.type(1);
attach.fileName("Path to File TC1");
attach.post();
run.post();.
String fileName = new File(Attachment).getName();
String folderName = new File(Attachment).getParent();
try{
IAttachmentFactory attachfac = tsteststeps.attachments().queryInterface(IAttachmentFactory.class);
IAttachment attach = attachfac.addItem(fileName).queryInterface(IAttachment.class);
IExtendedStorage extAttach = attach.attachmentStorage().queryInterface(IExtendedStorage.class);
extAttach.clientPath(folderName);
extAttach.save(fileName, true);
attach.description(Actual);
attach.post();
attach.refresh();
}catch(Exception e) {
System.out.println("QC Exceptione : "+e.getMessage());
}

OOo: UNO (Java) TrackedChanges: How to accept (or hide) Tracked Changes when Document is hidden?

My Problem: I write an automated system that needs to read .doc and .odt, performs some operation on it and exports it to pdf again.
Currently that works fine for everything I need, I could solve all problems until this one:
If a user provides a Document that had recorded changes (Redlines) I need to automatically accept all that changes or hide them.
I could solve that one with the code below as long as the OOo is showing on screen. When I launch it hidden, my calls do nothing at all.
So, here is what I do currently:
// DO NOT try to cast this to Desktop as com.sun.star.frame.Desktop is NOT a valid class!
// keep it as Object and cast it to XDesktop later (via queryInterface)
Object desktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
XMultiServiceFactory xFactory = (XMultiServiceFactory) UnoRuntime.queryInterface(
XMultiServiceFactory.class, xMCF);
// what goes for desktop above is valid for DispatchHelper as well.
Object dispatchHelper = xFactory.createInstance("com.sun.star.frame.DispatchHelper");
// the DispatchHelper is the class that handles the interaction with dialogs.
XDispatchHelper helper = (XDispatchHelper) UnoRuntime.queryInterface(
XDispatchHelper.class, dispatchHelper);
XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, desktop);
XFrame xFrame = xDesktop.getCurrentFrame();
XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, xFrame);
// We issute the Track Changes Dialog (Bearbeiten - Ă„nderungen // Edit - Changes) and tell it
// to ACCEPT all changes.
PropertyValue[] acceptChanges = new PropertyValue[1];
acceptChanges[0] = new PropertyValue();
acceptChanges[0].Name = "AcceptTrackedChanges";
acceptChanges[0].Value = Boolean.TRUE;
helper.executeDispatch(xDispatchProvider, ".uno:AcceptTrackedChanges", "", 0, acceptChanges);
// We issue it again to tell it to stop showing changes.
PropertyValue[] showChanges = new PropertyValue[1];
showChanges[0] = new PropertyValue();
showChanges[0].Name = "ShowTrackedChanges";
showChanges[0].Value = Boolean.FALSE;
helper.executeDispatch(xDispatchProvider, ".uno:ShowTrackedChanges", "", 0, showChanges);
My current guess is that I cannot call this because being hidden, I have no Frame to call any dispatcher to. But I could not find a way to get the Dispatcher for the Component.
I already tried to dispatch TrackChanges as well (to FALSE) but that didn't do it either.
After spending two days understanding the OOo API, I realized that the document isn't loaded in the frontend which is why this approach fails. However, you can modify the document's property directly:
XPropertySet docProperties = UnoRuntime.queryInterface(XPropertySet.class, document);
docProperties.setPropertyValue("RedlineDisplayType", RedlineDisplayType.NONE);
The property name "RedlineDisplayType" can be found in the RedlinePortion documentation

Categories