java – ¿Porqué solo lee primera línea de readobject?

tengo 3 clases, una llamada Mueble que implementa la serialización, otra Utilidades que tiene los métodos para visualizarMensaje, leerTeclado, etc.. y finalmente la appGestionMuebles la cual crea la aplicación que permite añadir muebles. Cuando pruebo a añadir muebles funciona perfectamente, es más si visualizo el archivo MUEBLES1.DAT puedo ver como si se ha añadido, pero al imprimir con readObject, solo me visualiza el primero que añadí, ¿cuál es el error que estoy cometiendo? Gracias.

private static void listarMuebles() {

try (ObjectInputStream fichMueble = new ObjectInputStream(new FileInputStream(new File("MUEBLES1.DAT")));){
    Mueble m ;
    Utilidades.visualizarMensaje(String.format("%10s", "ID MUEBLE") + String.format("%10s", "NOMBRE")
            + String.format("%10s", "TIPO") + String.format("%18s", "PRECIO UNITARIO")
            + String.format("%20s", "UNID. ALMACEN") + String.format("%10s", "TOTAL"));

    Utilidades.visualizarMensaje(String.format("%10s", "=========") + String.format("%10s", "======")
            + String.format("%10s", "====") + String.format("%18s", "===============")
            + String.format("%20s", "=============") + String.format("%10s", "====="));
    int i=0;
    while (i<5) {
        m = (Mueble) fichMueble.readObject();
        String tipoMueble = "";
        switch (m.getTipoMueble()) {
            case 'h':
            case 'H':
                tipoMueble = "HOGAR";
                break;
            case 'd':
            case 'D':
                tipoMueble = "DESPACHO";
                break;
            case 'c':
            case 'C':
                tipoMueble = "COLEGIOS";
                break;
            default:
                break;
        
        }

        Utilidades.visualizarMensaje(String.format("%10s", m.getIdMueble())
                + String.format("%10s", m.getDescripMueble()) + String.format("%10s", tipoMueble)
                + String.format("%18s", m.getPrecioUnario()) + String.format("%20s", m.getUnidadesMinimas())
                + String.format("%10s", m.getUnidadesAlmacen()));
        i++;
    }

} catch (IOException e) {
    System.out.println("Fin del fichero");

} catch (ClassNotFoundException ex) {
}

}

java – Como pasar la fecha que esta en una tabla seleccionando la columna y que se muestre en la caja de JDateChooser

Estoy haciendo un CRUD el cual tiene una fecha con JDateChooser y se muestra en una tabla de detalles, lo que quiero es dar clic en la columna de la fecha para que lo muestre en la caja de JDateChooser para modificar los datos ya que los demás si se muestran pero menos la fecha.

Este es mi código:

 private void JTlistaempleadoMouseClicked(java.awt.event.MouseEvent evt) {                                             
  int seleccion = JTlistaempleado.getSelectedRow();
   
    texid.setText(JTlistaempleado.getValueAt(seleccion,0).toString());
    texnombre.setText(JTlistaempleado.getValueAt(seleccion,1).toString());
    texdireccion.setText(JTlistaempleado.getValueAt(seleccion,2).toString());
    texsueldo.setText(JTlistaempleado.getValueAt(seleccion,3).toString());
    texpuesto.setText(JTlistaempleado.getValueAt(seleccion,4).toString());
    texnoempleado.setText(JTlistaempleado.getValueAt(seleccion,5).toString());
    JDfecha.setDate((Date) JTlistaempleado.getValueAt(seleccion,6));
    
    filas =seleccion;
  
    bloquear();
}               

Saludos.

How to create signature for the payload (data)using private key in java with bitcoinj?

I have private key as ‘cUN9LNcEC54HAbWAwUs6coPSc72TcQYzxf4qSqdHJPVKSapeHzFj’ and payload as ‘hello’, now how to create the signature for this payload using private key in java with bitcoinj library?

java – Capturar somente uma linha de uma planilha Excel com POI

Olá, pessoal!

Estou com um sistema que precisa validar o tipo do conteúdo das células de uma linha de uma planilha. Gostaria que fosse somente uma linha, pra evitar percorrer todas as linhas do arquivo, pra evitar processamento excessivo. Possuo esse código para percorrer o arquivo:

