java – Obtener todos los errores de un codigo escrito en un edit text

Actualmente trabajo en una aplicación que sirve para crear códigos de programación en Java, con acortadores, tipos de como usar el código, etc.). Estoy buscando un código que me ayude a buscar errores en el código escrito por el usuario. Soy un principiante, solo llevo 2 años de experiencia en Java.

PD: realize esta pregunta en el Stack Overflow en inglés, pero nunca tuve respuesta, así que por eso pregunto aquí. Les muestro el código que llevo de progreso:

En un tutorial, vi que alguien empezaba un service con este código, no se si sea necesario para el sistema:

Intent intent = new Intent(ClassNameActivity.this, thisistheservice.class);
startService(intent);

En otro post que está en inglés, me dijeron que usará los javax.tools, les dejo el post:
https://stackoverflow.com/questions/11298856/syntax-checking-in-java

Y así es como lo he escrito para adaptarlo a mi proyecto

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;

public class JavaSyntaxChecker {

private AlertDialog.Builder dialog;
private SharedPreferences path;

private String checkFile = "";

path = getSharedPreferences("path", Context.MODE_PRIVATE);

public static void main(String() args) {
checkFile = path.getString("path", "");
System.out.println(JavaSyntaxChecker.check(checkFile));
}
public static List<String> check(String file) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(file)); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call(); List<String> messages = new ArrayList<String>();
Formatter formatter = new Formatter();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
messages.add(diagnostic.getKind() + ":t Line (" + diagnostic.getLineNumber() + ") t Position (" + diagnostic.getPosition() + ")t" + diagnostic.getMessage(Locale.ROOT) + "n");
}
dialog.setTitle("Errores en el código");
dialog.setAdapter(new ArrayAdapter(JavaSyntaxCheckerActivity.this, android.R.layout.simple_list_item_1, messages), new DialogInterface.OnClickListener(){
@Override public void onClick(DialogInterface _di, int _pos){
textview1.setText(messages.get(_pos));
Intent intent = new Intent(JavaConstructorActivity.this, JavaSyntaxChecker.class);
stopService(intent);
}
}
);
dialog.create().show();
return messages;
}
}

Los errores que me muestra son estos:

The import javax.tools cannot be resolved

Cualquier ayuda será agradecida.

spring – How does class gets injected which implements interface method being called in Java or Groovy code?

I have below working groovy code from Spring framework project:

import org.springframework.oxm.Unmarshaller

public class ItemSearchService  {
    Unmarshaller unmarshaller;
public ItemSearchResponse getObject(InputStream xml) {
    
    ItemSearchResponse its = null;
    try {
        its = (ItemSearchResponse) unmarshaller.unmarshal(new StreamSource(xml));
    } finally {
        }
    return its;
}
}

Unmarshaller.unmarshaller is actually interface method:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/oxm/Unmarshaller.html

Unmarshaller interface is implemented by several classes.

Who decides which implementing class to inject during runtime and how it decides which class to use?

Does Spring IoC mechanism does this? If so does it pick up one specific implementing class during build time when jar is generated or it does it during run time?

Will above code work outside of Spring in ordinary Java file assuming dependent jars in classpath?

java – Is calling Session::evict() on Hibernate entities considered bad practice?

I’m using Hibernate in my application. When calling the setters on Hibernate entities that are in “managed” state, it will eventually write the changes back to database when the transaction is getting committed, even without explicitly calling Session::update().

Sometimes, I have to call Session::evict() in my code to avoid accidentally writing these changes into database. However, I have some problems:

  • I have to worry about the state of these entities all the time. When passing entities between services and DAOs, I need to keep track of the states of them. This increase the complexity of development.
  • Writing test cases became harder. Asserting the state of entities that must be “managed” or “detached” state is tedious and annoying.

Is calling Session::evict() considered bad practice? If so, what’s the best way to avoid it?

java – Como puedo hacer estas colas de impresion en Netbeans

Alguien me podría ayudar a desarrollar esto en java netbeans

