Why is my Udp.send using Akka.io always getting timeout? - udp

Executing this code always results in timeout error and never sending UDP packet.
Why?
I need to write somthing more because stackoverflow won't let me to send the question... ;-), but I think the question is very simple and the code is all needed.
package controllers;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.dispatch.Recover;
import akka.io.Tcp;
import akka.io.Udp;
import akka.io.UdpMessage;
import akka.japi.Procedure;
import akka.util.ByteString;
import java.net.InetSocketAddress;
import static akka.pattern.Patterns.ask;
import play.libs.Akka;
import play.mvc.Result;
import play.libs.F.Function;
import play.libs.F.Promise;
import play.mvc.*;
public class Application extends Controller {
static ActorRef myActor = Akka.system().actorOf(Props.create(Listener.class));
public static Result index() {
return async(
Akka.asPromise(
//Promise.wrap(
ask(
myActor,
UdpMessage.send(ByteString.fromString("esto es una prueba"), new InetSocketAddress("172.80.1.81", 21001)),
1000
)
// .recover(
// new Recover<Object>() {
// #Override
// public Object recover(Throwable t) throws Throwable {
// if( t instanceof AskTimeoutException ) {
// Logger.error("Got exception: ", t);
// return internalServerError("Timeout");
// }
// else {
// Logger.error("Got exception: ", t);
// return internalServerError("Got Exception: " + t.getMessage());
// }
// }
// })
).map(
new Function<Object,Result>() {
public Result apply(Object response) {
return ok(response.toString());
}
}
)
);
}
//http://doc.akka.io/docs/akka/2.2-M2/java/io.html
//https://gist.github.com/kafecho/5353393
//how to terminate actor on shutdown http://stackoverflow.com/questions/10875101/how-to-stop-an-akka-thread-on-shutdown
public static class Listener extends UntypedActor {
final ActorRef nextActor;
public Listener() {
this(null);
}
public Listener(ActorRef nextActor) {
this.nextActor = nextActor;
// request creation of a bound listen socket
final ActorRef mgr = Udp.get(getContext().system()).getManager();
mgr.tell(UdpMessage.bind(getSelf(), new InetSocketAddress("localhost",
31001)), getSelf());
}
#Override
public void onReceive(Object msg) {
if (msg instanceof Udp.Bound) {
final Udp.Bound b = (Udp.Bound) msg;
getContext().become(ready(getSender()));
} else
unhandled(msg);
}
private Procedure<Object> ready(final ActorRef socket) {
return new Procedure<Object>() {
#Override
public void apply(Object msg) throws Exception {
if (msg instanceof Udp.Received) {
final Udp.Received r = (Udp.Received) msg;
// echo server example: send back the data
socket.tell(UdpMessage.send(r.data(), r.sender()),
getSelf());
// or do some processing and forward it on
final Object processed = new Object();//TODO parse data etc., e.g. using PipelineStage
if(nextActor!=null){
nextActor.tell(processed, getSelf());
}
} else if (msg.equals(UdpMessage.unbind())) {
socket.tell(msg, getSelf());
} else if (msg instanceof Udp.Unbound) {
getContext().stop(getSelf());
} else if (msg instanceof Udp.Send){
socket.tell(msg, getSelf());
} else
unhandled(msg);
}
};
}
}
}

Related

In ActiveJDBC how to update value of one of the Composite Key fields?

