java – How to extract a record from the database using a spring batch based on an identifier

package com.csvpostgresspringbatch.config;

import com.csvpostgresspringbatch.dao.BankDAO;
import com.csvpostgresspringbatch.model.Bank;
import com.csvpostgresspringbatch.step.Listener;
import com.csvpostgresspringbatch.step.Processor;
import com.csvpostgresspringbatch.step.Reader;
import com.csvpostgresspringbatch.step.Writer;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableBatchProcessing
public class BatchConfig {

	@Autowired
	public JobBuilderFactory jobBuilderFactory;

	@Autowired
	public StepBuilderFactory stepBuilderFactory;

	@Autowired
	public BankDAO bankDao;




	@Bean
	public Job job() {
		return jobBuilderFactory.get("job").incrementer(new RunIdIncrementer()).listener(new Listener(bankDao))
				.flow(step1()).end().build();
	}

	@Bean
	public Step step1() {
		return stepBuilderFactory.get("step1").chunk(1)
				.reader(Reader.reader("bank-data.csv"))
				.processor(new Processor())
				.writer(new Writer(bankDao))
				.build();

	}



}

Send a Javascript object to java backend

Hi, I'm trying to send an object in JS to a backend in java, but I'm not able to … Follow the query code on the JS side.

function setCalendario(c){
$.ajax({
    type: "post",
    url: "setCalendario",
    dataType: "json",
    data: JSON.stringify(c),
    success: () => {
        alert('Requisição completa');

    },
    error: () => {
        alert('Requisição incompleta');
    }
})

}

Inheritance in Java – The call of a builder ignores its content and moves on to another?

I do not understand why in the constructor of C after finishing calling the constructor of A with a parameter, this instead of displaying on the screen "I am the constructor C" will directly instantiate a object of B and will access its constructor instead of saying "I am the constructor C" before "I am the builder B". I do not understand why … anyone who can make me understand, do you like it?

class A {
    public A ( ) {  System.out.println(" Soy el constructor A");    }
    public A (int a) { 
        System.out.println(" Soy el constructor A " + a);
    }
}

class B {
    public B ( ) {  System.out.println(" Soy el constructor B");    }
    /*public B (int b) { 
        System.out.println(" Soy el constructor B " + b);
    }*/
}

class C extends A {
    public C ( ) {
        super(1);
        System.out.println(" Soy el constructor C");
    }
    B ob= new B();
}

public class ex6b_2 {
    public static void main ( String args() ) {
        C oc= new C();
    }
}

java – How to avoid validation on the update of an object?

I have a form to register and update a "user". I could validate the form by registering correctly, the problem is that when I try to update this same object, the password is validated again and, since it is null, it gives an error to the message and the Prevents updating the user. I use spring and Thymeleaf

my controller:

@PostMapping("/{customerId}/createUser/{id}")
public String updateUser(@PathVariable(value = "customerId", required = false) Long customerId,
        @PathVariable(value = "id", required = true) Long id, @ModelAttribute(name = "user") @Valid Users user,
        BindingResult bindingResult, Model model) {

    if (bindingResult.hasErrors()) {
        model.addAttribute("user", user);

        Optional customerOptional = customerRepository.findById(customerId);
        Customers customer = customerOptional.get();
        model.addAttribute("customer", customer);
        return "customerNewUser";
    }

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        throw new RuntimeException();
    }

    if (user.getEmail().contains("@") && user.getFirstname().length() > 0) {
        Users existingUser = userRepository.findById(id).get();
        existingUser.setId(existingUser.getId());
        existingUser.setFirstname(user.getFirstname());
        existingUser.setSurname(user.getSurname());
        existingUser.setPassword(existingUser.getPassword());
        existingUser.setEmail(user.getEmail());
        if (user.getUserStatus().equals(UserStatus.ATIVO)) {
            existingUser.setEnabled(true);
        } else {
            existingUser.setEnabled(false);
        }
        existingUser.setEventDescription("Customer admin data update");
        userService.save(existingUser);
    } else {
        throw new RuntimeException();
    }

    return "redirect:/customers/?id=" + customerId;
}
}

My html form:

My model:

