class Task implements Runnable
{
private File file;
private String fileName;
public Task(File file, String fileName)
{
this.file = file;
this.fileName = fileName;
}
public void run()
{
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
for(String feature : StaticClass.STATIC_LIST_FEATURES)
{
if(line.contains(feature))
{
if (result.values().contains(feature))
{
List<String> list = result.get(feature);
list.add(fileName);
result.put(feature, list);
break;
}
else
result.put(feature, new ArrayList<>(List.of(fileName)));
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public class MainClass{
// Maximum number of threads in thread pool
static final int MAX_T = 5;
static final Map<String, List<String>> result = new ConcurrentHashMap<>();
public static void main(String[] args)
{
List<Runnable> runnableList = new ArrayList<Runnable>();
File myObj = new File("JsTsresult.txt");
try
{
Scanner myReader = new Scanner(myObj);
while(myReader.hasNextLine())
{
String data = myReader.nextLine().substring(1);
Runnable runnable = new Task(new File("/webdev/NetLedger_NewGitRepo/", data));
runnableList.add(runnable);
}
ExecutorService pool = Executors.newFixedThreadPool(MAX_T);
for(Runnable task : runnableList)
pool.execute(task);
pool.shutdown();
} catch(Exception e)
{
e.printStackTrace();
}
}
}
I am using threadpool to check if features are mentioned in some files that I have inside a file JSTSResult.txt. This txt file has a list of files. I am reading that file one-by-one and want to create a concurrent hash map where key would be that feature and value would be the list of those files. Here I am using a few tasks and I have initialized ConcurrentHashMap. But, not sure on how to share this ConcurrentHashMap to all those Tasks. I have this way, but of course it won't work. Any suggestions?
You can try creating a method to Task and then synchronized it so that only one thread can add in it at a time.
class Task implements Runnable
{
static final Map<String, List<String>> result = new ConcurrentHashMap<>();
public static synchronized void addToResult()
{
result.put();
}
}
If you want to know what synchronized is.
This is a sample explanation based on a book.
class SpeechSynthesizer
{
synchronized void say( String words )
{
// speak
}
}
Because say() is an instance method, a thread must acquire the lock on the SpeechSynthesizer instance it’s using before it can invoke the say() method. When say() has
completed, it gives up the lock, which allows the next waiting thread to acquire the lock
and run the method. It doesn’t matter whether the thread is owned by the SpeechSyn
thesizer itself or some other object; every thread must acquire the same lock, that of
the SpeechSynthesizer instance. If say() were a class (static) method instead of an
instance method, we could still mark it as synchronized. In this case, because no in‐
stance object is involved, the lock is on the class object itself. -Learning Java
Book by Jonathan Knudsen and Patrick
Related
I want to create a series of nodes like parentProduct/subCategory1/subCategory2/subCategory3/subCategory4 inside /var/temp location. I tried to use addNode() method of Node class and createPath() method of JcrUtil class but both did not work. addNode() method just creates only one immediate node(ex, parentProduct) but it is creating second level onwards.
Is there any API available that can create a series of nodes, ex-parentProduct/subCategory1/subCategory2/subCategory3/subCategory4?
protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
throws IOException {
final Session session;
final ResourceResolver resourceResolver = request.getResourceResolver();
session = resourceResolver.adaptTo(Session.class);
long count = 0;
final String path = "/var/temp";
final PrintWriter out = response.getWriter();
try {
if (session.nodeExists(path)) {
Node jcrNode = session.getNode(path);
jcrNode.addNode("parentProduct/subCategory1/subCategory2/subCategory3/subCategory4");
//jcrNode.addNode("parentProduct");
//JcrUtil.createPath("parentProduct/subCategory1/subCategory2/subCategory3/subCategory4",JcrConstants.NT_UNSTRUCTURED, session);
}
session.save();
} catch (ItemExistsException ex) {
LOG.error("ItemExistsException", ex);
} catch (RepositoryException exp) {
LOG.error("RepositoryException", exp);
} finally {
if (session != null) {
session.logout();
}
}
}
There is more than one way to do it. For example,
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.jackrabbit.JcrConstants;
String path = "/var/temp/parentProduct/subCategory1/subCategory2/subCategory3/subCategory4";
Resource subCategory4 = ResourceUtil.getOrCreateResource(
resourceResolver,
path, // The full path to be created
JcrConstants.NT_UNSTRUCTURED, // resource type of the final resource to create
JcrConstants.NT_UNSTRUCTURED, // resource type of all intermediate resources
true // save chnages
);
I want to make a FadeTransition within a pane in my application. Also, with this FadeTransition I set the visibitilitys of some JavaFX inside the pane to false, to make them disappear. It's working fine but, when I call another method that I named waitForResponse(event) after the FadeTransition it just stops working. I don't know why.
If I comment the waitForResponse(event) the FadeTransitions start working again.
I've thought that maybe it's a problem with the Socket and the InputStreamReader inside the waitForResponse(event), but I tested taking it out and making another basic thing inside this method still not work.
I've made other tests and dicovered that FadeTransition and other visibility changes doesn't work if I put any bufferedReader, other loops ou decision structures after it.
I just want to make a loading screen that prevent user to click anywhere until it's finished.
This is the code:
public class LoadingScreenController implements Initializable {
// Socket que vai ser utilizado nos vários métodos para conversar com o servidor
private Socket cliente;
// PrintWriter que vai ser utilizado pelos vários métodos e vai passar o
// argumento para o switch case
private PrintWriter pr;
private InputStreamReader in;
private BufferedReader bf;
private String option;
private String response;
#FXML
private Button refreshButton;
#FXML
private ImageView loadingGif;
#FXML
private Label txtLabel;
#FXML
private AnchorPane rootPane;
public String getOption() {
return option;
}
public void setOption(String option) {
this.option = option;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
private void makeFadeInTransition() {
FadeTransition fadeTransition = new FadeTransition(Duration.seconds(1), loadingGif);
fadeTransition.setFromValue(0.0);
fadeTransition.setToValue(1.0);
fadeTransition.play();
}
#FXML
private void onRefreshButtonAction(ActionEvent event) {
if (option == null) {
throw new IllegalStateException("Entity was null");
}
refreshButton.setVisible(false);
refreshButton.setDisable(true);
txtLabel.setVisible(false);
makeFadeInTransition();
sendOptionToServer(event);
}
#FXML
private void sendOptionToServer(ActionEvent event) {
try {
cliente = new Socket("localhost", 3322);
pr = new PrintWriter(cliente.getOutputStream());
in = new InputStreamReader(cliente.getInputStream());
bf = new BufferedReader(in);
pr.println(option);
pr.flush();
waitForReponse(event, bf);
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForReponse(ActionEvent event, BufferedReader bf) throws IOException {
response = bf.readLine();
switch (response) {
case "a":
Utils.currentStage(event).close();
break;
}
}
}
Your sendOptionToServer(...) method, and in particular your waitForResponse(...) method, contains blocking calls that block execution until they are complete (i.e. until you receive a response from the server). Since you're running these on the FX Application Thread, you prevent that thread from doing its normal work until those calls complete. This means it won't update the UI or process any user events until you have received and processed the response from the server.
You should place the calls to blocking methods in a background thread to allow the FX Application Thread to proceed in the meantime. The javafx.concurrent API makes this reasonably easy to do; here a Task should suffice.
Here's a version that uses a Task. I also used a "try with resources" to ensure everything that needs to be closed is correctly closed.
#FXML
private void sendOptionToServer(ActionEvent event) {
Task<String> serverCommunicationTask = new Task<>() {
#Override
protected String call() throws Exception {
try (
Socket cliente = new Socket("localhost", 3322);
PrintWriter pr = new PrintWriter(cliente.getOutputStream());
BufferedReader bf = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
) {
pr.println(option);
pr.flush();
return bf.readLine();
}
}
};
serverCommunicationTask.setOnSucceeded(event -> {
if ("a".equals(serverCommunicationTask.getValue())) {
rootPane.getScene().getWindow().hide();
}
});
serverCommunicationTask.setOnFailed(event -> {
event.getException().printStackTrace();
// handle exception...
});
Thread thread = new Thread(serverCommunicationTask);
thread.setDaemon(true);
thread.start();
}
I have written a code in java that reads the ontology and print the triplets. the code is working fine. i want to hide the URI's in output and also print the output in the tree hierarchy form. Currently it gives me output in lines. Any idea how can i do this.
Tree Form Like:
Thing
Class
SubClass
Individual
so on ...
this is the ReadOntology class, this class i use in servlet.
public class ReadOntology {
public static OntModel model;
public static void run(String ontologyInFile) {
model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
InputStream ontologyIn = FileManager.get().open(ontologyInFile);
loadModel(model, ontologyIn);
}
protected static void loadModel(OntModel m, InputStream ontologyIn) {
try {
m.read(ontologyIn, "RDF/XML");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
this is the servlet
public class Ontology extends HttpServlet{
OntClass ontClass = null;
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
PrintWriter out = res.getWriter();
ServletContext context = this.getServletContext();
String fullPath = context.getRealPath("/WEB-INF/Data/taxi.owl");
ReadOntology.run(fullPath);
SimpleSelector selector = new SimpleSelector(null, null, (RDFNode)null);
StmtIterator iter = ReadOntology.model.listStatements(selector);
while(iter.hasNext()) {
Statement stmt = iter.nextStatement();
out.print(stmt.getSubject().toString());
out.print(stmt.getPredicate().toString());
out.println(stmt.getObject().toString());
}
}
}
As one step towards your goal, this groups the statements by subject, and for the predicates only shows the local name:
ResIterator resIt = ReadOntology.model.listSubjects()
while (resIt.hasNext()) {
Resource r = resIt.nextResource();
out.println(r);
StmtIterator iter = r.listProperties();
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
out.print(" ");
out.print(stmt.getPredicate().getLocalName());
out.println(stmt.getObject());
}
}
There are lots of useful methods in the API for Resource and Model.
To render a full class tree, use the methods on OntModel and OntClass. Perhaps:
private void printClass(Writer out, OntClass clazz, int indentation) {
String space = ' '.repeat(indentation);
// print space + clazz.getLocalName()
...
// iterate over clazz.listSubClasses(true)
// and call printClass for each with indentation increased by 1
...
// iterator over clazz.listInstances()
// and print all their properties as in the
// snippet above but with space added
}
Then in the service method, iterate over the OntModel's classes, and for any where hasSuperClass() is false, call printClass(out, clazz, 0).
I want to use pre-populated database in Android Room. I found a way to make it through using the callback, and filled up the database files.
But something is wrong, I'm sure that the database is copied normally, but it remains empty in the device monitor and android emulator. Can you please help me
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
private static final String DB_NAME = "base.db";
static Context ctx;
public abstract Dao dao();
public static AppDatabase getDatabase(Context context) {
if (INSTANCE == null) {
ctx = context;
synchronized (AppDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context,
AppDatabase.class, DB_NAME)
.allowMainThreadQueries()
.addCallback(rdc)
.build();
}
}
}
return INSTANCE;
}
private static RoomDatabase.Callback rdc = new RoomDatabase.Callback() {
public void onCreate(SupportSQLiteDatabase db) {
new PopulateDbAsync(INSTANCE, ctx).execute();
Log.d("db create ", "table created when db created first time in onCreate");
}
public void onOpen(#NonNull SupportSQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
}
};
private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
private Dao dao;
AssetManager assetManager = ctx.getAssets();
PopulateDbAsync(AppDatabase db, Context context) {
Dao = db.Dao();
ctx = context;
}
#Override
protected Void doInBackground(final Void... params) {
String DB_PATH = "/data/data/mypackage/databases/";
String DB_NAME = "base.db";
try {
Log.d("AppDatabase","Trying copy database file");
OutputStream myOutput = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = ctx.getAssets().open("base.db");
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
I solved after spending 6 hours on researching and R & D .
Context is that : - I want to put already existing finaldb.db(which is present inside assests folder) into room database .
Step 1 :
copy this framework files from here link
Step 2 :
You need to migrate , chill i have code :)
#Database(entities = {Status.class}, version = 1,exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
public abstract DataDao StatusDao();
private static AppDatabase INSTANCE;
public static AppDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE = createDatabase(context);
}
return (INSTANCE);
}
private static final Migration MIGRATION_2_3 = new Migration(1, 2) {
#Override
public void migrate(#NonNull SupportSQLiteDatabase database) {
Log.d("kkkk","bc");
String SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS 'Status' " +
"( 'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
" 'category' TEXT NOT NULL," +
" 'sub_category' TEXT NOT NULL," +
" 'content' TEXT NOT NULL," +
" 'favourite' INTEGER DEFAULT(0))";
database.execSQL(SQL_CREATE_TABLE);
}
};
private static AppDatabase createDatabase(Context context) {
RoomDatabase.Builder<AppDatabase> builder =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class,
context.getString(R.string.dbase_name));
return (builder.openHelperFactory(new AssetSQLiteOpenHelperFactory())
.allowMainThreadQueries()
.addMigrations(MIGRATION_2_3)
.build());
}
}
In MIGRATION_2_3 you have to create table exactly same as current database(which is present in assests folder)
want to learn about migration
Step 3 :
Now table is created successfully in room database !
In case of crash see your logcat , in which its written in understandable form .
You cannot, properly, do the copy of the database in the onCreate method.
When the onCreate method is called the database has been created (the created database is passed to the method). You have to do the copy before the onCreate method and before the database is opened.
You could override's the RoomDatabase init method and do the copy from that method or do the copy before invoking the databaseBuilder.
I'm solved it.
Database class:
#Database(entities = {Entity1.class, Entity2.class, Entity3.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public abstract Entity1Dao 1Dao();
public abstract Entity2Dao 2Dao();
public abstract Entity3Dao 3Dao();
public static AppDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE = createDatabase(context);
}
return (INSTANCE);
}
private static AppDatabase createDatabase(Context context) {
RoomDatabase.Builder<AppDatabase> builder =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class,
context.getString(R.string.dbase_name));
return (builder.openHelperFactory(new AssetSQLiteOpenHelperFactory())
.allowMainThreadQueries()
.build());
}
}
Also you should get SQL Helpers, link
My issue is a little bit different than the OP.
I was copying the database file from internal storage which I downloaded from the internet, not from assets. And java.lang.RuntimeException: Unable to copy database file is raised because I didn't grant READ_EXTERNAL_STORAGE before this, or in general granting WRITE_EXTERNAL_STORAGE as READ_EXTERNAL_STORAGE is included in WRITE_EXTERNAL_STORAGE and already need the write permission for downloading the file.
i know how to implement it,using field assist and search pattern, but the mechanism each time triggers a new search. I am not sure, how the mechanism is implemented in Open Type for example ( i think with indexes). How to use this cache to make in time classpath search
This almost my entire solution. Each time a call createProposalData
private TreeSet<String> data;
private SearchParticipant[] participants = new SearchParticipant[] { SearchEngine
.getDefaultSearchParticipant() };
private SearchPattern pattern;
private IJavaProject prj;
private JavaSearchScope scope;
private SearchEngine searchEngine = new SearchEngine();
private SearchRequestor requestor = new SearchRequestor() {
#Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
String text = getText(match.getElement());
if (text != null) {
data.add(text);
}
}
public String getText(Object element) {
...
}
};
public ProposalEngine(IJavaProject prj) {
super();
this.prj = prj;
scope = new JavaSearchScope();
try {
scope.add(prj);
} catch (JavaModelException e) {
//
}
}
public Collection<String> createProposalData(final String patternText) {
data = new TreeSet<String>();
try {
pattern = getPatternForSeach(patternText);
searchEngine.search(pattern, participants, scope, requestor, null);
} catch (Exception e) {
// skip
}
return data;
}
protected SearchPattern getPatternForSeach(String patternText) {
return SearchPattern.createPattern(patternText,
IJavaSearchConstants.CLASS_AND_INTERFACE,
IJavaSearchConstants.DECLARATIONS,
SearchPattern.R_CAMELCASE_MATCH);
}
I believe that you are doing exactly what the Open Type dialog is doing. Indexing to speed up search happens underneath JDT API.