โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

How to configure different logging levels for different loggers in Log4j2

We are trying to utilize Log4j2 in our project. We want to configure Log4j2 via properties files.

To reduce the noise in our logs, we want to set the root logger to info and set debug logging only for specific loggers or packages. How do we configure logging levels for each of our classes under development and not get debug messages for all the other loggers?

Here is an example we are using in our project:

status = warn
name = StackOverflow

# Console appender configuration
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d [%p] %c{1} - %m%n

# Root logger level
rootLogger.level = info
rootLogger.appenderRef.stdout.ref = consoleLogger

# Only this class should be logging debug events
logger.mylogger.name = com.example.ClassUnderDevelopment
logger.mylogger.level = DEBUG

What would be the properties needed to configure Log4j2 to enable different log levels for different classes (named loggers)?

How to model from the distribution center to the mission point in java gurobi

Have a taskInfomation(list) include distribution center (0) and lots of tasks,so how to model in gurobi use java? As follow the picture.xijrk is binary variable

        for (int k = 0; k < VehicleInfo.size(); k++) {
            for (int r = 0; r < Route.getTrip(); r++) {
                for (int i = 0; i < 1; i++) {
                    for (int j = 1; j < taskInfo.size()-1; j++) {
                        GRBLinExpr expr = new GRBLinExpr();
                        expr.addTerm(1, csVariable.x[i][j][k][r]);
                        model.addConstr(expr, GRB.Less_EQUAL, 1, "name" + i + "_" + j + "_" + k + "_" + r);
                    }
                }
            }
        }

Select parent and only some fields from child in @OneToMany relationships using JPA and Criteria Builder

Implemented one to many relationship and select parent and child I have a onetomany relationship. Using criteria builder, i need to get parent and all related childs but selecting only some fields from each child.

@Entity
@Table(name="transaction_status")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class TransactionStatus implements Serializable {
@Id
@Column(name = "id")
@JsonProperty("id")
public String id;

@SerializedName("status")
public String status;

@Column(name="lastUpdatedDate")
@JsonProperty("lastUpdatedDate")
@SerializedName("lastUpdatedDate")
private Date lastUpdatedDate;

@JsonProperty("generatedAt")
@SerializedName("generatedAt")
@JsonIgnore
private Date generatedAt;

@JsonProperty("invoices")
@SerializedName("invoices")
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="transactionstatusId",referencedColumnName = "xmlFilename")
private List<InvoiceTransaction> invoiceTransactions = new ArrayList<>();

}

@Entity
@Table(name="invoice_transaction")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor

public class InvoiceTransaction implements Serializable {
    @Column(name = "status", nullable = false)
    @JsonProperty("status")
    @SerializedName("status")
    private String status;
    @Column(name = "originalStatus", nullable = false)
    @JsonProperty("originalStatus")
    @SerializedName("originalStatus")
    private String originalStatus;
    
    @Column(name = "errorMessage")
    @JsonProperty("errorMessage")
    @SerializedName("errorMessage")
    private String errorMessage;

    @Column(name = "generatedAt" )
    @JsonProperty("generatedAt")
    @SerializedName("generatedAt")
    private Date generatedAt;
}

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<TransactionStatus> cq = builder.createQuery(TransactionStatus.class);
Root<TransactionStatus> rootTrnStatus = cq.from(TransactionStatus.class);
List<TransactionStatus> resultList = entityManager.createQuery(cq).getResultList();

this implementation, gives me list of Transactionstatus objetc with list of its childs. what im seraching to get is: list of Transactionstatus object with list of its childs with olny status and errorMessage fileds. How can i get this result using Crtiteria builder? thank you

Are Java command execution methods worse than regular command line execution? [closed]

I am wondering if Java command execution methods are worse than regular command line execution. I mean, does executing "python3 my_script.py" in command line gives better performance than ProcessBuilder or Runtime.exec() (calling python is an example, it can be anything)? If it does, does the same thing apply in case that docker commands or making request to a server (I am asking because main process can be not started by Java in that case)? If it does not, which one is better in performance, ProcesssBuilder or Runtime.exec()? Can you give detailed answers, please? I researhed about that topic but could not find satisfying answer.

EDIT: Question is not answered yet, I am adding a new question. With respect to answer of above question, Does it differ when it comes to Java Native Build?

how to make a row in a matrix only go as long as the first number?

so i have this exercise on matrixes which needs to be done with two dimensional arrays. the first part was that you have n, which goes from 1 to 9. for each row, you need to output the muliplication table of that first number. so basically:

  • 1, 2, 3, 4, 5, 6, 7, 8, 9
  • 2, 4, 6, 8, 10, 12, 14, 16, 18
  • 3, 6, 9, 12, 15, 18, 21, 24, 27