@Entity
public class Users extends BaseEntity {

private static final long serialVersionUID = -1667698094711992210L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = 
"users_seq")
@SequenceGenerator(name = "users_seq", sequenceName = "users_seq", 
allocationSize = 50, initialValue = 1)
@JsonProperty(access = Access.READ_ONLY)
private Long id;
@NotBlank(message = "E-mail não pode estar em branco.")
@NotNull(message = "E-mail deve ser informado.")
@Email(message = "Formato inválido de E-mail.")
@Column(nullable = false, unique = true)
private String email;
@JsonProperty(access = Access.WRITE_ONLY)
@Size(min=6, message="A senha deve conter pelo menos 6 caracteres.")
@NotNull(message = "A senha deve ser informada.")
@NotBlank(message = "A senha não pode estar em branco.")
@NotEmpty(message = "A senha não pode estar vazia.")
@Column(nullable = false)
private String password;
@JsonIgnore
@Transient
private String matchPassword;
@JsonIgnore
@Column(nullable = false)
private Boolean enabled = true;
@NotNull(message = "O nome deve ser informada.")
@NotBlank(message = "O nome não pode estar em branco.")
@NotEmpty(message = "O nome não pode estar vazia.")
@Column(nullable = false)
private String firstname;
private String surname;
@Column(nullable = true)
private Long customerId;
@JsonIgnore
@Transient
private Boolean isAdmin;
@JsonIgnore
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private List authorities = new ArrayList<>();
@Enumerated(EnumType.STRING)
@Transient
private UserStatus userStatus;
}

I would like to avoid validating the password during the update, my password field is omitted when it is a question of updating, but the form ignores and validates all that I Assumed.

java – Is there some kind of smaller IDE with Android programming?

I have 8GB of RAM, i5 processor in a laptop that dual booted with Ubuntu 19.04 and Windows 10 Pro. Android is one of my subjects. I need to pass the exam. I use Linux Distro 90% of the time, which in my case is Ubuntu since it is 10 times faster than Windows. I am a Java programmer (beginner for 5 months now). For that, I use IntelliJ Ultimate for my training in Java, Grails, Groovy, etc. I want to learn basic Android programming as fast as possible because the exam is close.

Recently I have tried using IntelliJ Ultimate for Android programming. I felt behind and slow. Hugh SDK for each APT level. So, my main concern is that Is there a kind of very lightweight IDE that can be used for Android programming without delay or slowness? A technique, no matter what.

Note: My class contains only Java programming for Android. No other language

java – Using Spritesheet – Game Development Stack Exchange

I'm working on an RPG game and I store most of my textures in separate .png files, but for my sprites, I'd like to use a sprite sheet. How do you cut and store the sheet in individual images inside the program?

I use Java and the processing window.

java – I have finished a beginner challenge, but I have the impression that my code is unnecessarily complicated.

I am just starting to learn programming. I had already coded functions and elements in other languages ​​and, while trying to meet this challenge Python

View post on imgur.com

I went to Java.

Initially, I wanted to start learning Python, but the company I just started learning uses Java almost exclusively. So I thought I might as well learn that language.

I've tried to complete it using mostly essays and errors and some google, I have not watched a lot of guides so far, so I've figured out what I needed coding in what way it took me a lot of hours. Now, my code does what it's supposed to do, but I get the impression that it's written unnecessarily complicated and could be much shorter.

Having not yet really understood the scope and accessibility of the methods, I have not been able to reuse any code because I would have liked and much needed to rewrite it.

public static void main(String() args)
{
    System.out.println("Please enter a word");
    Scanner consoleInput = new Scanner(System.in);
    String userInput = consoleInput.nextLine(); 



    System.out.println(GetVowels(userInput).size() + " words starting with wovels: " + GetVowels(userInput));
    System.out.println(GetConsonants(userInput).size() + " words starting with consonants: " + GetConsonants(userInput));
}

 static ArrayList GetVowels(String userInput){ 
    char() vowels = "aeiou".toCharArray(); 
    ArrayList possibleWords = new ArrayList(); 

    for(int i = 0; i < vowels.length; i++){ 
        int offset = 0; 
        while(userInput.indexOf(vowels(i), offset) >= 0){ 
            int wordStartingIndex = userInput.indexOf(vowels(i), offset); 
            for (int u = wordStartingIndex; u <= userInput.length(); u++)  
            {
                String maybeAWord = userInput.substring(wordStartingIndex, u); 
                if(maybeAWord.length() > 0 && possibleWords.indexOf(maybeAWord) < 0) 
                {
                    possibleWords.add(maybeAWord); 
                }
            }
            offset = userInput.indexOf(vowels(i), offset) +1; 
        }
    }
  return possibleWords;

}


