QueryService in GemFire 8.2.x Function return null values - spring-data

I have created function to select data from Partition region Individual. When I try to execute the function at client side getting null.
output
[[], null]
public class MySelectPartitionFunction extends FunctionAdapter implements Declarable{
private static final long serialVersionUID = 1L;
#Override
public void execute(FunctionContext context) {
Cache cache = CacheFactory.getAnyInstance();
QueryService queryService = cache.getQueryService();
String qstr = (String) context.getArguments();
try {
Query query = queryService.newQuery(qstr);
RegionFunctionContext rContext = (RegionFunctionContext)context;
SelectResults results = (SelectResults) query.execute(rContext);
context.getResultSender().sendResult((ArrayList) (results).asList());
context.getResultSender().lastResult(null);
} catch (Exception e) {
throw new FunctionException(e);
}
}
#Override
public String getId() {
return getClass().getName();
}
#Override
public boolean hasResult() {
return true;
}
#Override
public boolean isHA() {
return false;
}
public void init(Properties arg0) {
}
}
public class TestFunctionQuery {
public static void main(String[] args) {
ResultCollector rcollector = null;
ClientCache cache;
Region<?, ?> individual;
cache = new ClientCacheFactory().set("name", "ClientWorker").set("cache-xml-file", "xml/clientCache.xml")
.create();
individual = cache.getRegion("Individual");
String qStr = "SELECT * FROM /Individual";
try {
Set keyFilter = new HashSet();
keyFilter.add(1);
rcollector = FunctionService
.onRegion(individual)
.withArgs(qStr)
.withFilter(keyFilter)
.execute("com.xxx.logic.MySelectPartitionFunction");
Object result = rcollector.getResult();
ArrayList resultList = (ArrayList)result;
List queryResults = new ArrayList();
if (resultList.size()!=0) {
for (Object obj: resultList) {
if (obj != null) {
queryResults.addAll((ArrayList)obj);
}
}
}
System.out.println((queryResults));
} catch (FunctionException ex) {
System.out.println("Exception");
}
}
}
gfsh>describe region --name=Individual
..........................................................
Name : Individual
Data Policy : partition
Hosting Members : server2
server1
Non-Default Attributes Shared By Hosting Members
Type | Name | Value
--------- | ---------------- | -----
Region | size | 3
Partition | redundant-copies | 1

I was able to retrieve the record after making changes in Function and client code
#Override
public void execute(FunctionContext context) {
Cache cache = CacheFactory.getAnyInstance();
QueryService queryService = cache.getQueryService();
String qstr = (String) context.getArguments();
try {
Query query = queryService.newQuery(qstr);
SelectResults<?> result = (SelectResults<?>) query.execute((RegionFunctionContext) context);
ArrayList<?> arrayResult = (ArrayList<?>) result.asList();
context.getResultSender().sendResult(arrayResult);
context.getResultSender().lastResult(null);
} catch (Exception e) {
throw new FunctionException(e);
}
}
ClientCache cache;
Region<?, ?> individual;
cache = new ClientCacheFactory().set("name", "ClientWorker").set("cache-xml-file", "xml/clientCache.xml")
.create();
individual = cache.getRegion("Individual");
String qStr = "SELECT r1.id,r1.firstName, r1.lastName FROM /Individual r1";
try {
Object result = FunctionService.onRegion(individual)
.withArgs(qStr).execute("com.xxx.logic.MySelectPartitionFunction").getResult();
Output
[[struct(id:2,firstName:Basha,lastName:Shaik), struct(id:1,firstName:Krish,lastName:Chaitu), struct(id:5,firstName:Vigneshwaran,lastName:Ganesan)], null, [struct(id:4,firstName:Arun,lastName:Kishore), struct(id:3,firstName:Anurag,lastName:Kshirsagar)], null]

Related

mybatis interceptor throw Reflection exception affects cpu performence

I had implement a interceptor of myabtis. but we found a problem, execute interceptor lead to throw so many IllegalAccessException, it affects cpu performence
Shown below is where the problem is, why did not check access permision of feild befor executed code "field.get(target)".
public class GetFieldInvoker implements Invoker {
private final Field field;
public GetFieldInvoker(Field field) {
this.field = field;
}
#Override
public Object invoke(Object target, Object[] args) throws IllegalAccessException {
try {
return field.get(target);
} catch (IllegalAccessException e) {
if (Reflector.canControlMemberAccessible()) {
field.setAccessible(true);
return field.get(target);
} else {
throw e;
}
}
}
#Override
public Class<?> getType() {
return field.getType();
}
}
the intercepor of mine:
#Intercepts({
#Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class})
})
public class SqlIdInterceptor implements Interceptor {
private static final int MAX_LEN = 256;
private final RoomboxLogger logger = RoomboxLogManager.getLogger();
#Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
String originalSql = boundSql.getSql();
MappedStatement mappedStatement =
(MappedStatement) metaObject.getValue("delegate.mappedStatement");
String id = mappedStatement.getId();
if (id != null) {
int len = id.length();
if (len > MAX_LEN) {
logger.warn("too long id", "id", id, "len", len);
}
}
String newSQL = "# " + id + "\n" + originalSql;
metaObject.setValue("delegate.boundSql.sql", newSQL);
return invocation.proceed();
}
#SuppressWarnings("unchecked")
public static <T> T realTarget(Object target) {
if (Proxy.isProxyClass(target.getClass())) {
MetaObject metaObject = SystemMetaObject.forObject(target);
return realTarget(metaObject.getValue("h.target"));
}
return (T) target;
}
}
Flame Graph
enter image description here
enter image description here
I need help, how to avoid throw exceptions, is any other way to reslove this problem?
thanks.