I am using ActiveJDBC. I have a table that is made up of a composite key (parentId, childId, effStartDate). I have a new requirement to allow the updating of the effStartDate field. When I tried to update the field and save, it errors out. Is there an appropriate way to update this using the ORM or a raw SQL approach in ActiveJDBC?
Current approach:
mymodel.setEffStartDate(newStartDate);
mymodel.saveIt();
Updated to provide more details. Here's the exact code:
try {
ri.setEffStartDate(ld);
boolean didItSave = ri.saveIt(user);
System.out.println("here - " + didItSave);
} catch(Exception e) {
System.out.println("Exception: " + e);
}
When the saveIt runs, it doesn't error out. However, it returns FALSE and nothing gets updated in the database. So I misused "errors" in my earlier statement. I should have said it just doesn't do anything.
We are using Oracle database.
The model class trying to update:
package com.brookdale.model;
import java.time.LocalDate;
import org.javalite.activejdbc.annotations.BelongsTo;
import org.javalite.activejdbc.annotations.BelongsToParents;
import org.javalite.activejdbc.annotations.CompositePK;
import org.javalite.activejdbc.annotations.Table;
import org.javalite.activejdbc.validation.ValidationException;
import com.brookdale.model.activejdbc.CecilModel;
#Table("MONET.CONTACTREL")
#CompositePK({ "parentContactID", "childContactID", "contactRelTypeID", "effStartDate" })
#BelongsToParents({
#BelongsTo(foreignKeyName="relationshipId",parent=Relationship.class),
#BelongsTo(foreignKeyName="contactRelTypeID",parent=ContactRelType.class),
// #BelongsTo(foreignKeyName="parentContactID",parent=Contact.class),
// #BelongsTo(foreignKeyName="childContactID",parent=Contact.class),
#BelongsTo(foreignKeyName="childContactID",parent=Contact.class),
#BelongsTo(foreignKeyName="childContactID",parent=ResidentContactDetail.class)
})
public class ContactRel extends CecilModel {
private ResidentContactDetail emergResidentContactDetail;
private ResidentContactDetail healthResidentContactDetail;
private ResidentContactDetail finResidentContactDetail;
private int emergresidentind = 0;
public Long getParentContactID() {
return getLong("parentContactID");
}
public void setParentContactID(Long parentContactID) {
set("parentContactID",parentContactID);
}
public Long getChildContactID() {
return getLong("childContactID");
}
public void setChildContactID(Long childContactID) {
set("childContactID",childContactID);
}
public LocalDate getEffStartDate() {
return getLocalDate("effStartDate");
}
public void setEffStartDate(LocalDate effStartDate) {
setLocalDate("effStartDate",effStartDate);
}
public LocalDate getEffEndDate() {
return getLocalDate("effEndDate");
}
public void setEffEndDate(LocalDate effEndDate) {
setLocalDate("effEndDate",effEndDate);
}
public Integer getContactRelTypeID() {
return getInteger("contactRelTypeID");
}
public void setContactRelTypeID(Integer contactRelTypeID) {
set("contactRelTypeID",contactRelTypeID);
}
public Integer getRelationshipId() {
return getInteger("relationshipId");
}
public void setRelationshipId(Integer relationshipId) {
set("relationshipId",relationshipId);
}
public Integer getParentIsPrimaryResidentInd() {
return getInteger("parentIsPrimaryResidentInd");
}
public void setParentIsPrimaryResidentInd(Integer parentIsPrimaryResidentInd) {
set("parentIsPrimaryResidentInd",parentIsPrimaryResidentInd);
}
public Integer getParentIsSecondPersonInd() {
return getInteger("parentIsSecondPersonInd");
}
public void setParentIsSecondPersonInd(Integer parentIsSecondPersonInd) {
set("parentIsSecondPersonInd",parentIsSecondPersonInd);
}
public int getCourtesyCopyInd() {
return getInteger("courtesyCopyInd");
}
public void setCourtesyCopyInd(Integer courtesyCopyInd) {
set("courtesyCopyInd",courtesyCopyInd);
}
/* Additional helper methods */
public Contact getParentContact() {
return Contact.findById(getParentContactID());
}
public Contact getChildContact() {
return Contact.findById(getChildContactID());
}
public int getEmergresidentind() {
return emergresidentind;
}
public void setEmergresidentind(int emergresidentind) {
this.emergresidentind = emergresidentind;
}
#Override
public void validate(){
super.validate();
validatePresenceOf("parentContactID", "Parent Contact is required.");
validatePresenceOf("childContactID", "Contact is required.");
validatePresenceOf("contactRelTypeID", "Resident relationship type is required.");
validatePresenceOf("effStartDate", "Effective Start Date is required.");
validatePresenceOf("relationshipid", "Relationship is required.");
if(this.getEffEndDate() != null) {
if(this.getEffEndDate().isBefore(this.getEffStartDate())) {
this.addError("effenddate", "End date must be on or after the start date.");
}
}
if(this.hasErrors()) {
throw new ValidationException(this);
}
}
}
Our CecilModel class we are extending the Model class.
package com.brookdale.model.activejdbc;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.axis.utils.StringUtils;
import org.apache.log4j.Logger;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.validation.ValidationBuilder;
import org.javalite.activejdbc.validation.ValidationException;
import org.javalite.activejdbc.validation.ValidatorAdapter;
import com.brookdale.core.CLArgs;
import com.brookdale.exception.CecilErrorsException;
import com.brookdale.message.CecilMessage;
import com.brookdale.model.Building;
import com.brookdale.security.bo.User;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import oracle.sql.DATE;
public abstract class CecilModel extends Model {
final static Logger logger = Logger.getLogger(CecilModel.class);
private static final transient TypeReference<HashMap<String, Object>> mapType = new TypeReference<HashMap<String, Object>>() {};
private static final transient TypeReference<ArrayList<HashMap<String, Object>>> listMapType = new TypeReference<ArrayList<HashMap<String, Object>>>() {};
//add -0600 to specify cental time zone
private static final transient SimpleDateFormat jsonDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
private transient Map<String, Collection<Map<String, Object>>> jsonInclude = new HashMap<>();
public Timestamp getUpdateDateTime() {
return getTimestamp("updateDateTime");
}
public void setUpdateDateTime(LocalDateTime updateDateTime) {
set("updateDateTime",updateDateTime == null ? null : Timestamp.valueOf(updateDateTime));
}
public Timestamp getCreateDateTime() {
return getTimestamp("createDateTime");
}
public void setCreateDateTime(LocalDateTime createDateTime) {
set("createDateTime",createDateTime == null ? null : Timestamp.valueOf(createDateTime));
}
public String getUpdateUsername() {
return getString("updateUsername");
}
public void setUpdateUsername(String updateUsername) {
set("updateUsername",updateUsername);
}
public String getCreateUsername() {
return getString("createUsername");
}
public void setCreateUsername(String createUsername) {
set("createUsername",createUsername);
}
public Long getUpdateTimeId() {
return getLong("updatetimeid");
}
public void setUpdateTimeId(Long updateTimeId) {
if (updateTimeId == null)
setLong("updatetimeid", 1);
else
setLong("updatetimeid",updateTimeId);
}
public void incrementUpdateTimeId() {
Long updatetimeid = this.getUpdateTimeId();
if (updatetimeid == null)
this.setUpdateTimeId(1L);
else
this.setUpdateTimeId(updatetimeid+1L);
}
public boolean save(User user) {
String userId = (CLArgs.args.isAuthenabled()) ? user.getUserid() : "TEST_MODE";
// insert
java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
if (this.getId() == null || this.getId().toString().equals("0")) {
this.setId(null);
this.set("createDateTime", now);
this.set("createUsername", userId);
this.set("updateDateTime", now);
this.set("updateUsername", userId);
this.set("updateTimeId", 1);
}
// update
else {
Long updatetimeid = this.getLong("updateTimeid");
this.set("updateDateTime", now);
this.set("updateUsername", userId);
this.set("updateTimeId", updatetimeid == null ? 1 : updatetimeid + 1);
}
return super.save();
}
public boolean saveIt(User user) {
String userId = (CLArgs.args.isAuthenabled()) ? user.getUserid() : "TEST_MODE";
// insert
java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
if (this.isNew()) {
this.setId(null);
this.set("createDateTime", now);
this.set("createUsername", userId);
this.set("updateDateTime", now);
this.set("updateUsername", userId);
this.set("updateTimeId", 1);
}
// update
else {
Long updatetimeid = this.getLong("updateTimeid");
this.set("updateDateTime", now);
this.set("updateUsername", userId);
this.set("updateTimeId", updatetimeid == null ? 1 : updatetimeid + 1);
}
return super.saveIt();
}
public boolean saveModel(User user, boolean insert) {
return saveModel(user.getUserid(), insert);
}
public boolean saveModel(String userId, boolean insert) {
userId = (CLArgs.args.isAuthenabled()) ? userId : "TEST_MODE";
if(insert){
return this.insertIt(userId);
}else{
return this.updateIt(userId);
}
}
public boolean insertIt(String user) {
user = (CLArgs.args.isAuthenabled()) ? user : "TEST_MODE";
// insert
java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
this.set("createDateTime", now);
this.set("createUsername", user);
this.set("updateDateTime", now);
this.set("updateUsername", user);
this.set("updateTimeId", 1);
this.validate();
if(this.hasErrors()){
throw new ValidationException(this);
}
boolean inserted = super.insert();
if (!inserted)
throw new CecilErrorsException(new CecilMessage().error("Failed to insert " + this.getClass().getSimpleName()));
return inserted;
}
public boolean updateIt(String user) {
user = (CLArgs.args.isAuthenabled()) ? user : "TEST_MODE";
// update
java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
this.set("updateDateTime", now);
this.set("updateUsername", user);
this.incrementUpdateTimeId();
this.validate();
if(this.hasErrors()){
throw new ValidationException(this);
}
boolean updated = super.save();
if (!updated)
throw new CecilErrorsException(new CecilMessage().error("Failed to update " + this.getClass().getSimpleName()));
return updated;
}
#Override
public <T extends Model> T set(String field, Object value) {
if (value instanceof LocalDate) {
return super.set(field, java.sql.Date.valueOf((LocalDate)value));
} else if (value instanceof LocalDateTime) {
return super.set(field, java.sql.Timestamp.valueOf((LocalDateTime)value));
} else {
return super.set(field, value);
}
}
public LocalDate getLocalDate(String field) {
if (field == null || "".equals(field))
return null;
else {
java.sql.Date d = getDate(field);
return d == null ? null : d.toLocalDate();
}
}
public void setLocalDate(String field, LocalDate value) {
if (value == null)
setDate(field, null);
else
setDate(field, java.sql.Date.valueOf(value));
}
public LocalDateTime getLocalDateTime(String field) {
java.sql.Timestamp d = getTimestamp(field);
return d == null ? null : d.toLocalDateTime();
}
public void setLocalDateTime(String field, LocalDateTime value) {
if (value == null)
setTimestamp(field, null);
else
setTimestamp(field, java.sql.Timestamp.valueOf(value));
}
}
The method Model.saveIt() will save the model attributes to a table if such a record (according to primary keys) already exists. If you are setting the primary keys to values not found in the database, this method will exit without doing much.
Additionally, there are a few issues in your code that are not idiomatic of JavaLite.
Update: based on your comment below, the framework will update the record if it is not "new", meaning if the PK or Composite Keys are not null, it will assume that you know what you are doing and will expect to find that record in the table by primary or composite keys, therefore if they key(s) are set and not null, it will always generate an UPDATE rather than insert. As a result, if you are setting primary keys to values not present in the table, the saveIt() or save() will do nothing. Please, see http://javalite.io/surrogate_primary_keys for more information.
Additionally, you can enable Logging to see what SQL it generates.