and so on until 9. this part i solved the following way:

public static void main(String[] args) {
        int[][] column = new int[][] { { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }, { 7 }, { 8 }, { 9 } };
        int[][] row = new int[][] { { 1, 2, 3, 4, 5, 6, 7, 8, 9 } };
        int[][] result = new int[column.length][row[0].length];
    
        for (int i = 0; i < column.length; i++) {
            for (int j = 0; j < row[0].length; j++) {
                for (int n = 0; n < column[0].length; n++) {
                    result[i][j] += column[i][n] * row[n][j];
                }
            }
        }
        System.out.println("Teilaufgabe a: " + "\r\n");
        for (int[] rowResult : result) {
            System.out.println(Arrays.toString(rowResult));
        }

    }

}

now my problem lies in the 2nd part of the exercise, where each line needs to be as long as the number of row[0], basically creating a stair structure.

it should look like this:

  • 1
  • 2, 4
  • 3, 6, 9
  • 4, 8, 12, 16

and so on

how can i make this happen? ive been struggling real hard with the implementation of it, it must have sth to do with the loop but ive been trying around a week to figure this out, so all help is greatly appreciated!! critique on my already working code is also appreciated, since one of my friends said in a comment that its weird that im using 3 for loops for this issue

i tried changing things within my third for loop but couldnt quite figure that out. my other idea was creating a 2nd "int[][] result2" and have it run in its own 4th loop, but i couldnt figure out the parameters for the loop to be doing what i wanted it to do, so i scrapped it.

Jackson serializing objects with circular reference

Is it possible to access or lookup annotation values that were placed on an object when using a custom serializer?


data class Parent(
  val name: String,
  @JsonIgnoreProperties("parent") 
  val child: Child
)
data class Child(
  val name: String,
  val parent: Parent,
)

class CustomSerializer : StdSerializer<Child>(Child::class.java) {
  override fun serialize(obj: Child, gen: JsonGenerator, provider: SerializerProvider) {
     gen.writeStartObject()
     gen.writeFieldName("name")
     gen.writeString(obj.name)
     // if i am serializing a child that is accessed from within a parent object
     // that should not be serialized because of @JsonIgnoreProperties
     // but if I am serializing a Child directly, the parent should be serialized
     gen.writeEndObject()
  }
}

Maven profile not activating when invoking plugin goal directly

I have set up a parent pom that contains executions for the plugin maven-protobuf-plugin.

In the parent pom, I created a profile for additional executions of this plugin. To configure this correctly, I used the answer from Define Maven plugins in parent pom, but only invoke plugins in child projects.

When I execute the following:

mvn -X compile -Pcustom-profile

I can see that both my standard executions and profile-based executions for maven-protobuf-plugin are being run. However, I want to clean this process up. I want to only run the plugin's goal with my profile.

When I execute the following:

mvn -X protobuf:generate -Pcustom-profile

I can no longer see that my profile-based executions are run from maven-protobuf-plugin. Comparing the runs side by side, the profile-based configurations/executions are all gone.

What am I missing to make this work? I would expect the profile-based configurations/executions to be available regardless of whether I execute standard lifecycle phases versus just the plugin's goal.

Update: For those who downvoted the question, instead of downvoting, explain what issues the question has and what further clarification you would like. Thank you.

Actual content length differs from Content-Length header length [closed]

When I hit my server url, my json response is getting truncated. This issue only came into existence when I updated to JBOSS EAP 7.4 from JBOSS EAP 7.2. When I am debugging my code on my ide, I see the response is good, but as soon as it reaches client, it is truncated. One more thing truncation only happens nodeData field is empty

I have made some progress, I have httpFilter which is compressing the bytes and setting content encoding to gzip. If I set my content encoding to "identity", then I am getting full response.

These are my response headers:-

Content-Encoding: gzip

Content-Length: 78

Content-Type: text/html;charset=UTF-8

Date: Tue, 30 Apr 2024 08:43:47 GMT

Response:

{ "status" : "OK" ,"lastModifiedStamp":"1713954485629","no

Expected response from server:

{ "status" : "OK" ,"lastModifiedStamp":"1713954485629","nodeData":[]}

Overlay layout covering only half screen (full height but half width)

I have a simple app that uses a foreground service that draw overlay a green view:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:orientation="vertical"
    android:visibility="visible"
    android:focusable="true"
    android:id="@+id/test_layout">
        <View
            android:id="@+id/test_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="visible"
            android:background="@color/colorGreen"
            />
</RelativeLayout>

But as mentioned in the title for some reason I am only able to draw half screen in width, while I am able to draw in full height screen.

This is the implementation:

private WindowManager.LayoutParams getLayoutParams()
    {
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                getLayoutFlag(),
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);


        //Specify the view position
        params.gravity = Gravity.TOP | Gravity.START; //Initially view will be added to top-left corner
        params.x = 0;
        params.y = 100;
        return params;
    }

    private int getLayoutFlag()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            return WindowManager.LayoutParams.TYPE_PHONE;
        }
    }


    public void create()
    {    
            mOverlayView = LayoutInflater.from(context).inflate(R.layout.invisible_view_layout, null);

            WindowManager.LayoutParams params = getLayoutParams();
            mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            mWindowManager.addView(mOverlayView, params);

            Display display = mWindowManager.getDefaultDisplay();
            final Point size = new Point();
            display.getSize(size);
    }

Please tell me if you need also a screenshot.

I really don't understand why is drawing only half width since both width and height are set to "wrap_content".

get protobuf over-the-wire size in bytes

is there a way in java to get the size of a protobuf in bytes? I know there exists the getSerializedSize function, but I believe that will include field names, etc. Is there a way to actually get the size of what is going to be transferred over the wire?

Java reworked 'FTP' File Transfer with Ascii and Binary

I'm having to implement a basic file transfer system in Java, one that accepts commands from the client. Unfortunately, the class this was for has so far been more about networking concepts as opposed to code, so I am struggling a bit with the proper way to go about it. For any kind enough to help, if there's a good guide or documentation somewhere as to how to do this I would be eternally grateful.

The current issue I am running into right now is that sometimes after I download or upload a file, it won't let me put any more input and the client is essentially frozen. I believe it to be the server and client getting out of sync, but I have no clue where.

I'm aware that this code is an absolute mess so if there's a guide already written or an example somewhere on how to properly do it you can just point me there instead of having to strain your eyes understanding all this spaghetti.

Client Side:

import java.io.*;
import java.net.*;

public class FTPClient {
   
    public static void main(String[] args) {
        String serverAddress = "localhost"; 
        int portNumber = 8888; 
        

        try (
            Socket socket = new Socket(serverAddress, portNumber);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
        ) {
            // Handle server's initial welcome message or prompt
            System.out.println(in.readLine());  // Read and display the "Please enter your username:" message

            // Send username and handle response
            String username = stdIn.readLine();
            out.println(username);
            System.out.println(in.readLine());  // Read and display the "Please enter your password:" message

            // Send password and check for authentication
            String password = stdIn.readLine();
            out.println(password);

            String serverResponse = in.readLine();
            if (!serverResponse.startsWith("230")) {
                System.out.println("Authentication failed: " + serverResponse);
                return;
            }

            System.out.println("Authentication successful. Enter commands:");

            // Handle commands
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                if (userInput.equalsIgnoreCase("QUIT")) {
                    out.println("QUIT");
                    System.out.println("Quitting...");
                    break;
                } else if (userInput.equalsIgnoreCase("LIST")) {
                    out.println("LIST");
                    String response;
                    while (!(response = in.readLine()).equals("226 Directory listing complete")) {
                        System.out.println(response);
                    }
                } else if (userInput.startsWith("DOWNLOAD ")) {
                    String fileName = userInput.substring(9); // Extracting filename from the command
                    receiveFile(fileName, socket);
                } else if (userInput.startsWith("UPLOAD ")) {
                    String fileName = userInput.substring(7); // Extracting filename from the command
                    sendFile(fileName, socket, in);
                } else {
                    System.out.println("Server response: " + in.readLine());
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("Unknown host: " + serverAddress);
        } catch (IOException e) {
            System.err.println("Error connecting to server: " + e.getMessage());
        }
    }

    private static void sendFile(String fileName, Socket socket, BufferedReader in) {
        try {
            File file = new File(fileName);
            if (file.exists()) {
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                out.println("UPLOAD " + fileName);
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = bis.read(buffer)) != -1) {
                    socket.getOutputStream().write(buffer, 0, bytesRead);
                }
                bis.close();    
                fis.close();


                out.println("226 Transfer complete.");
                System.out.println("File uploaded successfully");
               
                
            } else {
                System.out.println("File not found.");
            }
        } catch (IOException e) {
            System.err.println("Error sending file: " + e.getMessage());
        }
    }

    private static void receiveFile(String fileName, Socket socket) {
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("DOWNLOAD " + fileName);
            FileOutputStream fos = new FileOutputStream(fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = socket.getInputStream().read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
                if (bytesRead < 4096) {
                    break;
                }
                
            }
            bos.close();
            fos.close();
            
            
            
            System.out.println("File downloaded successfully");
        } catch (IOException e) {
            System.err.println("Error receiving file: " + e.getMessage());
        }
    }
}