Arrayadapter only returning the last element

I'm new to android development and right now I'm trying to parse an J SON array into object and then save each object into a array list then display the array list with a array adapter. But, right now I can only get the array adapter to display the last element.
Here is the main class
public class Venue extends Activity {
Venue_Listing venue = new Venue_Listing();
ArrayList<Venue_Listing> venueList;
ListView listview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.list);
new GetVenus().execute(URL);
venueList = new ArrayList<Venue_Listing>();
}
private class GetVenus extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
String data;
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Venue.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
protected Boolean doInBackground(String... url) {
try {
HttpGet httppost = new HttpGet(url[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
}
return true;
}
catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
Venue_Listing_Adapter adapter = new
Venue_Listing_Adapter(getApplicationContext(),R.layout.venue_list_layout, venueList);
try {
JSONArray jarray = new JSONArray(data);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
if (venue != null) {
venue.SET_ID(object.getString("venue_ID"));
venue.SET_NAME(object.getString("name"));
listview.setAdapter(adapter);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
}
This class holds all the J SON parse data
public class Venue_Listing {
private String ID;
private String NAME;
public Venue_Listing() {
}
public Venue_Listing(String ID, String NAME) {
super();
this.ID = ID;
this.NAME = NAME;
}
// setter & getter....
And here is what I have for my array adapter
public class Venue_Listing_Adapter extends ArrayAdapter<Venue_Listing> {
private ArrayList<Venue_Listing> objects;
public Venue_Listing_Adapter(Context context, int resource, ArrayList<Venue_Listing> objects) {
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.venue_list_layout, null);
}
Venue_Listing i = objects.get(position);
if (i != null) {
TextView id = (TextView) v.findViewById(R.id.id);
TextView name = (TextView) v.findViewById(R.id.name);
if (id != null ){
id.setText(i.GET_ID());
}
if (name != null) {
name.setText(i.GET_NAME());
}
}
return v;
}
}
Any help would be appreciated
Thank you
Please print and check the values of 'venueList'.
You have not added values in 'venueList' object.
You need to create 'venue' object every time and add object 'venue' in 'venueList'. Hence you are not getting all items in list view.
The Code may go this way: -
Venue_Listing venue;
try {
JSONArray jarray = new JSONArray(data);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
venue = new Venue_Listing();
if (object != null) {
venue.SET_ID(object.getString("venue_ID"));
venue.SET_NAME(object.getString("name"));
venueList.add(venue);
}
}
Venue_Listing_Adapter adapter = new Venue_Listing_Adapter(getApplicationContext(),R.layout.venue_list_layout, venueList);
listview.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}

Cannot understand ComboBoxTableCell in a TableView

I have read everything available on this site and others; I have cut and pasted every line of code ever written on this subject ( am willing to bet). This is what the result is:
final class Books extends Group {
private TableView table = new TableView();
private ObservableList<Book> data = FXCollections.observableArrayList();
final HBox hb = new HBox();
final TextField Title = new TextField();
final TextField Author = new TextField();
final TextField Publisher = new TextField();
final TextField Copywrite = new TextField();
final TextField ISBN = new TextField();
final Boolean CheckedOut = false;
final Label Whom;
final Button addButton = new Button("Add");
Boolean FirstRead = true;
public static class Book {
private final SimpleStringProperty title;
private final SimpleStringProperty author;
private final SimpleStringProperty publisher;
private final SimpleStringProperty copywrite;
private final SimpleStringProperty isbn;
private final BooleanProperty checkedout;
private final SimpleStringProperty who;
Book(String Titl, String Auth, String Publ,
String Cpywrit, String IsBn, Boolean ChkdOut, String WHO) {
this.title = new SimpleStringProperty(Titl);
this.author = new SimpleStringProperty(Auth);
this.publisher = new SimpleStringProperty(Publ);
this.copywrite = new SimpleStringProperty(Cpywrit);
this.isbn = new SimpleStringProperty(IsBn);
this.checkedout = new SimpleBooleanProperty(ChkdOut);
this.who = new SimpleStringProperty(WHO);
}
public boolean isCheckedOut() {
return checkedout.get();
}
public void setCheckedOut(boolean international) {
this.checkedout.set(international);
}
public BooleanProperty isCheckedOutProperty() {
return checkedout;
}
public String getTitle() {
return title.get();
}
public void setTitle(String Title) {
title.set(Title);
}
public String getAuthor() {
return author.get();
}
public void setAutor(String Author) {
author.set(Author);
}
public String getPublisher() {
return publisher.get();
}
public void setPublisher(String Publisher) {
publisher.set(Publisher);
}
public String getCopywrite() {
return copywrite.get();
}
public void setCopywrite(String Copywrite) {
copywrite.set(Copywrite);
}
public String getIsbn() {
return isbn.get();
}
public void setIsbn(String ISBN) {
isbn.set(ISBN);
}
public Boolean getIo() {
return checkedout.get();
}
public void setIo(Boolean CheckedOut) {
checkedout.set(CheckedOut);
}
public String getWho() {
return who.get();
}
public void setWho(String Who) {
who.set(Who);
}
public ObservableValue<String> whoProperty() {
return who;
}
}
public Books(final File User) throws IOException {
this.Whom = new Label("inLibrary");
this.data = FXCollections.<Book>observableArrayList(
(Book bk) -> new Observable[]{bk.isCheckedOutProperty()
});
final PhoneList p = new PhoneList(User);
final Label label = new Label("Book List");
label.setFont(new Font("Arial", 20));
table.setPrefSize(600, 400);
table.setEditable(true);
TableColumn nameCol = bookName();
TableColumn authorCol = bookAuthor();
TableColumn publisherCol = bookPublisher();
TableColumn copywriteCol = bookCopywrite();
TableColumn isbnCol = bookISBN();
final TableColumn<Book, Boolean> ioCol = new TableColumn<>("In/Out");
ioCol.setMinWidth(50);
ioCol.setEditable(true);
ioCol.setCellValueFactory(new PropertyValueFactory<>("isCheckedOut"));
final Callback<TableColumn<Book, Boolean>, TableCell<Book, Boolean>> iocellFactory = CheckBoxTableCell.forTableColumn(ioCol);
ioCol.setCellFactory((TableColumn<Book, Boolean> column) -> {
TableCell<Book, Boolean> iocell = iocellFactory.call(column);
iocell.setAlignment(Pos.CENTER);
return iocell;
});
ioCol.setCellFactory(iocellFactor
final TableColumn<String, Book> whoCol = new TableColumn<>("Who to");
whoCol.setMinWidth(100);
whoCol.setEditable(true);
whoCol.setCellValueFactory(new PropertyValueFactory<>("who"));
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {
#Override
public String toString(Book string) {
return string.getWho();
}
#Override
public Book fromString(String string) {
return null;
}
}, data));
AddBook(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol, User);
data.addListener((javafx.collections.ListChangeListener.Change<? extends Book> change) -> {
while (change.next()) {
if (change.wasUpdated() && FirstRead != true) {
try {
System.out.println("List changed");
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);
getChildren().addAll(vbox);
try {
readFile(User);
} catch (Exception ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
private TableColumn bookISBN() {
TableColumn isbnCol = new TableColumn("ISBN #");
isbnCol.setMinWidth(100);
isbnCol.setCellValueFactory(
new PropertyValueFactory<>("isbn"));
isbnCol.setCellFactory(TextFieldTableCell.forTableColumn());
return isbnCol;
}
private TableColumn bookCopywrite() {
TableColumn copywriteCol = new TableColumn("Copywrite");
copywriteCol.setMinWidth(100);
copywriteCol.setCellValueFactory(
new PropertyValueFactory<>("copywrite"));
copywriteCol.setCellFactory(TextFieldTableCell.forTableColumn());
return copywriteCol;
}
private TableColumn bookPublisher() {
TableColumn publisherCol = new TableColumn("Publisher");
publisherCol.setMinWidth(100);
publisherCol.setCellValueFactory(
new PropertyValueFactory<>("publisher"));
publisherCol.setCellFactory(TextFieldTableCell.forTableColumn());
return publisherCol;
}
private TableColumn bookAuthor() {
TableColumn authorCol = new TableColumn("Author");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(
new PropertyValueFactory<>("author"));
authorCol.setCellFactory(TextFieldTableCell.forTableColumn());
return authorCol;
}
private TableColumn bookName() {
TableColumn nameCol = new TableColumn("Title");
nameCol.setMaxWidth(100);
nameCol.setCellValueFactory(
new PropertyValueFactory<>("title"));
nameCol.setCellFactory(TextFieldTableCell.forTableColumn());
return nameCol;
}
private void AddBook(TableColumn nameCol, TableColumn authorCol, TableColumn publisherCol,
TableColumn copywriteCol, TableColumn isbnCol, TableColumn ioCol, TableColumn whoCol, final File User) {
table.setItems(data);
table.getColumns().addAll(nameCol, authorCol, publisherCol, copywriteCol, isbnCol, ioCol, whoCol);
addButton.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
addBook();
try {
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void addBook() {
data.add(new Book(
Title.getText(),
Author.getText(),
Publisher.getText(),
Copywrite.getText(),
ISBN.getText(),
CheckedOut,
Whom.getText()
));
Title.clear();
Author.clear();
Publisher.clear();
Copywrite.clear();
ISBN.clear();
}
});
hb.getChildren().addAll(Title, Author, Publisher,
Copywrite, ISBN, addButton);
hb.setSpacing(10);
Title.setPromptText("Tile of Book");
Title.setMaxWidth(nameCol.getPrefWidth());
Author.setMaxWidth(authorCol.getPrefWidth());
Author.setPromptText("Author");
Publisher.setMaxWidth(publisherCol.getPrefWidth());
Publisher.setPromptText("Publisher");
Copywrite.setMaxWidth(copywriteCol.getPrefWidth());
Copywrite.setPromptText("Year Copywrite");
ISBN.setMaxWidth(isbnCol.getPrefWidth());
ISBN.setPromptText("ISBN #");
}
private void writeFile(File User) throws IOException {
File file = new File(User + "/Books.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
if (table.getItems() != null) {
data.stream().map((data1) -> {
if (data1.getTitle().equals("")) {
data1.setTitle("No_Title");
}
return data1;
}).map((data1) -> {
if (data1.getAuthor().equals("")) {
data1.setAutor("No_Author");
}
return data1;
}).map((data1) -> {
if (data1.getPublisher().equals("")) {
data1.setPublisher("No_Publisher");
}
return data1;
}).map((data1) -> {
if (data1.getCopywrite().equals("")) {
data1.setCopywrite("No_Copywrite");
}
return data1;
}).map((data1) -> {
if (data1.getIsbn().equals("")) {
data1.setIsbn("No_ISBN");
}
return data1;
}).map((data1) -> {
if (data1.getWho().equals("")) {
data1.setWho("InLibrary");
}
return data1;
}).map((data1) -> {
outFile.println(data1.getTitle());
return data1;
}).map((data1) -> {
outFile.println(data1.getAuthor());
return data1;
}).map((data1) -> {
outFile.println(data1.getPublisher());
return data1;
}).map((data1) -> {
outFile.println(data1.getCopywrite());
return data1;
}).map((data1) -> {
outFile.println(data1.getIsbn());
return data1;
}).map((data1) -> {
outFile.println(data1.getIo());
return data1;
}).forEach((data1) -> {
outFile.println(data1.getWho());
});
outFile.close();
}
}
private void readFile(File User) throws Exception {
try {
String name, author, publisher, copywrite, isbn, whom;
Boolean InOut;
try (Scanner inFile = new Scanner(new File(User + "/Books.txt"))) {
while (inFile.hasNextLine()) {
name = inFile.next();
author = inFile.next();
publisher = inFile.next();
copywrite = inFile.next();
isbn = inFile.next();
InOut = inFile.nextBoolean();
whom = inFile.next();
data.add(new Book(name, author, publisher, copywrite,
isbn, InOut, whom));
}
}
table.setItems(data);
} //insert catch statements
catch (FileNotFoundException exception) {
System.out.println("File not found");
} catch (ArrayIndexOutOfBoundsException AIOOBexception) {
System.out.println("Array Index is out of bounds");
} catch (IllegalArgumentException IAexception) {
System.out.println("Divide by zero error");
} catch (NoSuchElementException NAexception) {
}
FirstRead = false;
}
}
This gives the following error:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: mediatracker.Books$Book cannot be cast to java.lang.String
at mediatracker.Books$1.toString(Books.java:198)
Line 198 starts:
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {
Can anyone type in the "theory" behind the ComboBoxTableCell, and list the parts necessary to accomoplish this. All I want to do is to change the value of the cell extracted from a PhoneList in another file.
I'm just going to assume that line 198 is
return (String) object ;
in the anonymous StringConverter's toString() method. When you post a question with a stack trace, always indicate which is the line in your code to which the exception is pointing.
First, it's always better to use generic types instead of raw types. So instead of
TableColumn whoCol = ...
you should have
TableColumn<S,T> whoCol = ...
where you replace S with the type of the data in the table and T with the type of the data in the column. Since you haven't given a complete example, I have no way of guessing what S is; from the error message it looks like the type of the data in the column might be Book.
Read the Javadocs for the method you are calling. They clearly state what the converter is:
converter - A StringConverter to convert the given item (of type T) to
a String for displaying to the user.
So, assuming that your TableColumn is displaying Books, and assuming data is of type ObservableList<Book>, you should have something like
ObservableList<Book> data = ... ;
TableColumn<S, Book> whoCol = new TableColumn<>("Who to");
// ...
whoCol.setCellFactory(ComboBoxTableCell.forTableColumn(new StringConverter<Book>() {
#Override
public String toString(Book book) {
// assuming your Book class defines a getTitle() method, and that's
// how you want to display it in your ComboBox:
return book.getTitle(); // or get a String from book some other way
}
#Override
public Book fromString(String string) {
// I think this is not actually used, as the combo box is not editable
// So you could probably safely just return null here.
// But in general:
Book book = ... ; // create a book from the string
return book ;
}
}, data));
Again, you replace S by whatever you are using for the type of the TableView; and again I had to make guesses at the type of your TableColumn as you didn't provide a complete example. But this should be enough for you to get the idea.
`final TableColumn<Book, String> whoCol = new TableColumn<>("Who to");
whoCol.setMinWidth(100);
whoCol.setEditable(true);
whoCol.setCellValueFactory(new PropertyValueFactory<>("who"));
whoCol.setCellFactory(ComboBoxTableCell.<Book, String>forTableColumn(p.data.get(myIndex()).toString()));
whoCol.setOnEditCommit((TableColumn.CellEditEvent<Book, String> t) -> {
((Book) t.getTableView().getItems().get(
t.getTablePosition().getRow()))
.setWho(t.getNewValue());
try {
writeFile(User);
} catch (IOException ex) {
Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
}
});`
This works - #James_D thank you for your aid - you sent me in the right direction
Your problems don't seem to have anything to do with a ComboBoxTableCell.
Your toString() method is wrong; you're trying to cast an Object to a String. That's (probably) why you're seeing a java.lang.ClassCastException. Can you verify which line is line 198?
Also, I notice all your fromString() method does is return its argument. What exactly are you trying to achieve here in this code snippet? Can you give us a little more background information?

Jenkins plugin development - persistence

I'm still learning plugin dev. This is my first one.
I would like to persist the configuration of my plugin, but it won't work.
Could you please tell me, what am I doing wrong?
I have tried debuging the process, starting from the addition of the plugin to the job 'til the saving of the job config.
I have found, that inside the load() method of the descriptor, no xml file is found!
The path it is looking for is something like: c:\users\Peter\workspace\r-script.\work\whatEverDir\xy.xml
I don't think that the .\ part is causing the config file not to be found, but since it is a Jenkins class generating this path, I would not bet on it. Although the system might have tried to create it here at the first place.
Thanks in advance!
Scriptrunner.jelly
<f:block>
<f:entry title="RScript" field="command">
<f:textarea style="width:99%" />
</f:entry>
</f:block>
<f:entry field="installedPackages" title="Installed packages">
<f:select style="width:40%" />
</f:entry>
<f:entry field="mirrors" title="Choose a mirror">
<f:select style="width:40%" />
</f:entry>
<f:entry>
<f:repeatableProperty field="availablePackages" minimum="1"/>
</f:entry>
AvailablePackage.jelly
<f:entry field="availablePackages">
<f:select style="width:40%" />
<f:repeatableDeleteButton />
</f:entry>
ScriptRunner.java
public class ScriptRunner extends Builder {
private static final String fileExtension = ".R";
private ArrayList<AvailablePackage> availablePackages;
private String command;
private String chosenMirror;
private List<String> mirrorList = new ArrayList<String>();
#DataBoundConstructor
public ScriptRunner(String command, ArrayList<String> installedPackages, ArrayList<String> mirrors, ArrayList<AvailablePackage> availablePackages) {
this.chosenMirror = mirrors.get(0);
this.availablePackages = availablePackages;
this.command = command;
}
public final String getCommand() {
return command;
}
#Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException {
return perform(build, launcher, (TaskListener) listener);
}
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
TaskListener listener) throws InterruptedException {
FilePath workSpace = build.getWorkspace();
FilePath rScript = null;
if (workSpace == null) {
try {
throw new NoSuchFileException("Workspace could not be set!");
} catch (NoSuchFileException e) {
e.printStackTrace();
}
}
try {
try {
String fullScript;
if (command.contains("options(repos=structure(")) {
fullScript = PackagesManager.singleton().createFullScript(availablePackages, "", command);
} else {
fullScript = PackagesManager.singleton().createFullScript(availablePackages, chosenMirror, command);
}
rScript = workSpace.createTextTempFile("RScriptTemp",
getFileExtension(), fullScript, false);
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToProduceScript()));
return false;
}
boolean successfullyRan = false;
try {
EnvVars envVars = build.getEnvironment(listener);
for (Map.Entry<String, String> e : build.getBuildVariables()
.entrySet()) {
envVars.put(e.getKey(), e.getValue());
}
if (launcher.launch().cmds(buildCommandLine(rScript))
.envs(envVars).stdout(listener).pwd(workSpace).join() == 1) {
successfullyRan = true;
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_CommandFailed()));
}
return successfullyRan;
} finally {
try {
if (rScript != null) {
rScript.delete();
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToDelete(rScript)));
} catch (Exception e) {
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToDelete(rScript)));
}
}
}
public String[] buildCommandLine(FilePath script) {
return new String[] { "Rscript", script.getRemote() };
}
protected String getFileExtension() {
return fileExtension;
}
public List<String> getMirrorList() {
return mirrorList;
}
public void setMirrorList(List<String> mirrorList) {
this.mirrorList = mirrorList;
}
public String getChosenMirror() {
return chosenMirror;
}
public void setChosenMirror(String chosenMirror) {
this.chosenMirror = chosenMirror;
}
public ArrayList<AvailablePackage> getAvailablePackages() {
return availablePackages;
}
#Override
public ScriptBuildStepDescriptorImplementation getDescriptor() {
return (ScriptBuildStepDescriptorImplementation)super.getDescriptor();
}
#Extension
public static class ScriptBuildStepDescriptorImplementation extends
BuildStepDescriptor<Builder> {
private boolean showInstalled;
private String command;
private String chosenMirror;
private ArrayList<AvailablePackage> availablePackages;
public ScriptBuildStepDescriptorImplementation() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
#Override
public String getDisplayName() {
return "Advanced R script runner";
}
#Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public ListBoxModel doFillInstalledPackagesItems() {
ListBoxModel mirrors = new ListBoxModel();
Set<String> mirrorsList = PackagesManager.singleton()
.getInstalledPackages();
for (String entry : mirrorsList) {
mirrors.add(entry);
}
return mirrors;
}
public ListBoxModel doFillAvailablePackagesItems() {
ListBoxModel packages = new ListBoxModel();
List<String> packageList = PackagesManager.singleton().getAvailablePackages();
Set<String> alreadyInstalled = PackagesManager.singleton().getInstalledPackages();
for (String entry : packageList) {
if (!alreadyInstalled.contains(entry)) {
packages.add(entry);
}
}
return packages;
}
public ListBoxModel doFillMirrorsItems() {
ListBoxModel mirrors = new ListBoxModel();
String[] mirrorsList = MirrorManager.singleton().getMirrors();
int selected = 34;
for (int i = 0; i < mirrorsList.length; i++) {
String[] splitCurrent = mirrorsList[i].split(" - ");
if (chosenMirror != null && chosenMirror.equals(splitCurrent[1])) {
selected = i;
}
mirrors.add(splitCurrent[1], splitCurrent[0]);
}
mirrors.get(selected).selected = true;
return mirrors;
}
public boolean getShowInstalled() {
return showInstalled;
}
public void setShowInstalled(boolean showInstalled) {
this.showInstalled = showInstalled;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getChosenMirror() {
return chosenMirror;
}
public void setChosenMirror(String chosenMirror) {
this.chosenMirror = chosenMirror;
}
}
}
AvailablePackage.java
public class AvailablePackage extends AbstractDescribableImpl<AvailablePackage> {
private String name;
#DataBoundConstructor
public AvailablePackage(String availablePackages) {
this.name = availablePackages;
}
public String getName() {
return name;
}
#Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
#Extension
public static class DescriptorImpl extends Descriptor<AvailablePackage> {
private String name;
public DescriptorImpl() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
public ListBoxModel doFillAvailablePackagesItems() {
return PackagesManager.singleton().getAvailablePackagesAsListBoxModel(name);
}
#Override
public String getDisplayName() {
return "";
}
public String getName() {
return name;
}
}
}
Sorry for the code formatting! First timer at stackoverflow code posting.
I think you may need to comment this line out
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
//return super.configure(req,formData);
return true;
}
as it will then save again but with no fields.
A good place to locate Jenkins plugin examples is in https://github.com/jenkinsci