Uno de los principales usos que se hace en la industria de la tecnología de las
estructuras FIFO es en la administración de las colas de impresión que realizan
los sistemas operativos.
En esta oportunidad, la empresa MINUTECH necesita un algoritmo que le
administre todos los trabajos de impresión que generan sus empleados teniendo
en cuenta las siguientes especificaciones:

  1. En la empresa sólo hay 2 impresoras las cuales están asignadas para
    usarse a dos áreas.
  2. En la empresa hay 4 áreas organizacionales: Gerencia, Administración,
    Mercadeo y Producción.
  3. La Impresora 1 será asignada para usarse por las áreas de Gerencia y
    Administración.
  4. La Impresora 2 será asignada para usarse por las áreas de Mercadeo y
    Producción.
  5. Se realizó un estudio donde se detectó el tiempo que duran en imprimirse
    los trabajos de la empresa según las siguientes categorías:
    Tipo Trabajo Duración
  6. Sencillo 1 minuto
  7. Informe 3 minutos
  8. Catálogo 5 minutos
  9. Por orden del Gerente General se ha dispuesto que cuando Gerencia envíe
    un trabajo de impresión, si en la impresora asignada por defecto tardaría
    más de 5 minutos en imprimirse, debe analizarse en cuál de las impresoras
    tardará menos tiempo y enviarse a dicha impresora.
  10. La Impresora 2 está diseñada para tener una altura limitada de 2 trabajos.
    Realice el algoritmo que permita leer en el momento que cada trabajo se ha
    enviado y a qué impresora, y se muestre por pantalla cada segundo el estado
    actual de las 2 impresoras, el cual va a ir cambiando a medida que se lee el
    archivo texto con los trabajos enviados y a medida que cada trabajo sea atendido,
    al pasar el tiempo de duración que se ha estipulado para cada uno de ellos.
    Estructura del Archivo texto con la información de los trabajos de Impresión
    AREA TIPO DE
    TRABAJO
    ADMON 1
    GERENCIA 3
    GERENCIA 3
    PRODUC 2
    GERENCIA 2
    GERENCIA 3
    PRODUC 3
    MERCADEO 3
    PRODUCC 1
    ADMON 3
    GERENCIA 2

web application – API Returning Java Exception. Safe?

I just wanted to ask if my concerns here are valid.

I am aware that it is unsafe for the api to return a stacktrace.

The question I have is whether there is also some standard regarding packaging up java exceptions into a 500 response and telling them only that. I am talking about sending back such things as “DataIntegrityViolationExceptio”, “NullPointerException” etc. Is this a good idea? Or should it be more generic than this?

I am currently warning folks against this and that they should “whitelist” their server responses (i.e. only send it if you have a conscious reason or are forced to by). I just wanted to know if I am wasting our time with this.

Thank you for any input on this.

functional programming – How to check if a string is null and use its value avoiding NullPointerException in Java

I need to map few object’s properties to another object but those properties could also have null values.

This can cause NullPointerExceptions that can be avoided using this code:

private static String nullOrString(Object o){
    return o==null?null:o.toString();
}

Can this function be improved / made more robust in modern Java?

java – Calling a SQL Server Stored Procedure with Spring JPA

I am new to spring but I had it working with JPA to where it returns the results from a SQL Server table without any issues (List of Applications). That table is now 3 separate tables that need to be joined which I did through a stored procedure. The stored procedure does not take any parameters, simple returns all the results but the results are exactly the same as the dropped table was returning, same number of columns and same column names. I tried following some online examples without success. Please help!!
Below are all the objects that I believe are relevant, I am not adding the application.properties file because the it was already working before I switch to pulling from a stored procedure instead of a single table. The First GET on the ApplicationJpaRepository.java file is the one that I am trying to figure out. I will probably create a new stored procedure or enhance the current one to also do crud operations by taking parameters but if I can solve this, it might give me enough knowledge to understand how to do the rest.enter image description here

Application.java

package com.perspecta.rest.application;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.Table;

@Entity
@Table(name = "Application")
@NamedStoredProcedureQuery(name = "Application.getListOfApplications", 
  procedureName = "pr_retrieve_application_list")
public class Application {

    @Id
    @GeneratedValue
    private Long id;
    private String application_name;
    private String application_description;
    private String data_types;

    protected Application() {
        
    }

    public Application(Long id, String application_name, String application_description, String data_types) {
        this.id = id;
        this.application_name = application_name;
        this.application_description = application_description;
        this.data_types = data_types;
    }

    @Column
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    @Column
    public String getApplication_name() {
        return application_name;
    }
    public void setApplication_name(String application_name) {
        this.application_name = application_name;
    }

    @Column
    public String getApplication_description() {
        return application_description;
    }
    public void setApplication_description(String application_description) {
        this.application_description = application_description;
    }

    @Column
    public String getData_types() {
        return data_types;
    }
    public void setData_types(String data_types) {
        this.data_types = data_types;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Application other = (Application) obj;
        if (id != other.id)
            return false;
        return true;
    }
}

ApplicationJpaRepository.java

package com.perspecta.rest.application;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.stereotype.Repository;

@Repository
public interface ApplicationJpaRepository extends JpaRepository<Application, Long> {
    @Procedure(value  = "pr_retrieve_application_list")
    void getListOfApplications(String model);    
}

ApplicationJpaResource.java

package com.perspecta.rest.application;