And this is the server side:

import java.io.*;
import java.net.*;
import java.nio.file.*;

public class FTPServer {
    private static final String ROOT_DIRECTORY = "C:\\Users\\pokem\\Documents\\CSCI 361\\Server Side"; // Directory where files are stored

    public static void main(String[] args) {
        int portNumber = 8888; 

        try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
            System.out.println("Server started. Waiting for clients...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected: " + clientSocket);

                // Handle each client in a separate thread
                new ClientHandler(clientSocket).start();
            }
        } catch (IOException e) {
            System.err.println("Error in server: " + e.getMessage());
        }
    }

    static class ClientHandler extends Thread {
        private Socket clientSocket;
        private PrintWriter out;
        private BufferedReader in;
        private boolean authenticated = false;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
            try {
                out = new PrintWriter(clientSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                // Authentication
                authenticate();
                if (!authenticated) {
                    clientSocket.close();
                    return;
                }

                // Main loop for handling client commands
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    if (inputLine.equalsIgnoreCase("QUIT")) {
                        System.out.println("Client disconnected: " + clientSocket);
                        break;
                    } else if (inputLine.equalsIgnoreCase("LIST")) {
                        listFiles();
                    } else if (inputLine.startsWith("DOWNLOAD ")) {
                        String fileName = inputLine.substring(9); // Extracting filename from the command
                        sendFile(fileName);
                    } else if (inputLine.startsWith("UPLOAD ")) {
                        String fileName = inputLine.substring(7); // Extracting filename from the command
                        receiveFile(fileName, in);
                    } else {
                        out.println("500 Invalid command.");
                    }
                }
            } catch (IOException e) {
                System.err.println("Error handling client: " + e.getMessage());
            }
        }

        private void authenticate() throws IOException {
            out.println("Please enter your username:");
            String username = in.readLine();
            out.println("Please enter your password:");
            String password = in.readLine();
            authenticated = authenticateUser(username, password);
            if (authenticated) {
                out.println("230 Authentication successful. Welcome " + username + "!");
            } else {
                out.println("530 Authentication failed. Disconnecting...");
            }
        }

        private boolean authenticateUser(String username, String password) {
            // Simulated authentication - just a placeholder
            return username.equals("admin") && password.equals("admin123");
        }

        private void listFiles() {
            try {
                File directory = new File(ROOT_DIRECTORY);
                File[] files = directory.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) {
                            out.println(file.getName());
                        }
                    }
                }
                out.println("226 Directory listing complete");
            } catch (Exception e) {
                out.println("550 Error listing directory");
            }
        }

        private void sendFile(String fileName) {
            try {
                File file = new File(ROOT_DIRECTORY + File.separator + fileName);
                if (file.exists()) {
                    FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        clientSocket.getOutputStream().write(buffer, 0, bytesRead);
                    }
                    bis.close();
                    fis.close();
                    
                    System.out.println("File sent: " + fileName);
                    out.println("226 Transfer complete.");
                    
                } else {
                    out.println("550 File not found.");
                }
            } catch (IOException e) {
                out.println("550 Error sending file");
            }
        }

        private void receiveFile(String fileName, BufferedReader in) {
            try {
                FileOutputStream fos = new FileOutputStream(fileName);
                BufferedOutputStream bos = new BufferedOutputStream(fos);

                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = clientSocket.getInputStream().read(buffer)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                    if (new String(buffer, 0, bytesRead).trim().equals("226 Transfer complete.")) {
                        break;
                    }
                }
                bos.close();
                fos.close();
                System.out.println("File received: " + fileName);
                
            } catch (IOException e) {
                out.println("550 Error receiving file");
            }
        }
    }
}

Java 8 JavaFX - How to set the color of the title text of a single tab

I have my UI layed out in an .fxml file, then I have a .css I use for defining the styles and a JavaFX Controller that extends AnchorPane.

In general it is not hard to style something, but the titles of Tabs are not explicitly defined in the .fxml and I seem to be unable to style it. I want to set the color of a single Tab to red.

Here are the approaches I have tried:

1- Setting the style directly in the .fxml:

    <Tab fx:id="tabRed" text="Tab 2" style="-fx-text-fill: red;">
        <content>
            <AnchorPane minHeight="0" minWidth="0" prefHeight="100" prefWidth="100"/>
        </content>
    </Tab>

2- Setting the style in the Controller

// an attribute of my Controller class
@FXML public Tab tabRed;

// inside the constructor of said Controller
tabRed.setStyle("-fx-text-fill: red;");