AbstractStringBuilder.ensureCapacityInternal get NullPointerException in storm bolt

online system, the storm Bolt get NullPointerException,though I think I check it before line 61; It gets NullPointerException once in a while;
import ***.KeyUtils;
import ***.redis.PipelineHelper;
import ***.redis.PipelinedCacheClusterClient;
import **.redis.R2mClusterClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Map;
/**
* RedisBolt batch operate
*/
public class RedisBolt implements IRichBolt {
static final long serialVersionUID = 737015318988609460L;
private static ApplicationContext applicationContext;
private static long logEmitNumber = 0;
private static StringBuffer totalCmds = new StringBuffer();
private Logger logger = LoggerFactory.getLogger(getClass());
private OutputCollector _collector;
private R2mClusterClient r2mClusterClient;
#Override
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
_collector = outputCollector;
if (applicationContext == null) {
applicationContext = new ClassPathXmlApplicationContext("spring/spring-config-redisbolt.xml");
}
if (r2mClusterClient == null) {
r2mClusterClient = (R2mClusterClient) applicationContext.getBean("r2mClusterClient");
}
}
#Override
public void execute(Tuple tuple) {
String log = tuple.getString(0);
String lastCommands = tuple.getString(1);
try {
//log count
if (StringUtils.isNotEmpty(log)) {
logEmitNumber++;
}
if (StringUtils.isNotEmpty(lastCommands)) {
if(totalCmds==null){
totalCmds = new StringBuffer();
}
totalCmds.append(lastCommands);//line 61
}
//日志数量控制
int numberLimit = 1;
String flow_log_limit = r2mClusterClient.get(KeyUtils.KEY_PIPELINE_LIMIT);
if (StringUtils.isNotEmpty(flow_log_limit)) {
try {
numberLimit = Integer.parseInt(flow_log_limit);
} catch (Exception e) {
numberLimit = 1;
logger.error("error", e);
}
}
if (logEmitNumber >= numberLimit) {
StringBuffer _totalCmds = new StringBuffer(totalCmds);
try {
//pipeline submit
PipelinedCacheClusterClient pip = r2mClusterClient.pipelined();
String[] commandArray = _totalCmds.toString().split(KeyUtils.REDIS_CMD_SPILT);
PipelineHelper.cmd(pip, commandArray);
pip.sync();
pip.close();
totalCmds = new StringBuffer();
} catch (Exception e) {
logger.error("error", e);
}
logEmitNumber = 0;
}
} catch (Exception e) {
logger.error(new StringBuffer("====RedisBolt error for log=[ ").append(log).append("] \n commands=[").append(lastCommands).append("]").toString(), e);
_collector.reportError(e);
_collector.fail(tuple);
}
_collector.ack(tuple);
}
#Override
public void cleanup() {
}
#Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
}
#Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
exception info:
java.lang.NullPointerException at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:113) at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:415) at java.lang.StringBuffer.append(StringBuffer.java:237) at com.jd.jr.dataeye.storm.bolt.RedisBolt.execute(RedisBolt.java:61) at org.apache.storm.daemon.executor$fn__5044$tuple_action_fn__5046.invoke(executor.clj:727) at org.apache.storm.daemon.executor$mk_task_receiver$fn__4965.invoke(executor.clj:459) at org.apache.storm.disruptor$clojure_handler$reify__4480.onEvent(disruptor.clj:40) at org.apache.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:472) at org.apache.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:451) at org.apache.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:73) at org.apache.storm.daemon.executor$fn__5044$fn__5057$fn__5110.invoke(executor.clj:846) at org.apache.storm.util$async_loop$fn__557.invoke(util.clj:484) at clojure.lang.AFn.run(AFn.java:22) at java.lang.Thread.run(Thread.java:745)
can anyone give me some advice to find the reason.
That is really odd thing to happen. Please read the code for two classes.
https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/lang/AbstractStringBuilder.java
https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/lang/StringBuffer.java
AbstractStringBuilder has constructor with no args which doesn't allocate the field 'value', which makes accessing the 'value' field being NPE. Any constructors in StringBuffer use that constructor. So maybe some odd thing happens in serialization/deserialization and unfortunately 'value' field in AbstractStringBuilder is being null.
Maybe initializing totalCmds in prepare() would be better, and also you need to consider synchronization (thread-safety) between bolts. prepare() can be called per bolt instance so fields are thread-safe, but class fields are not thread-safe.
I think I find the problem maybe;
the key point is
"StringBuffer _totalCmds = new StringBuffer(totalCmds);" and " totalCmds.append(lastCommands);//line 61"
when new a object, It takes serval steps:
(1) allocate memory and return reference
(2) initialize
if append after (1) and before (2) then the StringBuffer.java extends AbstractStringBuilder.java
/**
* The value is used for character storage.
*/
char[] value;
value is not initialized;so this will get null:
#Override
public synchronized void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > value.length) {
expandCapacity(minimumCapacity);
}
}
this blot has a another question, some data maybe lost under a multithreaded environment

