i have written the code of jsp,servlet for uploading the Doc file in database.
here is my code,but i am getting the error like this==java.io.FileNotFoundException: insert into resume(resume) values(?) (The filename, directory name, or volume label syntax is incorrect) .please help me how to remove this error???
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:jtds:sqlserver://W2K8SERVER:1433/career","sa","Alpha#123" );
pst = con.prepareStatement("select * from data1 where email=? and password=?");
pst = con.prepareStatement
("insert into resume(resume) "+ "values(?)");
File re = new File("" + pst);
fis = new FileInputStream(re);
pst.setBinaryStream(3, (InputStream)fis, (int)(re.length()));
pst.setString (1,upload);
//rs = pst.executeQuery();
while (rs.next())
cnt ++;
int s = pst.executeUpdate();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else {
System.out.println("unsucessfull to upload image.");
}
rs.close();
pst.close();
con.close();
}
It is because insert into resume(resume) values(?) is probably not the name of a file on your disk.
pst = con.prepareStatement ("insert into resume(resume) "+ "values(?)");
File re = new File("" + pst);
You are creating a File from ""+ pst, which is the result of toString() being called on a PreparedStatement. Did you put in the "" to get rid of the informative compilation error?
You probably have the real filename in some other variable.
File re = new File(theRealFileNameVariable);
File re = new File("" + pst);
please make sure the "pst" value is a valid file path, apparently the value "insert into resume(resume) values(?)" is not a valid file path
The java.io.File class has four (4) constructors
File(File parent, String child)
File(String pathname)
File(String parent, String child)
File(URI uri)
In your case you are trying to pass to the constructor an object or type java.sql.PreparedStatement that you trying to cast into a String. I don't see how (even if you arrived to convert pst into a string) pst will reference a path to a file. Please go back and read a little bit about java.io.
.
Related
I'm getting an error from SQLite when the connection string contains a comma. I don't have full control over where the database will end up, so it's possible a user will place it into a directory containing arbitrary characters. In this case, it appears that the presence of a comma (,) in the path causes an error when connecting. Here is the connection string:
Data Source=C:/Users/Dan/AppData/LocalLow/Gravia Software, LLC/Gravia/exampleDatabase.db;
This results in the following exception when trying to connect:
ArgumentException: Invalid ConnectionString format for parameter "LLC/Gravia/exampleDatabase.db"
It appears that the presence of the comma in the connection string is the issue. I've tried escaping the command (\,), wrapping the whole thing in quotes, but it doesn't seem to matter. Any ideas?
Edit:
The actual code I was executing comes from this page: https://ornithoptergames.com/how-to-set-up-sqlite-for-unity/
var dbPath = "URI=file:" + Application.persistentDataPath + "/exampleDatabase.db";
using (var conn = new SqliteConnection(dbPath)) {
conn.Open(); // Error occurs here
// etc
}
I tried changing out URI=file: for Data Source=, as the result was the same.
Try this ?
"Data Source=" + "C:/Users/Dan/AppData/LocalLow/Gravia Software," + "LLC/Gravia/exampleDatabase.db";
I solved this way:
var currDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.streamingAssetsPath + "/DB/"));
SqliteConnection dbcon = null;
try
{
dbcon = new SqliteConnection(_Connection);
dbcon.Open();
}
catch (Exception e)
{
Debug.Log(e.Message);
return null;
}
finally
{
Directory.SetCurrentDirectory(currDir);
}
You can escape unsupported characters in ODBC connection variables using curly-brackets ({}).
So wrap your variable, like below
Data Source={C:/Users/Dan/AppData/LocalLow/Gravia Software, LLC/Gravia/exampleDatabase.db};
Source
I am having trouble with displaying the results in the search activity of my app. I wonder where it went wrong.
The aim of the function below is to search the input query of the user and find it in every files listed. But the results only matches one data eventhough the query is also present in the other files. Here is the code.
public void searchFiles(File[] filelist, String query, String querysearch, String[] namesOfFiles){
querysearch = "SELECT * FROM Data WHERE ObjectID = ? ";
int temp2 = filelist.length;
for (int i = (temp2-1); i >= 0; i--) {
if(!(filelist[i].getName().equals("DataObjectDB.db")) && !(filelist[i].getName().endsWith("-journal"))){
temp1 = filelist[i].getName();
namesOfFiles[i] = temp1.replaceAll(".db$", "");
Toast.makeText(getApplicationContext(),"Searching " + query + " in: " + namesOfFiles[i], Toast.LENGTH_SHORT).show();
DatabaseHelper db1 = new DatabaseHelper(getApplicationContext(),namesOfFiles[i]);
SQLiteDatabase sqldb = db1.getWritableDatabase();
cursor = sqldb.rawQuery(querysearch, new String[]{query});
Toast.makeText(getApplicationContext(),cursor.toString(), Toast.LENGTH_SHORT).show();
}
}
final ListView listView = (ListView) findViewById(R.id.results_listview);
SearchAdapter adapter = new SearchAdapter(this, R.layout.results_column, cursor,0 );
listView.setAdapter(adapter);
}
The searchFiles() function passes the filelist, query, querysearch and namesOfFiles where 1) filelist contains the list of files in the source folder 2) query is the user input he/she wants to search 3) querysearch is the select statement 3) namesofFiles is just an empty string.
I indicate a toast to see if the code traverses through all the folders. And yes it is. But I don't know why it is not displaying all the results.
Any help? Thanks!
Found an answer on different posts. Basically, you just have to use hashmap and arraylist first before setting up the adapter directly.
I was setting up a storm cluster to calculate real time trending and other statistics, however I have some problems introducing the "recovery" feature into this project, by allowing the offset that was last read by the kafka-spout (the source code for kafka-spout comes from https://github.com/apache/incubator-storm/tree/master/external/storm-kafka) to be remembered. I start my kafka-spout in this way:
BrokerHosts zkHost = new ZkHosts("localhost:2181");
SpoutConfig kafkaConfig = new SpoutConfig(zkHost, "test", "", "test");
kafkaConfig.forceFromStart = false;
KafkaSpout kafkaSpout = new KafkaSpout(kafkaConfig);
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("test" + "spout", kafkaSpout, ESConfig.spoutParallelism);
The default settings should be doing this, but I think it is not doing so in my case, every time I start my project, the PartitionManager tries to look for the file with the offsets, then nothing is found:
2014-06-25 11:57:08 INFO PartitionManager:73 - Read partition information from: /storm/partition_1 --> null
2014-06-25 11:57:08 INFO PartitionManager:86 - No partition information found, using configuration to determine offset
Then it starts reading from the latest possible offset. Which is okay if my project never fails, but not exactly what I wanted.
I also looked a bit more into the PartitionManager class which uses Zkstate class to write the offsets, from this code snippet:
PartitionManeger
public void commit() {
long lastCompletedOffset = lastCompletedOffset();
if (_committedTo != lastCompletedOffset) {
LOG.debug("Writing last completed offset (" + lastCompletedOffset + ") to ZK for " + _partition + " for topology: " + _topologyInstanceId);
Map<Object, Object> data = (Map<Object, Object>) ImmutableMap.builder()
.put("topology", ImmutableMap.of("id", _topologyInstanceId,
"name", _stormConf.get(Config.TOPOLOGY_NAME)))
.put("offset", lastCompletedOffset)
.put("partition", _partition.partition)
.put("broker", ImmutableMap.of("host", _partition.host.host,
"port", _partition.host.port))
.put("topic", _spoutConfig.topic).build();
_state.writeJSON(committedPath(), data);
_committedTo = lastCompletedOffset;
LOG.debug("Wrote last completed offset (" + lastCompletedOffset + ") to ZK for " + _partition + " for topology: " + _topologyInstanceId);
} else {
LOG.debug("No new offset for " + _partition + " for topology: " + _topologyInstanceId);
}
}
ZkState
public void writeBytes(String path, byte[] bytes) {
try {
if (_curator.checkExists().forPath(path) == null) {
_curator.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(path, bytes);
} else {
_curator.setData().forPath(path, bytes);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I could see that for the first message, the writeBytes method gets into the if block and tries to create a path, then for the second message it goes into the else block, which seems to be ok. But when I start the project again, the same message as mentioned above shows up. No partition information can be found.
I had the same problem. Turned out I was running in local mode which uses an in memory zookeeper and not the zookeeper that Kafka is using.
To make sure that KafkaSpout doesn't use Storm's ZooKeeper for the ZkState that stores the offset, you need to set the SpoutConfig.zkServers, SpoutConfig.zkPort, and SpoutConfig.zkRoot in addition to the ZkHosts. For example
import org.apache.zookeeper.client.ConnectStringParser;
import storm.kafka.SpoutConfig;
import storm.kafka.ZkHosts;
import storm.kafka.KeyValueSchemeAsMultiScheme;
...
final ConnectStringParser connectStringParser = new ConnectStringParser(zkConnectStr);
final List<InetSocketAddress> serverInetAddresses = connectStringParser.getServerAddresses();
final List<String> serverAddresses = new ArrayList<>(serverInetAddresses.size());
final Integer zkPort = serverInetAddresses.get(0).getPort();
for (InetSocketAddress serverInetAddress : serverInetAddresses) {
serverAddresses.add(serverInetAddress.getHostName());
}
final ZkHosts zkHosts = new ZkHosts(zkConnectStr);
zkHosts.brokerZkPath = kafkaZnode + zkHosts.brokerZkPath;
final SpoutConfig spoutConfig = new SpoutConfig(zkHosts, inputTopic, kafkaZnode, kafkaConsumerGroup);
spoutConfig.scheme = new KeyValueSchemeAsMultiScheme(inputKafkaKeyValueScheme);
spoutConfig.zkServers = serverAddresses;
spoutConfig.zkPort = zkPort;
spoutConfig.zkRoot = kafkaZnode;
I think you are hitting this bug:
https://community.hortonworks.com/questions/66524/closedchannelexception-kafka-spout-cannot-read-kaf.html
And the comment from the colleague above fixed my issue. I added some newer libraries to.
I am using the code below for saving uploaded picture and makigna thumbnail but it saves a filename without the extension to the database, therefore, I get broken links. How can I stop a strongly typed dataset and dataadapter to stop removing the file extension? my nvarchar field has nvarchar(max) so problem is not string length.
I realized my problem was the maxsize in the dataset column, not sql statement parameter, so I fixed it. You may vote to close on this question.
hasTableAdapters.has_actorTableAdapter adp1 = new hasTableAdapters.has_actorTableAdapter();
if (Convert.ToInt16(adp1.UsernameExists(username.Text)) == 0)
{
adp1.Register(username.Text, password.Text,
ishairdresser.Checked, city.Text, address.Text);
string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName;
string originalrelative = "\\pictures\\" + actorimage.FileName;
actorimage.SaveAs(originalfilename);
string thumbfilename = Server.MapPath(" ") + "\\pictures\\t_" + actorimage.PostedFile.FileName;
string thumbrelative = "\\pictures\\t_" + actorimage.FileName;
Bitmap original = new Bitmap(originalfilename);
Bitmap thumb=(Bitmap)original.GetThumbnailImage(100, 100,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
thumb=(Bitmap)original.Clone(
new Rectangle(new Point(original.Width/2,original.Height/2), new Size(100,100)),
System.Drawing.Imaging.PixelFormat.DontCare);
/*
bmpImage.Clone(cropArea,bmpImage.PixelFormat);
*/
thumb.Save(thumbfilename);
adp1.UpdatePicture(originalrelative, thumbrelative, username.Text);
LoginActor();
Response.Redirect("Default.aspx");
}
}
Looks like the problem is you are using HttpPostedFile.FileName property, which returns fully-qualified file name on the client. So, this code string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName; generates something like this:
c:\inetpub\pictures\c:\Users\Username\Pictures\image1.jpg
Use FileUpload.FileName property everywhere and you will probably get what you want.
Use this to get Image or file extension :
string Extension = System.IO.Path.GetExtension(FileUpload.FileName);
i can replace the file name in particular folder , i wrote like this
FileInfo fsource = new FileInfo(Server.MapPath("~/PurchaseOrder/" + lblhideid.Text));
if (fsource.Exists)
{
string[] file = lblhideid.Text.Split('.');
string fName="Z-"+System.DateTime.Now.ToString("MM-dd-yyyy")+"-"+saveConsultantID+"."+file[1];
fsource.Name.Replace(lblhideid.Text, fName);
}
lblhideid.Text=image.jpeg , so i can replace the my own name like fName , how to replace the name pls give me any suggestion.
Thank u
Hemanth
I suspect you want that last line to be:
fsource.MoveTo(Server.MapPath("~/PuchaseOrder/" + fName));
You current code is only getting the filename as a string and manipulate that string. You want to manipulate the file itself.
EDIT:
Are you sure that ~/PurchaseOrder/ exists?
Try:
string originalPath = Server.MapPath("~/PurchaseOrder/" + lblhideid.Text);
FileInfo fsource = new FileInfo(originalPath);
if (fsource.Exists)
{
string newName = string.Format("Z-{0:MM-dd-yyyy}-{1}.{2}",
System.DateTime.Now,
saveConsultantID,
fsource.Extension);
string newPath = Path.Combine(fsource.DirectoryName, newName);
fsource.MoveTo(newPath);
}
Try this, what if they put a filename like file.tar.gz ?
string extension = Path.GetExtension("~/PurchaseOrder/" + lblhideid.Text);
string newName = "MYFILE." + extension
File.Move(
"~/PurchaseOrder/" + lblhideid.Text,
"~/PurchaseOrder/" + newName );