Note that I must use these versions of Java/JavaFX for reasons I do not control.

Creating a universal agent in a Java Agent Development Framework (JADE)

I'm new to JADE and have recently created a Service agent that looks up the definition of words from two dictionaries (WordNet(r) 3.0 (2006) and Easton's 1897 Bible Dictionary). I want to merge all services and behaviors of ServiceAgent into one. My goal is to end up having one agent class and one behavior class capable of handling requests to any dictionary from dict.org but I'm not sure how to do that.

I'm using Linux Red Hat and have downloaded Apache ANT 1.9.2 and Java JDK 1.5.0 if that helps.

Here is ServiceAgent.java code:

package jadelab1;

import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.*;
import jade.domain.*;
import jade.domain.FIPAAgentManagement.*;
import java.net.*;
import java.io.*;

public class ServiceAgent extends Agent {
        protected void setup () {
                //services registration at DF
                DFAgentDescription dfad = new DFAgentDescription();
                dfad.setName(getAID());
                //service no 1
                ServiceDescription sd1 = new ServiceDescription();
                sd1.setType("answers");
                sd1.setName("wordnet");
                //Serive no 2
                ServiceDescription sd2 = new ServiceDescription();
                sd2.setType("answers");
                sd2.setName("Easton's 1897 Bible Dictionary");
                //add them all
                dfad.addServices(sd1);
                dfad.addServices(sd2);
                try {
                        DFService.register(this,dfad);
                } catch (FIPAException ex) {
                        ex.printStackTrace();
                }

                addBehaviour(new AnotherDictionaryCyclicBehaviour(this));
                addBehaviour(new WordnetCyclicBehaviour(this));
                //doDelete();
        }
        protected void takeDown() {
                //services deregistration before termination
                try {
                        DFService.deregister(this);
                } catch (FIPAException ex) {
                        ex.printStackTrace();
                }
        }
        public String makeRequest(String serviceName, String word)
        {
                StringBuffer response = new StringBuffer();
                try
                {
                        URL url;
                        URLConnection urlConn;
                        DataOutputStream printout;
                        DataInputStream input;
                        url = new URL("http://dict.org/bin/Dict");
                        urlConn = url.openConnection();
                        urlConn.setDoInput(true);
                        urlConn.setDoOutput(true);
                        urlConn.setUseCaches(false);
                        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        String content = "Form=Dict1&Strategy=*&Database=" + URLEncoder.encode(serviceName) + "&Query=" + URLEncoder.encode(word) + "&submit=Submit+query";
                        //forth
                        printout = new DataOutputStream(urlConn.getOutputStream());
                        printout.writeBytes(content);
                        printout.flush();
                        printout.close();
                        //back
                        input = new DataInputStream(urlConn.getInputStream());
                        String str;
                        while (null != ((str = input.readLine())))
                        {
                                response.append(str);
                        }
                        input.close();
                }
                catch (Exception ex)
                {
                        System.out.println(ex.getMessage());
                }
                //cut what is unnecessary
                return response.substring(response.indexOf("<hr>")+4, response.lastIndexOf("<hr>"));
        }
}


class AnotherDictionaryCyclicBehaviour extends CyclicBehaviour {
    ServiceAgent agent;

    public AnotherDictionaryCyclicBehaviour(ServiceAgent agent) {
        this.agent = agent;
    }

    public void action() {
        MessageTemplate template = MessageTemplate.MatchOntology("Easton's 1897 Bible Dictionary");
        ACLMessage message = agent.receive(template);
        if (message == null) {
            block();
        }
 
        else {
                    // Process the incoming message and handle the request for the new dictionary service
                    String content = message.getContent();
                    ACLMessage reply = message.createReply();
                    reply.setPerformative(ACLMessage.INFORM);
                    String response = "";
                    try 
                       {
                        // Call the makeRequest method for the new dictionary service
                        response = agent.makeRequest("easton", content);
                       } 
                    catch (NumberFormatException ex) 
                       {
                        response = ex.getMessage();
                       }
            reply.setContent(response);
            agent.send(reply);
        }
    }
}


class WordnetCyclicBehaviour extends CyclicBehaviour
{
        ServiceAgent agent;
        public WordnetCyclicBehaviour(ServiceAgent agent)
        {
                this.agent = agent;
        }
        public void action()
        {
                MessageTemplate template = MessageTemplate.MatchOntology("wordnet");
                ACLMessage message = agent.receive(template);
                if (message == null)
                {
                        block();
                }
                else
                {
                        //process the incoming message
                        String content = message.getContent();
                        ACLMessage reply = message.createReply();
                        reply.setPerformative(ACLMessage.INFORM);
                        String response = "";
                        try
                        {
                                response = agent.makeRequest("wn",content);
                        }
                        catch (NumberFormatException ex)
                        {
                                response = ex.getMessage();
                        }
                        reply.setContent(response);
                        agent.send(reply);
                }
        }
}

