I am new to Java, have searched on the net and this forum but unable to figure out why my code is not compiling? Any help will be highly appreciated.
//filename is TestHTTPConnection.java
class TestHTTPConnection {
public static void main (String[] args){
String strUrl = "http://abc.com";
try {
URL url = new URL(strUrl);
URLConnection Conn = url.openConnection();
Conn.connect();
assertEquals(URLConnection.HTTP_OK, Conn.getResponseCode());
} catch (IOException e) {
System.err.println("Error creating HTTP connection");
e.printStackTrace();
throw e;
}
}
}
Compilation error - complains about "URL", "URLConnection" and "IOException".
You need to import those classes / interfaces !
You are missing two things:
a package line:
package yourdomain.yourapp;
and a list of imports:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
Most java developers use an IDE which automates all of this (such as NetBeans, IntelliJ IDEA, or Eclipse)
If your not using an IDE (Eclipse , NetBeans etc.) then download one which will give you content assist and point out mistakes like this.
Related
For a University project we need to implement a server 'registrar' that communicates with a client 'barowner' through a SSL RMI connection. When building the client, I get the error java: No enum constant javax.lang.model.element.Modifier.SEALED build error. The Server gets build without any problems.
BarownerMain.java
package com.example.BarOwner;
import com.example.registrar.RegistrarInterface;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class BarOwnerMain {
public static void main(String[] args) throws RemoteException {
String pass = "password";
System.setProperty("javax.net.ssl.debug", "all");
System.setProperty("javax.net.ssl.keyStore", System.getProperty("user.dir") + "/keys/raynaud.jks");
System.setProperty("javax.net.ssl.keyStorePassword", pass);
System.setProperty("javax.net.ssl.trustStore", System.getProperty("user.dir") + "/keys/raynaud.jks");
System.setProperty("javax.net.ssl.trustStorePassword", pass);
Registry registrarRegistry;
RegistrarInterface registrarInterface;
try {
registrarRegistry = LocateRegistry.getRegistry(
InetAddress.getLocalHost().getHostName(), 1112,
new RMISSLClientSocketFactory());
registrarInterface = (RegistrarInterface) registrarRegistry.lookup("RegistrarService");
BarOwnerMenu.showMenu(registrarInterface);
} catch (RemoteException | NotBoundException e) {
throw new RuntimeException(e);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
I already tried editing javax.lang.module as desribed in JDK-8244367 but IntelliJ doesn't let me. Any help would be appreciated!
Try to change the SDK version to 15, and then return it to the updated version.
You can change your DSK version in the "Project Structure", shortcut to get there:
ctrl+alt+shift+S
"Project Structure" window in IntelliJ
Make sure you click the "Apply" button.
It helps me solve the same problem.
This question already has answers here:
Why am I getting a NoClassDefFoundError in Java?
(31 answers)
Closed 6 years ago.
I'm so noob at external stuff to Bukkit programming, so I'm sorry if it's so easy to solve :P
I have a problem, and it's that when I try to use HikariCP in my project, it returns in an error (the title one).
I'm using it in a BungeeCord plugin.
The weird thing is that I have done this successfully couples of times, and I don't know why it isn't working this time.
The error / log:
06:13:36 [ADVERTENCIA] Exception encountered when loading plugin: DiverseReport java.lang.NoClassDefFoundError: com/zaxxer/hikari/HikariDataSource at net.srlegsini.DiverseReport.Bungee.MClass.onEnable(MClass.java:44) at net.md_5.bungee.api.plugin.PluginManager.enablePlugins(PluginManager.java:227) at net.md_5.bungee.BungeeCord.start(BungeeCord.java:272) at net.md_5.bungee.BungeeCordLauncher.main(BungeeCordLauncher.java:55) at net.md_5.bungee.Bootstrap.main(Bootstrap.java:15) Caused by: java.lang.ClassNotFoundException: com.zaxxer.hikari.HikariDataSource at net.md_5.bungee.api.plugin.PluginClassloader.loadClass0(PluginClassloader.java:53) at net.md_5.bungee.api.plugin.PluginClassloader.loadClass(PluginClassloader.java:27) at java.lang.ClassLoader.loadClass(Unknown Source) ... 5 more
My main class:
package net.srlegsini.DiverseReport.Bungee;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import com.zaxxer.hikari.HikariDataSource;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import net.srlegsini.DiverseReport.Bukkit.UUIDFetcher;
public class MClass extends Plugin {
static Configuration config;
static MClass plugin;
static HikariDataSource hikari;
static Connection connection;
public void onEnable() {
BungeeCord.getInstance().getPluginManager().registerListener(this, new ChannelListener());
BungeeCord.getInstance().registerChannel("Return");
loadCfg();
if (!config.contains("MySQL")) {
config.set("MySQL.Enable", false);
config.set("MySQL.Host", "localhost");
config.set("MySQL.Port", 3306);
config.set("MySQL.User", "user");
config.set("MySQL.Pass", "pass");
config.set("MySQL.Database", "Sr_DiverseReport");
}
saveCfg(getDataFolder());
hikari = new HikariDataSource();
hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
hikari.addDataSourceProperty("serverName", config.getString("MySQL.Host"));
hikari.addDataSourceProperty("port", 3306);
hikari.addDataSourceProperty("databaseName", config.getString("MySQL.Database"));
hikari.addDataSourceProperty("user", config.getString("MySQL.User"));
hikari.addDataSourceProperty("password", config.getString("MySQL.Pass"));
try {
Class.forName("com.mysql.jdbc.Driver");
connection = hikari.getConnection();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e2) {
}
saveCfg(getDataFolder());
}
public void loadCfg() {
try {
File file = new File(getDataFolder(), "config.yml");
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
config = ConfigurationProvider.getProvider(YamlConfiguration.class)
.load(new File(getDataFolder(), "config.yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void saveCfg(File dataFolder) {
try {
ConfigurationProvider.getProvider(YamlConfiguration.class).save(config, new File(dataFolder, "config.yml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings({ "unused", "deprecation" })
public static String getUUID(String playerName) {
UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList("evilmidget38", "mbaxter"));
String playerUUID = null;
try {
playerUUID = UUIDFetcher.getUUIDOf(playerName).toString();
} catch (Exception e2) {
playerUUID = BungeeCord.getInstance().getPlayer(playerName).getUniqueId().toString();
}
return playerUUID;
}
}
My procedure:
Create the project, import BungeeCord.jar, HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar in buildpath, import HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar
It worked in other projects, but magically, it's broken.
I don't want to use Maven, just because it must have a fix, because as I said, I used this same procedure so many times in the past.
Thank you for taking the time to read this :)
EDIT:
Image of the project
It's all in the exception:
Caused by: java.lang.ClassNotFoundException: com.zaxxer.hikari.HikariDataSource
The HikariDataSource is missing at runtime, you need to provide it somehow, for example by copying the relevant .jar with 'drivers' into your server libraries folder.
Also see some related questions:
How to set up datasource with Spring for HikariCP? and
How do I configure HikariCP in my Spring Boot app in my application.properties files?
From the exception it is clear that HikariCP-2.6.0.jar was in classpath during compile time but is missing in runtime and from the image of the project structure, it is also clear that both HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar are missing as library reference in the ide. You need to keep these jar in your classpath library during compile time and runtime.
I'm a novice at java and I'm working on a project that scans the source code of a website, and extracts all the hyperlinks contained in it.
So far I have my project working so that it scans every 'word' of the source code using a Scanner (in.next())
However Ive been told to use delimiters to extract the hyperlinks from this, but I can barely find any information out there to help me use them!
Someone couldnt help explain to me delimiters and how I could use them in this project? It would be really appreciated.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.ArrayList;
public class HyperlinkMain {
public static void main(String[] args) {
try {
Scanner in = new Scanner (System.in);
String URL = in.next();
URL website = new URL(URL);
Scanner inWebsite = new Scanner (website.openStream());
String inputLine;
while ((inWebsite.hasNext())) {
// Process each 'word'.
System.out.println(inWebsite.next());
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
}
You could use Regular expression on strings. Below is an existing Stack Overflow on this topic.
How to use regular expressions to parse HTML in Java?
I want to read object from Android internal storage.
The following is my code.
I write a static function for reading object from file in the same class.
No idea why this exception happen .
Really appreciate if you could give some suggestions.
thanks.
package com.crescent.programmercalculator;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.util.Log;
import android.content.Context;
public class CalculateConfigurations implements Serializable{
static String configLocation="configFile";
public short radix;
CalculateConfigurations(){
radix=16;
}
public static CalculateConfigurations loadObjectFromFile(Context context){
try {
FileInputStream fis = context.openFileInput(configLocation);
ObjectInputStream is = new ObjectInputStream(fis);
CalculateConfigurations config = (CalculateConfigurations) is.readObject();
is.close();
fis.close();
return config;
} catch (FileNotFoundException e) {
// first use case
Log.v("CalculateConfigurations", "first init for configuration file");
return new CalculateConfigurations();
} catch (IOException e) {
e.printStackTrace();
Log.e("CalculateConfigurations", "Fatal error, configuration file may be broken");
return new CalculateConfigurations();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e("CalculateConfigurations", "Fatal error, unknown");
return new CalculateConfigurations();
}
}
}
ClassNotFoundException
this is in most cases some mixup in your xml-files. If you post both stacktrace and the proper xml-file, it is easy to fix it!
Read on readObject
Exceptions are thrown for problems with the InputStream and for
classes that should not be deserialized. All exceptions are fatal to
the InputStream and leave it in an indeterminate state; it is up to
the caller to ignore or recover the stream state.
Since you are trying to read an android internal library, it cannot be casted to your custom Class. Hence the ClassNotFoundException.
Hope this helps.
I encounter the same problem today. I don't know how the serialization/deserialization is done but I notice that it is very unstable process.
If you serialize some objects and put the memory, you cannot change the data type/class name easily.. If it throws class not found exception like this, remove the app from device and install again. I hope, it helps some developers :)
Really simple, or so I thought.
Java Code
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class UrlConnectionTest {
private static final String TEST_URL = "http://localhost:3000/test/hitme";
public static void main(String[] args) throws IOException {
URLConnection urlCon = null;
URL url = null;
OutputStreamWriter osw = null;
try {
url = new URL(TEST_URL);
urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setRequestProperty("Content-Type", "text/plain");
osw = new OutputStreamWriter(urlCon.getOutputStream());
osw.write("HELLO WORLD");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (osw != null) {
osw.close();
}
}
}
}
TestController#hitme
def hitme
puts "SOMEONE IS HITTING ME!" * 100
puts request.env.inspect
end
When I run the Java code, I see nothing in my Rails Server Console. However, when I hit the URL in my browser, I get output as specified in TestController#hitme. I thought it would be simple, but haven't had any luck. Any ideas?
Thanks in advance!
You're probably getting an exception, which you aren't seeing, because you're swallowing it. At least print the exception in the catch block.
Even if this isn't the problem, your going to chase your tail a lot if you make a habit of swallowing errors.
I don't think you're actually sending any data until you call
urlCon.getInputStream();
Is it that your URL in your java code shows the controller name of "test" (test/hitme) but you mention that your controller name is TestController? i.e., the URL in your java code should be changed.
private static final String TEST_URL = "http://localhost:3000/TestController/hitme";
Don't fiddle around with URLConnection yourself, let Resty handle it.
Here's the code you would need to write (I assume you are getting text back):
import static us.monoid.web.Resty.*;
import us.monoid.web.Resty;
...
new Resty().text(TEST_URL, content("HELLO WORLD")).toString();