Exception in thread "pool-1-thread-7" java.lang.NullPointerException

I'm trying to figure it out y i get this exception as i wrote in the title.
i'm building a multi thread MMU (memory management unit) project, first i initialize and add some pages into the ram and to my HD also and then i create processes and running all the system. a bit of information about the project:
into runConfig i;m reading a json file with a list of processCycles and every processCycles including a list of processCycle that including a list of pageIds with a list of data of those pages.
i think i did everything ok but still i get this exception, can somebody help me?
MMUDriver is the class that run all the systems:
package hit.driver;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
import com.hit.algorithm.IAlgoCache;
import com.hit.algorithm.LRUAlgoCacheImpl;
import com.hit.algorithm.MRUAlgoCacheImpl;
import com.hit.algorithm.RandomReplacementAlgoCacheImpl;
import hit.memoryunits.HardDisk;
import hit.memoryunits.MemoryManagementUnit;
import hit.memoryunits.MemoryManagementUnitTest;
import hit.memoryunits.Page;
import hit.processes.ProcessCycles;
import hit.processes.Process;
import hit.processes.RunConfiguration;
#SuppressWarnings("unused")
public class MMUDriver {
private static final String CONFIG_FILE_NAME="Configuration.json";
// private static final String CONFIG_FILE_NAME="test.json";
//read from JSON file the lists of processCycles
private static RunConfiguration readConfigurationFile() throws JsonIOException, JsonSyntaxException, FileNotFoundException{
RunConfiguration runConfig = new Gson().fromJson(new JsonReader(new FileReader(CONFIG_FILE_NAME)), RunConfiguration.class);
return runConfig;
}
//
private static List<Process> createProcesses(List<ProcessCycles> processCycles,MemoryManagementUnit mmu ){
int i=0;
List<Process> processList = new ArrayList<Process>();
for ( ProcessCycles currentListProcess : processCycles) {
Process process = new Process(++i , mmu , currentListProcess);
processList.add(process);
}
return processList;
}
//
private static void runProcesses(List<Process> processes){
//Executor is a interface that take care of threads מתי מתחיל טרד מתי נגמר איך הם ירוצו במקביל וכו'
//thread pool - אוסף של threads
ExecutorService executorservice = Executors.newCachedThreadPool();
for (Process process : processes)
executorservice.execute(process);
executorservice.shutdown();//
}
//
public static void main(String[] args) throws java.lang.InterruptedException,
InvocationTargetException, JsonIOException, JsonSyntaxException, ClassNotFoundException, IOException{
CLI cli = new CLI(System.in,System.out);
String [] configuration;
while((configuration = cli.getConfiguration()) != null){
IAlgoCache<Long, Long> algo = null;
int capacity = Integer.valueOf(configuration[1]);
switch(configuration[0]){ //which configuration to play on LRU|MRU|RR
case "LRU":
algo = new LRUAlgoCacheImpl<Long, Long>(capacity);
break;
case "MRU":
algo = new MRUAlgoCacheImpl<Long, Long>(capacity);
break;
case "RR":
algo = new RandomReplacementAlgoCacheImpl<Long, Long>(capacity);
break;
}
MemoryManagementUnit mmu = new MemoryManagementUnit(algo, capacity);
MemoryManagementUnitTest.test(mmu);//add some pages to ram for test
RunConfiguration runConfig = readConfigurationFile(); //Getting the user request pages throw json file
List<ProcessCycles> processCycles = runConfig.getProcessesCycles();
List<Process> processes = createProcesses(processCycles , mmu);
runProcesses(processes);
Map<Long, Page<byte[]>> bla= mmu.getRam().getRamPages();
System.out.println("1");
// mmu.shoutDown();
}
}
}
Process is like a thread in this project
package hit.processes;
import java.io.IOException;
import java.util.List;
import hit.memoryunits.MemoryManagementUnit;
import hit.memoryunits.Page;
#SuppressWarnings("unused")
public class Process implements Runnable {
private int id;
private MemoryManagementUnit mmu;
private ProcessCycles processCycles;
private Thread processThread=null;
public Process(int id, MemoryManagementUnit mmu, ProcessCycles processCycles){
this.id=id;
this.mmu=mmu;
this.processCycles=processCycles;
}
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
/*
public void start(){
if(processThread==null)
processThread = new Thread(this,"process"); //
processThread.start();
}*/
#Override
public void run() {
synchronized(mmu){
//runing on all the list of processCycles
for (ProcessCycle currentProcessCycle : processCycles.getProcessCycles()) {
List<Long> pages = currentProcessCycle.getPages();
List<byte[]> data = currentProcessCycle.getData();
Page<byte[]>[] pagesList = null;
//creating a boolean array to know if the page is for writing or reading in size of pages.size()
boolean [] writePages = new boolean[pages.size()];
for (int i = 0; i < pages.size(); i++)
if(data.get(i) == null) //if the page is empty
writePages[i] = false;
else{
writePages[i] = true ;//if there is data in the page and we want to write it to the ram
}
try {
// Getting the pages from ram to see which we shall update
pagesList = mmu.getPages(pages.toArray(new Long[pages.size()]), writePages);
}
catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
for (int j = 0; j < pages.size(); j++)
if(writePages[j] == true) //if the page isn't for read only
pagesList[j].setContent(data.get(j));
try {
Thread.sleep(currentProcessCycle.getSleepMs());
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
MMU class is that class that take care of all the requests from the user and manage all the pagging
package hit.memoryunits;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.hit.algorithm.IAlgoCache;
public class MemoryManagementUnit {
private IAlgoCache<Long,Long> algo;
private RAM<Long, Page<byte[]>> ram;
public MemoryManagementUnit(IAlgoCache<Long, Long> algo, int ramCapacity) {
this.algo = algo;
this.ram= new RAM<Long, Page<byte[]>>(ramCapacity);
}
#SuppressWarnings("null")
public Page<byte[]> [] getPages(Long [] pageIds , boolean [] writePages) throws IOException, ClassNotFoundException{
for (int i = 0; i < pageIds.length; i++) {
if(algo.getElement((long) pageIds[i].hashCode())== null)//the page isn't exist in the cache
if(!ram.isFull())
{
if(writePages[i] == true){//if the page is for write we need to overwrite data
Page<byte[]> pageToRam = null;
pageToRam.setPageId(pageIds[i]);
pageToRam.setContent(null);
ram.addPage(pageToRam);// ram is not full need to upload from hd
}
else{//if the page is for read-only so we need to upload the page from HD
ram.addPage(HardDisk.getInstance().pageFault(pageIds[i]));// ram is not full need to upload from hd
}
algo.putElement(Long.valueOf(pageIds[i].hashCode()),pageIds[i]);//update cache
}
else
{
Page<byte[]> pageToRemove = ram.getPage(algo.putElement(Long.valueOf(pageIds[i].hashCode()),pageIds[i]));
ram.removePage(pageToRemove);
ram.addPage(HardDisk.getInstance().pageReplacement(pageToRemove,pageIds[i]));// ram full need to do replacement
algo.putElement(Long.valueOf(pageIds[i].hashCode()),pageIds[i]);//update cache
}
}
return ram.getPages(pageIds);
}
public RAM<Long, Page<byte[]>> getRam(){
return ram;
}
public IAlgoCache<Long,Long> getAlgo(){
return algo;
}
public void setAlgo(IAlgoCache<Long,Long> algo){
this.algo = algo;
}
public void setRam(RAM<Long, Page<byte[]>> ram){
this.ram = ram;
}
public void shoutDown() throws FileNotFoundException, IOException, ClassNotFoundException{
HardDisk.getInstance().saveToDisk(this.getRam().getRamPages());
}
}

Spigot Plugin - Cannot Build 1.10

I have created a Spigot plugin in 1.10. It is mostly essentials but I added in a compass inventory GUI and you receive it when you first log in. For some odd reason after I implemented this you cannot obtain items in your inventory, they instantly go away. The class for the GUI is below
package me.Roofah.Essentials;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Essentials extends JavaPlugin implements Listener{
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
this.getCommand("teleport").setExecutor(new Teleport(this));;
this.getCommand("vanish").setExecutor(new Vanish(this));;
this.getCommand("unvanish").setExecutor(new Vanish(this));;
Bukkit.getServer().getLogger().info("Teleport Plugin Enabled!");
}
public Player getPlayer(String name) {
for(Player p : Bukkit.getOnlinePlayers()) {
if(p.getName().equalsIgnoreCase(name))
return p;
}
return null;
}
public void onDisable() {
Bukkit.getServer().getLogger().info("Teleport Plugin Disabled!");
}
private void teleportInWord(Player player, int x, int y, int z) {
player.teleport(new Location(player.getWorld(), x, y, z));
}
private void openGUI(Player player) {
Inventory inv = Bukkit.createInventory(null, 9, ChatColor.DARK_RED + "Warp Selector || By Roofah");
ItemStack Spawn = new ItemStack(Material.DIAMOND_AXE);
ItemMeta SpawnMeta = Spawn.getItemMeta();
ItemStack Build = new ItemStack(Material.DIAMOND_PICKAXE);
ItemMeta BuildMeta = Build.getItemMeta();
SpawnMeta.setDisplayName(ChatColor.DARK_RED + "Spawn");
Spawn.setItemMeta(SpawnMeta);
BuildMeta.setDisplayName(ChatColor.GREEN + "Build");
Build.setItemMeta(BuildMeta);
// 35
inv.setItem(3, Spawn);
inv.setItem(5, Build);
player.openInventory(inv);
}
#EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase("Warp Selector")) {
return;
}
Player player = (Player) event.getWhoClicked();
event.setCancelled(true);
if (event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR
|| !event.getCurrentItem().hasItemMeta()) {
player.closeInventory();
return;
}
switch(event.getCurrentItem().getType()){
case DIAMOND_AXE:
teleportInWord(player, 967, 90, 484);
player.closeInventory();
player.sendMessage(String.format("%sTeleported to %sSpawn%s!", ChatColor.GOLD, ChatColor.DARK_RED, ChatColor.GOLD));
break;
case DIAMOND_PICKAXE:
teleportInWord(player, 906, 96, 428);
player.closeInventory();
player.sendMessage(String.format("%sTeleported to %sBUILD%s!", ChatColor.GOLD, ChatColor.GREEN, ChatColor.GOLD));
break;
default:
player.closeInventory();
break;
}
}
#EventHandler
public void onPlayerKoin(PlayerJoinEvent event) {
event.getPlayer().getInventory().addItem(new ItemStack(Material.COMPASS));
}
#EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Action a = event.getAction();
ItemStack is = event.getItem();
if (a == Action.PHYSICAL || is == null || is.getType() == Material.AIR) {
return;
}
if (is.getType() == Material.COMPASS) {
openGUI(event.getPlayer());
}
}
}
There are 2 other classes but I could still obtain blocks without adding in the GUI.
Your situation is a logic mistake at line 73 on your code.
You have the following:
if (ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase("Warp Selector")) //Line 73 {
return;
}
The situation is:
Whenever the inventory name is Warp Selector, return. So your code is only executing when the inventory name is not "Warp Selector".
What you probably want is to invert this logic, so that your code will execute when the inventory name is "Warp Selector".
if (!ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase("Warp Selector") {
return;
}
//Code continues

How to remove all comments from docx file with docx4j?

I'd like to remove all the comments from a docx file using docx4j.
I can remove the actual comments with a piece of code like is shown below, but I think I also need to remove the comment references from the main document part as well (otherwise the document is corrupted), but I can't figure out how to do that.
CommentsPart cmtsPart = wordMLPackage.getMainDocumentPart().getCommentsPart();
org.docx4j.wml.Comments cmts = cpart.getJaxbElement();
List<Comments.Comment> coms = cmts.getComment();
coms.clear();
Any guidance appreciated!
I also posted this question on the docx4j forum: http://www.docx4java.org/forums/docx-java-f6/how-to-remove-all-comments-from-docx-file-t1329.html.
Thanks.
You can use TraversalUtil to find the relevant objects (CommentRangeStart, CommentRangeEnd, R.CommentReference), and then remove them.
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.docx4j.TraversalUtil;
import org.docx4j.TraversalUtil.CallbackImpl;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Body;
import org.docx4j.wml.CommentRangeEnd;
import org.docx4j.wml.CommentRangeStart;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.R.CommentReference;
import org.jvnet.jaxb2_commons.ppp.Child;
public class Foo {
public static void main(String[] args) throws Exception {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(new java.io.File(System.getProperty("user.dir") + "/Foo.docx"));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart
.getJaxbElement();
Body body = wmlDocumentEl.getBody();
CommentFinder cf = new CommentFinder();
new TraversalUtil(body, cf);
for (Child commentElement : cf.commentElements) {
System.out.println(commentElement.getClass().getName());
Object parent = commentElement.getParent();
List<Object> theList = ((ContentAccessor)parent).getContent();
boolean removeResult = remove(theList, commentElement );
System.out.println(removeResult);
}
}
private static boolean remove(List<Object> theList, Object bm) {
// Can't just remove the object from the parent,
// since in the parent, it may be wrapped in a JAXBElement
for (Object ox : theList) {
if (XmlUtils.unwrap(ox).equals(bm)) {
return theList.remove(ox);
}
}
return false;
}
static class CommentFinder extends CallbackImpl {
List<Child> commentElements = new ArrayList<Child>();
#Override
public List<Object> apply(Object o) {
if (o instanceof javax.xml.bind.JAXBElement
&& (((JAXBElement)o).getName().getLocalPart().equals("commentReference")
|| ((JAXBElement)o).getName().getLocalPart().equals("commentRangeStart")
|| ((JAXBElement)o).getName().getLocalPart().equals("commentRangeEnd")
)) {
System.out.println(((JAXBElement)o).getName().getLocalPart());
commentElements.add( (Child)XmlUtils.unwrap(o) );
} else
if (o instanceof CommentReference ||
o instanceof CommentRangeStart ||
o instanceof CommentRangeEnd) {
System.out.println(o.getClass().getName());
commentElements.add((Child)o);
}
return null;
}
#Override // to setParent
public void walkJAXBElements(Object parent) {
List children = getChildren(parent);
if (children != null) {
for (Object o : children) {
if (o instanceof javax.xml.bind.JAXBElement
&& (((JAXBElement)o).getName().getLocalPart().equals("commentReference")
|| ((JAXBElement)o).getName().getLocalPart().equals("commentRangeStart")
|| ((JAXBElement)o).getName().getLocalPart().equals("commentRangeEnd")
)) {
((Child)((JAXBElement)o).getValue()).setParent(XmlUtils.unwrap(parent));
} else {
o = XmlUtils.unwrap(o);
if (o instanceof Child) {
((Child)o).setParent(XmlUtils.unwrap(parent));
}
}
this.apply(o);
if (this.shouldTraverse(o)) {
walkJAXBElements(o);
}
}
}
}
}
}