URL issue in Facebook in BlackBerry

I have integrated Facebook in my app and trying to share some content.When I call FaceBookMain() ,it shows error like :
"Success
SECURITY WARNINNG:Please treat the URL above as you would your password and do not share it with anyone."
Sometimes this error comes after login with Facebook in browser(Webview) otherwise it comes just after clicking on share button.
Most important thing here is ,I am not facing this problem in simulator.Sharing with Facebook is working properly in Simulator but not in Device.
I am adding some class files with it:
Here is FacebookMain.java class:
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.UiApplication;
public class FacebookMain implements ActionListener{// extends MainScreen implements ActionListener {
// Constants
public final static String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
public final static String APPLICATION_ID = "406758776102494";//"533918076671162" ;
private final static long persistentObjectId = 0x854d1b7fa43e3577L;
static final String ACTION_ENTER = "updateStatus";
static final String ACTION_SUCCESS = "statusUpdated";
static final String ACTION_ERROR = "error";
private ActionScreen actionScreen;
private PersistentObject store;
private LoginScreen loginScreen;
private LogoutScreen logoutScreen;
private HomeScreen homeScreen;
private UpdateStatusScreen updateStatusScreen;
private RecentUpdatesScreen recentUpdatesScreen;
private UploadPhotoScreen uploadPhotoScreen;
private FriendsListScreen friendsListScreen;
private PokeFriendScreen pokeFriendScreen;
private PostWallScreen postWallScreen;
private SendMessageScreen sendMessageScreen;
private String postMessage;
private FacebookContext fbc;
public static boolean isWallPosted=false;
public static boolean isFacebookScreen = false;
public FacebookMain(String postMessge) {
this.postMessage= postMessge;
isFacebookScreen = true;
checkPermissions();
fbc=new FacebookContext(NEXT_URL, APPLICATION_ID);
loginScreen = new LoginScreen(fbc,"KingdomConnect: "+postMessge);
loginScreen.addActionListener(this);
UiApplication.getUiApplication().pushScreen(loginScreen);
}
private void init() {
store = PersistentStore.getPersistentObject(persistentObjectId);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new FacebookContext(NEXT_URL, APPLICATION_ID));
store.commit();
}
}
fbc = (FacebookContext) store.getContents();
}
private void checkPermissions() {
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if ((original.getPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_INTERNET) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_EMAIL) == ApplicationPermissions.VALUE_ALLOW)) {
return;
}
/*ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_AUTHENTICATOR_API);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_WIFI);*/
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if (acceptance) {
// User has accepted all of the permissions.
return;
} else {
}
}
public void saveContext(FacebookContext pfbc) {
synchronized (store) {
store.setContents(pfbc);
System.out.println(pfbc);
store.commit();
}
}
public void logoutAndExit() {
saveContext(null);
logoutScreen = new LogoutScreen(fbc);
logoutScreen.addActionListener(this);
}
public void saveAndExit() {
saveContext(fbc);
exit();
}
private void exit() {
AppenderFactory.close();
System.exit(0);
}
public void onAction(Action event) {}
}
It is Facebook.java class:
public class Facebook {
protected Logger log = Logger.getLogger(getClass());
public static String API_URL = "https://graph.facebook.com";
public Facebook() {
}
public static Object read(String path, String accessToken) throws FacebookException {
return read(path, null, accessToken);
}
public static Object read(String path, Parameters params, String accessToken) throws FacebookException {
Hashtable args = new Hashtable();
args.put("access_token", accessToken);
args.put("format", "JSON");
if ((params != null) && (params.getCount() > 0)) {
Enumeration paramNamesEnum = params.getParameterNames();
while (paramNamesEnum.hasMoreElements()) {
String paramName = (String) paramNamesEnum.nextElement();
String paramValue = params.get(paramName).getValue();
args.put(paramName, paramValue);
}
}
try {
StringBuffer responseBuffer = HttpClient.getInstance().doGet(API_URL + '/' + path, args);
if (responseBuffer.length() == 0) {
throw new Exception("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Throwable t) {
t.printStackTrace();
throw new FacebookException(t.getMessage());
}
}
public static Object write(String path, Object object, String accessToken) throws FacebookException {
Hashtable data = new Hashtable();
data.put("access_token", accessToken);
data.put("format", "JSON");
try {
JSONObject jsonObject = (JSONObject) object;
Enumeration keysEnum = jsonObject.keys();
while (keysEnum.hasMoreElements()) {
String key = (String) keysEnum.nextElement();
Object val = jsonObject.get(key);
if (!(val instanceof JSONObject)) {
data.put(key, val.toString());
}
}
StringBuffer responseBuffer = HttpClient.getInstance().doPost(API_URL + '/' + path, data);
if (responseBuffer.length() == 0) {
throw new FacebookException("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Exception e) {
throw new FacebookException(e.getMessage());
}
}
public static Object delete(String path, String accessToken) throws FacebookException {
Hashtable data = new Hashtable();
data.put("access_token", accessToken);
data.put("format", "JSON");
data.put("method", "delete");
try {
StringBuffer responseBuffer = HttpClient.getInstance().doPost(API_URL + '/' + path, data);
if (responseBuffer.length() == 0) {
throw new FacebookException("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Exception e) {
throw new FacebookException(e.getMessage());
}
}
}
And it is BrowserScreen.class:
public class BrowserScreen extends ActionScreen {
// int[] preferredTransportTypes = { TransportInfo.TRANSPORT_TCP_CELLULAR, TransportInfo.TRANSPORT_WAP2, TransportInfo.TRANSPORT_BIS_B };
int[] preferredTransportTypes = TransportInfo.getAvailableTransportTypes();//{ TransportInfo.TRANSPORT_BIS_B };
ConnectionFactory cf;
BrowserFieldConfig bfc;
BrowserField bf;
String url;
public BrowserScreen(String pUrl) {
super();
url = pUrl;
cf = new ConnectionFactory();
cf.setPreferredTransportTypes(preferredTransportTypes);
bfc = new BrowserFieldConfig();
bfc.setProperty(BrowserFieldConfig.ALLOW_CS_XHR, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.USER_SCALABLE, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.MDS_TRANSCODING_ENABLED, Boolean.FALSE);
bfc.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
bfc.setProperty(BrowserFieldConfig.VIEWPORT_WIDTH, new Integer(Display.getWidth()));
// bfc.setProperty(BrowserFieldConfig.CONNECTION_FACTORY, cf);
bf = new BrowserField(bfc);
}
public void browse() {
show();
fetch();
}
public void show() {
add(bf);
}
public void fetch() {
bf.requestContent(url);
}
public void hide() {
delete(bf);
}
}
If any body has any clue or want some more related code to get it,please let me know.
do not use secure connection. use http instead of https.
you can refer here
same problem is presented in stackoverflow
facebook warning