I'm also including MyAgent.java code (just in case):

package jadelab1;

import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.*;
import jade.domain.*;
import jade.domain.FIPAAgentManagement.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyAgent extends Agent {
        protected void setup () {
                displayResponse("Hello, I am " + getAID().getLocalName());
                addBehaviour(new MyCyclicBehaviour(this));
                //doDelete();
        }
        protected void takeDown() {
                displayResponse("See you");
        }
        public void displayResponse(String message) {
                JOptionPane.showMessageDialog(null,message,"Message",JOptionPane.PLAIN_MESSAGE);
        }
        public void displayHtmlResponse(String html) {
                JTextPane tp = new JTextPane();
                JScrollPane js = new JScrollPane();
                js.getViewport().add(tp);
                JFrame jf = new JFrame();
                jf.getContentPane().add(js);
                jf.pack();
                jf.setSize(400,500);
                jf.setVisible(true);
                tp.setContentType("text/html");
                tp.setEditable(false);
                tp.setText(html);
        }
}

class MyCyclicBehaviour extends CyclicBehaviour {
        MyAgent myAgent;
        public MyCyclicBehaviour(MyAgent myAgent) {
                this.myAgent = myAgent;
        }
        public void action() {
                ACLMessage message = myAgent.receive();
                if (message == null) {
                        block();
                } else {
                        String ontology = message.getOntology();
                        String content = message.getContent();
                        int performative = message.getPerformative();
                        if (performative == ACLMessage.REQUEST)
                        {
                                //I cannot answer but I will search for someone who can
                                DFAgentDescription dfad = new DFAgentDescription();
                                ServiceDescription sd = new ServiceDescription();
                                sd.setName(ontology);
                                dfad.addServices(sd);
                                try
                                {
                                        DFAgentDescription[] result = DFService.search(myAgent, dfad);
                                        if (result.length == 0) myAgent.displayResponse("No service has been found ...");
                                        else
                                        {
                                                String foundAgent = result[0].getName().getLocalName();
                                                myAgent.displayResponse("Agent " + foundAgent + " is a service provider. Sending message to " + foundAgent);
                                                ACLMessage forward = new ACLMessage(ACLMessage.REQUEST);
                                                forward.addReceiver(new AID(foundAgent, AID.ISLOCALNAME));
                                                forward.setContent(content);
                                                forward.setOntology(ontology);
                                                myAgent.send(forward);
                                        }
                                }
                                catch (FIPAException ex)
                                {
                                        ex.printStackTrace();
                                        myAgent.displayResponse("Problem occured while searching for a service ...");
                                }
                        }
                        else
                        {       //when it is an answer
                                myAgent.displayHtmlResponse(content);
                        }
                }
        }
}

I noticed that the following lines in the ServiceAgent are the most important: sd2.setName("Easton's 1897 Bible Dictionary"); MessageTemplate template = MessageTemplate.MatchOntology("Easton's 1897 Bible Dictionary"); response = agent.makeRequest("easton", content);

Here's what I've already tried:

Modfied ServiceAgent class:

public class ServiceAgent extends Agent {
    private String dictionaryName;

    protected void setup() {

        // This should Get dictionary name from the arguments passed during agent creation
        Object[] args = getArguments();

        if (args != null && args.length > 0) {
            dictionaryName = (String) args[0];
            // rest of the original code here
        } else {
            System.out.println("No dictionary name provided. Agent will not provide any service.");
            doDelete();
        }
    }

    // rest of the original code here

    public String makeRequest(String word) {
        // rest of the original code here
        response = agent.makeRequest(dictionaryName, content);
        // rest of the original code here
    }
}

and the modified AnotherDictionaryCyclicBehaviour class:

class AnotherDictionaryCyclicBehaviour extends CyclicBehaviour {
    private String dictionaryName;
    ServiceAgent agent;

    public AnotherDictionaryCyclicBehaviour (ServiceAgent agent, String dictionaryName) {
        this.agent = agent;
        this.dictionaryName = dictionaryName;
    }

    public void action() {
        MessageTemplate template = MessageTemplate.MatchOntology(dictionaryName);
        // rest of the original code here
        response = agent.makeRequest(content);
        // rest of the original code here.
    }
}

By making these changes, the agent and its behavior should become more versatile. The dictionary name is no longer hard-coded, so users should be able to dynamically specify it during agent configuration. The problem is that after the changes, the agent stil did not recognize other dictionaries. I guess this problem is extremely simple, but I would still appreciate any help.

