/r/javahelp
General subreddit for helping with Java code.
General subreddit for helping with Java code.
Message the mods if you have suggestions.
Java Discord server (unofficial)
Learning Java
Please head over to /r/learnjava and read the sidebar there.
The best free Java tutorials are:
Use the MOOC as main course and Java for Complete Beginners as secondary resource.
Don't forget the Official Oracle Java Tutorials and the Official Java Documentation as they are extremely valuable resources.
Where should I download Java?
With the introduction of the new release cadence, many have asked where they should download Java, and if it is still free. To be clear, YES — Java is still free.
If you would like to download Java for free, you can get OpenJDK builds from the following vendors, among others:
Some vendors will be supporting releases for longer than six months. If you have any questions, please do not hesitate to ask them!
Posting rules
DO NOT DELETE your posts once they are solved!
No illegal/pirated content!
No "Do my homework" posts!
Describe the problem and what you want to achieve.
Do not ask for or reply with solutions or keys to solutions.
Use the search function.
No offers/requests to/for help via PM, Discord, Skype, etc.
Post titles must be descriptive.
No promises of rewards of any kind!
Don't be a Jerk!
No JavaScript, Android, Minecraft or Processing!
No links to your stackoverflow questions.
Format your code.
No screenshots of code!
No AI generated content!
/r/javahelp
I'm getting the following error in my java project on the startup:
java: cannot find symbol symbol: method setName(java.lang.String) location: variable user of type com.example.example.domain.user.User
In the settings, I have the annotation processor enabled and the lombok plugin.
What alternatives do I have to fix this? Is it possible that Android Studio is creating problems with IntelliJ?
My Java course needs me to use BlueJ and it has worked fine for quite a while but recently I have been getting some weird visual glitches. It used to go away when I restart the app but now they are very frequent and I need help getting rid of them. I attached some images of the glitches.
More than a decade ago when I did my last big project in Java for a global bank, I disliked Spring. Mainly because it had to support all those legacy stuff and the layers of abstractions to cover the mess. I never hated it because Spring pretty much covered everything you would need to build complex enterprise applications that would be used by millions of people every day. We at that time could not find an ecosystem that did a better job.
I want to implement a personal project and also to have some fun with it. Is there any Spring ecosystem alternative that started after JDK 8 and battle tested? Saw in latest web frameworks benchmark, ActiveJ and Vert.x leading but does not seem like an ecosystem with nuts and bolts attached.
I got exams for java coming in few days and the syllabus for the exam includes applet programming (I know my college is wayy out of touch). The first thing I saw online is you need some kind of appletViewer which was discontinued from Java v11.
So now I have no way of running the code and practicing applet programs. Is there any workaround to this?
So i am new in java and i got this issue
class Calculator
{
int a;
public int add(int n1, int n2){
int r = n1 + n2;
return r;
}
}
public class Demo
{
public static void main(String[] args){
int num1 = 4;
int num2 = 5;
Calculator calc = new Calculator(); //its a object like int num 1or 2
int result = calc.add(num1, num2);
System.out.println(result);
}
}
GOT THIS TERMINAL OUTPUT -->
PS C:\Users\USER\Desktop\Codes> javac Demo.java
PS C:\Users\USER\Desktop\Codes> java Demo.java
error: can't find main(String[]) method in class: Calculator
Hello, i am curently trying to make an chatting app. I managed to do login and sign in page but when i try to sned messages in chating page page freezes and acts weird. Also sql querries are not executed like shown in the video. I would appreciate any help. And sorry for turkish comments
SQL class in server:
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
//VeriTabanConnector adındaki sınıf sunucumuzun veritabanla iletişime geçmesini sağlar
public class VeriTabanIslemler {
private static Connection veritabanaBaglan() throws SQLException {
// Alttaki değerlerle sql kutuphanesindn aldığımız Connection sınıfından nesneyle veritabana bağlanalım
String url = "jdbc:mysql://localhost:3306/messenger?autoReconnect=true&useSSL=false";
String dbUsername = "root";
String password = "test123";
Connection connection = DriverManager.
getConnection
(url, dbUsername, password);
//Bağlantıyı dondurelim
return connection;
}
//Veri tabanda kullancıyı oluşturmamıza yardımcı olacak metod yazalım
public static int kullanciOlustur(User user) {
try (Connection connection =
veritabanaBaglan
()) {
if (connection.isClosed()){
System.
out
.println("Baglantı yok");
return 0;
}
//SQL injection'dan korunmak için PreparedStatement kullanalım
PreparedStatement preparedStatement;
String sql = "INSERT INTO users (username, isim, soyisim, sifreHash) VALUES (?, ?, ?, ? )";
// Log the connection state before query execution
System.
out
.println("Preparing to execute query with connection: " + (connection.isClosed() ? "Closed" : "Open"));
preparedStatement = connection.prepareStatement(sql);
//Sifreyi guvenlik nedenle hash şeklinde saklayalım
String sifreHash = HashOlustur.
md5HashOlustur
(user.sifre);
preparedStatement.setString(1, user.username);
preparedStatement.setString(2, user.isim);
preparedStatement.setString(3, user.soyisim);
preparedStatement.setString(4, sifreHash);
//Son olarak kullancı oluşturma işlemimizi sqlde çalıştıralım
int rowsAffected = preparedStatement.executeUpdate();
System.
out
.println("Kullanci olusturuldu");
//Her şey sorunsuz olursa ve kullancımız oluşturursa 1 donelim
return 21;
} catch (Exception e) {
//Hata oluşursa hata mesajını yazdırıp hata kodunu döndürelim
e.printStackTrace();
return 20;
}
}
public static int girisYap(User user) {
try(Connection connection =
veritabanaBaglan
()){
PreparedStatement preparedStatement;
String sql = "SELECT sifreHash FROM users WHERE username = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,user.username);
ResultSet rs = preparedStatement.executeQuery();
rs.next();
String veridekiHash = rs.getString("sifreHash");
String sifreHash = HashOlustur.
md5HashOlustur
(user.sifre);
if (veridekiHash.equals(sifreHash)){
System.
out
.println("Giris Basarili");
return 11;
}
else
return 10;
} catch (Exception e){
e.printStackTrace();
return 0;
}
}
public static Mesaj mesajEkle(Mesaj mesaj){
try(Connection connection =
veritabanaBaglan
()){
PreparedStatement preparedStatementInsert;
String sql = "INSERT INTO messages (gonderici, mesaj,time) VALUES (?, ?, ?) ";
preparedStatementInsert = connection.prepareStatement(sql);
preparedStatementInsert.setString(1, mesaj.getGonderici());
preparedStatementInsert.setString(2, mesaj.getMesaj());
preparedStatementInsert.setObject(3, LocalDateTime.
now
());
int rowsAffected = preparedStatementInsert.executeUpdate();
PreparedStatement preparedStatementSelect;
String sql1 = "SELECT id, gonderici, mesaj, time FROM messages WHERE gonderici = ? AND mesaj = ? ORDER BY time DESC LIMIT 1";
preparedStatementSelect = connection.prepareStatement(sql1);
preparedStatementSelect.setString(1, mesaj.getGonderici());
preparedStatementSelect.setString(2, mesaj.getMesaj());
ResultSet rs = preparedStatementSelect.executeQuery();
rs.next();
int id = rs.getInt("id");
String gonderici = rs.getString("gonderici");
String string = rs.getString("mesaj");
LocalDateTime time = rs.getObject("time",LocalDateTime.class);
return new Mesaj(id,gonderici,string,time);
}catch(Exception e){
e.printStackTrace();
return null;
}
}
//Gecmişi yuklemek için Veritabandan tum mesajları isteyiciye göndereceğiz
public static List<Mesaj> getAllMessages() {
List<Mesaj> messages = new ArrayList<>();
String query = "SELECT * FROM messages";
try (Connection connection =
veritabanaBaglan
();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query)) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
String gonderici = resultSet.getString("gonderici");
String mesaj = resultSet.getString("mesaj");
LocalDateTime time = resultSet.getObject("time", LocalDateTime.class);
// Create a Message object and add it to the list
messages.add(new Mesaj(id, gonderici, mesaj, time));
}
} catch (SQLException e) {
e.printStackTrace();
}
return messages;
}
}
Client side:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Client {
private LoginFrame loginUI = new LoginFrame();
private UyeOlFrame uyeolUI = new UyeOlFrame();
private ChatFrame chatUI = new ChatFrame();
private static final String
SERVER_ADDRESS
= "localhost";
private static final int
SERVER_PORT
= 1234;
private Socket socket;
private ObjectOutputStream out;
private ObjectInputStream in;
private User user;
//Client için Contructor
public Client() {
//İlk önce bizim için önemli olan socket oluşturalım ve sunucumuza bağlanalım
try {
socket = new Socket(
SERVER_ADDRESS
,
SERVER_PORT
);
System.
out
.println("Connected to the chat server!");
} catch (IOException e) {
e.printStackTrace();
}
//Sonra UI'daki butonların çalışmasını ayarlayalım
loginUI.addGirisListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
user = new User(loginUI.getUsername(), loginUI.getSifre());
String userString = SifrelemeClient.
userSifrele
(user);
out.writeObject(userString);
out.flush(); // Ensure data is sent
}catch(Exception ex){
ex.printStackTrace();
}
}});
loginUI.addUyeOlListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loginUI.setVisible(false);
uyeolUI.setVisible(true);
}
});
uyeolUI.addUyeOlListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
user = new User(uyeolUI.getUsername(), uyeolUI.getSifre(), uyeolUI.getIsim(), uyeolUI.getSoyisim());
String userString = SifrelemeClient.
userSifrele
(user);
out.writeObject(userString);
out.flush(); // Ensure data is sent
} catch (Exception ex) {
ex.printStackTrace();
Popup.
showPopup
(uyeolUI,"Bir hata oluştu");
}
}
});
uyeolUI.addGeriGitListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
uyeolUI.setVisible(false);
loginUI.setVisible(true);
}
});
chatUI.addSendListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String message = chatUI.getMessageField().getText();
if (message != null) {
chatUI.getSendButton().setEnabled(false);
// Şu anki tarih ve saati al ve biçimlendir
LocalDateTime currentTime = LocalDateTime.
now
();
DateTimeFormatter formatter = DateTimeFormatter.
ofPattern
("yyyy-MM-dd HH:mm:ss"); // Yıl-ay-gün saat:dakika:saniye
String formattedDateTime = currentTime.format(formatter);
// Mesajı kendi chatimize yazdıralım
chatUI.writeMessageArea("Sen (" + formattedDateTime + "): " + message + "\n");
chatUI.setMessageField("");
new Thread(() -> {
//Sonra bu mesaje başka kullancılara gönderelim.
Gonderi gonderi = new Gonderi(3, new Mesaj(user.username, message));
gonder(gonderi);
}).start();
chatUI.getSendButton().setEnabled(true);
}
}
});
}
//Şimdi aslında programın ana kısmını metod içine yazalım
public void clientCalistir() {
// İletişim için input/output oluşturalım
try {
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
// Gelen mesajları almak için Threat oluşturalım
new Thread(() -> {
try {
String serverResponseString = (String)in.readObject();
Gonderi serverResponse = SifrelemeClient.
cevir
(serverResponseString);
boolean isPopupShown = false;
while (serverResponse != null) {
switch (serverResponse.getResponseCode()){
case 10:
//hata popup
if (!isPopupShown){
Popup.
showPopup
(loginUI,"Giriş yapılamadı!");
isPopupShown = true;
}
break;
case 11:
loginUI.setVisible(false);
chatUI.setVisible(true);
break;
case 20:
//Hata popup
if (!isPopupShown) {
Popup.
showPopup
(uyeolUI, "Kullancı oluşturulmadı!");
isPopupShown = true;
}
break;
case 21:
//olumlu popup
if (!isPopupShown){
Popup.
showPopup
(uyeolUI,"Kullancı oluşturuldu!");
isPopupShown = true;
}
case 31:
//mesaj nesnesini alıp ondan anlamlı mesaj stringi oluşturalım
Mesaj mesaj = serverResponse.getMesaj();
String string = mesaj.getGonderici() + "[" + mesaj.getTime() + "]: " + mesaj.getMesaj() + "\n";
//Sonra mesajı chate yazdıralım ve alanı temizleyelim
chatUI.writeMessageArea(string);
chatUI.setMessageArea("");
break;
default:
System.
out
.println("Hata oluştu");
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
public void gonder(Gonderi gonderi) {
try {
String gonderiString = SifrelemeClient.
sifrele
(gonderi);
out.writeObject(gonderiString);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
//Ana sınıfımızdır bunu başlatarak programı çalıştırıyoruz
public class Main {
public static void main(String[] args) throws IOException {
Client client = new Client();
client.clientCalistir();
}
}
ServerSide :
public class Main {
public static void main(String[] args) {
Server.serveriCalistir();
}
}
import java.io.*;
import java.net.*;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class Server {
private static final int
PORT
= 1234;
private static CopyOnWriteArrayList<ClientHandler>
clients
= new CopyOnWriteArrayList<>();
public static void serveriCalistir(){
try {
ServerSocket serverSocket = new ServerSocket(
PORT
);
System.
out
.println("Server is running and waiting for connections..");
// Gelen bağlantıları kabul edelim
while (true) {
Socket clientSocket = serverSocket.accept();
System.
out
.println("New client connected: " + clientSocket);
// Her isteyici için clientHandler oluşturalım
Server.ClientHandler clientHandler = new Server.ClientHandler(clientSocket);
clients
.add(clientHandler);
new Thread(clientHandler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Tum kullancılara mesajı göndermek için metod oluşturalım
public static void broadcast(Gonderi gonderi, ClientHandler sender) {
for (ClientHandler client :
clients
) {
if (client != sender) {
try {
client.sendMessage(gonderi);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
//Sadece tek kullancıya gonderi gondermek için metod da lazım
//Bağlantıları ayarlamak için iç sınıf oluşturalım
protected static class ClientHandler implements Runnable {
private Socket clientSocket;
private ObjectOutputStream out;
private ObjectInputStream in;
private User user;
// Constructor
public ClientHandler(Socket socket) {
this.clientSocket = socket;
try {
// İletişim için input/output oluşturalım
out = new ObjectOutputStream(clientSocket.getOutputStream());
in = new ObjectInputStream(clientSocket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
// Kullancı ile iletişim için run() metodu
@Override
public void run() {
int loginOlduMu = 0;
try {
try{
//İlk önce kullancının girip girmemiş olduğundan emin olalım
if (loginOlduMu!=0){
String inputLine1 = (String) in.readObject();
Gonderi istek = SifrelemeServer.
cevir
(inputLine1);
System.
out
.println(istek.getMesaj().getMesaj());
// İstemciden gönderi almayı devam et
while (istek != null) {
// Mesaj varsa bunu tum kullancılara gonderelim
if (istek.getRequestType() == 3 & istek.getMesaj() != null){
Mesaj mesaj = VeriTabanIslemler.
mesajEkle
(istek.getMesaj());
istek.setMesaj(mesaj);
istek.setResponseCode(31);
broadcast
(istek, this);
}
//Geçmiş yuklemek isteniyorsa geçmişi diziye saklayıp tek tek gönderelim
if (istek.getRequestType() == 4){
List<Mesaj> mesajlar = VeriTabanIslemler.
getAllMessages
();
for (Mesaj mesaj: mesajlar){
Gonderi gonderi = new Gonderi(4,mesaj);
gonderi.setResponseCode(31);
sendMessage(gonderi);
}
}
}
}
else{
String inputLine = (String) in.readObject();
User user = SifrelemeServer.
userCevir
(inputLine);
//İsteyiciden gelen Kullancı varMı bilgisine göre kullancı ya üye olur ya giriş yapar
if(user.varMi){
loginOlduMu = VeriTabanIslemler.
girisYap
(user);
System.
out
.println(loginOlduMu);
//Giriş yapıldıysa olumlu response gönderelim
if(loginOlduMu==11) {
Gonderi gonderi = new Gonderi(1,null);
gonderi.setResponseCode(11);
sendMessage(gonderi);
}
}
else
VeriTabanIslemler.
kullanciOlustur
(user);
}
}catch (Exception e){
e.printStackTrace();
// Remove the client handler from the list
clients
.remove(this);
// Close the input and output streams and the client socket
in.close();
out.close();
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(Gonderi gonderi) throws IOException {
String responseString = SifrelemeServer.
sifrele
(gonderi);
out.writeObject(responseString);
}
}
}
Welcome to the daily Advent Of Code thread!
Please post all related topics only here and do not fill the subreddit with threads.
The rules are:
/u/Philboyd_studge contributed a couple helper classes:
FileIO
Direction
Enum ClassUse of the libraries is not mandatory! Feel free to use your own.
/u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627
If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb
to join. Note that people on the board will see your AoC username.
Happy coding!
I have been working on this for hours, I'm sure I've just missed something, but I have no clue what, because null doesn't tell me much of anything :( I'm trying to have this RecipeSearch program read this text file, but it only reads the first recipe and then stops. I have actually looked up other people having this issue, as well as tried copying correct solutions on GitHub and comparing them to my own, but I can't figure out why theirs work and mine doesn't? I don't just want to understand how to do this correctly, but why what I'm doing is wrong, because I thought I had it down until I executed it and hit a wall and now I want to mash my face into my keyboard.
https://github.com/tylermag/mooc-guide/tree/096631708da39f7470664ea27bf7797c3a145cf1
Hello. I am doing a chating app using swing in java for my project in OOP class. And im trying to implement signing-up by sending user information(as User classed object) trough socket. And to make it secure i encrypted it using aes key and converted it to base64 string when its received by server its gonna decrypt there to user object again. But when im sending user information i get this error on server side can anyone help please.
Also i wanna add that socket later on will be exchanging Gonderi(Request) object thats why there is different encrypt() decrypt() methods.
P.S sorry for turkish comments
//server side recieving object
...
@Override
public void run() {
try {
//İlk önce kullancının girip girmemiş olduğundan emin olalım
int loginOlduMu = 0;
try{
String inputLine = (String) in.readObject();
User user = SifrelemeServer.
userEncrypt
(inputLine);
if(user.varMi)
loginOlduMu = VeriTabanIslemler.
girisYap
(user);
else
VeriTabanIslemler.
kullanciOlustur
(user);
if (loginOlduMu==0){
Response response = new Response(2,null);
response.setResponseCode(20);
sendMessage(response);
}
else{
String inputLine1 = (String) in.readObject();
Gonderi istek = SifrelemeServer.decrypt(inputLine1);
RequestSolver istekCozucu = (RequestSolver)istek;
Response donus = (Response)istek;
// İstemciden gönderi almayı devam et
while (istekCozucu != null) {
// Mesaj varsa bunu tum kullancılara gonderelim
if (istekCozucu.requestType == 3 & istekCozucu.mesaj != null)
broadcast
(donus, this);
if (istekCozucu.requestType != 3){
donus.setResponseCode(istekCozucu.islemYap());
sendMessage(donus);
}
}
}
}catch (Exception e){
e.printStackTrace();
// Remove the client handler from the list
clients
.remove(this);
// Close the input and output streams and the client socket
in.close();
out.close();
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
...
//Client side sending user object
...
uyeolUI.addUyeOlListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
user = new User(uyeolUI.getUsername(), uyeolUI.getSifre(), uyeolUI.getIsim(), uyeolUI.getSoyisim());
String userString = SifrelemeClient.
userEncrypt
(user);
out
.writeObject(userString);
out
.flush(); // Ensure data is sent
} catch (IOException ex) {
ex.printStackTrace();
}
}
...
//Client side object encryption-decryption
import java.io.*;
import java.util.Base64;
public class SifrelemeClient {
private static final String SECRET_KEY = "5ROIfv7Sf0nK9RfeqIkhtC6378OiR5E0VyTnjmXejY0=";
public static String encrypt(Gonderi gonderi){
try{
//Gonderimizi bayt dizisine çevirelim
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(gonderi);
//Oluşan diziyi şifreleyelim
String sifrelenmisVeri = AESUtil.encrypt(new String(byteArrayOutputStream.toByteArray()), SECRET_KEY);
//Son olarak şifrelenmiş diziyi döndürelim
return sifrelenmisVeri;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String userEncrypt(User user){
try{
//Gonderimizi bayt dizisine çevirelim
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(user);
//Oluşan diziyi şifreleyelim
String sifrelenmisVeri = AESUtil.encrypt(new String(byteArrayOutputStream.toByteArray()), SECRET_KEY);
//Son olarak şifrelenmiş diziyi döndürelim
return sifrelenmisVeri;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Response decrypt(String sifrelenmisVeri){
try{
//Gelen String diziyi bayt dizisine çevirelim ve
byte[] decryptedBytes = AESUtil.decrypt(sifrelenmisVeri, SECRET_KEY).getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptedBytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
//Veriyi bizim anlayabileceğimiz türden objeye çevirelim
Response response = (Response)objectInputStream.readObject();
//Son olarak çıkan objemizi döndürelim
return response;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
//Server side object encryption-decryption
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SifrelemeServer {
private static final String SECRET_KEY = "5ROIfv7Sf0nK9RfeqIkhtC6378OiR5E0VyTnjmXejY0=";
public static String encrypt(Response response){
try{
//Gonderimizi bayt dizisine çevirelim
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(response);
//Oluşan diziyi şifreleyelim
String sifrelenmisVeri = AESUtil.encrypt(new String(byteArrayOutputStream.toByteArray()), SECRET_KEY);
//Son olarak şifrelenmiş diziyi döndürelim
return sifrelenmisVeri;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Gonderi decrypt(String sifrelenmisVeri){
try{
//ALdığımız verinin şifrelemesini çözelim
byte[] decryptedBytes = AESUtil.decrypt(sifrelenmisVeri, SECRET_KEY).getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptedBytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
//Veriyi bizim anlayabileceğimiz türden objeye çevirelim
Gonderi gonderi = (Gonderi)objectInputStream.readObject();
//Son olarak çıkan objemizi döndürelim
return gonderi;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public static User userDecrypt(String sifrelenmisVeri){
try{
//Aldığımız kullancı verinin şifrelemesini çözelim
byte[] decryptedBytes = AESUtil.decrypt(sifrelenmisVeri, SECRET_KEY).getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptedBytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
//Kullancı veriyi bizim anlayabileceğimiz türden objeye çevirelim
User user = (User)objectInputStream.readObject();
//Son olarak çıkan objemizi döndürelim
return user;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
//Aes encryption methods
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
private static final String
ALGORITHM
= "AES";
// Gonderiyi sifrelemek için metod yazalım
public static String encrypt(String data, String key) throws Exception {
SecretKey secretKey =
getKeyFromBase64
(key);
Cipher cipher = Cipher.
getInstance
(
ALGORITHM
);
cipher.init(Cipher.
ENCRYPT_MODE
, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.
getEncoder
().encodeToString(encryptedData);
}
// Gelen Gonderiyi çözmek için metod da oluşturalım
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKey secretKey =
getKeyFromBase64
(key);
Cipher cipher = Cipher.
getInstance
(
ALGORITHM
);
cipher.init(Cipher.
DECRYPT_MODE
, secretKey);
byte[] decodedData = Base64.
getDecoder
().decode(encryptedData);
return new String(cipher.doFinal(decodedData));
}
// Base64'li anahtarımızı Secret Key formatına çevirmek için metod da yazalım
private static SecretKey getKeyFromBase64(String key) {
byte[] decodedKey = Base64.
getDecoder
().decode(key);
return new SecretKeySpec(decodedKey,
ALGORITHM
);
}
}
I’m working with JNI and I need to capture user input in C to return it to Java. However, when using both scanf
and fgets
, my program ends up in an infinite loop. Is there a way to safely use scanf
or any other input function in C without getting stuck in a loop? Any suggestions on how to handle this correctly?
I have a java app in ubuntu, that every few hours/days gets killed because it took too much memory.
I have a .hprof file that gets generated every few weeks!
Why? How can I get it printed every time the app gets killed?
I run my app with this command:LANG=en_US.utf8 java -Xdebug -Xnoagent -XX:-OmitStackTraceInFastThrow -XX:MaxRAM=2048m -Xmx2048m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath="/opt/Alpaca/jar" -Dspring.profiles.active=linode-projection -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar /opt/Alpaca/jar/Alpaca/target/Alpaca-1.0-SNAPSHOT.jar projection &
The kenel log shows:Dec 20 18:24:36 localhost kernel: Out of memory: Killed process 2373458 (java) total-vm:4863272kB, anon-rss:1184432kB, file-rss:88kB, shmem-rss:0kB, UID:0 pgtables:2844kB oom_score_adj:0
A few seconds before it got killed, it had only 449.58475MB used memory (I logged the memory).
Why doesn't it crate a .hprof file all the time?
I am creating some methods of class USD that convert dollars to several other currencies. My USD class is not dependent on creating objects; it’s almost like the Math class. For example my methods are called like this: USD.toEUR(1) - this converts dollars to euros. The conversions are hard coded with data I found on google, but those values are different from the conversions today.
I don’t know how feasible this is, but I’d like a way to define the conversions using up to date information. Somehow the program will look up the conversion rate and utilize that data in the function? I don’t know how to do that. I’ve never actually programmed anything that accesses the web. Any advice?
Welcome to the daily Advent Of Code thread!
Please post all related topics only here and do not fill the subreddit with threads.
The rules are:
/u/Philboyd_studge contributed a couple helper classes:
FileIO
Direction
Enum ClassUse of the libraries is not mandatory! Feel free to use your own.
/u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627
If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb
to join. Note that people on the board will see your AoC username.
Happy coding!
I used to be a Software Engineer before I switched to employee management several years ago. I don't enjoy the job nearly as much and I really miss developing and solving problems again. Therefore, I would like to build up current knowledge and am wondering which technologies and frameworks in the Java environment are currently simply “must have's” that you need to know and be able to use.
Do you have any recommendations for me? What about cloud topics? Would certifications be useful? If so, what would you recommend?
Thank you very much in advance!
I have some POST code that does not work when threaded. It throws an IOException with the message of:
No subject alternative DNS name matching oranum.com found.
I manage my own certificates, and I have never heard of oranum.com
. It doesn't exist anywhere in my project.
I'm posting to https://127.0.0.1:8443/api
. So it shouldn't be trying to resolve any hostname.
My Maven dependencies are maven-compiler-plugin
, junit
, jackson-core
, and jackson-databind
.
My request looks like this:
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri( URI.create( this.endpoint ) )
.headers( "Content-Type", "application/json" )
.timeout( postTimeout )
.POST( HttpRequest.BodyPublishers.ofString( jsonString ) )
.build();
And my .send
looks like this:
HttpResponse<String> response = httpClient.send( httpRequest, HttpResponse.BodyHandlers.ofString() );
This code works perfectly in hundreds of unit tests, except for my two threaded tests. Since this is for work I can probably share my unit tests, but will need permission to share the API classes.
My hosts file is empty (IP addresses ignore the hosts file), and this happens on multiple machines. I'm not using any containers.
How should I troubleshoot this?
Edit: It happens on at least two different Windows machines, but does not happen on my Linux VM.
I’ve been assigned an IKM Java SE9+ test. Was wondering what I should expect and how to best prepare?
Hi
I was refactoring some older systems, and came across this question during design.
public interface IMyFunction extends Function<Snapshot, Optional<MyResult> {}
implementations currently allow null to be returned
I am not sure if it is cleaner to have Optional or leave it out
Thoughts?
Hi, is it possible to share jfxpanel between jnotebook tabs? I'm using singleton to share my jfxpanel, but as far it works only 'forward', I mean if tab1 initialize and display jfxpanel, I can see it on tab2. But when I go back to tab1, my jfxpanel is empty. Did anyone done something similar? I prefer to use single jfxpanel for performance.
Welcome to the daily Advent Of Code thread!
Please post all related topics only here and do not fill the subreddit with threads.
The rules are:
/u/Philboyd_studge contributed a couple helper classes:
FileIO
Direction
Enum ClassUse of the libraries is not mandatory! Feel free to use your own.
/u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627
If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb
to join. Note that people on the board will see your AoC username.
Happy coding!
I am following this tutorial for making a minecraft mod using IntelliJ and when i get to the point where you type
./gradlew genSources
into the terminal (at about 12:08) i always get
ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
I have tried deleting and reinstalling both Eclipse Adoptium and IntelliJ as well as going into the System Environment Variables and deleting the JAVA_HOME variable and creating it again with this file path: C:\Program Files\Eclipse Adoptium\jdk-21.0.5.11-hotspot
, I have also edited the Path system variable to include %JAVA_HOME%\bin
and so far I have experienced no change. I don't know much about programming or java but as far as I know your JAVA_HOME is supposed to be linked to a JDK, and as far as I can tell mine is so I don't know whats the problem
I have successfully used FFI to call a method, in my case prctl
, but it is failing, and returning -1. Which is correct, as the error is set into errno
, but how can I print the name of the error? None of the examples that I have been able to find show this, and chatGPT just hallucinates all over the place, variously showing Java 19, or invalid Java 22.
I can get errno
:
// Get the location to errno from libc. It's in the libc, so no dlopen(3) / arena
// required! Also, it's an integer, not a function.
MemorySegment errno = Linker.nativeLinker().defaultLookup().find("errno").get();
// It's unsafe memory by default.
assert 0 == errno.byteSize();
// We know that errno has the type of int, so manually reinterpret it to 4 bytes,
// and JVM will automatically do boundary check for us later on.
// Remember, this is an unsafe operation because JVM has no guarantee of what
// the memory layout is at the target location.
errno = errno.reinterpret(4);
assert 4 == errno.byteSize();
// Get as usual as a int
System.out.println("errno: " + errno.get(ValueLayout.JAVA_INT, 0));
And I can print out that value, but I really want to call strerror
now. I get part of the way there:
Linker linker = Linker.nativeLinker();
SymbolLookup stdlib = linker.defaultLookup();
// Find the strerror function
MethodHandle strerrorHandle = linker.downcallHandle(
stdlib.find("strerror").orElseThrow(),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.JAVA_INT)
);
strerrorHandle.invoke(errno.get(ValueLayout.JAVA_INT, 0));
This then returns a MemorySegment
, but how do I know how big this memory segment should be for the reinerpret? For example, if I do:
try (Arena arena = Arena.ofConfined()) {
a.reinterpret(500).getString(0);;
}
then it works, but how can I work out how big should that 500
actually be?
[4:06:36 PM] AdoptOpenJDK-17-x64
[4:07:06 PM] Unexpected token '<', "<!DOCTYPE "... is not valid JSON
[4:07:06 PM] Retry downloading ... [1]
[4:07:36 PM] Unexpected token '<', "<!DOCTYPE "... is not valid JSON
[4:07:36 PM] Retry downloading ... [2]
[4:08:06 PM] Unexpected token '<', "<!DOCTYPE "... is not valid JSON
[4:08:06 PM] fallback to Adopt API v3
[4:08:12 PM] Download JDK ... [Completed]
[4:08:12 PM] Install JDK
[4:08:12 PM] Installing AdoptOpenJDK-17-x64...
[4:08:12 PM] Error occurred
[4:08:12 PM] Error: Command failed with exit code 1619: C:\Windows\System32\msiexec.exe /i "C:\Users\Matt\AppData\Local\Temp\vscode-java-installer\binaries\jdk\17\x64\OpenJDK17U-jdk_x64_windows_hotspot_17.0.13_11.msi" MSIINSTALLPERUSER=1 ADDLOCAL=FeatureJavaHome,FeatureEnvironment,FeatureJarFileRunWith /passive /l*v "C:\Users\Matt\AppData\Local\Temp\vscode-java-installer\AdoptOpenJDK-MSI.log"
This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.
These are the errors im getting, trying to setup VScode with Java but it does not seem to want to work. Any advice?
Hi All,
I have been trying to Connect my React Front-end to Spring-Boot back-end with Web Socket, After Following couple tutorials i managed to send message to my react app, but after a restart i couldn't connect anymore.
React-Code
import SockJS from 'sockjs-client';
import { Client } from "@stomp/stompjs";
useEffect(() => {
try {
const socket = new SockJS("http://localhost:7911/ws");
const stompClient = new Client({
webSocketFactory: () => socket,
debug: (str) => { console.log(str); },
onConnect: () => {
stompClient.subscribe("/notification/all", (response) => {
console.log('Received message:', response.body);
});
},
onStompError: (e) => {
console.log(e);
},
});
stompClient.activate();
return () => {
console.log("Deactivate");
stompClient.deactivate();
};
} catch (e) {
console.log(e)
}
}, [])
Java Code
@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/notification");
}
}
I am Using SimpMessagingTemplate to Send the Notification.
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
private static final Logger log = LoggerFactory.getLogger(MessagingService.class);
public void sendNotification(Message message){
try {
simpMessagingTemplate.convertAndSend("/notification/all",message.toString());
}catch (Exception e){
log.error("Exception Occurred While Sending Message {}",e);
}
}
SecurityConfiguration Class:
public SecurityFilterChain mainFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity.httpBasic((basic) -> basic.disable()).csrf((csrf) -> csrf.disable()).authorizeHttpRequests((auth) -> { auth.requestMatchers(AntPathRequestMatcher.antMatcher(SECURED_API_PATTERN)).authenticated(); auth.requestMatchers(AntPathRequestMatcher.antMatcher(OPEN_API_PATTERN)).permitAll(); auth.requestMatchers(AntPathRequestMatcher.antMatcher("/")).permitAll(); auth.requestMatchers(AntPathRequestMatcher.antMatcher("/ws/")).permitAll();
})
.rememberMe(rememberMe -> rememberMe.key(REMEMBER_ME_SECRET)
.tokenValiditySeconds(REMEMBER_ME_DURATION)
.rememberMeParameter(REMEMBER_ME_PARAMETER))
.sessionManagement((session)->session.maximumSessions(1).sessionRegistry(sessionRegistry()))
.formLogin(httpSecurityFormLoginConfigurer -> {
httpSecurityFormLoginConfigurer
.loginPage(LOGIN_REQUEST_PAGE)
.successHandler(authenticationSuccessHandler())
.failureHandler(authenticationFailureHandler())
.loginProcessingUrl(LOGIN_PROCESSING_URL)
.usernameParameter(EMAIL_PARAMETER)
.passwordParameter(PASSWORD_PARAMETER)
.permitAll();
}).logout((logout) -> logout.logoutUrl(LOGOUT_URL)
.logoutSuccessHandler(logOutSuccessHandler)
.deleteCookies(COOKIE_PARAM)
.permitAll())
.build();
}
url returns : http://localhost:7911/ws
Welcome to SockJS!
This is Console Debug from the Browser
Opening Web Socket... index-Qpo0fazg.js:400:15644
Connection closed to http://localhost:7911/ws index-Qpo0fazg.js:400:15644
STOMP: scheduling reconnection in 5000ms index-Qpo0fazg.js:400:15644 Opening Web Socket...
Its Quite Curious i managed to get response at first and couldn't afterwards. I checked Windows Fire-Wall Setting didn't find any thing odd there.
Any Help Would mean a lot
Thanks
Welcome to the daily Advent Of Code thread!
Please post all related topics only here and do not fill the subreddit with threads.
The rules are:
/u/Philboyd_studge contributed a couple helper classes:
FileIO
Direction
Enum ClassUse of the libraries is not mandatory! Feel free to use your own.
/u/TheHorribleTruth has set up a private leaderboard for Advent Of Code. https://adventofcode.com/2020/leaderboard/private/view/15627
If you want to join the board go to your leaderboard page and use the code 15627-af1db2bb
to join. Note that people on the board will see your AoC username.
Happy coding!
I have two CSV files which contain exported data from two different sources. Data don't have something like a Primary key column. We can create a Primary key based on four columns . We have to compare two CSV and produce a very good result in some output format highlighting mismatched Cells in a row. Missing Row or additional rows . Is there a solution readily available out there
Year 2 uni student I have a module on OOP and we will also do GUI development. Which of the 2 books should I buy:
OR
Edit: Please feel free to recommend other books if needed
Thank you!
Which is the recommended approach out of the 2. My use case is fairly simple. I just want to wrap an InputStream and send it as a MultiPartFile in another Microservice.
I want to send ByteArrayInputStream in a request to different service which accepts a MultiPartFile. Is there a better way than implementing the MultiPartFile interface? MockMultiPartFile is for testing only, right?
Semi-experienced developer trying to learn java here. I come from a very functional coding env so I am really trying to learn OOP and Java the way it's meant to be written. I realize making three classes for such a simple problem is overkill but like I said, im trying to do it the OOP and Java way.
So I attempted the Advent of Code day one in Java. Would love any feedback, tips, and or pointers.
The requirements of the problem need two arrays so the DayOne class processes the input into two arrays on instantiation then each the solvePartOne and solvePartTwo use that processed data to complete the problem.
Main.java
public class Main {
public static void main(String[] args) {
DayOne dayOne = new DayOne("input-day-one.txt");
var partOneAnswer = dayOne.solvePartOne();
var partTwoAnswer = dayOne.solvePartTwo();
System.out.println(partOneAnswer);
System.out.println(partTwoAnswer);
}
}
import java.util.Arrays;
import java.util.HashMap;
public class DayOne {
private static int [][] parsedData;
public DayOne(String fileName) {
parsedData = parseData(fileName);
}
public int solvePartOne() {
int answer = 0;
for (int i = 0; i < parsedData[0].length; i++) {
answer += Math.abs(parsedData[0][i] - parsedData[1][i]);
}
return answer;
}
public int solvePartTwo() {
int similarity = 0;
HashMap<Integer, Integer> occurrences = new HashMap<Integer, Integer>();
var columnTwo = parsedData[1];
for (int item : columnTwo) {
if (occurrences.containsKey(item)) {
occurrences.put(item, occurrences.get(item) + 1);
} else {
occurrences.put(item, 1);
}
}
var columnOne = parsedData[0];
for (int item : columnOne) {
similarity += item * (occurrences.getOrDefault(item, 0));
}
return similarity;
}
private static int[][] parseData (String fileName) {
FileHandler fileHandler = new FileHandler();
var lines = fileHandler.readFile(fileName);
int[] columnOne = new int[lines.size()];
int[] columnTwo = new int[lines.size()];
for (int i = 0; i < lines.size(); i++) {
String c1 = lines.get(i).substring(0, 5);
String c2 = lines.get(i).substring(8, 13);
columnOne[i] = Integer.parseInt(c1);
columnTwo[i] = Integer.parseInt(c2);
}
Arrays.sort(columnOne);
Arrays.sort(columnTwo);
int[][] result = new int[2][];
result[0] = columnOne;
result[1] = columnTwo;
return result;
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FileHandler {
public ArrayList<String> readFile(String fileName) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
ArrayList<String> lines = new ArrayList<>();
while ((line = reader.readLine()) != null) {
lines.add(line);
}
reader.close();
return lines;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
I have a class called "Ability" and a class called "Phase" which extends it.
I have a variable X, defined as "Class<? extends Ability> X = Phase.class"
I also have an Ability variable, which we'll call Y
How can I set Y equal to a new instance of a phase class, given only the variable X?