file copy error, detail information:
2012-06-12 09:21:38.557 mead_debug[10314:fb03] [INFO] parent_entry := /Users/laiqinyi/Library/Application Support/iPhone Simulator/4.3.2/Applications/5EFBD6D1-66EB-4DEC-8AE7-D386729744E9/Documents/dest/
2012-06-12 09:22:34.640 mead_debug[10314:fb03] [INFO] upload error source undefined
2012-06-12 09:22:34.641 mead_debug[10314:fb03] [INFO] upload error target undefined
I follow the API instruction, and do not think there are some thing wrong with this "copyTo" code.
In addition, there are folder "Documents/dest" and file "Documents/readme.txt"
http://docs.phonegap.com/en/1.8.0/cordova_file_file.md.html#File
**var FileSystem = {
copy : function(src, dest){
var parentEntry = new DirectoryEntry({fullPath:("/dest")});
console.log("parent_entry := " + FileSystem.root_path+"/dest");
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.copyTo(parentEntry, "file.copy", function(e){console.log("copy okay");}, fail);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
}**
copy : function(fromUrl, toPath, toName){
console.log("copyFile - From: [" + fromUrl + "] To: " + toPath + " Name: " + toName);
// Set up some storage
var destPath = '';
var destName = '';
doMoveFile(fromUrl);
// Called when file needs to be moved / after capture
function doMoveFile(fileUrl){
//console.log("doMoveFile - fileUrl: " + JSON.stringify(fileUrl));
// Remember the source file name just in case it was not passed so reuse it, and for logging
var destName = fileUrl.name;
var destPath = fileUrl;
// Resolve the file system
window.resolveLocalFileSystemURI(fileUrl,resFSSuccess, resFSError);
// Called upon successful File System resolution
function resFSSuccess(entry){
//console.log("resFSSuccess Success - entry: " + JSON.stringify(entry));
// Request a file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
requestFileSystemSuccess, requestFileSystemError);
// Called upon successful File System request
function requestFileSystemSuccess(fileSys){
// Get the source directory
fileSys.root.getDirectory(toPath, {create: true, exclusive:false}, getDestDirSuccess, getDestDirError);
// Called upon successful Get Of Destination Directory
function getDestDirSuccess(directory){
// Get the destination file name, set it if it is blank or not passed by the App
toName = (toName) ? toName : destName;
// Remember the full path name for the console log
fullDestPath = directory.fullPath + '/' + toName;
// Make the move
entry.copyTo(directory, toName, moveSuccess, moveError);
function moveSuccess(){
console.log("Successful copy of " + destPath + " to " + fullDestPath);
};
function moveError(error){
console.log("copyError code: " + JSON.stringify(error));
};
}
// Get Destination Dir Failure
function getDestDirError(error){
console.log("getDestDirError code: " + JSON.stringify(error));
};
}
// File System Request Failure
function requestFileSystemError(error){
console.log("requestFileSystemError code: " + JSON.stringify(error));
};
}
// Note File System failure
function resFSError(error){
console.log("resFSError code: " + JSON.stringify(error));
};
}
}
Related
class FileClassOne {
public static void main(String args[]) {
File myDir = new File(File.separator);
System.out.println("myDir.getAbsolutePath() = " + myDir.getAbsolutePath());
System.out.println("myDir.isDirectory() = " + myDir.isDirectory());
System.out.println("myDir.isFile() = " + myDir.isFile());
System.out.println();
myDir = new File(File.separator+"Java"+File.separator+"FilePartOne");
System.out.println("myDir.getAbsolutePath() = " + myDir.getAbsolutePath());
System.out.println("myDir.isDirectory() = " + myDir.isDirectory());
System.out.println("myDir.isFile() = " + myDir.isFile());
System.out.println();
File myFile = new File(myDir, "Temp.txt");
System.out.println("myFile.getAbsolutePath() = " + myFile.getAbsolutePath());
System.out.println("myFile.isDirectory() = " + myFile.isDirectory());
System.out.println("myFile.isFile() = " + myFile.isFile());
System.out.println("myFile.exists() = " + myFile.exists());
try {
myFile.createNewFile();
} catch (IOException e) {
System.out.println(e.getMessage());
}
Output:
myDir.getAbsolutePath() = C:\
myDir.isDirectory() = true
myDir.isFile() = false
myDir.getAbsolutePath() = C:\Java\FilePartOne
myDir.isDirectory() = false
myDir.isFile() = false
myFile.getAbsolutePath() = C:\Java\FilePartOne\Temp.txt
myFile.isDirectory() = false
myFile.isFile() = false
myFile.exists() = false
The system cannot find the path specified
This code if from an online tutorial that works in the video and it's copied verbatim. IDE is eclipse.
I would say its likely because of missing directories along the path "C:\Java\FilePartOne".
The statement:
myFile.createNewFile();
Will attempt to create a file on a given path, not create any missing directories. You therefore get the error "The system cannot find the path specified" if any directories are missing when executing the statement.
A quick way to fix this would be to either create the missing folders yourself or add the code below just before myFile.createNewFile();.
myFile.getParentFile().mkdirs();
I am writing API which insert into a table with multiple rows, I am using UNNEST to make it work.
What I have done:
in js file:
api.post(PREFIX + '/class/insert', function (request) {
var db = pgp(dbconnect);
//Params
var data = request.body; //should be an array
var classes = [];
var starts = [];
var ends = [];
for (var i = 0; i < data.length; i++) {
classes.push(data[i].class_id);
starts.push(data[i].timestamp_start);
ends.push(data[i].timestamp_end);
}
const PQ = require('pg-promise').ParameterizedQuery;
var sql =
"INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
"VALUES( "+
"UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + ")"
const final_sql = new PQ(sql);
return db.any(final_sql)
.then(function (data) {
pgp.end();
return 'successful';
})
.catch(function (error) {
console.log("Error: " + error);
pgp.end();
});
}
Request body
[{
"class_id":"1",
"timestamp_start":"2017-11-14 14:01:23.634437+00",
"timestamp_end":"2017-11-14 15:20:23.634437+00"
}, {
"class_id":"2",
"timestamp_start":"2017-11-14 15:01:23.634437+00",
"timestamp_end": "2017-11-14 16:20:23.634437+00"
}]
When I run api in postman, I get the error is:
column "timestamp_start" is of type timestamp with time zone but
expression is of type text
Issue is obviously from ARRAY of string that I used in sql, my question is how to create ARRAY of timestamp for UNNEST, or any suggestion are appreciated.
Thanks
Never initialize the database inside the handler, see: Where should I initialize pg-promise
Never call pgp-end() inside HTTP handlers, it destroys all connection pools.
Use static ColumnSet type to generate multi-insert queries.
Do not return from db.any, there is no point in that context
You must provide an HTTP response within an HTTP handler
You are providing a confusing semantics for column class_id. Why is it called like that and yet being converted into a timestamp?
Never concatenate objects with strings directly.
Never concatenate SQL strings manually, it will break formatting and open your code to SQL injection.
Use Database methods according to the expected result, i.e. none in your case, and not any. See: https://github.com/vitaly-t/pg-promise#methods
Initialize everything needed only once:
const db = pgp(/*connection*/);
const cs = new pgp.helpers.ColumnSet([
'class_id',
{
name: 'timestamp_start',
cast: 'timestamp'
},
{
name: 'timestamp_end',
cast: 'timestamp'
}
], {table: {table: 'class', schema: 'sa1'}});
Implement the handler:
api.post(PREFIX + '/class/insert', request => {
const sql = pgp.helpers.insert(request.body, cs);
db.none(sql)
.then(data => {
// provide an HTTP response here
})
.catch(error => {
console.log('Error:', error);
// provide an HTTP response here
});
}
Many thanks to #JustMe,
It worked after casting array
var sql =
"INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
"VALUES( "+
"UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "::timestamp[]), " +
"UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + "::timestamp[])"
JSP code --- I have used Angular js in scripting. The issue is that the form Data is not being sent to the resource method in portlet class. Also when I log the form data in console it displays empty. It takes up JSON data and append into form data. the json value is passed as transaction data { 1: "1", purchaseRegisterId: 33411, undefined: "book3.jpg" } and documentId is passed as documentId :: documents33411. these data is taken from the console log.
$scope.savePurchaseRegisterEntry=function(documentId, json){
console.log("documentId :: "+documentId);
//console.log("json");
console.log(json);
var fd = new FormData();
fd.append('auditDetailesId',$scope.auditDetailesId);
console.log(fd);
var documentcollection=[];
for(var key in json){
fd.append(key,json[key]);
if("purchaseRegisterId"!=key && key!=='undefined'){
documentcollection.push(key);
}
}
$.each( $("#"+documentId), function( input_key, input_value ) {
$.each( input_value.files, function( file_key, file_value ) {
fd.append('myFiles', file_value);
});
});
fd.append("documentCollectionIds",documentcollection.join(','));
console.log("fd");
console.log(fd);
console.log("documentcollectionids :: "+documentcollection.join(','))
//return false;
$http({
method:'POST',
url:'<%=savePurchaseRegisterEntry%>',
type:"json",
data:fd,
headers: {'Content-Type': undefined},
transformRequest:angular.identity
}).success(function(response){
console.log(response);
var response=angular.fromJson(response.selectedTransactionList);
$scope.dataList=angular.fromJson(response.data);
$scope.ariaValuenow =response.currentCount;
$scope.ariaValuemin=0;
$scope.ariaValueMax=response.data[0]['maxInputDocCount']* response.total;
$scope.percentageComplete=(($scope.ariaValuenow - $scope.ariaValuemin) * 100) / ($scope.ariaValueMax - $scope.ariaValuemin);
if($scope.percentageComplete==100){
$scope.saveStatus();
$scope.readyForAudit=true;
}else{
$scope.readyForAudit=false;
}
});
}
Resurces Method --- the data is being fetched here to store the values into database table.
public void savePurchaseRegisterEntry(ResourceRequest req,
ResourceResponse res) throws SystemException, IOException {
_log.info("i am in savePurchaseRegisterEntry!!!");
ThemeDisplay themeDisplay = (ThemeDisplay) req
.getAttribute(WebKeys.THEME_DISPLAY);
_log.info(" ----- " + ParamUtil.getString(req, "purchaseRegisterId"));
_log.info(" ----- " + ParamUtil.getLong(req, "purchaseRegisterId"));
String documentCollectionIds=ParamUtil.getString(req, "documentCollectionIds");
String[] documentCollectionIdArray=documentCollectionIds.split(",");
MultiDocumentUploadUtil.createFolder(req, themeDisplay ,ParamUtil.getLong(req, "purchaseRegisterId") , "purchaseRegisterId");
String fileIds=MultiDocumentUploadUtil.fileUpload(themeDisplay, req);
_log.info("fileIds : "+fileIds);
long purchaseRegisterId =ParamUtil.getLong(req, "purchaseRegisterId");
for(String s : documentCollectionIdArray){
System.out.println("s is "+Long.parseLong(s));
_log.info(Long.parseLong(s)+"long sssss "+ s+" s :: "+ParamUtil.getLong(req, s));
_log.info(Long.valueOf(s)+"long sssss "+ s+" s :: "+ParamUtil.getLong(req, s));
AuditDocumentCollection adc= AuditDocumentCollectionLocalServiceUtil.fetchByPurchaseRegisterIdAnddocumentCollectionId(purchaseRegisterId, Long.valueOf(s));
AuditDocumentCollection adc1=adc;
if(adc==null){
adc=AuditDocumentCollectionLocalServiceUtil.createAuditDocumentCollection(CounterLocalServiceUtil.increment());
}
adc.setDocumentCollectionId(Long.valueOf(s));
adc.setPurchaseRegisterId(purchaseRegisterId);
adc.setValue(ParamUtil.getLong(req, s));
if(adc1==null){
adc.setCreateDate(new Date());
adc.setCreatedBy(themeDisplay.getUserId());
adc.setModifiedBy(themeDisplay.getUserId());
adc.setModifiedDate(new Date());
AuditDocumentCollectionLocalServiceUtil.addAuditDocumentCollection(adc);
}else{
adc.setModifiedBy(themeDisplay.getUserId());
adc.setModifiedDate(new Date());
AuditDocumentCollectionLocalServiceUtil.updateAuditDocumentCollection(adc);
}
}
PurchaseRegister purchaseRegister=PurchaseRegisterLocalServiceUtil.fetchPurchaseRegister(purchaseRegisterId);
if(!fileIds.isEmpty()){
purchaseRegister.setDocumentIds(fileIds);
}
PurchaseRegisterLocalServiceUtil.updatePurchaseRegister(purchaseRegister);
JSONObject jsonobject = JSONFactoryUtil.createJSONObject();
long auditDetailesId=ParamUtil.getLong(req, "auditDetailesId");
jsonobject.put("selectedTransactionList",CommonUtil.getAuditProcessInfo( auditDetailesId));
PrintWriter out = res.getWriter();
out.write(jsonobject.toString());
out.flush();
out.close();
}
I suppose the data present in form data is being sent to resource method. it is not taking documentCollectionIds and its empty. The error I get is this,
[http-bio-3030-exec-10][PurchaseRegisterPortlet:644] i am in savePurchaseRegisterEntry!!!
05:58:34,050 INFO [http-bio-3030-exec-10][PurchaseRegisterPortlet:648] -----
05:58:34,050 INFO [http-bio-3030-exec-10][PurchaseRegisterPortlet:649] ----- 0
Folder is already Exist
fileEntryList.toArray().toString() :: 34529
05:58:34,255 INFO [http-bio-3030-exec-10][PurchaseRegisterPortlet:657]fileIds : 34529
Exception in thread "liferay/document_library_image_processor-3"05:58:34,256 ERROR [DispatcherPortlet:559] Could not complete request
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:453)
at java.lang.Long.parseLong(Long.java:483)
at com.auditcompliance.purchaseregister.controller.PurchaseRegisterPortlet.savePurchaseRegisterEntry(PurchaseRegisterPortlet.java:660)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
check your file first the typscript file of your component if you give
it exactly the type Number, then your service
Or if it's through the html file of your component that you give it
the right type in parameter
For me it was in the html file that I gave him another type
different from number
fist at all sorry for my bad English.
I'm trying to get the IP in the login option to save them as a "Session" in the database and register who and where is using the app.
I try this, but it obvious that it isn't going to work.
var ip = new System.Net.WebClient().DownloadString("http://ipinfo.io/json");
It Gets the IP Client. So it logical that I need to do this get in the Client side. But the problem is that the Client can change this values before its send to the Web API
$http.get("http://ipinfo.io/json").then(function (response) {
return response.data;
}).catch(function (response) {
console.log(response.data);
});
The users can change this value to send me a false data in the login and I don't have how to validate if this information is valid or real. So, the question is ¿How can I do this without let the user manipulate this data?
Create a method in web API, and we can save all the information needed directly to database.
public static string UserIp()
{
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
try
{
string url1 = "http://geoip.nekudo.com/api/" + ip.ToString(); // passing IP address will return location information.
WebClient client = new WebClient(); // Intialize the webclient
string jsonstring = client.DownloadString(url1);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring); // De-serialize the JSON string
string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "Ip.txt";
using (System.IO.StreamWriter writer = new StreamWriter(filePath, true))
{
// you can save the information to database instead of writing to a file
writer.WriteLine("UserIp:" + ip);
writer.WriteLine("Date:" + DateTime.Now);
writer.WriteLine("JsonString:" + jsonstring);
writer.WriteLine("Country name:" + dynObj.country.code);
}
return dynObj;
}
catch (Exception ex)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Logs\\" + "I.txt";
string url1 = "http://geoip.nekudo.com/api/" + ip.ToString();
WebClient client = new WebClient(); // Intialize the webclient
string jsonstring = client.DownloadString(url1);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
// string a = dynObj.country.code;
using (System.IO.StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" +
ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
writer.WriteLine("UserIp:" + ip);
writer.WriteLine("Dynamic obj:" + dynObj);
}
return null;
}
}
I am getting a response after I run a function that calls a cordova navigator.camera.getPicture() function. All works well and the response is below, however I can not access individual value-pairs
({"tagone" : "optimal", "datex" : "Thursday"})
I try this: r.response['tagone'] and just returns empty.
$scope.win = function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
$("#camLoader").hide();
$("#resultDiv").show();
$("#finalResult").append(r.response['tagone']);
//alert(r.response);
};