IFogSim: Link between the GUI and the code

Are there any links between the GUI and the code in IFogSim toolkit?

What I found is that code does not work with the typology made by GUI. Instead, the typology built in the code is the one used in the program. Is that right?

Call to REST WS Fails with javax.crypto.AEADBadTagException: Tag mismatch but succeeds in curl and Postman

I am calling a GET JSON REST web service from a J2EE 10 application running on Payara 6 that works fine with curl (from the same instance) and postman (from home PC) and also works fine and consistently inside the exact same application (via the same ami) from a different AWS VPC. But it fails every time on the production server implementation.

It works intermittently from my home computer - no idea why it works sometimes and not others. Postman from home computer works every time.

Here's the error:

jakarta.ws.rs.ProcessingException: javax.net.ssl.SSLException: Tag mismatch
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:270)
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:300)
    at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:675)
    at org.glassfish.jersey.client.JerseyInvocation.call(JerseyInvocation.java:697)
    at org.glassfish.jersey.client.JerseyInvocation.lambda$runInScope$3(JerseyInvocation.java:691)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:205)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:390)
    at org.glassfish.jersey.client.JerseyInvocation.runInScope(JerseyInvocation.java:691)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:674)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:422)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:318)
    at com.tm2builder.careeronestop.CosBuilder.getOccupationJsonResponse(CosBuilder.java:696)
    at com.tm2builder.careeronestop.CosUtils.processGetOccupationData(CosUtils.java:236)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
    at java.base/java.lang.reflect.Method.invoke(Method.java:580)
    at org.glassfish.expressly.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:186)
    at org.glassfish.expressly.parser.AstValue.invoke(AstValue.java:253)
    at org.glassfish.expressly.MethodExpressionImpl.invoke(MethodExpressionImpl.java:248)
    at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:70)
    at com.sun.faces.application.ActionListenerImpl.getNavigationOutcome(ActionListenerImpl.java:74)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:62)
    at jakarta.faces.component.UICommand.broadcast(UICommand.java:205)
    at jakarta.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:858)
    at jakarta.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1332)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:56)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:72)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:159)
    at jakarta.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:691)
    at jakarta.faces.webapp.FacesServlet.service(FacesServlet.java:449)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1554)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:331)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)
    at com.tm2builder.util.SetEncodingFilter.doFilter(SetEncodingFilter.java:92)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:257)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:166)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:757)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:577)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:158)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:372)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:239)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:174)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:153)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:196)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:88)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:246)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:178)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:118)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:96)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:51)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:510)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:82)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:83)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:101)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:535)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:515)
    at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: javax.net.ssl.SSLException: Tag mismatch
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:132)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:378)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:321)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:316)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:123)
    at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1506)
    at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1421)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:455)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:426)
    at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:586)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:187)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1675)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1599)
    at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:531)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:307)
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:423)
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:268)
    ... 64 more
Caused by: javax.crypto.AEADBadTagException: Tag mismatch
    at java.base/com.sun.crypto.provider.GaloisCounterMode$GCMDecrypt.doFinal(GaloisCounterMode.java:1652)
    at java.base/com.sun.crypto.provider.GaloisCounterMode.engineDoFinal(GaloisCounterMode.java:458)
    at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2543)
    at java.base/sun.security.ssl.SSLCipher$T13GcmReadCipherGenerator$GcmReadCipher.decrypt(SSLCipher.java:1908)
    at java.base/sun.security.ssl.SSLSocketInputRecord.decodeInputRecord(SSLSocketInputRecord.java:264)
    at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:181)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:111)
    ... 76 more

Here's the curl without the API Key:

 curl --location 'https://api.careeronestop.org/v1/occupation/KTlBjGthMe8nDlZ/11-1011.00/0?wages=true&projectedEmployment=true&videos=true' --header 'Content-Type: application/json' --header 'Authorization: Bearer *********'

curl - Works every time from all instances and home PC. postman - Works every time from home PC (windows). Java app - Works every time from an instance in an AWS VPC (Amazon Linux 2023)

  • Fails every time from an instance in a different AWS VPC, even when I use an ami created from the instance where it works every time. But curl works every time from this instance. (Amazon Linux 2023)
  • Works sometimes from the same app on my PC.

Since it works in curl every time from the same instance, I don't think it's a network issue.

When it works, the web service returns well-formed JSON.

I've tried everything I can think of, from every possible method of calling the GET using Jersey (above), httpclient, httpclient5, always with the same results.

I've tried JDK 21 (above), 22, and 17. No change. Have done a complete re-install of Payara, and using completely new instances of AL 2023, and the apps - no change.