import java.net.URI;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class ApplicationJpaResource {

    @Autowired
    private ApplicationJpaRepository applicationJpaRepository;


    **@GetMapping("/jpa/users/{username}/applications")
    public List<Application> getAllApplications(@PathVariable String username){
        return applicationJpaRepository.findAll();
    }**

    @GetMapping("/jpa/users/{username}/applications/{id}")
    public Application getApplication(@PathVariable String username, @PathVariable long id){
        return applicationJpaRepository.findById(id).get();
    }

    //DELETE /users/{username}/applications/{id}
    @DeleteMapping("/jpa/users/{username}/applications/{id}")
    public ResponseEntity<Void> deleteApplication(@PathVariable String username, @PathVariable long id){
        
        applicationJpaRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    // Edit/Update an Application
    // PUT /users/{username}/applications/{id}
    @PutMapping("/jpa/users/{username}/applications/{id}")
    public ResponseEntity<Application> updateApplication(@PathVariable String username, @PathVariable long id, @RequestBody Application application){

        Application applicationUpdated = applicationJpaRepository.save(application);
        return new ResponseEntity<Application>(application, HttpStatus.OK);
    }

    // Create a new Application
    // POST /users/{username}/applications/
    @PostMapping("/jpa/users/{username}/applications")
    public ResponseEntity<Void> createApplication(@PathVariable String username, @RequestBody Application application){

        Application createdApplication = applicationJpaRepository.save(application);

        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(createdApplication.getId()).toUri();
        return ResponseEntity.created(uri).build();
    }

}

design – Java: Splitting a large unit test class

The project (Java/Spring) I currently work on has a rather large unit-test class for one of its services : more than 1000 lines, several Nested class (one per big functionality), some tests without a Nested class, …

Finding this file rather difficult to read, and to manage (a modification in the service, and you have to take time to find the corrects tests to fix/update), I proposed to split the class to have one test file per Nested Class, each one linked to a “principal” test file, which will be managing the Mock & the tests without Nested Class. All the tests files would be put into a specific package.

I am wondering if this would be a good thing to do? or if it was something to avoid to do ?

I hope i was clear enough.
Have a nice day

java – Call center modelling

I have a requirement to deign a call center.
Details:
-using OOP design a tech center apps
-the user may choose options from a menu(language,problem type(hw/sw))
-the user can choose one of the solutions: system restart,plug in , plug off) or he can choose to speak to a technician(two options : describe problem , solve problem).
Can you give me a hand to model this in Java please?
Can i use an interface?

public interface CallCenterApps {
    public Technician getCall() ;
    public User();
    public Issue();
}

thank you

java – I consistently get an error with respect to the final output

I consistently get an error with respect to the final output. However, the code very apparently is running correctly, providing the desired output elements, with some additional redundant elements like an appetizer and with no errors.

Please, see the attached piece of code, and output when run on the Eclipse IDE.


 m, n, k;

while (true) {

Menu:

// proocess to select the menu items
System.out.println("Select from menu, " + name);

display(mainMenu);

n = sc.nextInt();
if (n == 0)
break;

if (n == 1) {
while (true) {
System.out.println("");
System.out.println("Appetizer Menu:");
display(appetizerMenu);

m = sc.nextInt();
list = list + "Appetizer:(" + appetizerMenu(m) + ": ";

if (m == 0) {
break;
}

while (true) {

System.out.println("");
System.out.println("Toppings Menu:");
display(toppingsMenu);
k = sc.nextInt();
if (k == 0)
break;
list = list + toppingsMenu(k) + " ";
}

list = list + ")n";

}

}

if (n == 2) {

while (true) {
System.out.println("");
System.out.println("Main Course Menu:");
display(mainCourseMenu);

m = sc.nextInt();
list = list + "Main Course :(" + mainCourseMenu(m) + ": ";

if (m == 0) {
break;
}

while (true) {

System.out.println("");
System.out.println("Toppings Menu:");
display(toppingsMenu);
k = sc.nextInt();
if (k == 0)
break;
list = list + toppingsMenu(k) + ")n";
}

}

}

if (n == 3) {

while (true) {
System.out.println("");
System.out.println("Dessert Menu:");
display(dessertMenu);

m = sc.nextInt();
list = list + "Main Course :(" + dessertMenu(m) + ": ";

if (m == 0) {
break;`
}

while (true) {

System.out.println("");
System.out.println("Toppings Menu:");
display(toppingsMenu);
k = sc.nextInt();
if (k == 0)
break;
list = list + toppingsMenu(k) + ")n";
}

}

}

} // end while loop

System.out.println("Here is your order " + name);
System.out.println(list);
System.out.println("Enjoy your meal!");

} // end of if
}// main method
}// end of class




==========================
This is the output I am supposed to get :

Here is your order Superman:

Appetizer: ( Hummus: Olives, Olive Oil )

Main Course: ( Fish: Paprika )

Dessert: ( Baklava: )


Enjoy your meal!

Unfortunately, I am getting this output:

Here is your order Superman:
Appetizer:(Hummus: Olives Olive Oil )
Appetizer:(Nothing: Main Course :(Fish: Paprika)
Main Course :(Nothing: Main Course :(Baklava: Main Course :(Nothing:
Enjoy your meal!