static ArrayList GetConsonants(String userInput){
    char() vowels = "aeiou".toCharArray();
    ArrayList possibleWords = new ArrayList();
    ArrayList vowelIndexes = new ArrayList();
    ArrayList consonantIndexes = new ArrayList();


    for(int i = 0; i < vowels.length; i++) { 
        int offset = 0;
        while (userInput.indexOf(vowels(i), offset) >= 0)
        {
            vowelIndexes.add(userInput.indexOf(vowels(i), offset));
            offset = userInput.indexOf(vowels(i), offset) + 1;
        }

    }

    for(int i = 0; i < userInput.length(); i++)
    {
        if(vowelIndexes.indexOf(i) < 0)
        {
            int wordStartingIndex = i;
            int offset = wordStartingIndex;

            while(offset <= userInput.length())
            {
                String maybeAWord = userInput.substring(wordStartingIndex, offset);
                if(maybeAWord.length() > 0 && possibleWords.indexOf(maybeAWord) < 0)
                {
                   possibleWords.add(maybeAWord);
                }
                offset = offset + 1;
            }

        }

    }
    return possibleWords;
}

I do not expect anyone to rewrite part of my code in a more compact or efficient way, but I would be very grateful if you could give advice or tips on what I could write differently, how I could reuse some of these codes. I had to write several times, or just things that I should avoid in the future.

Thanks in advance!

java – recording call in the background with the help of a service (No Show Audio)

I have an application that runs in the background. As soon as the user opens the application, a service is started to record the calls and send them to a certain folder.

Today, the service identifies the call and records, but the audio sometimes misses in the show. I've noticed that if I open the app and make a call, it will register properly, but if I close the application or if it stays open for more than 5 minutes, the l & # 39; registration will be without broadcast.

Follow my code:

package com.example.call;

public class BroadcastSistemas extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            String estado = intent.getStringExtra("state");
            String num = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            String msg = null;

            if (estado.equals("RINGING")) {
                msg = "O número " + num + " está chamando.";
            } else if (estado.equals("OFFHOOK")) {
                msg = "Em ligação.";
            } else if (estado.equals("IDLE")) {
                msg = "O número " + num + " desligou.";
            }

            Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

public class ServicoChamada extends Service {
    MediaRecorder recorder;
    File audiofile;
    String name, phonenumber;
    String audio_format;
    public String Audio_Type;
    int audioSource;
    Context context;
    private Handler handler;
    Timer timer;
    Boolean offHook = false, ringing = false;
    Toast toast;
    Boolean isOffHook = false;
    private boolean recordstarted = false;

    private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
    private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
    private CallBr br_call;

    public List threads = new ArrayList();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Worker w = new Worker(startId);
        w.start();
        threads.add(w);

        final IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_OUT);
        filter.addAction(ACTION_IN);
        this.br_call = new CallBr();
        this.registerReceiver(this.br_call, filter);

        return (super.onStartCommand(intent, flags, startId));
    }

    class Worker extends Thread {
        public int count = 0;
        public int startId;
        public boolean ativo = true;

        public Worker(int startId) {
            this.startId = startId;

        }

        public void run() {
        }
    }

    public class CallBr extends BroadcastReceiver {
        Bundle bundle;
        String state;
        String inCall, outCall;
        public boolean wasRinging = false;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_IN)) {
                if ((bundle = intent.getExtras()) != null) {
                    state = bundle.getString(TelephonyManager.EXTRA_STATE);
                    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                        inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                        wasRinging = true;
                        Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
                    } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                        Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();

                        String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
                        File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
                        if (!sampleDir.exists()) {
                            sampleDir.mkdirs();
                        }
                        String file_name = "Record";
                        try {
                            audiofile = File.createTempFile(file_name, ".amr", sampleDir);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

                        recorder = new MediaRecorder();

                        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
                        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
                        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                        recorder.setOutputFile(audiofile.getAbsolutePath());
                        try {
                            recorder.prepare();
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        recorder.start();
                        recordstarted = true;
                    } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                        wasRinging = false;
                        Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                        if (recordstarted) {
                            recorder.stop();
                            recordstarted = false;
                        }
                    }
                }
            } else if (intent.getAction().equals(ACTION_OUT)) {
                if ((bundle = intent.getExtras()) != null) {
                    outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                    Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
                }
            }
        }
    }

}

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(MainActivity.this, ServicoChamada.class);    
        startService(intent);
    }
}



    

    
    
    
    
    
    
    
    

    
        
            
                

                
            
        

        
            
                
            
        

        
            
                
            
        
    


Sum of complex numbers in Java?

package exercicio3;