I've inspected the java security policy and see no differences between the working and non-working instances.

The AWS Security Groups involved are completely open for HTTPS 443 Outbound traffic.

The Network ACLs involved allow all outbound and inbound traffic.

The Java code to make the call (using Jersey) is very simple:

Client client = ClientBuilder.newClient();
WebTarget target = client.target(uri);
JsonObject response = target.request(MediaType.APPLICATION_JSON).header( HttpHeaders.AUTHORIZATION, "Bearer " + COS_API_KEY ).get(JsonObject.class);

I've also tried Apache httpclient and httpclient5 with the exact same results.

Understanding the Technique of Converting Negative Decimal Numbers to Binary in JAVA

I'm currently trying to understand a specific step in a code snippet used for converting negative decimal numbers to their binary representation.

In the provided code, there's a line

n = (long) (Math.pow(2, 16) + n); //this line

Here's the entire code snippet :

public static long negativeDecimalToBinary(long n) {

    if (n < 0) {
        n = (long) (Math.pow(2, 16) + n);
    }

    long ans = 0;
    int i = 0;
    while (n != 0) {
        long lastBit = n & 1;
        System.out.print(lastBit);
        ans = (long) ((Math.pow(10, i) * lastBit) + ans);
        n = n >> 1;
        i++;
    }
    return ans;
}

I'm struggling to grasp why specifically 2^16 is added and how it aids in the binary conversion process. Could someone please provide a clear explanation of the underlying logic behind this step? I'm looking for an explanation that's accessible and easy to understand. Additionally, if there's an easier approach than, I'd love to learn about it. Thank you!

How do I see full contents of array in IntelliJ Debugger?

How do I see full contents of a Java array in IntelliJ Debugger? Here's what I get for a relatively large byte array. So far, I couldn't find a way to expand the trimmed value

package org.example._misc;


import java.nio.charset.StandardCharsets;
import java.util.concurrent.ThreadLocalRandom;

import org.junit.jupiter.api.Test;

public class GenericTest {
    @Test
    void test() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 1000; i++) {
            sb.append(getRandomCharacter());
        }
        String s = sb.toString();
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        System.out.println(); // dummy statement to stop the debugger and evaluate bytes
    }

    private char getRandomCharacter() {
        return (char)(ThreadLocalRandom.current().nextInt(26) + 'a');
    }
}
[106, 110, 113, 119, 97, 117, 107, 102, 104, 118, 121, 104, 118, 122, 109, 
112, 121, 119, 119, 107, 111, 97, 113, 119, 107, 106, 115, 114, 122, 118, 
101, 122, 118, 101, 106, 109, 113, 121, 97, 101, 97, 97, 110, 107, 106, 
107, 106, 98, 117, 103, 99, 98, 110, 110, 106, 113, 106, 110, 100, 100, 
120, 112, 115, 103, 105, 101, 115, 100, 100, 122, 102, 110, 118, 121, 116, 
97, 120, 106, 115, 119, 101, 120, 98, 111, 109, 97, 119, 121, 116, 116, 
109, 107, 97, 97, 98, 119, 106, 121, 100, 99, +900 more]

trimmed expression value in IntelliJ IDEA

This SO answer, while useful, requires defining a custom renderer for every array type which is troublesome

How to use gRPC with cloudflare+nginx+fabio?

I have a gRPC Java app and I configured Fabio to balance the load (I will be running 2+ instances of app) and CloudFlare for proxy.

What I have done so far:

Nginx reverse proxy setup

server {
    listen [::]:443 ssl http2 ipv6only=on;
        listen 443 ssl http2;

    server_name grpc.example.com;

    location /{
        grpc_pass grpc://127.0.0.1:9999;
    }
        ssl_certificate /etc/letsencrypt/live/grpc.example.com/fullchain.pem; 
        ssl_certificate_key /etc/letsencrypt/live/grpc.example.com/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

}

CloudFlare setup:
Grpc is enabled

Subdomain configuration for domain (IP is random in picture)
subdomain

Fabio setup
gRPC app runs in a Docker container

running app

When I connect to this server using gRPC client, I get nginx error "502 Bad Gateway".

I can see from access.log that request actually reaches with http/2.0 but I am confused and I don't know where to look for problem.

Also error.log shows this for requests:

2022/12/12 23:38:45 [error] 506072#506072: *1020 upstream sent too large http2 frame: 4740180 while reading response header from upstream, client: 61.142.22.151, server: grpc.example.com, request: "POST /Syncer/doUpdate HTTP/2.0", upstream: "grpc://127.0.0.1:9999", host: "grpc.example.com:443"

โŒ
โŒ