while (rowIterator.hasNext()) {
        Row row = (Row) rowIterator.next();

        // Descantando a primeira linha com o header
        if (row.getRowNum() == 0) {
            continue;
        }

        Iterator cellIterator = row.cellIterator();
        ItemExcel item = new ItemExcel();
        itens.add(item);

        while (cellIterator.hasNext()) {
            Cell cell = (Cell) cellIterator.next();

            switch (cell.getColumnIndex()) {
            case 0:
                item.setDado0((int) cell.getNumericCellValue());
                break;
            case 1:
                item.setDado1(formatter.formatCellValue(cell));
                break;
            case 2:
                item.setDado2(formatter.formatCellValue(cell));
                break;
            case 3:
                item.setDado3(formatter.formatCellValue(cell));
                break;
            case 4:
                item.setDado4(formatter.formatCellValue(cell));
                break;
            case 5:
                item.setDado5(cell.getNumericCellValue());
                break;
            }
        }
    }

Mas preciso somente de validar células de uma linha só. Como fosse fazer isso?

java – ScheduledExecutorService running a couple of scheduleAtFixedRate

I have created a task that I need to query database for List of String and store it in neededDataList. I will use neededDataList in a scheduled task every 10 minutes to do a simple task.
And I need to retrieve a fresh data of neededDataList every 1 hour.. Will the scheduledExecutorService2 can pick up the fresh neededDataList?
Can someone review my code if it will cause some problem?

//assuming my code has its main method and it will call the run(Database database)

    public class Handler {
            
            private static final ScheduledExecutorService scheduledExecutorService1 = MDScheduledExecutorService.wrap(
                        new ScheduledThreadPoolExecutor(1), "ses-1-thread-%d");
            private static final ScheduledExecutorService scheduledExecutorService2 = MDScheduledExecutorService.wrap(
                        new ScheduledThreadPoolExecutor(5), "ses-2-thread-%d");
        
            private List<String> neededDataList;
        
            private void run(Database database) {
                scheduledExecutorService1.scheduleAtFixedRate(() -> {
                    neededDataList= database.getNeededData();
                }, 1, 60, TimeUnit.MINUTES);
                
                scheduledExecutorService2.scheduleAtFixedRate(new HandlerImpl(), 1, 10, TimeUnit.MINUTES);
            }
    
            private class HandlerImpl implements Runnable {
            
            @Override
            public void run() {
               executeTask(neededDataList);
            }
        
        
            }
}

Buscar string dentro de lista Java

Tenho um array com informações de vários filmes, e preciso buscar o nome dos filmes independente de ele estar UpperCase ou LowerCase, e preciso que por exemplo, ao buscar o nome “para” ele me retorne todos os filmes que tenham “para” no nome, independente de estar no inicio ou no final. Eu encontrei duas formas:

if (filmes.getNomeFilme().contains(name)) {

Dessa forma ele me retorna os filmes mas não ignora o case sensitive

Essa outra forma aqui:

if (filmes.getNomeFilme().equalsIgnoreCase(name)) {

Dessa forma ele ignora o case sensitive mas o usuário tem que passar o nome completo do filme para ele encontrar.

Agradeço desde já a ajuda.

java – Is there anything that should be removed that is “uselesss” in this code?

So this is a blackjack game, any feedback or tips on what I should remove from the code that is not needed is very appreciated.

Note: some of the names of classes or variables are in Swedish but it should not interfere with understanding the code I think.

Blackjack.java

import java.util.Scanner;

class Card {
    private final Face face;

    private final Suit suit;

    public Card(Face face, Suit suit) {
        this.face = face;
        this.suit = suit;
    }

    public Face getFace() {
        return face;
    }
    public Suit getSuit() {
        return suit;
    }

    @Override
    public String toString() {
        return face + " of " + suit;
    }
}

enum Face {
    Ace(11), Deuce(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), Ten(10), Jack(10), Queen(10), King(10);

    private final int value;

    private Face(int value) {
        this.value = value;
    }
    
    public int getValue() {
        return value;
    }
}

enum Suit {
    hearts, spades, diamonds, clubs;
}

public class BlackJack {
    public static void main(String() args) {

        int wins = 0;
        int losses = 0;

        Scanner scanner = new Scanner(System.in);
        String input;
        
        //Clear Terminal from file paths
        System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");
        
        //Start loop
        do {

            //Clear Terminal from last game
            System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");System.out.println(" ");

            //Create players, shuffle deck and turn gameOver off
            Player player = new Player("You");
            Player dealer = new Player("Dealer");
            Deck deck = new Deck();
            deck.shuffle();
            boolean gameOver = false;

            //Get cards for player
            player.addCard(deck.draw());
            player.addCard(deck.draw());
            System.out.print(player.getHandAsString(false));
            System.out.println("Total: " + player.getHandSum());
            System.out.println("");System.out.println("");

            //Get cards for dealer
            dealer.addCard(deck.draw());
            dealer.addCard(deck.draw());

            

            //Player turn
            do {
                if (player.getHandSum() == 21) {
                    System.out.println("Super lucky Blackjack! You win.");
                    wins = wins + 1;
                    gameOver = true;
                    break;
                }
                if (player.getHandSum() > 21) {
                    System.out.println("Super unlucky! You lost.");
                    losses = losses + 1;
                    gameOver = true;
                    break;
                }

                System.out.println("");System.out.println("");
                System.out.println("Draw or stay?");
                do {
                    input = scanner.nextLine();
                } while (!input.equalsIgnoreCase("Draw") && !input.equalsIgnoreCase("Stay"));

                //Draw
                if (input.equalsIgnoreCase("Draw")) {
                    player.addCard(deck.draw());
                    System.out.println("");
                    System.out.print(player.getHandAsString(false));
                    System.out.println("Total: " + player.getHandSum());
                    System.out.println("");System.out.println("");
                    if (player.getHandSum() == 21) {
                        System.out.println("Blackjack! You win.");
                        wins = wins + 1;
                        gameOver = true;
                    }
                    if (player.getHandSum() > 21) {
                        System.out.println("You busted with " + player.getHandSum() + " in your hand. Dealer wins!");
                        losses = losses + 1;
                        gameOver = true;
                    }
                }
                //Stay
                if (input.equalsIgnoreCase("stay")) {
                    System.out.println("You have chosen to stay. Your hand: " + player.getHandSum());
                }
            } while (input.equalsIgnoreCase("Draw") && !gameOver);

            //Dealer turn
            if (!gameOver) {
                System.out.println("");System.out.println("");System.out.println("");System.out.println("");System.out.println("");
                System.out.println("________________________________________________________________________");
                System.out.println("Dealers turn");
                System.out.println("________________________________________________________________________");
                
                System.out.println("");
                System.out.print(dealer.getHandAsString(false));
                
                System.out.println(dealer.getHandSum());
                System.out.println("");System.out.println(""); 

                if (dealer.getHandSum() == 21) {
                    System.out.println("Blackjack! Dealer won.");
                    losses = losses + 1;
                    gameOver = true;
                }
            }
            while (!gameOver) {
                if (dealer.getHandSum() <= 17) {
                    //Draw card
                    dealer.addCard(deck.draw());
                    System.out.println(dealer.getVem() + " drew another card");
                    System.out.println("");
                    System.out.print(dealer.getHandAsString(false));
                    System.out.println(dealer.getHandSum());
                    System.out.println("");System.out.println(""); 
                    
                    if (dealer.getHandSum() == 17) {
                        if (player.getHandSum() == 17) {
                            System.out.println("Dealer won.");
                            losses = losses + 1;
                            gameOver = true;
                        }
                    }

                    if (dealer.getHandSum() == 18) {
                        if (player.getHandSum() == 18) {
                            System.out.println("Dealer won.");
                            losses = losses + 1;
                            gameOver = true;
                        }
                    }

                    if (dealer.getHandSum() == 19) {
                        if (player.getHandSum() == 19) {
                            System.out.println("Dealer won.");
                            losses = losses + 1;
                            gameOver = true;
                        }
                    }
                    
                    if (dealer.getHandSum() == 20) {
                        if (player.getHandSum() == 20) {
                            System.out.println("It's a draw!");
                            gameOver = true;
                        }
                    }

                    if (dealer.getHandSum() == 21) {
                        System.out.println("Blackjack! Dealer won.");
                        losses = losses + 1;
                        gameOver = true;
                    }
                    if (dealer.getHandSum() > 21) {
                        System.out.println("Dealer busted with " + dealer.getHandSum() + " in their hand. You win!");
                        wins = wins + 1;
                        gameOver = true;
                    }

                } else {
                    //Stay
                    System.out.println("Dealer chose to stay!");
                    System.out.println("");
                    int totalDealerSum = dealer.getHandSum();
                    int totalPlayerSum = player.getHandSum();

                    if (totalDealerSum > totalPlayerSum) {
                        System.out.println("Both players decided to stay. The Dealer won with a total of " + totalDealerSum + " in their hand.");
                        losses = losses + 1;
                    } else {
                        System.out.println("Both players decided to stay. You win with a total of " + totalPlayerSum + " in your hand.");
                        wins = wins + 1;
                    }
                    gameOver = true;
                }
            }

            //New game? And Score
            System.out.println("");System.out.println("");System.out.println("");
            
            if(wins==1 && losses==0){
                System.out.println("You have won " + wins + " time and lost " + losses + " times.");
            }
            if(wins==0 && losses==1){
                System.out.println("You have won " + wins + " times and lost " + losses + " time.");
            }
            
            if(wins>1 && losses>1){
                System.out.println("You have won " + wins + " times and lost " + losses + " times.");
            }
            if(wins==0 && losses>1){
                System.out.println("You have won " + wins + " times and lost " + losses + " times.");
            }
            if(wins>1 && losses==0){
                System.out.println("You have won " + wins + " times and lost " + losses + " times.");
            }

            if(wins>1 && losses==1){
                System.out.println("You have won " + wins + " times and lost " + losses + " time.");
            }
            if(wins==1 && losses==1){
                System.out.println("You have won " + wins + " time and lost " + losses + " time.");
            }
            if(wins==1 && losses>1){
                System.out.println("You have won " + wins + " time and lost " + losses + " times.");
            }

            System.out.println("");
            System.out.println("Play again?");
            do {
                input = scanner.nextLine();
            } while (!input.equalsIgnoreCase("Yes") && !input.equalsIgnoreCase("No"));
            

        } while (input.equalsIgnoreCase("Yes"));
        
        scanner.close();
    }
}

Deck.java

import java.util.ArrayList;
import java.util.Collections;

public class Deck {

    private final ArrayList<Card> cards;

    public Deck() {
        cards = new ArrayList<Card>();
        // populate deck with cards
        for (Suit suit : Suit.values()) {
            for (Face face : Face.values()) {
                cards.add(new Card(face, suit));
            }
        }
    }

    public void shuffle() {
        Collections.shuffle(cards);
    }

    public Card draw() {
        return cards.remove(0);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < cards.size(); i++) {
            sb.append(i + 1);
            sb.append('/');
            sb.append(cards.size());
            sb.append(' ');
            sb.append(cards.get(i));
            sb.append('n');
        }
        return sb.toString();
    }
}

Player.java

import java.util.ArrayList;

//Player class
public class Player {

    private final String vem;

    private final ArrayList<Card> hand;

    public Player(String vem) {
        this.vem = vem;
        this.hand = new ArrayList<Card>();
    }

    public String getVem() {
        return vem;
    }

    public void addCard(Card card) {
        hand.add(card);
    }

    public int getHandSum() {
        int handSum = 0;
        for (Card card : hand) {
            handSum += card.getFace().getValue();
        }
        return handSum;
    }

    public String getHandAsString(boolean b) {
        StringBuilder sb = new StringBuilder();
        sb.append(vem); //'s'
        sb.append('n');
        for (int i = 0; i < hand.size(); i++) {
            if (i == 0 && b) {
                sb.append('n');
            } else {
                sb.append(hand.get(i));
                sb.append('n');
            }
        }
        return sb.toString();
    }
}

Thank you for any help, tips or feedback!

java – Explain the weakness in the design of the Server

So firstly this is not exactly homework … but it is a question on a past exam paper and I am studying for the exam and can not figure this one out. (Ignore any imports which are not here)

Also I know that Double is a very bad name for the class not only is it a built-in type but not very descriptive but i do not think this would gain any marks.

Also the port is hard coded as this is how we have learned so this would not be the problem as we have not been taught yet any other way.

I think this is solely based on code.

The questions states

The code of a simple server is shown below. It offers the trivial service of accepting an integer
value from a client and returning twice the value received.
Explain the weakness in the design
of the server and re-write it in light of your critique 

After reviewing the code myself I can not see any problems in the initial Server Class from what I understand so far everything is in order.

class DoubleServer{
   private static int port = 1234;       #2
   public static void main(String args()){
     try{
        ServerSocket serversock = new ServerSocket(port);    #5
        while(true){                                         #6
          Socket socket = serversock.accept();               #7
          new Thread(new Double(socket)).start();            #8
        }
    }catch(IOException e){}
  }
} 

We have

  • The Port is created (I initially thought that the port should not be private but this is ok) #2
  • The ServerSocket is created and passes the port #5
  • A continues loop starts to keep the server waiting for requests #6
  • The Socket is waiting to receive a request #7
  • Once a requests is submitted it calls the server Thread #8

I can see no problem here

Then we have the server thread

class Double implements Runnable{
    Socket socket;
    public Double(Socket s){socket = s;}
    public void run(){
      try{
         DataInputStream in = new DataInputStream(socket.getInputStream());  
         DataOutputStream out = new DataOutputStream(socket.getOutputStream()); 

         int x = in.readInt();
         out.write(2*x);
         socket.close();
       }
       catch(IOException e){}
    }
}

This is where the problem

  • We crated the socket which is passed and the Data in/out streams
  • The we read the int from the client
  • The out method is where I think the problem is as the calculation of squaring the number is done here
    which I do not think you can do or is bad practice. Also I would flush() after the write to ensure
    any buffered bytes are written.
  • The Socket is closed and I would also close the Data in/out streams

If this is not correct and I have missed something I would appreciate help or a push in the right direction

Still learning, looking for general advice about a 4-function calculator I programmed using java

here’s some code I wrote in java SE to get use to if statements and scanning. just looking for suggestions that will improve this program or/and teach me techniques that I should get use to using.

import java.util.Scanner;

public class Calculator {
   public static void main(String() args) {
      System.out.print("Enter the first value ");
      Scanner scan = new Scanner(System.in);
      int x = scan.nextInt();
      System.out.print("Enter the next value ");
      int y = scan.nextInt();
      System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");
      int z = scan.nextInt();
      if (z == 1) {
         int a = x * y;
         System.out.println("Result: " + a);
      }//end of if multiply
      else if (z == 2) {
         int a = x / y;
         System.out.println("Result: " + a);
      }//end of if divide
      else if (z == 3) {
         int a = x + y;
         System.out.println("Result: " + a);
      }// end of if add
      else {
         int a = x-y;
         System.out.println("Result: " + a);
      } //end of is subtract
   }// End of main
}// End of public class
```

java – Value cannot injected into service class spring boot

I already try to search through stackoverflow, and I don’t think I find the solution I want…

Also I try to use answer https://stackoverflow.com/questions/45970442/spring-boot-value-returning-null and still doesn’t work…

Here is my controller class

package com.vincent.springoauth.controller;
import com.vincent.springoauth.model.GiftCardRequest;
import com.vincent.springoauth.model.GiftCardResponse;
import com.vincent.springoauth.service.InCommGiftCardServiceImpl;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/gift-card")
public class GiftCardController{


    @PostMapping("/activate")
    public @ResponseBody
    GiftCardResponse activate(GiftCardRequest request) {
        GiftCardServiceImpl giftCardService = new GiftCardServiceImpl("");
        return giftCardService.activate(request);
    }
}

And here is my service class

package com.vincent.springoauth.service;

import com.vincent.springoauth.model.GiftCardRequest;
import com.vincent.springoauth.model.GiftCardResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Log4j2
public class GiftCardServiceImpl {


    private final String baseEndpoint;

    public GiftCardServiceImpl( @Value("${webserviceurl}")String baseEndpoint){
        this.baseEndpoint = baseEndpoint;
    }



    public String accessToken() {
        log.info("Access oauth token url address: " + baseEndpoint);

        // will be use that base endpoint to manipulate stuff later
        return "abcdefg";

    }

    public GiftCardResponse activate(GiftCardRequest request) {

        log.info("Calling token ...");
        accessToken();
        log.info("Incomm Pre Auth Service");

        // Generate preAuth request;
        //RetailTransactionGenericRequestWrapper retailTransactionGenericRequest = buildRequest(request);
        //log.info("RetailTransactionGenericRequest: " + retailTransactionGenericRequest);
        GiftCardResponse response = GiftCardResponse.builder().responseCode("0").responseMessage("Success").build();
        return response;
    }
}

And in my application.properties I have following line webserviceurl=https://localhost/giftcard

The issue that in my service class the webserviceurl return null. How can I fix this?