public class Complexo {

private int numeroReal1;
private int numeroImaginario1;
private int numeroReal2;
private int numeroImaginario2;

public Complexo(int numeroReal1, int numeroImaginario1, int numeroReal2, int numeroImaginario2) {
    this.numeroReal1 = numeroReal1;
    this.numeroImaginario1 = numeroImaginario1;
    this.numeroReal2 = numeroReal2;
    this.numeroImaginario2 = numeroImaginario2;
}

public int getNumeroReal1() {
    return numeroReal1;
}

public void setNumeroReal1(int numeroReal1) {
    this.numeroReal1 = numeroReal1;
}

public int getNumeroReal2() {
    return numeroReal2;
}

public void setNumeroReal2(int numeroReal2) {
    this.numeroReal2 = numeroReal2;
}

public int getNumeroImaginario1() {
    return numeroImaginario1;
}

public void setNumeroImaginario1(int numeroImaginario1) {
    this.numeroImaginario1 = numeroImaginario1;
}

public int getNumeroImaginario2() {
    return numeroImaginario2;
}

public void setNumeroImaginario2(int numeroImaginario2) {
    this.numeroImaginario2 = numeroImaginario2;
}

public int somarComplexos()
{
    return (numeroReal1 + numeroImaginario1) + (numeroReal2 + numeroImaginario2);
}

}

package exercicio3;

public class Principal {

public static void main(String() args) {
    Complexo somaComplexo1 = new Complexo(4, 6, 5, 3);
    System.out.println("Numero Real1: " + somaComplexo1.getNumeroReal1() + " Numero imaginario1: " + somaComplexo1.getNumeroImaginario1() + "i");
    System.out.println("Numero Rea2: " + somaComplexo1.getNumeroReal2() + " Numero imaginario1: " + somaComplexo1.getNumeroImaginario2() + "i");
    System.out.println("Soma Complexos: " + somaComplexo1.somarComplexos());

    }

}

java – How to save multiple images with a one-to-many relationship in a SQLite database

I develop a simple form in which the user can attach multiple images and save locally with the help of SQLite. I am able to save other data and have already saved it when attaching a single image. However, you must create the one-to-many patient relationship for photo and save all photos from the form. Since I am now learning how to use SQLite and I do not have much experience with Android, I can not save multiple images of a single form and create the relationship one to several of the SQLite schema.

INSERT DATA CODE IN BANK

public class PacienteDAO {

private Conexao conexao;
private SQLiteDatabase banco;
private byte() imageInBytes;

public PacienteDAO(Context context) {
    conexao = new Conexao(context);
    banco = conexao.getWritableDatabase();
}


public long inserirPaciente(Paciente paciente){

   /*Bitmap() imageToStoreBitmap = paciente.getFotos();
    ByteArrayOutputStream objectByteArrayOutputStream = new ByteArrayOutputStream();
    imageToStoreBitmap.compress(Bitmap.CompressFormat.PNG, 100, objectByteArrayOutputStream);
    imageInBytes = objectByteArrayOutputStream.toByteArray();*/

    ContentValues values = new ContentValues();
    values.put("nome", paciente.getNome());
    values.put("cpf", paciente.getCpf());
    values.put("data", paciente.getData());
    values.put("foto",imageInBytes);
    return banco.insert("paciente", null, values);

}
}

Creating the table

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("create table paciente(id integer primary key autoincrement, nome varchar(50), cpf varchar(11), data varchar(15), fotos BLOB )");
    //db.execSQL("create table foto(id integer primary key autoincrement, enviado int(2), fotoBitmap BLOB,  FOREIGN KEY(pacienteId) REFERENCES paciente(id))");
    Log.d("TAG", "Banco criado com sucesso");

}

In this part, I add all the images, whether from the mobile gallery or taken by the camera in a list of tables: final List bitmaps = new ArrayList<>();

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    final ImageView imageView = findViewById(R.id.imageDisplay);
    if(requestCode == 0 && resultCode == RESULT_OK && data != null) {
        Bitmap bt = (Bitmap) data.getExtras().get("data");
        bitmaps.add(bt);

    }else {
        ClipData clipData = data.getClipData();
        if (clipData != null) {
            for (int i = 0; i < clipData.getItemCount(); i++) {
                Uri uri = clipData.getItemAt(i).getUri();

                try {
                    InputStream inputStream = getContentResolver().openInputStream(uri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    bitmaps.add(bitmap);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }else {
            Uri uri = data.getData();
            try {
                InputStream inputStream = getContentResolver().openInputStream(uri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                bitmaps.add(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

    }
  }

The patient model:

public class Paciente implements Serializable {

@NonNull
@Expose
private String nome;
@NonNull
@Expose
private String cpf;
@NonNull
@Expose
public  List fotos;
@Expose
@NonNull
private String data;

...GETTER E SETTER.

Patient is the Photo class that contains the list of captured images.

public class Foto implements Serializable {
@Expose
private List fotoBitmap;
@Expose
private boolean enviado;
...GETTER E SETTER.