diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/activity/newsfeed/NewsFeedFragment.java b/src/activity/newsfeed/NewsFeedFragment.java
index 8a8320e..75e2aad 100644
--- a/src/activity/newsfeed/NewsFeedFragment.java
+++ b/src/activity/newsfeed/NewsFeedFragment.java
@@ -1,189 +1,189 @@
package activity.newsfeed;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import util.GetRequest;
import activity.newsfeed.PullAndLoadListView.OnLoadMoreListener;
import activity.newsfeed.PullToRefreshListView.OnRefreshListener;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.ebay.ebayfriend.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class NewsFeedFragment extends Fragment {
private PullAndLoadListView lv;
private NewsFeedItemAdapter adapter;
protected ImageLoader imageLoader = ImageLoader.getInstance();
Activity activity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsfeed, container, false);
TextView windowTitleView = (TextView) getActivity().findViewById(
R.id.window_title);
- windowTitleView.setText("News Feeding");
+ windowTitleView.setText("News Feed");
this.activity = getActivity();
List<NewsFeedItem> itemList = new ArrayList<NewsFeedItem>();
lv = (PullAndLoadListView) view.findViewById(R.id.listview);
imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
adapter = new NewsFeedItemAdapter(getActivity(), itemList, imageLoader,
lv);
lv.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
new RefreshNewsFeedTask(adapter, lv).execute();
}
});
lv.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
new MoreNewsFeedTask(adapter, lv).execute();
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(getActivity(), ReplyActivity.class);
intent.putExtra("currentNewsFeed", adapter.getItemList().get(position - 1));
getActivity().startActivity(intent);
}
});
lv.setLongClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
LayoutInflater inflater = activity.getLayoutInflater();
View layout = inflater.inflate(R.layout.like_toast, null);
Toast toast = new Toast(activity);
int[] location = new int[2];
view.getLocationOnScreen(location);
toast.setGravity(Gravity.CENTER, location[0], location[1] - 200);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
return true;
}
});
lv.setAdapter(adapter);
new RefreshNewsFeedTask(adapter, lv).execute();
return view;
}
private class RefreshNewsFeedTask extends AsyncTask<Void, Void, List<NewsFeedItem>> {
private NewsFeedItemAdapter adapter;
private PullAndLoadListView lv;
public RefreshNewsFeedTask(NewsFeedItemAdapter adapter, PullAndLoadListView lv) {
this.adapter = adapter;
this.lv = lv;
}
@Override
protected List<NewsFeedItem> doInBackground(Void... params) {
return getNewsFeedList(0);
}
@Override
protected void onPostExecute(List<NewsFeedItem> result) {
super.onPostExecute(result);
adapter.updateList(result);
adapter.resetPage();
lv.onRefreshComplete();
}
}
private class MoreNewsFeedTask extends AsyncTask<Void, Void, List<NewsFeedItem>> {
private NewsFeedItemAdapter adapter;
private PullAndLoadListView lv;
public MoreNewsFeedTask(NewsFeedItemAdapter adapter, PullAndLoadListView lv) {
this.adapter = adapter;
this.lv = lv;
}
@Override
protected List<NewsFeedItem> doInBackground(Void... params) {
int currentPage = adapter.getCurrentPage() + 1;
List<NewsFeedItem> fetchList = getNewsFeedList(currentPage);
if(fetchList.size() > 0) adapter.incrementCurrentPage();
return fetchList;
}
@Override
protected void onPostExecute(List<NewsFeedItem> result) {
super.onPostExecute(result);
List<NewsFeedItem> currentList = adapter.getItemList();
for(NewsFeedItem item: result){
currentList.add(item);
}
adapter.notifyDataSetChanged();
int index = lv.getFirstVisiblePosition();
View v = lv.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
lv.setSelectionFromTop(index, top);
if (result.size() == 0){
lv.notifyNoMore();
}
lv.onLoadMoreComplete();
}
}
private List<NewsFeedItem> getNewsFeedList(int page){
List<NewsFeedItem> list = new ArrayList<NewsFeedItem>();
String getURL = Constants.GET_NEWSFEED_URL_PREFIX + page;
GetRequest getRequest = new GetRequest(getURL);
String jsonResult = getRequest.getContent();
Log.v("NewsFeedFragment", "Request URL: " + getURL);
Log.v("NewsFeedFragment", "Response: " + jsonResult);
if (jsonResult == null) {
Log.e("NewsFeedFragment", "Json Parse Error");
} else {
try {
JSONArray itemArray = new JSONArray(jsonResult);
for (int i = 0; i < itemArray.length(); i++) {
JSONObject item = itemArray.getJSONObject(i);
String imageURL = item.getString("picture");
String voiceURL = item.getString("voice");
JSONObject person = item.getJSONObject("author");
String portraitURL = person.getString("portrait");
String authorName = person.getString("name");
String commentsURL = item.getString("comments");
String goodURL = item.getString("good");
NewsFeedItem newsFeedItem = new NewsFeedItem(imageURL,
portraitURL, authorName, voiceURL, commentsURL, goodURL);
list.add(newsFeedItem);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("NewsFeedFragment", "Parse Json Error");
}
}
return list;
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsfeed, container, false);
TextView windowTitleView = (TextView) getActivity().findViewById(
R.id.window_title);
windowTitleView.setText("News Feeding");
this.activity = getActivity();
List<NewsFeedItem> itemList = new ArrayList<NewsFeedItem>();
lv = (PullAndLoadListView) view.findViewById(R.id.listview);
imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
adapter = new NewsFeedItemAdapter(getActivity(), itemList, imageLoader,
lv);
lv.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
new RefreshNewsFeedTask(adapter, lv).execute();
}
});
lv.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
new MoreNewsFeedTask(adapter, lv).execute();
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(getActivity(), ReplyActivity.class);
intent.putExtra("currentNewsFeed", adapter.getItemList().get(position - 1));
getActivity().startActivity(intent);
}
});
lv.setLongClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
LayoutInflater inflater = activity.getLayoutInflater();
View layout = inflater.inflate(R.layout.like_toast, null);
Toast toast = new Toast(activity);
int[] location = new int[2];
view.getLocationOnScreen(location);
toast.setGravity(Gravity.CENTER, location[0], location[1] - 200);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
return true;
}
});
lv.setAdapter(adapter);
new RefreshNewsFeedTask(adapter, lv).execute();
return view;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsfeed, container, false);
TextView windowTitleView = (TextView) getActivity().findViewById(
R.id.window_title);
windowTitleView.setText("News Feed");
this.activity = getActivity();
List<NewsFeedItem> itemList = new ArrayList<NewsFeedItem>();
lv = (PullAndLoadListView) view.findViewById(R.id.listview);
imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
adapter = new NewsFeedItemAdapter(getActivity(), itemList, imageLoader,
lv);
lv.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
new RefreshNewsFeedTask(adapter, lv).execute();
}
});
lv.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
new MoreNewsFeedTask(adapter, lv).execute();
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(getActivity(), ReplyActivity.class);
intent.putExtra("currentNewsFeed", adapter.getItemList().get(position - 1));
getActivity().startActivity(intent);
}
});
lv.setLongClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
LayoutInflater inflater = activity.getLayoutInflater();
View layout = inflater.inflate(R.layout.like_toast, null);
Toast toast = new Toast(activity);
int[] location = new int[2];
view.getLocationOnScreen(location);
toast.setGravity(Gravity.CENTER, location[0], location[1] - 200);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
return true;
}
});
lv.setAdapter(adapter);
new RefreshNewsFeedTask(adapter, lv).execute();
return view;
}
|
diff --git a/src/web/org/openmrs/web/controller/observation/PersonObsFormController.java b/src/web/org/openmrs/web/controller/observation/PersonObsFormController.java
index 085e6601..1b957d8e 100644
--- a/src/web/org/openmrs/web/controller/observation/PersonObsFormController.java
+++ b/src/web/org/openmrs/web/controller/observation/PersonObsFormController.java
@@ -1,112 +1,114 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.observation;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.Obs;
import org.openmrs.Person;
import org.openmrs.api.ObsService;
import org.openmrs.api.context.Context;
import org.openmrs.util.OpenmrsUtil;
import org.springframework.web.servlet.mvc.SimpleFormController;
/**
* Controller for the page that shows an administrator's view of all a patients observations
* (possibly only for a specified concept)
*/
public class PersonObsFormController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
@Override
protected CommandObject formBackingObject(HttpServletRequest request) throws Exception {
if (!Context.isAuthenticated())
return new CommandObject();
Person person = Context.getPersonService().getPerson(Integer.valueOf(request.getParameter("personId")));
+ List<Concept> concepts = null;
Concept concept = null;
- if (request.getParameter("conceptId") != null)
+ if (request.getParameter("conceptId") != null) {
concept = Context.getConceptService().getConcept(Integer.valueOf(request.getParameter("conceptId")));
+ concepts = Collections.singletonList(concept);
+ }
ObsService os = Context.getObsService();
- List<Obs> ret = concept == null ? os.getObservationsByPerson(person) : os.getObservationsByPersonAndConcept(person,
- concept);
+ List<Obs> ret = os.getObservations(Collections.singletonList(person), null, concepts, null, null, null, null, null, null, null, null, true);
Collections.sort(ret, new Comparator<Obs>() {
public int compare(Obs left, Obs right) {
int temp = left.getConcept().getName().getName().compareTo(right.getConcept().getName().getName());
if (temp == 0)
temp = OpenmrsUtil.compareWithNullAsGreatest(left.getVoided(), right.getVoided());
if (temp == 0)
temp = OpenmrsUtil.compareWithNullAsLatest(left.getObsDatetime(), right.getObsDatetime());
return temp;
}
});
return new CommandObject(person, concept, ret);
}
public class CommandObject {
private Person person;
private Concept concept;
private List<Obs> observations;
public CommandObject() {
}
public CommandObject(Person person, Concept concept, List<Obs> observations) {
super();
this.person = person;
this.concept = concept;
this.observations = observations;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Concept getConcept() {
return concept;
}
public void setConcept(Concept concept) {
this.concept = concept;
}
public List<Obs> getObservations() {
return observations;
}
public void setObservations(List<Obs> observations) {
this.observations = observations;
}
}
}
| false | true | protected CommandObject formBackingObject(HttpServletRequest request) throws Exception {
if (!Context.isAuthenticated())
return new CommandObject();
Person person = Context.getPersonService().getPerson(Integer.valueOf(request.getParameter("personId")));
Concept concept = null;
if (request.getParameter("conceptId") != null)
concept = Context.getConceptService().getConcept(Integer.valueOf(request.getParameter("conceptId")));
ObsService os = Context.getObsService();
List<Obs> ret = concept == null ? os.getObservationsByPerson(person) : os.getObservationsByPersonAndConcept(person,
concept);
Collections.sort(ret, new Comparator<Obs>() {
public int compare(Obs left, Obs right) {
int temp = left.getConcept().getName().getName().compareTo(right.getConcept().getName().getName());
if (temp == 0)
temp = OpenmrsUtil.compareWithNullAsGreatest(left.getVoided(), right.getVoided());
if (temp == 0)
temp = OpenmrsUtil.compareWithNullAsLatest(left.getObsDatetime(), right.getObsDatetime());
return temp;
}
});
return new CommandObject(person, concept, ret);
}
| protected CommandObject formBackingObject(HttpServletRequest request) throws Exception {
if (!Context.isAuthenticated())
return new CommandObject();
Person person = Context.getPersonService().getPerson(Integer.valueOf(request.getParameter("personId")));
List<Concept> concepts = null;
Concept concept = null;
if (request.getParameter("conceptId") != null) {
concept = Context.getConceptService().getConcept(Integer.valueOf(request.getParameter("conceptId")));
concepts = Collections.singletonList(concept);
}
ObsService os = Context.getObsService();
List<Obs> ret = os.getObservations(Collections.singletonList(person), null, concepts, null, null, null, null, null, null, null, null, true);
Collections.sort(ret, new Comparator<Obs>() {
public int compare(Obs left, Obs right) {
int temp = left.getConcept().getName().getName().compareTo(right.getConcept().getName().getName());
if (temp == 0)
temp = OpenmrsUtil.compareWithNullAsGreatest(left.getVoided(), right.getVoided());
if (temp == 0)
temp = OpenmrsUtil.compareWithNullAsLatest(left.getObsDatetime(), right.getObsDatetime());
return temp;
}
});
return new CommandObject(person, concept, ret);
}
|
diff --git a/com/buglabs/util/StreamMultiplexer.java b/com/buglabs/util/StreamMultiplexer.java
index 61b06c2..3d3f68f 100644
--- a/com/buglabs/util/StreamMultiplexer.java
+++ b/com/buglabs/util/StreamMultiplexer.java
@@ -1,228 +1,229 @@
/* Copyright (c) 2007, 2008 Bug Labs, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
package com.buglabs.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import org.osgi.service.log.LogService;
/**
* A class for sharing an InputStream among multiple clients.
* @author Angel Roman
*
*/
public class StreamMultiplexer extends Thread {
private ArrayList outputStreamWriters = new ArrayList();
private InputStream is;
private int bufferLength = 1;
private ArrayList listeners = new ArrayList();
private int delay = 0;
private long read_delay = 0;
private LogService log;
/**
*
* @param is InputStream to use as source
* @param bufferLength the number of bytes to attempt reading simultaneously from the Input Stream.
* @param delay how long to wait in milliseconds until we check if anyone has requested an inputstream.
*/
public StreamMultiplexer(InputStream is, int bufferLength, int delay) {
this.is = is;
this.bufferLength = bufferLength;
this.delay = delay;
}
/**
*
* @param is InputStream to use as source
* @param bufferLength the number of bytes to attempt reading simultaneously from the Input Stream.
* @param delay how long to wait in milliseconds until we check if anyone has requested an inputstream.
* @param read_delay the amount of time to wait between empty reads.
*/
public StreamMultiplexer(InputStream is, int bufferLength, int delay, long read_delay) {
this.is = is;
this.bufferLength = bufferLength;
this.delay = delay;
this.read_delay = read_delay;
}
/**
* @param is The input stream to multiplex.
* @param bufferLength The amounts of bytes to read simultaneously.
*/
public StreamMultiplexer(InputStream is, int bufferLength) {
this.is = is;
this.bufferLength = bufferLength;
}
public StreamMultiplexer(InputStream is) {
this.is = is;
}
public void setLogService(LogService logService) {
this.log = logService;
}
private void notifyStreamMultiplexerListeners(StreamMultiplexerEvent event) {
synchronized (listeners) {
Iterator iter = listeners.iterator();
while(iter.hasNext()) {
IStreamMultiplexerListener listener = (IStreamMultiplexerListener) iter.next();
listener.streamNotification(event);
}
}
}
public void run() {
int read = 0;
byte[] buff = new byte[bufferLength];
String name = getName();
try {
ArrayList faultyStreams = new ArrayList();
if (log != null) {
log.log(LogService.LOG_DEBUG, name + ": Started");
}
while(!isInterrupted()) {
if(outputStreamWriters.size() > 0) {
read = is.read(buff);
if(read == -1) {
if(read_delay != 0) {
sleep(read_delay);
}
continue;
}
synchronized(outputStreamWriters) {
Iterator iter = outputStreamWriters.iterator();
while(iter.hasNext() && read != -1) {
PipedOutputStream osw = (PipedOutputStream) iter.next();
try {
osw.write(buff, 0, read);
} catch (IOException e) {
osw.close();
faultyStreams.add(osw);
}
}
}
removeStreams(faultyStreams);
}
try {
if((delay > 0) && (outputStreamWriters.size() == 0)) {
sleep(delay);
}
} catch (InterruptedException e) {
// this is not an error.
}
}
} catch (IOException e1) {
if (log != null) {
log.log(LogService.LOG_WARNING, "An IOException was generated", e1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//If we are going down, close all streams.
try {
Iterator iter = outputStreamWriters.iterator();
while(iter.hasNext()) {
PipedOutputStream pos = (PipedOutputStream) iter.next();
try {
pos.close();
} catch (IOException e) {
// Log This
e.printStackTrace();
}
}
//Close the gps stream
- is.close();
+ if(is != null)
+ is.close();
} catch (IOException e) {
if (log != null) {
log.log(LogService.LOG_WARNING, "An IOException was generated", e);
}
}
}
if (log != null) {
log.log(LogService.LOG_DEBUG, name + ": Goodbye!");
}
}
public void register(IStreamMultiplexerListener listener) {
synchronized(listeners) {
listeners.add(listener);
}
}
public void unregister(IStreamMultiplexerListener listener) {
synchronized(listeners) {
listeners.remove(listener);
}
}
private void removeStreams(ArrayList faultyStreams) {
if(faultyStreams.size() > 0) {
//Remove faulty streams
Iterator iter = faultyStreams.iterator();
while(iter.hasNext()) {
outputStreamWriters.remove(iter.next());
}
notifyStreamMultiplexerListeners(new StreamMultiplexerEvent(StreamMultiplexerEvent.EVENT_STREAM_REMOVED,
outputStreamWriters.size()));
}
}
public InputStream getInputStream() {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = null;
try {
pis = new PipedInputStream(pos);
} catch (IOException e) {
if (log != null) {
log.log(LogService.LOG_WARNING, "An IOException was generated", e);
}
}
if(pis != null) {
synchronized(outputStreamWriters) {
outputStreamWriters.add(pos);
notifyStreamMultiplexerListeners(new StreamMultiplexerEvent(StreamMultiplexerEvent.EVENT_STREAM_ADDED,
outputStreamWriters.size()));
}
}
return pis;
}
}
| true | true | public void run() {
int read = 0;
byte[] buff = new byte[bufferLength];
String name = getName();
try {
ArrayList faultyStreams = new ArrayList();
if (log != null) {
log.log(LogService.LOG_DEBUG, name + ": Started");
}
while(!isInterrupted()) {
if(outputStreamWriters.size() > 0) {
read = is.read(buff);
if(read == -1) {
if(read_delay != 0) {
sleep(read_delay);
}
continue;
}
synchronized(outputStreamWriters) {
Iterator iter = outputStreamWriters.iterator();
while(iter.hasNext() && read != -1) {
PipedOutputStream osw = (PipedOutputStream) iter.next();
try {
osw.write(buff, 0, read);
} catch (IOException e) {
osw.close();
faultyStreams.add(osw);
}
}
}
removeStreams(faultyStreams);
}
try {
if((delay > 0) && (outputStreamWriters.size() == 0)) {
sleep(delay);
}
} catch (InterruptedException e) {
// this is not an error.
}
}
} catch (IOException e1) {
if (log != null) {
log.log(LogService.LOG_WARNING, "An IOException was generated", e1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//If we are going down, close all streams.
try {
Iterator iter = outputStreamWriters.iterator();
while(iter.hasNext()) {
PipedOutputStream pos = (PipedOutputStream) iter.next();
try {
pos.close();
} catch (IOException e) {
// Log This
e.printStackTrace();
}
}
//Close the gps stream
is.close();
} catch (IOException e) {
if (log != null) {
log.log(LogService.LOG_WARNING, "An IOException was generated", e);
}
}
}
if (log != null) {
log.log(LogService.LOG_DEBUG, name + ": Goodbye!");
}
}
| public void run() {
int read = 0;
byte[] buff = new byte[bufferLength];
String name = getName();
try {
ArrayList faultyStreams = new ArrayList();
if (log != null) {
log.log(LogService.LOG_DEBUG, name + ": Started");
}
while(!isInterrupted()) {
if(outputStreamWriters.size() > 0) {
read = is.read(buff);
if(read == -1) {
if(read_delay != 0) {
sleep(read_delay);
}
continue;
}
synchronized(outputStreamWriters) {
Iterator iter = outputStreamWriters.iterator();
while(iter.hasNext() && read != -1) {
PipedOutputStream osw = (PipedOutputStream) iter.next();
try {
osw.write(buff, 0, read);
} catch (IOException e) {
osw.close();
faultyStreams.add(osw);
}
}
}
removeStreams(faultyStreams);
}
try {
if((delay > 0) && (outputStreamWriters.size() == 0)) {
sleep(delay);
}
} catch (InterruptedException e) {
// this is not an error.
}
}
} catch (IOException e1) {
if (log != null) {
log.log(LogService.LOG_WARNING, "An IOException was generated", e1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//If we are going down, close all streams.
try {
Iterator iter = outputStreamWriters.iterator();
while(iter.hasNext()) {
PipedOutputStream pos = (PipedOutputStream) iter.next();
try {
pos.close();
} catch (IOException e) {
// Log This
e.printStackTrace();
}
}
//Close the gps stream
if(is != null)
is.close();
} catch (IOException e) {
if (log != null) {
log.log(LogService.LOG_WARNING, "An IOException was generated", e);
}
}
}
if (log != null) {
log.log(LogService.LOG_DEBUG, name + ": Goodbye!");
}
}
|
diff --git a/src/uk/badger/bConomy/config/DatabaseManager.java b/src/uk/badger/bConomy/config/DatabaseManager.java
index b4cba5f..b842242 100644
--- a/src/uk/badger/bConomy/config/DatabaseManager.java
+++ b/src/uk/badger/bConomy/config/DatabaseManager.java
@@ -1,124 +1,124 @@
package uk.badger.bConomy.config;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.java.JavaPlugin;
import uk.badger.bConomy.Global;
import uk.badger.bConomy.account.Account;
import n3wton.me.BukkitDatabaseManager.BukkitDatabaseManager;
import n3wton.me.BukkitDatabaseManager.BukkitDatabaseManager.DatabaseType;
public class DatabaseManager {
/**
* Sets up the database and loads in all the infomation in the table
*
* @param plugin - the java plugin used to setup the database, used to get the offline player
*/
public static void setupDatabase(JavaPlugin plugin) {
// creates the database instance
Global.m_database = BukkitDatabaseManager.CreateDatabase(Config.m_dbInfo.dbname, Global.getPlugin(), DatabaseType.SQL);
// logs in using values from the config
Global.m_database.login(Config.m_dbInfo.host, Config.m_dbInfo.user, Config.m_dbInfo.password, Config.m_dbInfo.port);
if (!Global.m_database.TableExists("accounts")) {
Global.outputToConsole("Could not find 'accounts' table, creating default now.");
// creates the accounts table
String query = "CREATE TABLE accounts (" +
- "id INT" +
- "name VARCHAR(64)" +
+ "id INT," +
+ "name VARCHAR(64)," +
"balance DOUBLE" +
");";
Global.m_database.Query(query, true);
}
String query = "SELECT * FROM accounts";
ResultSet result = Global.m_database.QueryResult(query);
if (result == null)
return;
// load in the accounts
try {
while(result.next()) {
int id = result.getInt("id");
String name = result.getString("name");
OfflinePlayer player = plugin.getServer().getOfflinePlayer(name);
double balance = result.getDouble("balance");
// create the account and then add it to the array
Account account = new Account(id, player, balance);
Global.addAccout(account);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void addAccount(Account account) {
if (account == null)
return;
String query = "INSET INTO accounts (" +
"'id', 'name', 'balance') VALUES" +
"'" + account.getId() + "', " +
"'" + account.getPlayer().getName() + ", " +
"'" + account.getBalance() + "'" +
");";
Global.m_database.Query(query, true);
Global.outputToConsole("Account " + account.getId() + " has been added to the database.");
}
public static void updateAccount(Account account){
if (account == null)
return;
String query = "SELECT * FROM accounts WHERE name='"+ account.getPlayer().getName() + "';";
ResultSet result = Global.m_database.QueryResult(query);
try {
if (result.next() == false)
return;
} catch (SQLException ex) {
ex.printStackTrace();
return;
}
query = "UPDATE accounts (" +
"SET name='" + account.getPlayer().getName() + ", " +
"balance='" + account.getBalance() + "'" +
"WHERE id='" + account.getId() +
";";
Global.m_database.Query(query);
}
public static void removeAccount(Account account) {
if (account == null)
return;
String query = "DELETE * FROM accounts WHERE " +
"id=" + account.getId() + " AND" +
"name='" + account.getPlayer().getName() + "'" +
";";
Global.m_database.Query(query);
}
public static void executeQuery(String query) {
Global.m_database.Query(query);
}
}
| true | true | public static void setupDatabase(JavaPlugin plugin) {
// creates the database instance
Global.m_database = BukkitDatabaseManager.CreateDatabase(Config.m_dbInfo.dbname, Global.getPlugin(), DatabaseType.SQL);
// logs in using values from the config
Global.m_database.login(Config.m_dbInfo.host, Config.m_dbInfo.user, Config.m_dbInfo.password, Config.m_dbInfo.port);
if (!Global.m_database.TableExists("accounts")) {
Global.outputToConsole("Could not find 'accounts' table, creating default now.");
// creates the accounts table
String query = "CREATE TABLE accounts (" +
"id INT" +
"name VARCHAR(64)" +
"balance DOUBLE" +
");";
Global.m_database.Query(query, true);
}
String query = "SELECT * FROM accounts";
ResultSet result = Global.m_database.QueryResult(query);
if (result == null)
return;
// load in the accounts
try {
while(result.next()) {
int id = result.getInt("id");
String name = result.getString("name");
OfflinePlayer player = plugin.getServer().getOfflinePlayer(name);
double balance = result.getDouble("balance");
// create the account and then add it to the array
Account account = new Account(id, player, balance);
Global.addAccout(account);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
| public static void setupDatabase(JavaPlugin plugin) {
// creates the database instance
Global.m_database = BukkitDatabaseManager.CreateDatabase(Config.m_dbInfo.dbname, Global.getPlugin(), DatabaseType.SQL);
// logs in using values from the config
Global.m_database.login(Config.m_dbInfo.host, Config.m_dbInfo.user, Config.m_dbInfo.password, Config.m_dbInfo.port);
if (!Global.m_database.TableExists("accounts")) {
Global.outputToConsole("Could not find 'accounts' table, creating default now.");
// creates the accounts table
String query = "CREATE TABLE accounts (" +
"id INT," +
"name VARCHAR(64)," +
"balance DOUBLE" +
");";
Global.m_database.Query(query, true);
}
String query = "SELECT * FROM accounts";
ResultSet result = Global.m_database.QueryResult(query);
if (result == null)
return;
// load in the accounts
try {
while(result.next()) {
int id = result.getInt("id");
String name = result.getString("name");
OfflinePlayer player = plugin.getServer().getOfflinePlayer(name);
double balance = result.getDouble("balance");
// create the account and then add it to the array
Account account = new Account(id, player, balance);
Global.addAccout(account);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
|
diff --git a/src/com/example/ad_creation/PublishActivity.java b/src/com/example/ad_creation/PublishActivity.java
index e1ffb9b..2733f25 100644
--- a/src/com/example/ad_creation/PublishActivity.java
+++ b/src/com/example/ad_creation/PublishActivity.java
@@ -1,113 +1,112 @@
package com.example.ad_creation;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.browsing.PopularAdsActivity;
import com.example.custom_views.ProgressView;
import com.example.maple_android.AdCreationManager;
import com.example.maple_android.MapleApplication;
import com.example.maple_android.MapleHttpClient;
import com.example.maple_android.R;
import com.example.maple_android.Utility;
import com.facebook.Session;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class PublishActivity extends FunnelActivity {
private ImageView mAdView;
private ProgressView mProgressBar;
private RelativeLayout mLoading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCustomContent(R.layout.activity_publish);
mConfig.put(Config.HELP_MESSAGE, "You're done! Congrats");
mConfig.put(Config.NAME, "Publish");
setNextBtn(R.drawable.check, R.drawable.check_pressed);
mAdCreationManager.setup(this);
mLoading = (RelativeLayout) findViewById(R.id.ad_loading);
}
public void publish(View view) {
// get user's session details
//TODO: Handle session error edge cases?
Session session = Session.getActiveSession();
EditText contentView = (EditText) findViewById(R.id.ad_content);
EditText titleView = (EditText) findViewById(R.id.ad_title);
Bitmap currBitmap = mApp.getAdCreationManager().getCurrentBitmap();
Uri fileUri = mApp.getAdCreationManager().getFileUri();
Utility.saveBitmap(fileUri, currBitmap, this);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
currBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] photoByteArray = stream.toByteArray();
RequestParams params = new RequestParams();
params.put("post[image]", new ByteArrayInputStream(photoByteArray), fileUri.getPath());
params.put("post[title]", titleView.getText().toString());
params.put("post[content]", contentView.getText().toString());
- //TODO Eventually switch this to actual company_id when we have access to it
- params.put("post[company_id]", "1");
+ params.put("post[company_id]", Integer.toString(mAdCreationManager.getCompany().getId()));
params.put("token", session.getAccessToken());
mLoading.setVisibility(View.VISIBLE);
MapleHttpClient.post("posts", params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, String response) {
Intent i = new Intent(PublishActivity.this, PopularAdsActivity.class);
i.putExtra("successMessage",
"Posted picture successfully! Go to the website to check it out.");
startActivity(i);
mLoading.setVisibility(View.GONE);
}
@Override
public void onFailure(Throwable error, String response) {
Toast.makeText(getApplicationContext(), "Sugar! We ran into a problem!", Toast.LENGTH_LONG).show();
mLoading.setVisibility(View.GONE);
}
});
}
/**
* Publish the ad to the website
* @param view
*/
public void nextStage(View view) {
selectNext();
publish(view);
}
/**
* Return to the previous stage without saving any changes
*
* @param view
*/
public void prevStage(View view) {
selectPrev();
mAdCreationManager.previousStage(this);
}
}
| true | true | public void publish(View view) {
// get user's session details
//TODO: Handle session error edge cases?
Session session = Session.getActiveSession();
EditText contentView = (EditText) findViewById(R.id.ad_content);
EditText titleView = (EditText) findViewById(R.id.ad_title);
Bitmap currBitmap = mApp.getAdCreationManager().getCurrentBitmap();
Uri fileUri = mApp.getAdCreationManager().getFileUri();
Utility.saveBitmap(fileUri, currBitmap, this);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
currBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] photoByteArray = stream.toByteArray();
RequestParams params = new RequestParams();
params.put("post[image]", new ByteArrayInputStream(photoByteArray), fileUri.getPath());
params.put("post[title]", titleView.getText().toString());
params.put("post[content]", contentView.getText().toString());
//TODO Eventually switch this to actual company_id when we have access to it
params.put("post[company_id]", "1");
params.put("token", session.getAccessToken());
mLoading.setVisibility(View.VISIBLE);
MapleHttpClient.post("posts", params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, String response) {
Intent i = new Intent(PublishActivity.this, PopularAdsActivity.class);
i.putExtra("successMessage",
"Posted picture successfully! Go to the website to check it out.");
startActivity(i);
mLoading.setVisibility(View.GONE);
}
@Override
public void onFailure(Throwable error, String response) {
Toast.makeText(getApplicationContext(), "Sugar! We ran into a problem!", Toast.LENGTH_LONG).show();
mLoading.setVisibility(View.GONE);
}
});
}
| public void publish(View view) {
// get user's session details
//TODO: Handle session error edge cases?
Session session = Session.getActiveSession();
EditText contentView = (EditText) findViewById(R.id.ad_content);
EditText titleView = (EditText) findViewById(R.id.ad_title);
Bitmap currBitmap = mApp.getAdCreationManager().getCurrentBitmap();
Uri fileUri = mApp.getAdCreationManager().getFileUri();
Utility.saveBitmap(fileUri, currBitmap, this);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
currBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] photoByteArray = stream.toByteArray();
RequestParams params = new RequestParams();
params.put("post[image]", new ByteArrayInputStream(photoByteArray), fileUri.getPath());
params.put("post[title]", titleView.getText().toString());
params.put("post[content]", contentView.getText().toString());
params.put("post[company_id]", Integer.toString(mAdCreationManager.getCompany().getId()));
params.put("token", session.getAccessToken());
mLoading.setVisibility(View.VISIBLE);
MapleHttpClient.post("posts", params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, String response) {
Intent i = new Intent(PublishActivity.this, PopularAdsActivity.class);
i.putExtra("successMessage",
"Posted picture successfully! Go to the website to check it out.");
startActivity(i);
mLoading.setVisibility(View.GONE);
}
@Override
public void onFailure(Throwable error, String response) {
Toast.makeText(getApplicationContext(), "Sugar! We ran into a problem!", Toast.LENGTH_LONG).show();
mLoading.setVisibility(View.GONE);
}
});
}
|
diff --git a/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java b/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
index f7bfc8611..6676ad6b5 100644
--- a/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
+++ b/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
@@ -1,2156 +1,2165 @@
//
// ZeissLSMReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveInteger;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.Region;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.ImageTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.services.MDBService;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffCompression;
import loci.formats.tiff.TiffConstants;
import loci.formats.tiff.TiffParser;
/**
* ZeissLSMReader is the file format reader for Zeiss LSM files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java">Trac</a>,
* <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java">SVN</a></dd></dl>
*
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert melissa at glencoesoftware.com
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class ZeissLSMReader extends FormatReader {
// -- Constants --
public static final String[] MDB_SUFFIX = {"mdb"};
/** Tag identifying a Zeiss LSM file. */
private static final int ZEISS_ID = 34412;
/** Data types. */
private static final int TYPE_SUBBLOCK = 0;
private static final int TYPE_ASCII = 2;
private static final int TYPE_LONG = 4;
private static final int TYPE_RATIONAL = 5;
/** Subblock types. */
private static final int SUBBLOCK_RECORDING = 0x10000000;
private static final int SUBBLOCK_LASER = 0x50000000;
private static final int SUBBLOCK_TRACK = 0x40000000;
private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000;
private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000;
private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000;
private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000;
private static final int SUBBLOCK_TIMER = 0x12000000;
private static final int SUBBLOCK_MARKER = 0x14000000;
private static final int SUBBLOCK_END = (int) 0xffffffff;
/** Data types. */
private static final int RECORDING_NAME = 0x10000001;
private static final int RECORDING_DESCRIPTION = 0x10000002;
private static final int RECORDING_OBJECTIVE = 0x10000004;
private static final int RECORDING_ZOOM = 0x10000016;
private static final int RECORDING_SAMPLE_0TIME = 0x10000036;
private static final int RECORDING_CAMERA_BINNING = 0x10000052;
private static final int TRACK_ACQUIRE = 0x40000006;
private static final int TRACK_TIME_BETWEEN_STACKS = 0x4000000b;
private static final int LASER_NAME = 0x50000001;
private static final int LASER_ACQUIRE = 0x50000002;
private static final int LASER_POWER = 0x50000003;
private static final int CHANNEL_DETECTOR_GAIN = 0x70000003;
private static final int CHANNEL_PINHOLE_DIAMETER = 0x70000009;
private static final int CHANNEL_AMPLIFIER_GAIN = 0x70000005;
private static final int CHANNEL_FILTER_SET = 0x7000000f;
private static final int CHANNEL_FILTER = 0x70000010;
private static final int CHANNEL_ACQUIRE = 0x7000000b;
private static final int CHANNEL_NAME = 0x70000014;
private static final int ILLUM_CHANNEL_NAME = 0x90000001;
private static final int ILLUM_CHANNEL_ATTENUATION = 0x90000002;
private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003;
private static final int ILLUM_CHANNEL_ACQUIRE = 0x90000004;
private static final int START_TIME = 0x10000036;
private static final int DATA_CHANNEL_NAME = 0xd0000001;
private static final int DATA_CHANNEL_ACQUIRE = 0xd0000017;
private static final int BEAM_SPLITTER_FILTER = 0xb0000002;
private static final int BEAM_SPLITTER_FILTER_SET = 0xb0000003;
/** Drawing element types. */
private static final int TEXT = 13;
private static final int LINE = 14;
private static final int SCALE_BAR = 15;
private static final int OPEN_ARROW = 16;
private static final int CLOSED_ARROW = 17;
private static final int RECTANGLE = 18;
private static final int ELLIPSE = 19;
private static final int CLOSED_POLYLINE = 20;
private static final int OPEN_POLYLINE = 21;
private static final int CLOSED_BEZIER = 22;
private static final int OPEN_BEZIER = 23;
private static final int CIRCLE = 24;
private static final int PALETTE = 25;
private static final int POLYLINE_ARROW = 26;
private static final int BEZIER_WITH_ARROW = 27;
private static final int ANGLE = 28;
private static final int CIRCLE_3POINT = 29;
// -- Static fields --
private static final Hashtable<Integer, String> METADATA_KEYS = createKeys();
// -- Fields --
private double pixelSizeX, pixelSizeY, pixelSizeZ;
private byte[][][] lut = null;
private Vector<Double> timestamps;
private int validChannels;
private String[] lsmFilenames;
private Vector<IFDList> ifdsList;
private TiffParser tiffParser;
private int nextLaser = 0, nextDetector = 0;
private int nextFilter = 0, nextDichroicChannel = 0, nextDichroic = 0;
private int nextDataChannel = 0, nextIllumChannel = 0, nextDetectChannel = 0;
private boolean splitPlanes = false;
private double zoom;
private Vector<String> imageNames;
private String binning;
private Vector<Double> xCoordinates, yCoordinates, zCoordinates;
private int dimensionM, dimensionP;
private Hashtable<String, Integer> seriesCounts;
private String userName;
private double originX, originY, originZ;
private int totalROIs = 0;
private int prevPlane = -1;
private int prevChannel = 0;
private byte[] prevBuf = null;
private Region prevRegion = null;
// -- Constructor --
/** Constructs a new Zeiss LSM reader. */
public ZeissLSMReader() {
super("Zeiss Laser-Scanning Microscopy", new String[] {"lsm", "mdb"});
domains = new String[] {FormatTools.LM_DOMAIN};
hasCompanionFiles = true;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
if (checkSuffix(id, MDB_SUFFIX)) return false;
return isGroupFiles() ? getMDBFile(id) != null : true;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
pixelSizeX = pixelSizeY = pixelSizeZ = 0;
lut = null;
timestamps = null;
validChannels = 0;
lsmFilenames = null;
ifdsList = null;
tiffParser = null;
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextDataChannel = nextIllumChannel = nextDetectChannel = 0;
splitPlanes = false;
zoom = 0;
imageNames = null;
binning = null;
totalROIs = 0;
prevPlane = -1;
prevChannel = 0;
prevBuf = null;
prevRegion = null;
xCoordinates = null;
yCoordinates = null;
zCoordinates = null;
dimensionM = 0;
dimensionP = 0;
seriesCounts = null;
originX = originY = originZ = 0d;
userName = null;
}
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 4;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
TiffParser parser = new TiffParser(stream);
return parser.isValidHeader() || stream.readShort() == 0x5374;
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (noPixels) {
if (checkSuffix(currentId, MDB_SUFFIX)) return new String[] {currentId};
return null;
}
if (lsmFilenames == null) return new String[] {currentId};
if (lsmFilenames.length == 1 && currentId.equals(lsmFilenames[0])) {
return lsmFilenames;
}
return new String[] {currentId, getLSMFileFromSeries(getSeries())};
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lut == null || lut[getSeries()] == null ||
getPixelType() != FormatTools.UINT8)
{
return null;
}
byte[][] b = new byte[3][];
b[0] = lut[getSeries()][prevChannel * 3];
b[1] = lut[getSeries()][prevChannel * 3 + 1];
b[2] = lut[getSeries()][prevChannel * 3 + 2];
return b;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lut == null || lut[getSeries()] == null ||
getPixelType() != FormatTools.UINT16)
{
return null;
}
short[][] s = new short[3][65536];
for (int i=2; i>=3-validChannels; i--) {
for (int j=0; j<s[i].length; j++) {
s[i][j] = (short) j;
}
}
return s;
}
/* @see loci.formats.IFormatReader#setSeries(int) */
public void setSeries(int series) {
if (series != getSeries()) {
prevBuf = null;
}
super.setSeries(series);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
if (getSeriesCount() > 1) {
in.close();
in = new RandomAccessInputStream(getLSMFileFromSeries(getSeries()));
in.order(!isLittleEndian());
tiffParser = new TiffParser(in);
}
IFDList ifds = ifdsList.get(getSeries());
if (splitPlanes && getSizeC() > 1 && ifds.size() == getSizeZ() * getSizeT())
{
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int plane = no / getSizeC();
int c = no % getSizeC();
Region region = new Region(x, y, w, h);
if (prevPlane != plane || prevBuf == null ||
prevBuf.length < w * h * bpp * getSizeC() || !region.equals(prevRegion))
{
prevBuf = new byte[w * h * bpp * getSizeC()];
tiffParser.getSamples(ifds.get(plane), prevBuf, x, y, w, h);
prevPlane = plane;
prevRegion = region;
}
ImageTools.splitChannels(
prevBuf, buf, c, getSizeC(), bpp, false, false, w * h * bpp);
prevChannel = c;
}
else {
tiffParser.getSamples(ifds.get(no), buf, x, y, w, h);
prevChannel = getZCTCoords(no)[1];
}
if (getSeriesCount() > 1) in.close();
return buf;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
if (!checkSuffix(id, MDB_SUFFIX) && isGroupFiles()) {
String mdb = getMDBFile(id);
if (mdb != null) {
setId(mdb);
return;
}
lsmFilenames = new String[] {id};
}
else if (checkSuffix(id, MDB_SUFFIX)) {
lsmFilenames = parseMDB(id);
}
else lsmFilenames = new String[] {id};
if (lsmFilenames == null || lsmFilenames.length == 0) {
throw new FormatException("LSM files were not found.");
}
timestamps = new Vector<Double>();
imageNames = new Vector<String>();
xCoordinates = new Vector<Double>();
yCoordinates = new Vector<Double>();
zCoordinates = new Vector<Double>();
seriesCounts = new Hashtable<String, Integer>();
int seriesCount = 0;
Vector<String> validFiles = new Vector<String>();
for (String filename : lsmFilenames) {
try {
int extraSeries = getExtraSeries(filename);
seriesCounts.put(filename, extraSeries);
seriesCount += extraSeries;
validFiles.add(filename);
}
catch (IOException e) {
LOGGER.debug("Failed to parse " + filename, e);
}
}
lsmFilenames = validFiles.toArray(new String[validFiles.size()]);
core = new CoreMetadata[seriesCount];
ifdsList = new Vector<IFDList>();
ifdsList.setSize(core.length);
int realSeries = 0;
for (int i=0; i<lsmFilenames.length; i++) {
RandomAccessInputStream stream =
new RandomAccessInputStream(lsmFilenames[i]);
int count = seriesCounts.get(lsmFilenames[i]);
TiffParser tp = new TiffParser(stream);
Boolean littleEndian = tp.checkHeader();
long[] ifdOffsets = tp.getIFDOffsets();
int ifdsPerSeries = (ifdOffsets.length / 2) / count;
int offset = 0;
Object zeissTag = null;
for (int s=0; s<count; s++, realSeries++) {
core[realSeries] = new CoreMetadata();
core[realSeries].littleEndian = littleEndian;
IFDList ifds = new IFDList();
while (ifds.size() < ifdsPerSeries) {
tp.setDoCaching(offset == 0);
IFD ifd = tp.getIFD(ifdOffsets[offset]);
if (offset == 0) zeissTag = ifd.get(ZEISS_ID);
if (offset > 0 && ifds.size() == 0) {
ifd.putIFDValue(ZEISS_ID, zeissTag);
}
ifds.add(ifd);
if (zeissTag != null) offset += 2;
else offset++;
}
for (IFD ifd : ifds) {
tp.fillInIFD(ifd);
}
ifdsList.set(realSeries, ifds);
}
stream.close();
}
MetadataStore store = makeFilterMetadata();
lut = new byte[ifdsList.size()][][];
for (int series=0; series<ifdsList.size(); series++) {
IFDList ifds = ifdsList.get(series);
for (IFD ifd : ifds) {
// check that predictor is set to 1 if anything other
// than LZW compression is used
if (ifd.getCompression() != TiffCompression.LZW) {
ifd.putIFDValue(IFD.PREDICTOR, 1);
}
}
// fix the offsets for > 4 GB files
RandomAccessInputStream s =
new RandomAccessInputStream(getLSMFileFromSeries(series));
for (int i=1; i<ifds.size(); i++) {
long[] stripOffsets = ifds.get(i).getStripOffsets();
long[] previousStripOffsets = ifds.get(i - 1).getStripOffsets();
if (stripOffsets == null || previousStripOffsets == null) {
throw new FormatException(
"Strip offsets are missing; this is an invalid file.");
}
boolean neededAdjustment = false;
for (int j=0; j<stripOffsets.length; j++) {
if (j >= previousStripOffsets.length) break;
if (stripOffsets[j] < previousStripOffsets[j]) {
stripOffsets[j] = (previousStripOffsets[j] & ~0xffffffffL) |
(stripOffsets[j] & 0xffffffffL);
if (stripOffsets[j] < previousStripOffsets[j]) {
stripOffsets[j] += 0x100000000L;
}
neededAdjustment = true;
}
if (neededAdjustment) {
ifds.get(i).putIFDValue(IFD.STRIP_OFFSETS, stripOffsets);
}
}
}
s.close();
initMetadata(series);
}
for (int i=0; i<getSeriesCount(); i++) {
core[i].imageCount = core[i].sizeZ * core[i].sizeC * core[i].sizeT;
}
MetadataTools.populatePixels(store, this, true);
for (int series=0; series<ifdsList.size(); series++) {
setSeries(series);
if (series < imageNames.size()) {
store.setImageName(imageNames.get(series), series);
}
store.setPixelsBinDataBigEndian(!isLittleEndian(), series, 0);
}
setSeries(0);
}
// -- Helper methods --
private String getMDBFile(String id) throws FormatException, IOException {
Location parentFile = new Location(id).getAbsoluteFile().getParentFile();
String[] fileList = parentFile.list();
for (int i=0; i<fileList.length; i++) {
if (fileList[i].startsWith(".")) continue;
if (checkSuffix(fileList[i], MDB_SUFFIX)) {
Location file =
new Location(parentFile, fileList[i]).getAbsoluteFile();
if (file.isDirectory()) continue;
// make sure that the .mdb references this .lsm
String[] lsms = parseMDB(file.getAbsolutePath());
if (lsms == null) return null;
for (String lsm : lsms) {
if (id.endsWith(lsm) || lsm.endsWith(id)) {
return file.getAbsolutePath();
}
}
}
}
return null;
}
private int getEffectiveSeries(int currentSeries) {
int seriesCount = 0;
for (int i=0; i<lsmFilenames.length; i++) {
Integer count = seriesCounts.get(lsmFilenames[i]);
if (count == null) count = 1;
seriesCount += count;
if (seriesCount > currentSeries) return i;
}
return -1;
}
private String getLSMFileFromSeries(int currentSeries) {
int effectiveSeries = getEffectiveSeries(currentSeries);
return effectiveSeries < 0 ? null : lsmFilenames[effectiveSeries];
}
private int getExtraSeries(String file) throws FormatException, IOException {
if (in != null) in.close();
in = new RandomAccessInputStream(file);
boolean littleEndian = in.read() == TiffConstants.LITTLE;
in.order(littleEndian);
tiffParser = new TiffParser(in);
IFD ifd = tiffParser.getFirstIFD();
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) return 1;
ras.order(littleEndian);
ras.seek(264);
dimensionP = ras.readInt();
dimensionM = ras.readInt();
ras.close();
int nSeries = dimensionM * dimensionP;
return nSeries <= 0 ? 1 : nSeries;
}
private int getPosition(int currentSeries) {
int effectiveSeries = getEffectiveSeries(currentSeries);
int firstPosition = 0;
for (int i=0; i<effectiveSeries; i++) {
firstPosition += seriesCounts.get(lsmFilenames[i]);
}
return currentSeries - firstPosition;
}
private RandomAccessInputStream getCZTag(IFD ifd)
throws FormatException, IOException
{
// get TIF_CZ_LSMINFO structure
short[] s = ifd.getIFDShortArray(ZEISS_ID);
if (s == null) {
LOGGER.warn("Invalid Zeiss LSM file. Tag {} not found.", ZEISS_ID);
TiffReader reader = new TiffReader();
reader.setId(getLSMFileFromSeries(series));
core[getSeries()] = reader.getCoreMetadata()[0];
reader.close();
return null;
}
byte[] cz = new byte[s.length];
for (int i=0; i<s.length; i++) {
cz[i] = (byte) s[i];
}
RandomAccessInputStream ras = new RandomAccessInputStream(cz);
ras.order(isLittleEndian());
return ras;
}
protected void initMetadata(int series) throws FormatException, IOException {
setSeries(series);
IFDList ifds = ifdsList.get(series);
IFD ifd = ifds.get(0);
in.close();
in = new RandomAccessInputStream(getLSMFileFromSeries(series));
in.order(isLittleEndian());
tiffParser = new TiffParser(in);
PhotoInterp photo = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[series].sizeX = (int) ifd.getImageWidth();
core[series].sizeY = (int) ifd.getImageLength();
core[series].rgb = samples > 1 || photo == PhotoInterp.RGB;
core[series].interleaved = false;
core[series].sizeC = isRGB() ? samples : 1;
core[series].pixelType = ifd.getPixelType();
core[series].imageCount = ifds.size();
core[series].sizeZ = getImageCount();
core[series].sizeT = 1;
LOGGER.info("Reading LSM metadata for series #{}", series);
MetadataStore store = makeFilterMetadata();
int instrument = getEffectiveSeries(series);
String imageName = getLSMFileFromSeries(series);
if (imageName.indexOf(".") != -1) {
imageName = imageName.substring(0, imageName.lastIndexOf("."));
}
if (imageName.indexOf(File.separator) != -1) {
imageName =
imageName.substring(imageName.lastIndexOf(File.separator) + 1);
}
if (lsmFilenames.length != getSeriesCount()) {
imageName += " #" + (getPosition(series) + 1);
}
// link Instrument and Image
store.setImageID(MetadataTools.createLSID("Image", series), series);
String instrumentID = MetadataTools.createLSID("Instrument", instrument);
store.setInstrumentID(instrumentID, instrument);
store.setImageInstrumentRef(instrumentID, series);
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) {
imageNames.add(imageName);
return;
}
ras.seek(16);
core[series].sizeZ = ras.readInt();
ras.skipBytes(4);
core[series].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
addSeriesMeta("DataType", "12 bit unsigned integer");
break;
case 5:
addSeriesMeta("DataType", "32 bit float");
break;
case 0:
addSeriesMeta("DataType", "varying data types");
break;
default:
addSeriesMeta("DataType", "8 bit unsigned integer");
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
ras.seek(0);
addSeriesMeta("MagicNumber ", ras.readInt());
addSeriesMeta("StructureSize", ras.readInt());
addSeriesMeta("DimensionX", ras.readInt());
addSeriesMeta("DimensionY", ras.readInt());
ras.seek(32);
addSeriesMeta("ThumbnailX", ras.readInt());
addSeriesMeta("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
addSeriesMeta("VoxelSizeX", new Double(pixelSizeX));
addSeriesMeta("VoxelSizeY", new Double(pixelSizeY));
addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ));
originX = ras.readDouble() * 1000000;
originY = ras.readDouble() * 1000000;
originZ = ras.readDouble() * 1000000;
addSeriesMeta("OriginX", originX);
addSeriesMeta("OriginY", originY);
addSeriesMeta("OriginZ", originZ);
}
else ras.seek(88);
int scanType = ras.readShort();
switch (scanType) {
case 0:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
break;
case 1:
addSeriesMeta("ScanType", "z scan (x-z plane)");
core[series].dimensionOrder = "XYZCT";
break;
case 2:
addSeriesMeta("ScanType", "line scan");
core[series].dimensionOrder = "XYZCT";
break;
case 3:
addSeriesMeta("ScanType", "time series x-y");
core[series].dimensionOrder = "XYTCZ";
break;
case 4:
addSeriesMeta("ScanType", "time series x-z");
core[series].dimensionOrder = "XYZTC";
break;
case 5:
addSeriesMeta("ScanType", "time series 'Mean of ROIs'");
core[series].dimensionOrder = "XYTCZ";
break;
case 6:
addSeriesMeta("ScanType", "time series x-y-z");
core[series].dimensionOrder = "XYZTC";
break;
case 7:
addSeriesMeta("ScanType", "spline scan");
core[series].dimensionOrder = "XYCTZ";
break;
case 8:
addSeriesMeta("ScanType", "spline scan x-z");
core[series].dimensionOrder = "XYCZT";
break;
case 9:
addSeriesMeta("ScanType", "time series spline plane x-z");
core[series].dimensionOrder = "XYTCZ";
break;
case 10:
addSeriesMeta("ScanType", "point mode");
core[series].dimensionOrder = "XYZCT";
break;
default:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
}
core[series].indexed = lut != null && lut[series] != null;
if (isIndexed()) {
core[series].rgb = false;
}
if (getSizeC() == 0) core[series].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[series].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
if (getEffectiveSizeC() == 0) {
core[series].imageCount = getSizeZ() * getSizeT();
}
else {
core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
}
if (getImageCount() != ifds.size()) {
int diff = getImageCount() - ifds.size();
core[series].imageCount = ifds.size();
if (diff % getSizeZ() == 0) {
core[series].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[series].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[series].sizeZ = ifds.size();
core[series].sizeT = 1;
}
else if (getSizeT() > 1) {
core[series].sizeT = ifds.size();
core[series].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[series].sizeZ = getImageCount();
if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ();
long channelColorsOffset = 0;
long timeStampOffset = 0;
long eventListOffset = 0;
long scanInformationOffset = 0;
long channelWavelengthOffset = 0;
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
int spectralScan = ras.readShort();
if (spectralScan != 1) {
addSeriesMeta("SpectralScan", "no spectral scan");
}
else addSeriesMeta("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
addSeriesMeta("DataType2", "calculated data");
break;
case 2:
addSeriesMeta("DataType2", "animation");
break;
default:
addSeriesMeta("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
channelColorsOffset = ras.readInt();
addSeriesMeta("TimeInterval", ras.readDouble());
ras.skipBytes(4);
scanInformationOffset = ras.readInt();
ras.skipBytes(4);
timeStampOffset = ras.readInt();
eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
addSeriesMeta("DisplayAspectX", ras.readDouble());
addSeriesMeta("DisplayAspectY", ras.readDouble());
addSeriesMeta("DisplayAspectZ", ras.readDouble());
addSeriesMeta("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS)
{
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(series, overlayOffsets[i], overlayKeys[i], store);
}
}
totalROIs = 0;
addSeriesMeta("ToolbarFlags", ras.readInt());
channelWavelengthOffset = ras.readInt();
ras.skipBytes(64);
}
else ras.skipBytes(182);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series);
if (getSizeC() > 1) {
if (!splitPlanes) splitPlanes = isRGB();
core[series].rgb = false;
if (splitPlanes) core[series].imageCount *= getSizeC();
}
for (int c=0; c<getEffectiveSizeC(); c++) {
String lsid = MetadataTools.createLSID("Channel", series, c);
store.setChannelID(lsid, series, c);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// NB: the Zeiss LSM 5.5 specification indicates that there should be
// 15 32-bit integers here; however, there are actually 16 32-bit
// integers before the tile position offset.
// We have confirmed with Zeiss that this is correct, and the 6.0
// specification was updated to contain the correct information.
ras.skipBytes(64);
int tilePositionOffset = ras.readInt();
ras.skipBytes(36);
int positionOffset = ras.readInt();
// read referenced structures
addSeriesMeta("DimensionZ", getSizeZ());
addSeriesMeta("DimensionChannels", getSizeC());
addSeriesMeta("DimensionM", dimensionM);
addSeriesMeta("DimensionP", dimensionP);
if (positionOffset != 0) {
in.seek(positionOffset);
int nPositions = in.readInt();
for (int i=0; i<nPositions; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
xCoordinates.add(xPos);
yCoordinates.add(yPos);
zCoordinates.add(zPos);
addGlobalMeta("X position for position #" + (i + 1), xPos);
addGlobalMeta("Y position for position #" + (i + 1), yPos);
addGlobalMeta("Z position for position #" + (i + 1), zPos);
}
}
if (tilePositionOffset != 0) {
in.seek(tilePositionOffset);
int nTiles = in.readInt();
for (int i=0; i<nTiles; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
if (xCoordinates.size() > i) {
xPos += xCoordinates.get(i);
xCoordinates.setElementAt(xPos, i);
}
+ else if (xCoordinates.size() == i - 1) {
+ xCoordinates.add(xPos);
+ }
if (yCoordinates.size() > i) {
yPos += yCoordinates.get(i);
yCoordinates.setElementAt(yPos, i);
}
+ else if (yCoordinates.size() == i - 1) {
+ yCoordinates.add(yPos);
+ }
if (zCoordinates.size() > i) {
zPos += zCoordinates.get(i);
zCoordinates.setElementAt(zPos, i);
}
+ else if (zCoordinates.size() == i - 1) {
+ zCoordinates.add(zPos);
+ }
addGlobalMeta("X position for position #" + (i + 1), xPos);
addGlobalMeta("Y position for position #" + (i + 1), yPos);
addGlobalMeta("Z position for position #" + (i + 1), zPos);
}
}
if (channelColorsOffset != 0) {
in.seek(channelColorsOffset + 12);
int colorsOffset = in.readInt();
int namesOffset = in.readInt();
// read the color of each channel
if (colorsOffset > 0) {
in.seek(channelColorsOffset + colorsOffset);
lut[getSeries()] = new byte[getSizeC() * 3][256];
core[getSeries()].indexed = true;
for (int i=0; i<getSizeC(); i++) {
int color = in.readInt();
int red = color & 0xff;
int green = (color & 0xff00) >> 8;
int blue = (color & 0xff0000) >> 16;
for (int j=0; j<256; j++) {
lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j);
lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j);
lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j);
}
}
}
// read the name of each channel
if (namesOffset > 0) {
in.seek(channelColorsOffset + namesOffset + 4);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) {
addSeriesMeta("ChannelName" + i, name);
}
}
}
}
if (timeStampOffset != 0) {
in.seek(timeStampOffset + 8);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
addSeriesMeta("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
addSeriesMeta("Event" + i + " Time", eventTime);
addSeriesMeta("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
addSeriesMeta("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextDataChannel = nextDetectChannel = nextIllumChannel = 0;
Vector<SubBlock> blocks = new Vector<SubBlock>();
while (in.getFilePointer() < in.length() - 12) {
if (in.getFilePointer() < 0) break;
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
if (blockType == TYPE_SUBBLOCK) {
SubBlock block = null;
switch (entry) {
case SUBBLOCK_RECORDING:
block = new Recording();
break;
case SUBBLOCK_LASER:
block = new Laser();
break;
case SUBBLOCK_TRACK:
block = new Track();
break;
case SUBBLOCK_DETECTION_CHANNEL:
block = new DetectionChannel();
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
block = new IlluminationChannel();
break;
case SUBBLOCK_BEAM_SPLITTER:
block = new BeamSplitter();
break;
case SUBBLOCK_DATA_CHANNEL:
block = new DataChannel();
break;
case SUBBLOCK_TIMER:
block = new Timer();
break;
case SUBBLOCK_MARKER:
block = new Marker();
break;
}
if (block != null) {
blocks.add(block);
}
}
else if (dataSize + in.getFilePointer() <= in.length() &&
dataSize > 0)
{
in.skipBytes(dataSize);
}
else break;
}
Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>();
SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]);
for (SubBlock block : metadataBlocks) {
block.addToHashtable();
if (!block.acquire) {
nonAcquiredBlocks.add(block);
blocks.remove(block);
}
}
for (int i=0; i<blocks.size(); i++) {
SubBlock block = blocks.get(i);
// every valid IlluminationChannel must be immediately followed by
// a valid DataChannel or IlluminationChannel
if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) {
SubBlock nextBlock = blocks.get(i + 1);
if (!(nextBlock instanceof DataChannel) &&
!(nextBlock instanceof IlluminationChannel))
{
((IlluminationChannel) block).wavelength = null;
}
}
// every valid DetectionChannel must be immediately preceded by
// a valid Track or DetectionChannel
else if ((block instanceof DetectionChannel) && i > 0) {
SubBlock prevBlock = blocks.get(i - 1);
if (!(prevBlock instanceof Track) &&
!(prevBlock instanceof DetectionChannel))
{
block.acquire = false;
nonAcquiredBlocks.add(block);
}
}
if (block.acquire) populateMetadataStore(block, store, series);
}
for (SubBlock block : nonAcquiredBlocks) {
populateMetadataStore(block, store, series);
}
}
}
imageNames.add(imageName);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (userName != null) {
String experimenterID = MetadataTools.createLSID("Experimenter", 0);
store.setExperimenterID(experimenterID, 0);
store.setExperimenterUserName(userName, 0);
store.setExperimenterDisplayName(userName, 0);
}
Double pixX = new Double(pixelSizeX);
Double pixY = new Double(pixelSizeY);
Double pixZ = new Double(pixelSizeZ);
store.setPixelsPhysicalSizeX(pixX, series);
store.setPixelsPhysicalSizeY(pixY, series);
store.setPixelsPhysicalSizeZ(pixZ, series);
double firstStamp = 0;
if (timestamps.size() > 0) {
firstStamp = timestamps.get(0).doubleValue();
}
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
double thisStamp = timestamps.get(zct[2]).doubleValue();
store.setPlaneDeltaT(thisStamp - firstStamp, series, i);
int index = zct[2] + 1;
double nextStamp = index < timestamps.size() ?
timestamps.get(index).doubleValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = timestamps.get(zct[2] - 1).doubleValue();
}
store.setPlaneExposureTime(nextStamp - thisStamp, series, i);
}
if (xCoordinates.size() > series) {
store.setPlanePositionX(xCoordinates.get(series), series, i);
store.setPlanePositionY(yCoordinates.get(series), series, i);
store.setPlanePositionZ(zCoordinates.get(series), series, i);
}
}
}
ras.close();
}
protected void populateMetadataStore(SubBlock block, MetadataStore store,
int series)
throws FormatException
{
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
return;
}
int instrument = getEffectiveSeries(series);
// NB: block.acquire can be false. If that is the case, Instrument data
// is the only thing that should be populated.
if (block instanceof Recording) {
Recording recording = (Recording) block;
String objectiveID = MetadataTools.createLSID("Objective", instrument, 0);
if (recording.acquire) {
store.setImageDescription(recording.description, series);
store.setImageAcquiredDate(recording.startTime, series);
store.setImageObjectiveSettingsID(objectiveID, series);
binning = recording.binning;
}
store.setObjectiveCorrection(
getCorrection(recording.correction), instrument, 0);
store.setObjectiveImmersion(
getImmersion(recording.immersion), instrument, 0);
if (recording.magnification != null && recording.magnification > 0) {
store.setObjectiveNominalMagnification(
new PositiveInteger(recording.magnification), instrument, 0);
}
store.setObjectiveLensNA(recording.lensNA, instrument, 0);
store.setObjectiveIris(recording.iris, instrument, 0);
store.setObjectiveID(objectiveID, instrument, 0);
}
else if (block instanceof Laser) {
Laser laser = (Laser) block;
if (laser.medium != null) {
store.setLaserLaserMedium(getLaserMedium(laser.medium),
instrument, nextLaser);
}
if (laser.type != null) {
store.setLaserType(getLaserType(laser.type), instrument, nextLaser);
}
if (laser.model != null) {
store.setLaserModel(laser.model, instrument, nextLaser);
}
String lightSourceID =
MetadataTools.createLSID("LightSource", instrument, nextLaser);
store.setLaserID(lightSourceID, instrument, nextLaser);
nextLaser++;
}
else if (block instanceof Track) {
Track track = (Track) block;
if (track.acquire) {
store.setPixelsTimeIncrement(track.timeIncrement, series);
}
}
else if (block instanceof DataChannel) {
DataChannel channel = (DataChannel) block;
if (channel.name != null && nextDataChannel < getSizeC() &&
channel.acquire)
{
store.setChannelName(channel.name, series, nextDataChannel++);
}
}
else if (block instanceof DetectionChannel) {
DetectionChannel channel = (DetectionChannel) block;
if (channel.pinhole != null && channel.pinhole.doubleValue() != 0f &&
nextDetectChannel < getSizeC() && channel.acquire)
{
store.setChannelPinholeSize(channel.pinhole, series, nextDetectChannel);
}
if (channel.filter != null) {
String id = MetadataTools.createLSID("Filter", instrument, nextFilter);
if (channel.acquire && nextDetectChannel < getSizeC()) {
store.setLightPathEmissionFilterRef(
id, instrument, nextDetectChannel, 0);
}
store.setFilterID(id, instrument, nextFilter);
store.setFilterModel(channel.filter, instrument, nextFilter);
int space = channel.filter.indexOf(" ");
if (space != -1) {
String type = channel.filter.substring(0, space).trim();
if (type.equals("BP")) type = "BandPass";
else if (type.equals("LP")) type = "LongPass";
store.setFilterType(getFilterType(type), instrument, nextFilter);
String transmittance = channel.filter.substring(space + 1).trim();
String[] v = transmittance.split("-");
try {
store.setTransmittanceRangeCutIn(
PositiveInteger.valueOf(v[0].trim()), instrument, nextFilter);
}
catch (NumberFormatException e) { }
if (v.length > 1) {
try {
store.setTransmittanceRangeCutOut(
PositiveInteger.valueOf(v[1].trim()), instrument, nextFilter);
}
catch (NumberFormatException e) { }
}
}
nextFilter++;
}
if (channel.channelName != null) {
String detectorID =
MetadataTools.createLSID("Detector", instrument, nextDetector);
store.setDetectorID(detectorID, instrument, nextDetector);
if (channel.acquire && nextDetector < getSizeC()) {
store.setDetectorSettingsID(detectorID, series, nextDetector);
store.setDetectorSettingsBinning(
getBinning(binning), series, nextDetector);
}
}
if (channel.amplificationGain != null) {
store.setDetectorAmplificationGain(
channel.amplificationGain, instrument, nextDetector);
}
if (channel.gain != null) {
store.setDetectorGain(channel.gain, instrument, nextDetector);
}
store.setDetectorType(getDetectorType("PMT"), instrument, nextDetector);
store.setDetectorZoom(zoom, instrument, nextDetector);
nextDetectChannel++;
nextDetector++;
}
else if (block instanceof BeamSplitter) {
BeamSplitter beamSplitter = (BeamSplitter) block;
if (beamSplitter.filterSet != null) {
if (beamSplitter.filter != null) {
String id = MetadataTools.createLSID(
"Dichroic", instrument, nextDichroic);
store.setDichroicID(id, instrument, nextDichroic);
store.setDichroicModel(beamSplitter.filter, instrument, nextDichroic);
if (nextDichroicChannel < getEffectiveSizeC()) {
store.setLightPathDichroicRef(id, series, nextDichroicChannel);
}
nextDichroic++;
}
nextDichroicChannel++;
}
}
else if (block instanceof IlluminationChannel) {
IlluminationChannel channel = (IlluminationChannel) block;
if (channel.acquire && channel.wavelength != null) {
store.setChannelEmissionWavelength(
new PositiveInteger(channel.wavelength), series, nextIllumChannel++);
}
}
}
/** Parses overlay-related fields. */
protected void parseOverlays(int series, long data, String suffix,
MetadataStore store) throws IOException
{
if (data == 0) return;
String prefix = "Series " + series + " ";
in.seek(data);
int numberOfShapes = in.readInt();
int size = in.readInt();
if (size <= 194) return;
in.skipBytes(20);
boolean valid = in.readInt() == 1;
in.skipBytes(164);
for (int i=totalROIs; i<totalROIs+numberOfShapes; i++) {
long offset = in.getFilePointer();
int type = in.readInt();
int blockLength = in.readInt();
double lineWidth = in.readInt();
int measurements = in.readInt();
double textOffsetX = in.readDouble();
double textOffsetY = in.readDouble();
int color = in.readInt();
boolean validShape = in.readInt() != 0;
int knotWidth = in.readInt();
int catchArea = in.readInt();
int fontHeight = in.readInt();
int fontWidth = in.readInt();
int fontEscapement = in.readInt();
int fontOrientation = in.readInt();
int fontWeight = in.readInt();
boolean fontItalic = in.readInt() != 0;
boolean fontUnderlined = in.readInt() != 0;
boolean fontStrikeout = in.readInt() != 0;
int fontCharSet = in.readInt();
int fontOutputPrecision = in.readInt();
int fontClipPrecision = in.readInt();
int fontQuality = in.readInt();
int fontPitchAndFamily = in.readInt();
String fontName = DataTools.stripString(in.readString(64));
boolean enabled = in.readShort() == 0;
boolean moveable = in.readInt() == 0;
in.skipBytes(34);
String roiID = MetadataTools.createLSID("ROI", i);
String shapeID = MetadataTools.createLSID("Shape", i, 0);
switch (type) {
case TEXT:
double x = in.readDouble();
double y = in.readDouble();
String text = DataTools.stripString(in.readCString());
store.setTextValue(text, i, 0);
store.setTextFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setTextStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setTextID(shapeID, i, 0);
break;
case LINE:
in.skipBytes(4);
double startX = in.readDouble();
double startY = in.readDouble();
double endX = in.readDouble();
double endY = in.readDouble();
store.setLineX1(startX, i, 0);
store.setLineY1(startY, i, 0);
store.setLineX2(endX, i, 0);
store.setLineY2(endY, i, 0);
store.setLineFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setLineStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setLineID(shapeID, i, 0);
break;
case SCALE_BAR:
case OPEN_ARROW:
case CLOSED_ARROW:
case PALETTE:
in.skipBytes(36);
break;
case RECTANGLE:
in.skipBytes(4);
double topX = in.readDouble();
double topY = in.readDouble();
double bottomX = in.readDouble();
double bottomY = in.readDouble();
double width = Math.abs(bottomX - topX);
double height = Math.abs(bottomY - topY);
topX = Math.min(topX, bottomX);
topY = Math.min(topY, bottomY);
store.setRectangleX(topX, i, 0);
store.setRectangleY(topY, i, 0);
store.setRectangleWidth(width, i, 0);
store.setRectangleHeight(height, i, 0);
store.setRectangleFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setRectangleStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setRectangleID(shapeID, i, 0);
break;
case ELLIPSE:
int knots = in.readInt();
double[] xs = new double[knots];
double[] ys = new double[knots];
for (int j=0; j<xs.length; j++) {
xs[j] = in.readDouble();
ys[j] = in.readDouble();
}
double rx = 0, ry = 0, centerX = 0, centerY = 0;
if (knots == 4) {
double r1x = Math.abs(xs[2] - xs[0]) / 2;
double r1y = Math.abs(ys[2] - ys[0]) / 2;
double r2x = Math.abs(xs[3] - xs[1]) / 2;
double r2y = Math.abs(ys[3] - ys[1]) / 2;
if (r1x > r2x) {
ry = r1y;
rx = r2x;
centerX = Math.min(xs[3], xs[1]) + rx;
centerY = Math.min(ys[2], ys[0]) + ry;
}
else {
ry = r2y;
rx = r1x;
centerX = Math.min(xs[2], xs[0]) + rx;
centerY = Math.min(ys[3], ys[1]) + ry;
}
}
else if (knots == 3) {
// we are given the center point and one cut point for each axis
centerX = xs[0];
centerY = ys[0];
rx = Math.sqrt(Math.pow(xs[1] - xs[0], 2) +
Math.pow(ys[1] - ys[0], 2));
ry = Math.sqrt(Math.pow(xs[2] - xs[0], 2) +
Math.pow(ys[2] - ys[0], 2));
// calculate rotation angle
double slope = (ys[2] - centerY) / (xs[2] - centerX);
double theta = Math.toDegrees(Math.atan(slope));
store.setEllipseTransform("rotate(" + theta + " " + centerX +
" " + centerY + ")", i, 0);
}
store.setEllipseX(centerX, i, 0);
store.setEllipseY(centerY, i, 0);
store.setEllipseRadiusX(rx, i, 0);
store.setEllipseRadiusY(ry, i, 0);
store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setEllipseStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setEllipseID(shapeID, i, 0);
break;
case CIRCLE:
in.skipBytes(4);
centerX = in.readDouble();
centerY = in.readDouble();
double curveX = in.readDouble();
double curveY = in.readDouble();
double radius = Math.sqrt(Math.pow(curveX - centerX, 2) +
Math.pow(curveY - centerY, 2));
store.setEllipseX(centerX, i, 0);
store.setEllipseY(centerY, i, 0);
store.setEllipseRadiusX(radius, i, 0);
store.setEllipseRadiusY(radius, i, 0);
store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setEllipseStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setEllipseID(shapeID, i, 0);
break;
case CIRCLE_3POINT:
in.skipBytes(4);
// given 3 points on the perimeter of the circle, we need to
// calculate the center and radius
double[][] points = new double[3][2];
for (int j=0; j<points.length; j++) {
for (int k=0; k<points[j].length; k++) {
points[j][k] = in.readDouble();
}
}
double s = 0.5 * ((points[1][0] - points[2][0]) *
(points[0][0] - points[2][0]) - (points[1][1] - points[2][1]) *
(points[2][1] - points[0][1]));
double div = (points[0][0] - points[1][0]) *
(points[2][1] - points[0][1]) - (points[1][1] - points[0][1]) *
(points[0][0] - points[2][0]);
s /= div;
double cx = 0.5 * (points[0][0] + points[1][0]) +
s * (points[1][1] - points[0][1]);
double cy = 0.5 * (points[0][1] + points[1][1]) +
s * (points[0][0] - points[1][0]);
double r = Math.sqrt(Math.pow(points[0][0] - cx, 2) +
Math.pow(points[0][1] - cy, 2));
store.setEllipseX(cx, i, 0);
store.setEllipseY(cy, i, 0);
store.setEllipseRadiusX(r, i, 0);
store.setEllipseRadiusY(r, i, 0);
store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setEllipseStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setEllipseID(shapeID, i, 0);
break;
case ANGLE:
in.skipBytes(4);
points = new double[3][2];
for (int j=0; j<points.length; j++) {
for (int k=0; k<points[j].length; k++) {
points[j][k] = in.readDouble();
}
}
StringBuffer p = new StringBuffer();
for (int j=0; j<points.length; j++) {
p.append(points[j][0]);
p.append(",");
p.append(points[j][1]);
if (j < points.length - 1) p.append(" ");
}
store.setPolylinePoints(p.toString(), i, 0);
store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setPolylineStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setPolylineID(shapeID, i, 0);
break;
case CLOSED_POLYLINE:
case OPEN_POLYLINE:
case POLYLINE_ARROW:
int nKnots = in.readInt();
points = new double[nKnots][2];
for (int j=0; j<points.length; j++) {
for (int k=0; k<points[j].length; k++) {
points[j][k] = in.readDouble();
}
}
p = new StringBuffer();
for (int j=0; j<points.length; j++) {
p.append(points[j][0]);
p.append(",");
p.append(points[j][1]);
if (j < points.length - 1) p.append(" ");
}
store.setPolylinePoints(p.toString(), i, 0);
store.setPolylineClosed(type == CLOSED_POLYLINE, i, 0);
store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setPolylineStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setPolylineID(shapeID, i, 0);
break;
case CLOSED_BEZIER:
case OPEN_BEZIER:
case BEZIER_WITH_ARROW:
nKnots = in.readInt();
points = new double[nKnots][2];
for (int j=0; j<points.length; j++) {
for (int k=0; k<points[j].length; k++) {
points[j][k] = in.readDouble();
}
}
p = new StringBuffer();
for (int j=0; j<points.length; j++) {
p.append(points[j][0]);
p.append(",");
p.append(points[j][1]);
if (j < points.length - 1) p.append(" ");
}
store.setPolylinePoints(p.toString(), i, 0);
store.setPolylineClosed(type != OPEN_BEZIER, i, 0);
store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setPolylineStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setPolylineID(shapeID, i, 0);
break;
default:
i--;
numberOfShapes--;
continue;
}
// populate shape attributes
in.seek(offset + blockLength);
}
totalROIs += numberOfShapes;
}
/** Parse a .mdb file and return a list of referenced .lsm files. */
private String[] parseMDB(String mdbFile) throws FormatException, IOException
{
Location mdb = new Location(mdbFile).getAbsoluteFile();
Location parent = mdb.getParentFile();
MDBService mdbService = null;
try {
ServiceFactory factory = new ServiceFactory();
mdbService = factory.getInstance(MDBService.class);
}
catch (DependencyException de) {
throw new FormatException("MDB Tools Java library not found", de);
}
try {
mdbService.initialize(mdbFile);
}
catch (Exception e) {
return null;
}
Vector<Vector<String[]>> tables = mdbService.parseDatabase();
Vector<String> referencedLSMs = new Vector<String>();
for (Vector<String[]> table : tables) {
String[] columnNames = table.get(0);
String tableName = columnNames[0];
for (int row=1; row<table.size(); row++) {
String[] tableRow = table.get(row);
for (int col=0; col<tableRow.length; col++) {
String key = tableName + " " + columnNames[col + 1] + " " + row;
if (currentId != null) {
addGlobalMeta(key, tableRow[col]);
}
if (tableName.equals("Recordings") && columnNames[col + 1] != null &&
columnNames[col + 1].equals("SampleData"))
{
String filename = tableRow[col].trim();
filename = filename.replace('\\', File.separatorChar);
filename = filename.replace('/', File.separatorChar);
filename =
filename.substring(filename.lastIndexOf(File.separator) + 1);
if (filename.length() > 0) {
Location file = new Location(parent, filename);
if (file.exists()) {
referencedLSMs.add(file.getAbsolutePath());
}
}
}
}
}
}
if (referencedLSMs.size() > 0) {
return referencedLSMs.toArray(new String[0]);
}
String[] fileList = parent.list(true);
for (int i=0; i<fileList.length; i++) {
if (checkSuffix(fileList[i], new String[] {"lsm"}) &&
!fileList[i].startsWith("."))
{
referencedLSMs.add(new Location(parent, fileList[i]).getAbsolutePath());
}
}
return referencedLSMs.toArray(new String[0]);
}
private static Hashtable<Integer, String> createKeys() {
Hashtable<Integer, String> h = new Hashtable<Integer, String>();
h.put(new Integer(0x10000001), "Name");
h.put(new Integer(0x4000000c), "Name");
h.put(new Integer(0x50000001), "Name");
h.put(new Integer(0x90000001), "Name");
h.put(new Integer(0x90000005), "Detection Channel Name");
h.put(new Integer(0xb0000003), "Name");
h.put(new Integer(0xd0000001), "Name");
h.put(new Integer(0x12000001), "Name");
h.put(new Integer(0x14000001), "Name");
h.put(new Integer(0x10000002), "Description");
h.put(new Integer(0x14000002), "Description");
h.put(new Integer(0x10000003), "Notes");
h.put(new Integer(0x10000004), "Objective");
h.put(new Integer(0x10000005), "Processing Summary");
h.put(new Integer(0x10000006), "Special Scan Mode");
h.put(new Integer(0x10000007), "Scan Type");
h.put(new Integer(0x10000008), "Scan Mode");
h.put(new Integer(0x10000009), "Number of Stacks");
h.put(new Integer(0x1000000a), "Lines Per Plane");
h.put(new Integer(0x1000000b), "Samples Per Line");
h.put(new Integer(0x1000000c), "Planes Per Volume");
h.put(new Integer(0x1000000d), "Images Width");
h.put(new Integer(0x1000000e), "Images Height");
h.put(new Integer(0x1000000f), "Number of Planes");
h.put(new Integer(0x10000010), "Number of Stacks");
h.put(new Integer(0x10000011), "Number of Channels");
h.put(new Integer(0x10000012), "Linescan XY Size");
h.put(new Integer(0x10000013), "Scan Direction");
h.put(new Integer(0x10000014), "Time Series");
h.put(new Integer(0x10000015), "Original Scan Data");
h.put(new Integer(0x10000016), "Zoom X");
h.put(new Integer(0x10000017), "Zoom Y");
h.put(new Integer(0x10000018), "Zoom Z");
h.put(new Integer(0x10000019), "Sample 0X");
h.put(new Integer(0x1000001a), "Sample 0Y");
h.put(new Integer(0x1000001b), "Sample 0Z");
h.put(new Integer(0x1000001c), "Sample Spacing");
h.put(new Integer(0x1000001d), "Line Spacing");
h.put(new Integer(0x1000001e), "Plane Spacing");
h.put(new Integer(0x1000001f), "Plane Width");
h.put(new Integer(0x10000020), "Plane Height");
h.put(new Integer(0x10000021), "Volume Depth");
h.put(new Integer(0x10000034), "Rotation");
h.put(new Integer(0x10000035), "Precession");
h.put(new Integer(0x10000036), "Sample 0Time");
h.put(new Integer(0x10000037), "Start Scan Trigger In");
h.put(new Integer(0x10000038), "Start Scan Trigger Out");
h.put(new Integer(0x10000039), "Start Scan Event");
h.put(new Integer(0x10000040), "Start Scan Time");
h.put(new Integer(0x10000041), "Stop Scan Trigger In");
h.put(new Integer(0x10000042), "Stop Scan Trigger Out");
h.put(new Integer(0x10000043), "Stop Scan Event");
h.put(new Integer(0x10000044), "Stop Scan Time");
h.put(new Integer(0x10000045), "Use ROIs");
h.put(new Integer(0x10000046), "Use Reduced Memory ROIs");
h.put(new Integer(0x10000047), "User");
h.put(new Integer(0x10000048), "Use B/C Correction");
h.put(new Integer(0x10000049), "Position B/C Contrast 1");
h.put(new Integer(0x10000050), "Position B/C Contrast 2");
h.put(new Integer(0x10000051), "Interpolation Y");
h.put(new Integer(0x10000052), "Camera Binning");
h.put(new Integer(0x10000053), "Camera Supersampling");
h.put(new Integer(0x10000054), "Camera Frame Width");
h.put(new Integer(0x10000055), "Camera Frame Height");
h.put(new Integer(0x10000056), "Camera Offset X");
h.put(new Integer(0x10000057), "Camera Offset Y");
h.put(new Integer(0x40000001), "Multiplex Type");
h.put(new Integer(0x40000002), "Multiplex Order");
h.put(new Integer(0x40000003), "Sampling Mode");
h.put(new Integer(0x40000004), "Sampling Method");
h.put(new Integer(0x40000005), "Sampling Number");
h.put(new Integer(0x40000006), "Acquire");
h.put(new Integer(0x50000002), "Acquire");
h.put(new Integer(0x7000000b), "Acquire");
h.put(new Integer(0x90000004), "Acquire");
h.put(new Integer(0xd0000017), "Acquire");
h.put(new Integer(0x40000007), "Sample Observation Time");
h.put(new Integer(0x40000008), "Time Between Stacks");
h.put(new Integer(0x4000000d), "Collimator 1 Name");
h.put(new Integer(0x4000000e), "Collimator 1 Position");
h.put(new Integer(0x4000000f), "Collimator 2 Name");
h.put(new Integer(0x40000010), "Collimator 2 Position");
h.put(new Integer(0x40000011), "Is Bleach Track");
h.put(new Integer(0x40000012), "Bleach After Scan Number");
h.put(new Integer(0x40000013), "Bleach Scan Number");
h.put(new Integer(0x40000014), "Trigger In");
h.put(new Integer(0x12000004), "Trigger In");
h.put(new Integer(0x14000003), "Trigger In");
h.put(new Integer(0x40000015), "Trigger Out");
h.put(new Integer(0x12000005), "Trigger Out");
h.put(new Integer(0x14000004), "Trigger Out");
h.put(new Integer(0x40000016), "Is Ratio Track");
h.put(new Integer(0x40000017), "Bleach Count");
h.put(new Integer(0x40000018), "SPI Center Wavelength");
h.put(new Integer(0x40000019), "Pixel Time");
h.put(new Integer(0x40000020), "ID Condensor Frontlens");
h.put(new Integer(0x40000021), "Condensor Frontlens");
h.put(new Integer(0x40000022), "ID Field Stop");
h.put(new Integer(0x40000023), "Field Stop Value");
h.put(new Integer(0x40000024), "ID Condensor Aperture");
h.put(new Integer(0x40000025), "Condensor Aperture");
h.put(new Integer(0x40000026), "ID Condensor Revolver");
h.put(new Integer(0x40000027), "Condensor Revolver");
h.put(new Integer(0x40000028), "ID Transmission Filter 1");
h.put(new Integer(0x40000029), "ID Transmission 1");
h.put(new Integer(0x40000030), "ID Transmission Filter 2");
h.put(new Integer(0x40000031), "ID Transmission 2");
h.put(new Integer(0x40000032), "Repeat Bleach");
h.put(new Integer(0x40000033), "Enable Spot Bleach Pos");
h.put(new Integer(0x40000034), "Spot Bleach Position X");
h.put(new Integer(0x40000035), "Spot Bleach Position Y");
h.put(new Integer(0x40000036), "Bleach Position Z");
h.put(new Integer(0x50000003), "Power");
h.put(new Integer(0x90000002), "Power");
h.put(new Integer(0x70000003), "Detector Gain");
h.put(new Integer(0x70000005), "Amplifier Gain");
h.put(new Integer(0x70000007), "Amplifier Offset");
h.put(new Integer(0x70000009), "Pinhole Diameter");
h.put(new Integer(0x7000000c), "Detector Name");
h.put(new Integer(0x7000000d), "Amplifier Name");
h.put(new Integer(0x7000000e), "Pinhole Name");
h.put(new Integer(0x7000000f), "Filter Set Name");
h.put(new Integer(0x70000010), "Filter Name");
h.put(new Integer(0x70000013), "Integrator Name");
h.put(new Integer(0x70000014), "Detection Channel Name");
h.put(new Integer(0x70000015), "Detector Gain B/C 1");
h.put(new Integer(0x70000016), "Detector Gain B/C 2");
h.put(new Integer(0x70000017), "Amplifier Gain B/C 1");
h.put(new Integer(0x70000018), "Amplifier Gain B/C 2");
h.put(new Integer(0x70000019), "Amplifier Offset B/C 1");
h.put(new Integer(0x70000020), "Amplifier Offset B/C 2");
h.put(new Integer(0x70000021), "Spectral Scan Channels");
h.put(new Integer(0x70000022), "SPI Wavelength Start");
h.put(new Integer(0x70000023), "SPI Wavelength End");
h.put(new Integer(0x70000026), "Dye Name");
h.put(new Integer(0xd0000014), "Dye Name");
h.put(new Integer(0x70000027), "Dye Folder");
h.put(new Integer(0xd0000015), "Dye Folder");
h.put(new Integer(0x90000003), "Wavelength");
h.put(new Integer(0x90000006), "Power B/C 1");
h.put(new Integer(0x90000007), "Power B/C 2");
h.put(new Integer(0xb0000001), "Filter Set");
h.put(new Integer(0xb0000002), "Filter");
h.put(new Integer(0xd0000004), "Color");
h.put(new Integer(0xd0000005), "Sample Type");
h.put(new Integer(0xd0000006), "Bits Per Sample");
h.put(new Integer(0xd0000007), "Ratio Type");
h.put(new Integer(0xd0000008), "Ratio Track 1");
h.put(new Integer(0xd0000009), "Ratio Track 2");
h.put(new Integer(0xd000000a), "Ratio Channel 1");
h.put(new Integer(0xd000000b), "Ratio Channel 2");
h.put(new Integer(0xd000000c), "Ratio Const. 1");
h.put(new Integer(0xd000000d), "Ratio Const. 2");
h.put(new Integer(0xd000000e), "Ratio Const. 3");
h.put(new Integer(0xd000000f), "Ratio Const. 4");
h.put(new Integer(0xd0000010), "Ratio Const. 5");
h.put(new Integer(0xd0000011), "Ratio Const. 6");
h.put(new Integer(0xd0000012), "Ratio First Images 1");
h.put(new Integer(0xd0000013), "Ratio First Images 2");
h.put(new Integer(0xd0000016), "Spectrum");
h.put(new Integer(0x12000003), "Interval");
return h;
}
private Integer readEntry() throws IOException {
return new Integer(in.readInt());
}
private Object readValue() throws IOException {
int blockType = in.readInt();
int dataSize = in.readInt();
switch (blockType) {
case TYPE_LONG:
return new Long(in.readInt());
case TYPE_RATIONAL:
return new Double(in.readDouble());
case TYPE_ASCII:
String s = in.readString(dataSize).trim();
StringBuffer sb = new StringBuffer();
for (int i=0; i<s.length(); i++) {
if (s.charAt(i) >= 10) sb.append(s.charAt(i));
else break;
}
return sb.toString();
case TYPE_SUBBLOCK:
return null;
}
in.skipBytes(dataSize);
return "";
}
// -- Helper classes --
class SubBlock {
public Hashtable<Integer, Object> blockData;
public boolean acquire = true;
public SubBlock() {
try {
read();
}
catch (IOException e) {
LOGGER.debug("Failed to read sub-block data", e);
}
}
protected int getIntValue(int key) {
Object o = blockData.get(new Integer(key));
if (o == null) return -1;
return !(o instanceof Number) ? -1 : ((Number) o).intValue();
}
protected float getFloatValue(int key) {
Object o = blockData.get(new Integer(key));
if (o == null) return -1f;
return !(o instanceof Number) ? -1f : ((Number) o).floatValue();
}
protected double getDoubleValue(int key) {
Object o = blockData.get(new Integer(key));
if (o == null) return -1d;
return !(o instanceof Number) ? -1d : ((Number) o).doubleValue();
}
protected String getStringValue(int key) {
Object o = blockData.get(new Integer(key));
return o == null ? null : o.toString();
}
protected void read() throws IOException {
blockData = new Hashtable<Integer, Object>();
Integer entry = readEntry();
Object value = readValue();
while (value != null) {
if (!blockData.containsKey(entry)) blockData.put(entry, value);
entry = readEntry();
value = readValue();
}
}
public void addToHashtable() {
String prefix = this.getClass().getSimpleName() + " #";
int index = 1;
while (getSeriesMeta(prefix + index + " Acquire") != null) index++;
prefix += index;
Integer[] keys = blockData.keySet().toArray(new Integer[0]);
for (Integer key : keys) {
if (METADATA_KEYS.get(key) != null) {
addSeriesMeta(prefix + " " + METADATA_KEYS.get(key),
blockData.get(key));
if (METADATA_KEYS.get(key).equals("Bits Per Sample")) {
core[getSeries()].bitsPerPixel =
Integer.parseInt(blockData.get(key).toString());
}
else if (METADATA_KEYS.get(key).equals("User")) {
userName = blockData.get(key).toString();
}
}
}
addGlobalMeta(prefix + " Acquire", new Boolean(acquire));
}
}
class Recording extends SubBlock {
public String description;
public String name;
public String binning;
public String startTime;
// Objective data
public String correction, immersion;
public Integer magnification;
public Double lensNA;
public Boolean iris;
protected void read() throws IOException {
super.read();
description = getStringValue(RECORDING_DESCRIPTION);
name = getStringValue(RECORDING_NAME);
binning = getStringValue(RECORDING_CAMERA_BINNING);
if (binning != null && binning.indexOf("x") == -1) {
if (binning.equals("0")) binning = null;
else binning += "x" + binning;
}
// start time in days since Dec 30 1899
long stamp = (long) (getDoubleValue(RECORDING_SAMPLE_0TIME) * 86400000);
if (stamp > 0) {
startTime = DateTools.convertDate(stamp, DateTools.MICROSOFT);
}
zoom = getDoubleValue(RECORDING_ZOOM);
String objective = getStringValue(RECORDING_OBJECTIVE);
correction = "";
if (objective == null) objective = "";
String[] tokens = objective.split(" ");
int next = 0;
for (; next<tokens.length; next++) {
if (tokens[next].indexOf("/") != -1) break;
correction += tokens[next];
}
if (next < tokens.length) {
String p = tokens[next++];
try {
magnification = new Integer(p.substring(0, p.indexOf("/") - 1));
}
catch (NumberFormatException e) { }
try {
lensNA = new Double(p.substring(p.indexOf("/") + 1));
}
catch (NumberFormatException e) { }
}
immersion = next < tokens.length ? tokens[next++] : "Unknown";
iris = Boolean.FALSE;
if (next < tokens.length) {
iris = new Boolean(tokens[next++].trim().equalsIgnoreCase("iris"));
}
}
}
class Laser extends SubBlock {
public String medium, type, model;
public Double power;
protected void read() throws IOException {
super.read();
model = getStringValue(LASER_NAME);
type = getStringValue(LASER_NAME);
if (type == null) type = "";
medium = "";
if (type.startsWith("HeNe")) {
medium = "HeNe";
type = "Gas";
}
else if (type.startsWith("Argon")) {
medium = "Ar";
type = "Gas";
}
else if (type.equals("Titanium:Sapphire") || type.equals("Mai Tai")) {
medium = "TiSapphire";
type = "SolidState";
}
else if (type.equals("YAG")) {
medium = "";
type = "SolidState";
}
else if (type.equals("Ar/Kr")) {
medium = "";
type = "Gas";
}
acquire = getIntValue(LASER_ACQUIRE) != 0;
power = getDoubleValue(LASER_POWER);
}
}
class Track extends SubBlock {
public Double timeIncrement;
protected void read() throws IOException {
super.read();
timeIncrement = getDoubleValue(TRACK_TIME_BETWEEN_STACKS);
acquire = getIntValue(TRACK_ACQUIRE) != 0;
}
}
class DetectionChannel extends SubBlock {
public Double pinhole;
public Double gain, amplificationGain;
public String filter, filterSet;
public String channelName;
protected void read() throws IOException {
super.read();
pinhole = new Double(getDoubleValue(CHANNEL_PINHOLE_DIAMETER));
gain = new Double(getDoubleValue(CHANNEL_DETECTOR_GAIN));
amplificationGain = new Double(getDoubleValue(CHANNEL_AMPLIFIER_GAIN));
filter = getStringValue(CHANNEL_FILTER);
if (filter != null) {
filter = filter.trim();
if (filter.length() == 0 || filter.equals("None")) {
filter = null;
}
}
filterSet = getStringValue(CHANNEL_FILTER_SET);
channelName = getStringValue(CHANNEL_NAME);
acquire = getIntValue(CHANNEL_ACQUIRE) != 0;
}
}
class IlluminationChannel extends SubBlock {
public Integer wavelength;
public Double attenuation;
public String name;
protected void read() throws IOException {
super.read();
wavelength = new Integer(getIntValue(ILLUM_CHANNEL_WAVELENGTH));
attenuation = new Double(getDoubleValue(ILLUM_CHANNEL_ATTENUATION));
acquire = getIntValue(ILLUM_CHANNEL_ACQUIRE) != 0;
name = getStringValue(ILLUM_CHANNEL_NAME);
try {
wavelength = new Integer(name);
}
catch (NumberFormatException e) { }
}
}
class DataChannel extends SubBlock {
public String name;
protected void read() throws IOException {
super.read();
name = getStringValue(DATA_CHANNEL_NAME);
for (int i=0; i<name.length(); i++) {
if (name.charAt(i) < 10) {
name = name.substring(0, i);
break;
}
}
acquire = getIntValue(DATA_CHANNEL_ACQUIRE) != 0;
}
}
class BeamSplitter extends SubBlock {
public String filter, filterSet;
protected void read() throws IOException {
super.read();
filter = getStringValue(BEAM_SPLITTER_FILTER);
if (filter != null) {
filter = filter.trim();
if (filter.length() == 0 || filter.equals("None")) {
filter = null;
}
}
filterSet = getStringValue(BEAM_SPLITTER_FILTER_SET);
}
}
class Timer extends SubBlock { }
class Marker extends SubBlock { }
}
| false | true | protected void initMetadata(int series) throws FormatException, IOException {
setSeries(series);
IFDList ifds = ifdsList.get(series);
IFD ifd = ifds.get(0);
in.close();
in = new RandomAccessInputStream(getLSMFileFromSeries(series));
in.order(isLittleEndian());
tiffParser = new TiffParser(in);
PhotoInterp photo = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[series].sizeX = (int) ifd.getImageWidth();
core[series].sizeY = (int) ifd.getImageLength();
core[series].rgb = samples > 1 || photo == PhotoInterp.RGB;
core[series].interleaved = false;
core[series].sizeC = isRGB() ? samples : 1;
core[series].pixelType = ifd.getPixelType();
core[series].imageCount = ifds.size();
core[series].sizeZ = getImageCount();
core[series].sizeT = 1;
LOGGER.info("Reading LSM metadata for series #{}", series);
MetadataStore store = makeFilterMetadata();
int instrument = getEffectiveSeries(series);
String imageName = getLSMFileFromSeries(series);
if (imageName.indexOf(".") != -1) {
imageName = imageName.substring(0, imageName.lastIndexOf("."));
}
if (imageName.indexOf(File.separator) != -1) {
imageName =
imageName.substring(imageName.lastIndexOf(File.separator) + 1);
}
if (lsmFilenames.length != getSeriesCount()) {
imageName += " #" + (getPosition(series) + 1);
}
// link Instrument and Image
store.setImageID(MetadataTools.createLSID("Image", series), series);
String instrumentID = MetadataTools.createLSID("Instrument", instrument);
store.setInstrumentID(instrumentID, instrument);
store.setImageInstrumentRef(instrumentID, series);
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) {
imageNames.add(imageName);
return;
}
ras.seek(16);
core[series].sizeZ = ras.readInt();
ras.skipBytes(4);
core[series].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
addSeriesMeta("DataType", "12 bit unsigned integer");
break;
case 5:
addSeriesMeta("DataType", "32 bit float");
break;
case 0:
addSeriesMeta("DataType", "varying data types");
break;
default:
addSeriesMeta("DataType", "8 bit unsigned integer");
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
ras.seek(0);
addSeriesMeta("MagicNumber ", ras.readInt());
addSeriesMeta("StructureSize", ras.readInt());
addSeriesMeta("DimensionX", ras.readInt());
addSeriesMeta("DimensionY", ras.readInt());
ras.seek(32);
addSeriesMeta("ThumbnailX", ras.readInt());
addSeriesMeta("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
addSeriesMeta("VoxelSizeX", new Double(pixelSizeX));
addSeriesMeta("VoxelSizeY", new Double(pixelSizeY));
addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ));
originX = ras.readDouble() * 1000000;
originY = ras.readDouble() * 1000000;
originZ = ras.readDouble() * 1000000;
addSeriesMeta("OriginX", originX);
addSeriesMeta("OriginY", originY);
addSeriesMeta("OriginZ", originZ);
}
else ras.seek(88);
int scanType = ras.readShort();
switch (scanType) {
case 0:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
break;
case 1:
addSeriesMeta("ScanType", "z scan (x-z plane)");
core[series].dimensionOrder = "XYZCT";
break;
case 2:
addSeriesMeta("ScanType", "line scan");
core[series].dimensionOrder = "XYZCT";
break;
case 3:
addSeriesMeta("ScanType", "time series x-y");
core[series].dimensionOrder = "XYTCZ";
break;
case 4:
addSeriesMeta("ScanType", "time series x-z");
core[series].dimensionOrder = "XYZTC";
break;
case 5:
addSeriesMeta("ScanType", "time series 'Mean of ROIs'");
core[series].dimensionOrder = "XYTCZ";
break;
case 6:
addSeriesMeta("ScanType", "time series x-y-z");
core[series].dimensionOrder = "XYZTC";
break;
case 7:
addSeriesMeta("ScanType", "spline scan");
core[series].dimensionOrder = "XYCTZ";
break;
case 8:
addSeriesMeta("ScanType", "spline scan x-z");
core[series].dimensionOrder = "XYCZT";
break;
case 9:
addSeriesMeta("ScanType", "time series spline plane x-z");
core[series].dimensionOrder = "XYTCZ";
break;
case 10:
addSeriesMeta("ScanType", "point mode");
core[series].dimensionOrder = "XYZCT";
break;
default:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
}
core[series].indexed = lut != null && lut[series] != null;
if (isIndexed()) {
core[series].rgb = false;
}
if (getSizeC() == 0) core[series].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[series].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
if (getEffectiveSizeC() == 0) {
core[series].imageCount = getSizeZ() * getSizeT();
}
else {
core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
}
if (getImageCount() != ifds.size()) {
int diff = getImageCount() - ifds.size();
core[series].imageCount = ifds.size();
if (diff % getSizeZ() == 0) {
core[series].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[series].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[series].sizeZ = ifds.size();
core[series].sizeT = 1;
}
else if (getSizeT() > 1) {
core[series].sizeT = ifds.size();
core[series].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[series].sizeZ = getImageCount();
if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ();
long channelColorsOffset = 0;
long timeStampOffset = 0;
long eventListOffset = 0;
long scanInformationOffset = 0;
long channelWavelengthOffset = 0;
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
int spectralScan = ras.readShort();
if (spectralScan != 1) {
addSeriesMeta("SpectralScan", "no spectral scan");
}
else addSeriesMeta("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
addSeriesMeta("DataType2", "calculated data");
break;
case 2:
addSeriesMeta("DataType2", "animation");
break;
default:
addSeriesMeta("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
channelColorsOffset = ras.readInt();
addSeriesMeta("TimeInterval", ras.readDouble());
ras.skipBytes(4);
scanInformationOffset = ras.readInt();
ras.skipBytes(4);
timeStampOffset = ras.readInt();
eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
addSeriesMeta("DisplayAspectX", ras.readDouble());
addSeriesMeta("DisplayAspectY", ras.readDouble());
addSeriesMeta("DisplayAspectZ", ras.readDouble());
addSeriesMeta("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS)
{
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(series, overlayOffsets[i], overlayKeys[i], store);
}
}
totalROIs = 0;
addSeriesMeta("ToolbarFlags", ras.readInt());
channelWavelengthOffset = ras.readInt();
ras.skipBytes(64);
}
else ras.skipBytes(182);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series);
if (getSizeC() > 1) {
if (!splitPlanes) splitPlanes = isRGB();
core[series].rgb = false;
if (splitPlanes) core[series].imageCount *= getSizeC();
}
for (int c=0; c<getEffectiveSizeC(); c++) {
String lsid = MetadataTools.createLSID("Channel", series, c);
store.setChannelID(lsid, series, c);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// NB: the Zeiss LSM 5.5 specification indicates that there should be
// 15 32-bit integers here; however, there are actually 16 32-bit
// integers before the tile position offset.
// We have confirmed with Zeiss that this is correct, and the 6.0
// specification was updated to contain the correct information.
ras.skipBytes(64);
int tilePositionOffset = ras.readInt();
ras.skipBytes(36);
int positionOffset = ras.readInt();
// read referenced structures
addSeriesMeta("DimensionZ", getSizeZ());
addSeriesMeta("DimensionChannels", getSizeC());
addSeriesMeta("DimensionM", dimensionM);
addSeriesMeta("DimensionP", dimensionP);
if (positionOffset != 0) {
in.seek(positionOffset);
int nPositions = in.readInt();
for (int i=0; i<nPositions; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
xCoordinates.add(xPos);
yCoordinates.add(yPos);
zCoordinates.add(zPos);
addGlobalMeta("X position for position #" + (i + 1), xPos);
addGlobalMeta("Y position for position #" + (i + 1), yPos);
addGlobalMeta("Z position for position #" + (i + 1), zPos);
}
}
if (tilePositionOffset != 0) {
in.seek(tilePositionOffset);
int nTiles = in.readInt();
for (int i=0; i<nTiles; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
if (xCoordinates.size() > i) {
xPos += xCoordinates.get(i);
xCoordinates.setElementAt(xPos, i);
}
if (yCoordinates.size() > i) {
yPos += yCoordinates.get(i);
yCoordinates.setElementAt(yPos, i);
}
if (zCoordinates.size() > i) {
zPos += zCoordinates.get(i);
zCoordinates.setElementAt(zPos, i);
}
addGlobalMeta("X position for position #" + (i + 1), xPos);
addGlobalMeta("Y position for position #" + (i + 1), yPos);
addGlobalMeta("Z position for position #" + (i + 1), zPos);
}
}
if (channelColorsOffset != 0) {
in.seek(channelColorsOffset + 12);
int colorsOffset = in.readInt();
int namesOffset = in.readInt();
// read the color of each channel
if (colorsOffset > 0) {
in.seek(channelColorsOffset + colorsOffset);
lut[getSeries()] = new byte[getSizeC() * 3][256];
core[getSeries()].indexed = true;
for (int i=0; i<getSizeC(); i++) {
int color = in.readInt();
int red = color & 0xff;
int green = (color & 0xff00) >> 8;
int blue = (color & 0xff0000) >> 16;
for (int j=0; j<256; j++) {
lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j);
lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j);
lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j);
}
}
}
// read the name of each channel
if (namesOffset > 0) {
in.seek(channelColorsOffset + namesOffset + 4);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) {
addSeriesMeta("ChannelName" + i, name);
}
}
}
}
if (timeStampOffset != 0) {
in.seek(timeStampOffset + 8);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
addSeriesMeta("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
addSeriesMeta("Event" + i + " Time", eventTime);
addSeriesMeta("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
addSeriesMeta("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextDataChannel = nextDetectChannel = nextIllumChannel = 0;
Vector<SubBlock> blocks = new Vector<SubBlock>();
while (in.getFilePointer() < in.length() - 12) {
if (in.getFilePointer() < 0) break;
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
if (blockType == TYPE_SUBBLOCK) {
SubBlock block = null;
switch (entry) {
case SUBBLOCK_RECORDING:
block = new Recording();
break;
case SUBBLOCK_LASER:
block = new Laser();
break;
case SUBBLOCK_TRACK:
block = new Track();
break;
case SUBBLOCK_DETECTION_CHANNEL:
block = new DetectionChannel();
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
block = new IlluminationChannel();
break;
case SUBBLOCK_BEAM_SPLITTER:
block = new BeamSplitter();
break;
case SUBBLOCK_DATA_CHANNEL:
block = new DataChannel();
break;
case SUBBLOCK_TIMER:
block = new Timer();
break;
case SUBBLOCK_MARKER:
block = new Marker();
break;
}
if (block != null) {
blocks.add(block);
}
}
else if (dataSize + in.getFilePointer() <= in.length() &&
dataSize > 0)
{
in.skipBytes(dataSize);
}
else break;
}
Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>();
SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]);
for (SubBlock block : metadataBlocks) {
block.addToHashtable();
if (!block.acquire) {
nonAcquiredBlocks.add(block);
blocks.remove(block);
}
}
for (int i=0; i<blocks.size(); i++) {
SubBlock block = blocks.get(i);
// every valid IlluminationChannel must be immediately followed by
// a valid DataChannel or IlluminationChannel
if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) {
SubBlock nextBlock = blocks.get(i + 1);
if (!(nextBlock instanceof DataChannel) &&
!(nextBlock instanceof IlluminationChannel))
{
((IlluminationChannel) block).wavelength = null;
}
}
// every valid DetectionChannel must be immediately preceded by
// a valid Track or DetectionChannel
else if ((block instanceof DetectionChannel) && i > 0) {
SubBlock prevBlock = blocks.get(i - 1);
if (!(prevBlock instanceof Track) &&
!(prevBlock instanceof DetectionChannel))
{
block.acquire = false;
nonAcquiredBlocks.add(block);
}
}
if (block.acquire) populateMetadataStore(block, store, series);
}
for (SubBlock block : nonAcquiredBlocks) {
populateMetadataStore(block, store, series);
}
}
}
imageNames.add(imageName);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (userName != null) {
String experimenterID = MetadataTools.createLSID("Experimenter", 0);
store.setExperimenterID(experimenterID, 0);
store.setExperimenterUserName(userName, 0);
store.setExperimenterDisplayName(userName, 0);
}
Double pixX = new Double(pixelSizeX);
Double pixY = new Double(pixelSizeY);
Double pixZ = new Double(pixelSizeZ);
store.setPixelsPhysicalSizeX(pixX, series);
store.setPixelsPhysicalSizeY(pixY, series);
store.setPixelsPhysicalSizeZ(pixZ, series);
double firstStamp = 0;
if (timestamps.size() > 0) {
firstStamp = timestamps.get(0).doubleValue();
}
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
double thisStamp = timestamps.get(zct[2]).doubleValue();
store.setPlaneDeltaT(thisStamp - firstStamp, series, i);
int index = zct[2] + 1;
double nextStamp = index < timestamps.size() ?
timestamps.get(index).doubleValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = timestamps.get(zct[2] - 1).doubleValue();
}
store.setPlaneExposureTime(nextStamp - thisStamp, series, i);
}
if (xCoordinates.size() > series) {
store.setPlanePositionX(xCoordinates.get(series), series, i);
store.setPlanePositionY(yCoordinates.get(series), series, i);
store.setPlanePositionZ(zCoordinates.get(series), series, i);
}
}
}
ras.close();
}
| protected void initMetadata(int series) throws FormatException, IOException {
setSeries(series);
IFDList ifds = ifdsList.get(series);
IFD ifd = ifds.get(0);
in.close();
in = new RandomAccessInputStream(getLSMFileFromSeries(series));
in.order(isLittleEndian());
tiffParser = new TiffParser(in);
PhotoInterp photo = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[series].sizeX = (int) ifd.getImageWidth();
core[series].sizeY = (int) ifd.getImageLength();
core[series].rgb = samples > 1 || photo == PhotoInterp.RGB;
core[series].interleaved = false;
core[series].sizeC = isRGB() ? samples : 1;
core[series].pixelType = ifd.getPixelType();
core[series].imageCount = ifds.size();
core[series].sizeZ = getImageCount();
core[series].sizeT = 1;
LOGGER.info("Reading LSM metadata for series #{}", series);
MetadataStore store = makeFilterMetadata();
int instrument = getEffectiveSeries(series);
String imageName = getLSMFileFromSeries(series);
if (imageName.indexOf(".") != -1) {
imageName = imageName.substring(0, imageName.lastIndexOf("."));
}
if (imageName.indexOf(File.separator) != -1) {
imageName =
imageName.substring(imageName.lastIndexOf(File.separator) + 1);
}
if (lsmFilenames.length != getSeriesCount()) {
imageName += " #" + (getPosition(series) + 1);
}
// link Instrument and Image
store.setImageID(MetadataTools.createLSID("Image", series), series);
String instrumentID = MetadataTools.createLSID("Instrument", instrument);
store.setInstrumentID(instrumentID, instrument);
store.setImageInstrumentRef(instrumentID, series);
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) {
imageNames.add(imageName);
return;
}
ras.seek(16);
core[series].sizeZ = ras.readInt();
ras.skipBytes(4);
core[series].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
addSeriesMeta("DataType", "12 bit unsigned integer");
break;
case 5:
addSeriesMeta("DataType", "32 bit float");
break;
case 0:
addSeriesMeta("DataType", "varying data types");
break;
default:
addSeriesMeta("DataType", "8 bit unsigned integer");
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
ras.seek(0);
addSeriesMeta("MagicNumber ", ras.readInt());
addSeriesMeta("StructureSize", ras.readInt());
addSeriesMeta("DimensionX", ras.readInt());
addSeriesMeta("DimensionY", ras.readInt());
ras.seek(32);
addSeriesMeta("ThumbnailX", ras.readInt());
addSeriesMeta("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
addSeriesMeta("VoxelSizeX", new Double(pixelSizeX));
addSeriesMeta("VoxelSizeY", new Double(pixelSizeY));
addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ));
originX = ras.readDouble() * 1000000;
originY = ras.readDouble() * 1000000;
originZ = ras.readDouble() * 1000000;
addSeriesMeta("OriginX", originX);
addSeriesMeta("OriginY", originY);
addSeriesMeta("OriginZ", originZ);
}
else ras.seek(88);
int scanType = ras.readShort();
switch (scanType) {
case 0:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
break;
case 1:
addSeriesMeta("ScanType", "z scan (x-z plane)");
core[series].dimensionOrder = "XYZCT";
break;
case 2:
addSeriesMeta("ScanType", "line scan");
core[series].dimensionOrder = "XYZCT";
break;
case 3:
addSeriesMeta("ScanType", "time series x-y");
core[series].dimensionOrder = "XYTCZ";
break;
case 4:
addSeriesMeta("ScanType", "time series x-z");
core[series].dimensionOrder = "XYZTC";
break;
case 5:
addSeriesMeta("ScanType", "time series 'Mean of ROIs'");
core[series].dimensionOrder = "XYTCZ";
break;
case 6:
addSeriesMeta("ScanType", "time series x-y-z");
core[series].dimensionOrder = "XYZTC";
break;
case 7:
addSeriesMeta("ScanType", "spline scan");
core[series].dimensionOrder = "XYCTZ";
break;
case 8:
addSeriesMeta("ScanType", "spline scan x-z");
core[series].dimensionOrder = "XYCZT";
break;
case 9:
addSeriesMeta("ScanType", "time series spline plane x-z");
core[series].dimensionOrder = "XYTCZ";
break;
case 10:
addSeriesMeta("ScanType", "point mode");
core[series].dimensionOrder = "XYZCT";
break;
default:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
}
core[series].indexed = lut != null && lut[series] != null;
if (isIndexed()) {
core[series].rgb = false;
}
if (getSizeC() == 0) core[series].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[series].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
if (getEffectiveSizeC() == 0) {
core[series].imageCount = getSizeZ() * getSizeT();
}
else {
core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
}
if (getImageCount() != ifds.size()) {
int diff = getImageCount() - ifds.size();
core[series].imageCount = ifds.size();
if (diff % getSizeZ() == 0) {
core[series].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[series].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[series].sizeZ = ifds.size();
core[series].sizeT = 1;
}
else if (getSizeT() > 1) {
core[series].sizeT = ifds.size();
core[series].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[series].sizeZ = getImageCount();
if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ();
long channelColorsOffset = 0;
long timeStampOffset = 0;
long eventListOffset = 0;
long scanInformationOffset = 0;
long channelWavelengthOffset = 0;
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
int spectralScan = ras.readShort();
if (spectralScan != 1) {
addSeriesMeta("SpectralScan", "no spectral scan");
}
else addSeriesMeta("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
addSeriesMeta("DataType2", "calculated data");
break;
case 2:
addSeriesMeta("DataType2", "animation");
break;
default:
addSeriesMeta("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
channelColorsOffset = ras.readInt();
addSeriesMeta("TimeInterval", ras.readDouble());
ras.skipBytes(4);
scanInformationOffset = ras.readInt();
ras.skipBytes(4);
timeStampOffset = ras.readInt();
eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
addSeriesMeta("DisplayAspectX", ras.readDouble());
addSeriesMeta("DisplayAspectY", ras.readDouble());
addSeriesMeta("DisplayAspectZ", ras.readDouble());
addSeriesMeta("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS)
{
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(series, overlayOffsets[i], overlayKeys[i], store);
}
}
totalROIs = 0;
addSeriesMeta("ToolbarFlags", ras.readInt());
channelWavelengthOffset = ras.readInt();
ras.skipBytes(64);
}
else ras.skipBytes(182);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series);
if (getSizeC() > 1) {
if (!splitPlanes) splitPlanes = isRGB();
core[series].rgb = false;
if (splitPlanes) core[series].imageCount *= getSizeC();
}
for (int c=0; c<getEffectiveSizeC(); c++) {
String lsid = MetadataTools.createLSID("Channel", series, c);
store.setChannelID(lsid, series, c);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// NB: the Zeiss LSM 5.5 specification indicates that there should be
// 15 32-bit integers here; however, there are actually 16 32-bit
// integers before the tile position offset.
// We have confirmed with Zeiss that this is correct, and the 6.0
// specification was updated to contain the correct information.
ras.skipBytes(64);
int tilePositionOffset = ras.readInt();
ras.skipBytes(36);
int positionOffset = ras.readInt();
// read referenced structures
addSeriesMeta("DimensionZ", getSizeZ());
addSeriesMeta("DimensionChannels", getSizeC());
addSeriesMeta("DimensionM", dimensionM);
addSeriesMeta("DimensionP", dimensionP);
if (positionOffset != 0) {
in.seek(positionOffset);
int nPositions = in.readInt();
for (int i=0; i<nPositions; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
xCoordinates.add(xPos);
yCoordinates.add(yPos);
zCoordinates.add(zPos);
addGlobalMeta("X position for position #" + (i + 1), xPos);
addGlobalMeta("Y position for position #" + (i + 1), yPos);
addGlobalMeta("Z position for position #" + (i + 1), zPos);
}
}
if (tilePositionOffset != 0) {
in.seek(tilePositionOffset);
int nTiles = in.readInt();
for (int i=0; i<nTiles; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
if (xCoordinates.size() > i) {
xPos += xCoordinates.get(i);
xCoordinates.setElementAt(xPos, i);
}
else if (xCoordinates.size() == i - 1) {
xCoordinates.add(xPos);
}
if (yCoordinates.size() > i) {
yPos += yCoordinates.get(i);
yCoordinates.setElementAt(yPos, i);
}
else if (yCoordinates.size() == i - 1) {
yCoordinates.add(yPos);
}
if (zCoordinates.size() > i) {
zPos += zCoordinates.get(i);
zCoordinates.setElementAt(zPos, i);
}
else if (zCoordinates.size() == i - 1) {
zCoordinates.add(zPos);
}
addGlobalMeta("X position for position #" + (i + 1), xPos);
addGlobalMeta("Y position for position #" + (i + 1), yPos);
addGlobalMeta("Z position for position #" + (i + 1), zPos);
}
}
if (channelColorsOffset != 0) {
in.seek(channelColorsOffset + 12);
int colorsOffset = in.readInt();
int namesOffset = in.readInt();
// read the color of each channel
if (colorsOffset > 0) {
in.seek(channelColorsOffset + colorsOffset);
lut[getSeries()] = new byte[getSizeC() * 3][256];
core[getSeries()].indexed = true;
for (int i=0; i<getSizeC(); i++) {
int color = in.readInt();
int red = color & 0xff;
int green = (color & 0xff00) >> 8;
int blue = (color & 0xff0000) >> 16;
for (int j=0; j<256; j++) {
lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j);
lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j);
lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j);
}
}
}
// read the name of each channel
if (namesOffset > 0) {
in.seek(channelColorsOffset + namesOffset + 4);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) {
addSeriesMeta("ChannelName" + i, name);
}
}
}
}
if (timeStampOffset != 0) {
in.seek(timeStampOffset + 8);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
addSeriesMeta("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
addSeriesMeta("Event" + i + " Time", eventTime);
addSeriesMeta("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
addSeriesMeta("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextDataChannel = nextDetectChannel = nextIllumChannel = 0;
Vector<SubBlock> blocks = new Vector<SubBlock>();
while (in.getFilePointer() < in.length() - 12) {
if (in.getFilePointer() < 0) break;
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
if (blockType == TYPE_SUBBLOCK) {
SubBlock block = null;
switch (entry) {
case SUBBLOCK_RECORDING:
block = new Recording();
break;
case SUBBLOCK_LASER:
block = new Laser();
break;
case SUBBLOCK_TRACK:
block = new Track();
break;
case SUBBLOCK_DETECTION_CHANNEL:
block = new DetectionChannel();
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
block = new IlluminationChannel();
break;
case SUBBLOCK_BEAM_SPLITTER:
block = new BeamSplitter();
break;
case SUBBLOCK_DATA_CHANNEL:
block = new DataChannel();
break;
case SUBBLOCK_TIMER:
block = new Timer();
break;
case SUBBLOCK_MARKER:
block = new Marker();
break;
}
if (block != null) {
blocks.add(block);
}
}
else if (dataSize + in.getFilePointer() <= in.length() &&
dataSize > 0)
{
in.skipBytes(dataSize);
}
else break;
}
Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>();
SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]);
for (SubBlock block : metadataBlocks) {
block.addToHashtable();
if (!block.acquire) {
nonAcquiredBlocks.add(block);
blocks.remove(block);
}
}
for (int i=0; i<blocks.size(); i++) {
SubBlock block = blocks.get(i);
// every valid IlluminationChannel must be immediately followed by
// a valid DataChannel or IlluminationChannel
if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) {
SubBlock nextBlock = blocks.get(i + 1);
if (!(nextBlock instanceof DataChannel) &&
!(nextBlock instanceof IlluminationChannel))
{
((IlluminationChannel) block).wavelength = null;
}
}
// every valid DetectionChannel must be immediately preceded by
// a valid Track or DetectionChannel
else if ((block instanceof DetectionChannel) && i > 0) {
SubBlock prevBlock = blocks.get(i - 1);
if (!(prevBlock instanceof Track) &&
!(prevBlock instanceof DetectionChannel))
{
block.acquire = false;
nonAcquiredBlocks.add(block);
}
}
if (block.acquire) populateMetadataStore(block, store, series);
}
for (SubBlock block : nonAcquiredBlocks) {
populateMetadataStore(block, store, series);
}
}
}
imageNames.add(imageName);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (userName != null) {
String experimenterID = MetadataTools.createLSID("Experimenter", 0);
store.setExperimenterID(experimenterID, 0);
store.setExperimenterUserName(userName, 0);
store.setExperimenterDisplayName(userName, 0);
}
Double pixX = new Double(pixelSizeX);
Double pixY = new Double(pixelSizeY);
Double pixZ = new Double(pixelSizeZ);
store.setPixelsPhysicalSizeX(pixX, series);
store.setPixelsPhysicalSizeY(pixY, series);
store.setPixelsPhysicalSizeZ(pixZ, series);
double firstStamp = 0;
if (timestamps.size() > 0) {
firstStamp = timestamps.get(0).doubleValue();
}
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
double thisStamp = timestamps.get(zct[2]).doubleValue();
store.setPlaneDeltaT(thisStamp - firstStamp, series, i);
int index = zct[2] + 1;
double nextStamp = index < timestamps.size() ?
timestamps.get(index).doubleValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = timestamps.get(zct[2] - 1).doubleValue();
}
store.setPlaneExposureTime(nextStamp - thisStamp, series, i);
}
if (xCoordinates.size() > series) {
store.setPlanePositionX(xCoordinates.get(series), series, i);
store.setPlanePositionY(yCoordinates.get(series), series, i);
store.setPlanePositionZ(zCoordinates.get(series), series, i);
}
}
}
ras.close();
}
|
diff --git a/src/net/sourceforge/peers/gui/CallFrame.java b/src/net/sourceforge/peers/gui/CallFrame.java
index 5a9e2a7..a70d2e8 100644
--- a/src/net/sourceforge/peers/gui/CallFrame.java
+++ b/src/net/sourceforge/peers/gui/CallFrame.java
@@ -1,314 +1,318 @@
/*
This file is part of Peers.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008 Yohann Martineau
*/
package net.sourceforge.peers.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.JavaUtils;
import net.sourceforge.peers.sip.Utils;
import net.sourceforge.peers.sip.core.useragent.SipEvent;
import net.sourceforge.peers.sip.core.useragent.UserAgent;
import net.sourceforge.peers.sip.core.useragent.SipEvent.EventType;
import net.sourceforge.peers.sip.core.useragent.handlers.InviteHandler;
import net.sourceforge.peers.sip.transactionuser.Dialog;
import net.sourceforge.peers.sip.transactionuser.DialogState;
import net.sourceforge.peers.sip.transactionuser.DialogStateConfirmed;
import net.sourceforge.peers.sip.transactionuser.DialogStateEarly;
import net.sourceforge.peers.sip.transactionuser.DialogStateTerminated;
import net.sourceforge.peers.sip.transport.SipMessage;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;
public class CallFrame implements ActionListener, Observer {
//GUI strings
public static final String ACCEPT_ACTION = "Accept";
public static final String BYE_ACTION = "Bye";
public static final String CANCEL_ACTION = "Cancel";
public static final String CLOSE_ACTION = "Close";
public static final String REJECT_ACTION = "Reject";
//GUI objects
private JFrame frame;
private JPanel mainPanel;
private JLabel text;
private JButton acceptButton;
private JButton byeButton;
private JButton cancelButton;
private JButton closeButton;
private JButton rejectButton;
//sip stack objects
private String callId;
private boolean isUac;
private Dialog dialog;
private SipRequest sipRequest;
private InviteHandler inviteHandler;
private UserAgent userAgent;
//for uac
public CallFrame(String requestUri, String callId, UserAgent userAgent) {
isUac = true;
this.callId = callId;
this.userAgent = userAgent;
inviteHandler = userAgent.getUac().getInviteHandler();
frame = new JFrame(requestUri);
//TODO window listener
// frame.addWindowListener(new WindowAdapter() {
// @Override
// public void windowClosing(WindowEvent we) {
// closeFrame();
// }
// });
mainPanel = new JPanel();
text = new JLabel("Calling " + requestUri);
closeButton = new JButton(CLOSE_ACTION);
closeButton.setActionCommand(CLOSE_ACTION);
closeButton.addActionListener(this);
mainPanel.add(text);
mainPanel.add(closeButton);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
inviteHandler.addObserver(this);
}
//for uas
public CallFrame(SipResponse sipResponse, UserAgent userAgent) {
isUac = false;
sipRequest = userAgent.getSipRequest(sipResponse);
dialog = userAgent.getDialogManager().getDialog(sipResponse);
dialog.addObserver(this);
callId = dialog.getCallId();
this.userAgent = userAgent;
inviteHandler = userAgent.getUas()
.getInitialRequestManager().getInviteHandler();
}
private void acceptCall() {
SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
//FIXME redisgn interface, only use useragent
inviteHandler.acceptCall(sipRequest, dialog);
return null;
}
};
swingWorker.execute();
}
private void rejectCall() {
SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
inviteHandler.rejectCall(sipRequest);
return null;
}
};
swingWorker.execute();
}
private void cancel() {
SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
userAgent.getUac().terminate(dialog, sipRequest);
return null;
}
};
swingWorker.execute();
}
private void hangup() {
SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
userAgent.getUac().terminate(dialog);
return null;
}
};
swingWorker.execute();
}
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
Logger.debug(callId + " action performed: " + actionCommand);
if (CLOSE_ACTION.equals(actionCommand)) {
hangup();
} else if (CANCEL_ACTION.equals(actionCommand)) {
cancel();
} else if (ACCEPT_ACTION.equals(actionCommand)) {
acceptCall();
} else if (REJECT_ACTION.equals(actionCommand)) {
rejectCall();
closeFrame();
} else if (BYE_ACTION.equals(actionCommand)) {
hangup();
closeFrame();
}
}
public void update(Observable o, Object arg) {
Logger.debug("update with observable " + o + " arg = " + arg);
if (o.equals(inviteHandler)) {
if (arg instanceof SipEvent) {
SipEvent sipEvent = (SipEvent) arg;
SipMessage sipMessage = sipEvent.getSipMessage();
if (Utils.getMessageCallId(sipMessage).equals(callId)) {
manageInviteHandlerEvent(sipEvent);
}
//if event is not for this frame (conversation) simply discard it
} else {
System.err.println("invite handler notification unknown");
}
} else if (o instanceof Dialog) {
if (dialog == null) {
dialog = (Dialog) o;
}
if (arg instanceof DialogState) {
DialogState dialogState = (DialogState) arg;
updateGui(dialogState);
} else {
System.err.println("dialog notification unknown");
}
}
}
private void manageInviteHandlerEvent(SipEvent sipEvent) {
EventType eventType = sipEvent.getEventType();
switch (eventType) {
case RINGING:
dialog = userAgent.getDialogManager().getDialog(sipEvent.getSipMessage());
sipRequest = userAgent.getSipRequest(sipEvent.getSipMessage());
dialog.addObserver(this);
break;
case CALLEE_PICKUP:
dialog = userAgent.getDialogManager().getDialog(sipEvent.getSipMessage());
dialog.addObserver(this);
break;
case ERROR:
closeFrame();
break;
default:
System.err.println("unknown sip event: " + sipEvent);
break;
}
}
private void updateGui(DialogState dialogState) {
//TODO use a real state machine
//state.setText(JavaUtils.getShortClassName(dialogState.getClass()));
StringBuffer buf = new StringBuffer();
buf.append("updateGui ");
buf.append(dialog.getId());
buf.append(" [");
buf.append(JavaUtils.getShortClassName(dialog.getState().getClass()));
buf.append(" -> ");
buf.append(JavaUtils.getShortClassName(dialogState.getClass()));
buf.append("]");
Logger.debug(buf.toString());
if (dialogState instanceof DialogStateEarly) {
if (isUac && cancelButton == null) {
//TODO implement cancel in core
text.setText("Ringing " + dialog.getRemoteUri());
cancelButton = new JButton(CANCEL_ACTION);
cancelButton.setActionCommand(CANCEL_ACTION);
cancelButton.addActionListener(this);
mainPanel.remove(closeButton);
mainPanel.add(cancelButton);
frame.pack();
} else {
frame = new JFrame(dialog.getRemoteUri());
mainPanel = new JPanel();
text = new JLabel("Incoming call from " + dialog.getRemoteUri());
acceptButton = new JButton(ACCEPT_ACTION);
acceptButton.setActionCommand(ACCEPT_ACTION);
acceptButton.addActionListener(this);
rejectButton = new JButton(REJECT_ACTION);
rejectButton.setActionCommand(REJECT_ACTION);
rejectButton.addActionListener(this);
mainPanel.add(text);
mainPanel.add(acceptButton);
mainPanel.add(rejectButton);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
}
} else if (dialogState instanceof DialogStateConfirmed) {
//TODO create hangup button and remove previous buttons for both uac and uas
text.setText("Talk to " + dialog.getRemoteUri());
byeButton = new JButton(BYE_ACTION);
byeButton.setActionCommand(BYE_ACTION);
byeButton.addActionListener(this);
if (isUac) {
mainPanel.remove(closeButton);
closeButton = null;
- mainPanel.remove(cancelButton);
+ if (cancelButton != null) {
+ mainPanel.remove(cancelButton);
+ }
cancelButton = null;
} else {
mainPanel.remove(acceptButton);
acceptButton = null;
- mainPanel.remove(rejectButton);
+ if (rejectButton != null) {
+ mainPanel.remove(rejectButton);
+ }
rejectButton = null;
}
mainPanel.add(byeButton);
frame.pack();
} else if (dialogState instanceof DialogStateTerminated) {
//TODO close frame for both uac and uas
closeFrame();
}
}
private void closeFrame() {
if (frame != null) {
frame.dispose();
frame = null;
}
mainPanel = null;
text = null;
rejectButton = null;
acceptButton = null;
closeButton = null;
cancelButton = null;
byeButton = null;
}
}
| false | true | private void updateGui(DialogState dialogState) {
//TODO use a real state machine
//state.setText(JavaUtils.getShortClassName(dialogState.getClass()));
StringBuffer buf = new StringBuffer();
buf.append("updateGui ");
buf.append(dialog.getId());
buf.append(" [");
buf.append(JavaUtils.getShortClassName(dialog.getState().getClass()));
buf.append(" -> ");
buf.append(JavaUtils.getShortClassName(dialogState.getClass()));
buf.append("]");
Logger.debug(buf.toString());
if (dialogState instanceof DialogStateEarly) {
if (isUac && cancelButton == null) {
//TODO implement cancel in core
text.setText("Ringing " + dialog.getRemoteUri());
cancelButton = new JButton(CANCEL_ACTION);
cancelButton.setActionCommand(CANCEL_ACTION);
cancelButton.addActionListener(this);
mainPanel.remove(closeButton);
mainPanel.add(cancelButton);
frame.pack();
} else {
frame = new JFrame(dialog.getRemoteUri());
mainPanel = new JPanel();
text = new JLabel("Incoming call from " + dialog.getRemoteUri());
acceptButton = new JButton(ACCEPT_ACTION);
acceptButton.setActionCommand(ACCEPT_ACTION);
acceptButton.addActionListener(this);
rejectButton = new JButton(REJECT_ACTION);
rejectButton.setActionCommand(REJECT_ACTION);
rejectButton.addActionListener(this);
mainPanel.add(text);
mainPanel.add(acceptButton);
mainPanel.add(rejectButton);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
}
} else if (dialogState instanceof DialogStateConfirmed) {
//TODO create hangup button and remove previous buttons for both uac and uas
text.setText("Talk to " + dialog.getRemoteUri());
byeButton = new JButton(BYE_ACTION);
byeButton.setActionCommand(BYE_ACTION);
byeButton.addActionListener(this);
if (isUac) {
mainPanel.remove(closeButton);
closeButton = null;
mainPanel.remove(cancelButton);
cancelButton = null;
} else {
mainPanel.remove(acceptButton);
acceptButton = null;
mainPanel.remove(rejectButton);
rejectButton = null;
}
mainPanel.add(byeButton);
frame.pack();
} else if (dialogState instanceof DialogStateTerminated) {
//TODO close frame for both uac and uas
closeFrame();
}
}
| private void updateGui(DialogState dialogState) {
//TODO use a real state machine
//state.setText(JavaUtils.getShortClassName(dialogState.getClass()));
StringBuffer buf = new StringBuffer();
buf.append("updateGui ");
buf.append(dialog.getId());
buf.append(" [");
buf.append(JavaUtils.getShortClassName(dialog.getState().getClass()));
buf.append(" -> ");
buf.append(JavaUtils.getShortClassName(dialogState.getClass()));
buf.append("]");
Logger.debug(buf.toString());
if (dialogState instanceof DialogStateEarly) {
if (isUac && cancelButton == null) {
//TODO implement cancel in core
text.setText("Ringing " + dialog.getRemoteUri());
cancelButton = new JButton(CANCEL_ACTION);
cancelButton.setActionCommand(CANCEL_ACTION);
cancelButton.addActionListener(this);
mainPanel.remove(closeButton);
mainPanel.add(cancelButton);
frame.pack();
} else {
frame = new JFrame(dialog.getRemoteUri());
mainPanel = new JPanel();
text = new JLabel("Incoming call from " + dialog.getRemoteUri());
acceptButton = new JButton(ACCEPT_ACTION);
acceptButton.setActionCommand(ACCEPT_ACTION);
acceptButton.addActionListener(this);
rejectButton = new JButton(REJECT_ACTION);
rejectButton.setActionCommand(REJECT_ACTION);
rejectButton.addActionListener(this);
mainPanel.add(text);
mainPanel.add(acceptButton);
mainPanel.add(rejectButton);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
}
} else if (dialogState instanceof DialogStateConfirmed) {
//TODO create hangup button and remove previous buttons for both uac and uas
text.setText("Talk to " + dialog.getRemoteUri());
byeButton = new JButton(BYE_ACTION);
byeButton.setActionCommand(BYE_ACTION);
byeButton.addActionListener(this);
if (isUac) {
mainPanel.remove(closeButton);
closeButton = null;
if (cancelButton != null) {
mainPanel.remove(cancelButton);
}
cancelButton = null;
} else {
mainPanel.remove(acceptButton);
acceptButton = null;
if (rejectButton != null) {
mainPanel.remove(rejectButton);
}
rejectButton = null;
}
mainPanel.add(byeButton);
frame.pack();
} else if (dialogState instanceof DialogStateTerminated) {
//TODO close frame for both uac and uas
closeFrame();
}
}
|
diff --git a/core/src/main/java/org/apache/mina/filter/traffic/WriteThrottleFilter.java b/core/src/main/java/org/apache/mina/filter/traffic/WriteThrottleFilter.java
index 53976dae..e47ae03c 100644
--- a/core/src/main/java/org/apache/mina/filter/traffic/WriteThrottleFilter.java
+++ b/core/src/main/java/org/apache/mina/filter/traffic/WriteThrottleFilter.java
@@ -1,454 +1,454 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.filter.traffic;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.mina.common.IoFilter;
import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoFilterChain;
import org.apache.mina.common.IoService;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.IoSessionLogger;
import org.apache.mina.common.WriteException;
import org.apache.mina.common.WriteRequest;
import org.apache.mina.util.CopyOnWriteMap;
import org.apache.mina.util.MapBackedSet;
/**
* An {@link IoFilter} that throttles outgoing traffic to prevent a unwanted
* {@link OutOfMemoryError} under heavy load.
* <p>
* This filter will automatically enforce the specified {@link WriteThrottlePolicy}
* when the {@link IoSession#getScheduledWriteBytes() sessionScheduledWriteBytes},
* {@link IoSession#getScheduledWriteMessages() sessionScheduledWriteMessages},
* {@link IoService#getScheduledWriteBytes() serviceScheduledWriteBytes} or
* {@link IoService#getScheduledWriteMessages() serviceScheduledWriteMessages}
* exceeds the specified limit values.
* <p>
* Please add this filter at the end of the filter chain.
* @author The Apache MINA Project ([email protected])
* @version $Rev$, $Date$
*/
public class WriteThrottleFilter extends IoFilterAdapter {
private static final Set<IoService> activeServices =
new MapBackedSet<IoService>(new CopyOnWriteMap<IoService, Boolean>());
public static int getGlobalScheduledWriteMessages() {
int answer = 0;
List<IoService> inactiveServices = null;
for (IoService s: activeServices) {
if (s.isActive()) {
answer += s.getScheduledWriteMessages();
} else {
if (inactiveServices == null) {
inactiveServices = new ArrayList<IoService>();
}
inactiveServices.add(s);
}
}
if (inactiveServices != null) {
activeServices.removeAll(inactiveServices);
}
return answer;
}
public static long getGlobalScheduledWriteBytes() {
long answer = 0;
List<IoService> inactiveServices = null;
for (IoService s: activeServices) {
if (s.isActive()) {
answer += s.getScheduledWriteBytes();
} else {
if (inactiveServices == null) {
inactiveServices = new ArrayList<IoService>();
}
inactiveServices.add(s);
}
}
if (inactiveServices != null) {
activeServices.removeAll(inactiveServices);
}
return answer;
}
private static int getGlobalScheduledWriteMessages(IoService service) {
if (!activeServices.contains(service)) {
activeServices.add(service);
}
return getGlobalScheduledWriteMessages();
}
private static long getGlobalScheduledWriteBytes(IoService service) {
if (!activeServices.contains(service)) {
activeServices.add(service);
}
return getGlobalScheduledWriteBytes();
}
private final Object logLock = new Object();
private final Object blockLock = new Object();
private long lastLogTime = 0;
private int blockWaiters = 0;
private volatile WriteThrottlePolicy policy;
private volatile int maxSessionScheduledWriteMessages;
private volatile long maxSessionScheduledWriteBytes;
private volatile int maxServiceScheduledWriteMessages;
private volatile long maxServiceScheduledWriteBytes;
private volatile int maxGlobalScheduledWriteMessages;
private volatile long maxGlobalScheduledWriteBytes;
/**
* Creates a new instance with the default policy
* ({@link WriteThrottlePolicy#LOG}) and limit values.
*/
public WriteThrottleFilter() {
this(WriteThrottlePolicy.LOG);
}
/**
* Creates a new instance with the specified <tt>policy</tt> and the
* default limit values.
*/
public WriteThrottleFilter(WriteThrottlePolicy policy) {
// 4K, 64K, 128K, 64M, 256K, 128M
this(policy, 4096, 65536, 1024 * 128, 1048576 * 64, 1024 * 256, 1028576 * 128);
}
/**
* Creates a new instance with the default policy
* ({@link WriteThrottlePolicy#LOG}) and the specified limit values.
*/
public WriteThrottleFilter(
int maxSessionScheduledWriteMessages, long maxSessionScheduledWriteBytes,
int maxServiceScheduledWriteMessages, long maxServiceScheduledWriteBytes,
int maxGlobalScheduledWriteMessages, long maxGlobalScheduledWriteBytes) {
this(WriteThrottlePolicy.LOG,
maxSessionScheduledWriteMessages, maxSessionScheduledWriteBytes,
maxServiceScheduledWriteMessages, maxServiceScheduledWriteBytes,
maxGlobalScheduledWriteMessages, maxGlobalScheduledWriteBytes);
}
/**
* Creates a new instance with the specified <tt>policy</tt> and limit
* values.
*/
public WriteThrottleFilter(
WriteThrottlePolicy policy,
int maxSessionScheduledWriteMessages, long maxSessionScheduledWriteBytes,
int maxServiceScheduledWriteMessages, long maxServiceScheduledWriteBytes,
int maxGlobalScheduledWriteMessages, long maxGlobalScheduledWriteBytes) {
setPolicy(policy);
setMaxSessionScheduledWriteMessages(maxSessionScheduledWriteMessages);
setMaxSessionScheduledWriteBytes(maxSessionScheduledWriteBytes);
setMaxServiceScheduledWriteMessages(maxServiceScheduledWriteMessages);
setMaxServiceScheduledWriteBytes(maxServiceScheduledWriteBytes);
setMaxGlobalScheduledWriteMessages(maxGlobalScheduledWriteMessages);
setMaxGlobalScheduledWriteBytes(maxGlobalScheduledWriteBytes);
}
public WriteThrottlePolicy getPolicy() {
return policy;
}
public void setPolicy(WriteThrottlePolicy policy) {
if (policy == null) {
throw new NullPointerException("policy");
}
this.policy = policy;
}
public int getMaxSessionScheduledWriteMessages() {
return maxSessionScheduledWriteMessages;
}
public void setMaxSessionScheduledWriteMessages(int maxSessionScheduledWriteMessages) {
if (maxSessionScheduledWriteMessages < 0) {
maxSessionScheduledWriteMessages = 0;
}
this.maxSessionScheduledWriteMessages = maxSessionScheduledWriteMessages;
}
public long getMaxSessionScheduledWriteBytes() {
return maxSessionScheduledWriteBytes;
}
public void setMaxSessionScheduledWriteBytes(long maxSessionScheduledWriteBytes) {
if (maxSessionScheduledWriteBytes < 0) {
maxSessionScheduledWriteBytes = 0;
}
this.maxSessionScheduledWriteBytes = maxSessionScheduledWriteBytes;
}
public int getMaxServiceScheduledWriteMessages() {
return maxServiceScheduledWriteMessages;
}
public void setMaxServiceScheduledWriteMessages(int maxServiceScheduledWriteMessages) {
if (maxServiceScheduledWriteMessages < 0) {
maxServiceScheduledWriteMessages = 0;
}
this.maxServiceScheduledWriteMessages = maxServiceScheduledWriteMessages;
}
public long getMaxServiceScheduledWriteBytes() {
return maxServiceScheduledWriteBytes;
}
public void setMaxServiceScheduledWriteBytes(long maxServiceScheduledWriteBytes) {
if (maxServiceScheduledWriteBytes < 0) {
maxServiceScheduledWriteBytes = 0;
}
this.maxServiceScheduledWriteBytes = maxServiceScheduledWriteBytes;
}
public int getMaxGlobalScheduledWriteMessages() {
return maxGlobalScheduledWriteMessages;
}
public void setMaxGlobalScheduledWriteMessages(int maxGlobalScheduledWriteMessages) {
if (maxGlobalScheduledWriteMessages < 0) {
maxGlobalScheduledWriteMessages = 0;
}
this.maxGlobalScheduledWriteMessages = maxGlobalScheduledWriteMessages;
}
public long getMaxGlobalScheduledWriteBytes() {
return maxGlobalScheduledWriteBytes;
}
public void setMaxGlobalScheduledWriteBytes(long maxGlobalScheduledWriteBytes) {
if (maxGlobalScheduledWriteBytes < 0) {
maxGlobalScheduledWriteBytes = 0;
}
this.maxGlobalScheduledWriteBytes = maxGlobalScheduledWriteBytes;
}
@Override
public void onPreAdd(
IoFilterChain parent, String name, NextFilter nextFilter) throws Exception {
if (parent.contains(WriteThrottleFilter.class)) {
throw new IllegalStateException(
"Only one " + WriteThrottleFilter.class.getName() + " is allowed per chain.");
}
}
@Override
public void filterWrite(NextFilter nextFilter, IoSession session,
WriteRequest writeRequest) throws Exception {
WriteThrottlePolicy policy = getPolicy();
if (policy != WriteThrottlePolicy.OFF) {
if (!readyToWrite(session)) {
switch (policy) {
case FAIL:
log(session);
fail(session, writeRequest);
break;
case BLOCK:
log(session);
block(session);
break;
case LOG:
log(session);
break;
}
}
}
nextFilter.filterWrite(session, writeRequest);
}
private boolean readyToWrite(IoSession session) {
if (session.isClosing()) {
return true;
}
int mSession = maxSessionScheduledWriteMessages;
long bSession = maxSessionScheduledWriteBytes;
int mService = maxServiceScheduledWriteMessages;
long bService = maxServiceScheduledWriteBytes;
int mGlobal = maxGlobalScheduledWriteMessages;
long bGlobal = maxGlobalScheduledWriteBytes;
return (mSession == 0 || session.getScheduledWriteMessages() < mSession) &&
(bSession == 0 || session.getScheduledWriteBytes() < bSession) &&
(mService == 0 || session.getService().getScheduledWriteMessages() < mService) &&
(bService == 0 || session.getService().getScheduledWriteBytes() < bService) &&
(mGlobal == 0 || getGlobalScheduledWriteMessages(session.getService()) < mGlobal) &&
(bGlobal == 0 || getGlobalScheduledWriteBytes(session.getService()) < bGlobal);
}
private void log(IoSession session) {
long currentTime = System.currentTimeMillis();
// Prevent log flood by logging every 3 seconds.
boolean log;
synchronized (logLock) {
if (currentTime - lastLogTime > 3000) {
lastLogTime = currentTime;
log = true;
} else {
log = false;
}
}
if (log) {
IoSessionLogger.getLogger(session, getClass()).warn(getMessage(session));
}
}
@Override
public void messageSent(
NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
notifyWaitingWriters();
nextFilter.messageSent(session, writeRequest);
}
@Override
public void exceptionCaught(NextFilter nextFilter, IoSession session,
Throwable cause) throws Exception {
try {
nextFilter.exceptionCaught(session, cause);
} finally {
notifyWaitingWriters();
}
}
@Override
public void sessionClosed(NextFilter nextFilter, IoSession session)
throws Exception {
notifyWaitingWriters();
nextFilter.sessionClosed(session);
}
private void block(IoSession session) {
synchronized (blockLock) {
blockWaiters ++;
while (!readyToWrite(session)) {
try {
blockLock.wait();
} catch (InterruptedException e) {
// Ignore.
}
}
blockWaiters --;
}
}
private void notifyWaitingWriters() {
synchronized (blockLock) {
if (blockWaiters != 0) {
blockLock.notifyAll();
}
}
}
private void fail(IoSession session, WriteRequest writeRequest) throws WriteException {
throw new WriteFloodException(writeRequest, getMessage(session));
}
private String getMessage(IoSession session) {
int mSession = maxSessionScheduledWriteMessages;
long bSession = maxSessionScheduledWriteBytes;
int mService = maxServiceScheduledWriteMessages;
long bService = maxServiceScheduledWriteBytes;
int mGlobal = maxGlobalScheduledWriteMessages;
long bGlobal = maxGlobalScheduledWriteBytes;
StringBuilder buf = new StringBuilder(512);
buf.append("Write requests flooded - session: ");
if (mSession != 0) {
buf.append(session.getScheduledWriteMessages());
buf.append(" / ");
buf.append(mSession);
buf.append(" msgs, ");
} else {
buf.append(session.getScheduledWriteMessages());
buf.append(" / unlimited msgs, ");
}
if (bSession != 0) {
buf.append(session.getScheduledWriteBytes());
buf.append(" / ");
buf.append(bSession);
buf.append(" bytes, ");
} else {
buf.append(session.getScheduledWriteBytes());
buf.append(" / unlimited bytes, ");
}
buf.append("service: ");
if (mService != 0) {
buf.append(session.getService().getScheduledWriteMessages());
buf.append(" / ");
buf.append(mService);
buf.append(" msgs, ");
} else {
buf.append(session.getService().getScheduledWriteMessages());
buf.append(" / unlimited msgs, ");
}
if (bService != 0) {
buf.append(session.getService().getScheduledWriteBytes());
buf.append(" / ");
buf.append(bService);
buf.append(" bytes, ");
} else {
buf.append(session.getService().getScheduledWriteBytes());
buf.append(" / unlimited bytes, ");
}
buf.append("global: ");
if (mGlobal != 0) {
buf.append(getGlobalScheduledWriteMessages());
buf.append(" / ");
buf.append(mGlobal);
- buf.append(" msgs.");
+ buf.append(" msgs, ");
} else {
buf.append(getGlobalScheduledWriteMessages());
- buf.append(" / unlimited msgs.");
+ buf.append(" / unlimited msgs, ");
}
if (bGlobal != 0) {
buf.append(getGlobalScheduledWriteBytes());
buf.append(" / ");
buf.append(bGlobal);
buf.append(" bytes.");
} else {
buf.append(getGlobalScheduledWriteBytes());
buf.append(" / unlimited bytes.");
}
return buf.toString();
}
}
| false | true | private String getMessage(IoSession session) {
int mSession = maxSessionScheduledWriteMessages;
long bSession = maxSessionScheduledWriteBytes;
int mService = maxServiceScheduledWriteMessages;
long bService = maxServiceScheduledWriteBytes;
int mGlobal = maxGlobalScheduledWriteMessages;
long bGlobal = maxGlobalScheduledWriteBytes;
StringBuilder buf = new StringBuilder(512);
buf.append("Write requests flooded - session: ");
if (mSession != 0) {
buf.append(session.getScheduledWriteMessages());
buf.append(" / ");
buf.append(mSession);
buf.append(" msgs, ");
} else {
buf.append(session.getScheduledWriteMessages());
buf.append(" / unlimited msgs, ");
}
if (bSession != 0) {
buf.append(session.getScheduledWriteBytes());
buf.append(" / ");
buf.append(bSession);
buf.append(" bytes, ");
} else {
buf.append(session.getScheduledWriteBytes());
buf.append(" / unlimited bytes, ");
}
buf.append("service: ");
if (mService != 0) {
buf.append(session.getService().getScheduledWriteMessages());
buf.append(" / ");
buf.append(mService);
buf.append(" msgs, ");
} else {
buf.append(session.getService().getScheduledWriteMessages());
buf.append(" / unlimited msgs, ");
}
if (bService != 0) {
buf.append(session.getService().getScheduledWriteBytes());
buf.append(" / ");
buf.append(bService);
buf.append(" bytes, ");
} else {
buf.append(session.getService().getScheduledWriteBytes());
buf.append(" / unlimited bytes, ");
}
buf.append("global: ");
if (mGlobal != 0) {
buf.append(getGlobalScheduledWriteMessages());
buf.append(" / ");
buf.append(mGlobal);
buf.append(" msgs.");
} else {
buf.append(getGlobalScheduledWriteMessages());
buf.append(" / unlimited msgs.");
}
if (bGlobal != 0) {
buf.append(getGlobalScheduledWriteBytes());
buf.append(" / ");
buf.append(bGlobal);
buf.append(" bytes.");
} else {
buf.append(getGlobalScheduledWriteBytes());
buf.append(" / unlimited bytes.");
}
return buf.toString();
}
| private String getMessage(IoSession session) {
int mSession = maxSessionScheduledWriteMessages;
long bSession = maxSessionScheduledWriteBytes;
int mService = maxServiceScheduledWriteMessages;
long bService = maxServiceScheduledWriteBytes;
int mGlobal = maxGlobalScheduledWriteMessages;
long bGlobal = maxGlobalScheduledWriteBytes;
StringBuilder buf = new StringBuilder(512);
buf.append("Write requests flooded - session: ");
if (mSession != 0) {
buf.append(session.getScheduledWriteMessages());
buf.append(" / ");
buf.append(mSession);
buf.append(" msgs, ");
} else {
buf.append(session.getScheduledWriteMessages());
buf.append(" / unlimited msgs, ");
}
if (bSession != 0) {
buf.append(session.getScheduledWriteBytes());
buf.append(" / ");
buf.append(bSession);
buf.append(" bytes, ");
} else {
buf.append(session.getScheduledWriteBytes());
buf.append(" / unlimited bytes, ");
}
buf.append("service: ");
if (mService != 0) {
buf.append(session.getService().getScheduledWriteMessages());
buf.append(" / ");
buf.append(mService);
buf.append(" msgs, ");
} else {
buf.append(session.getService().getScheduledWriteMessages());
buf.append(" / unlimited msgs, ");
}
if (bService != 0) {
buf.append(session.getService().getScheduledWriteBytes());
buf.append(" / ");
buf.append(bService);
buf.append(" bytes, ");
} else {
buf.append(session.getService().getScheduledWriteBytes());
buf.append(" / unlimited bytes, ");
}
buf.append("global: ");
if (mGlobal != 0) {
buf.append(getGlobalScheduledWriteMessages());
buf.append(" / ");
buf.append(mGlobal);
buf.append(" msgs, ");
} else {
buf.append(getGlobalScheduledWriteMessages());
buf.append(" / unlimited msgs, ");
}
if (bGlobal != 0) {
buf.append(getGlobalScheduledWriteBytes());
buf.append(" / ");
buf.append(bGlobal);
buf.append(" bytes.");
} else {
buf.append(getGlobalScheduledWriteBytes());
buf.append(" / unlimited bytes.");
}
return buf.toString();
}
|
diff --git a/x10.compiler/src/x10/ast/X10FieldDecl_c.java b/x10.compiler/src/x10/ast/X10FieldDecl_c.java
index dc7675de8..4c8e18325 100644
--- a/x10.compiler/src/x10/ast/X10FieldDecl_c.java
+++ b/x10.compiler/src/x10/ast/X10FieldDecl_c.java
@@ -1,671 +1,672 @@
/*
* This file is part of the X10 project (http://x10-lang.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright IBM Corporation 2006-2010.
*/
package x10.ast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;
import polyglot.ast.Expr;
import polyglot.ast.FieldDecl_c;
import polyglot.ast.FlagsNode;
import polyglot.ast.FloatLit;
import polyglot.ast.Id;
import polyglot.ast.IntLit;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.ast.StringLit;
import polyglot.ast.TypeNode;
import polyglot.ast.CanonicalTypeNode;
import polyglot.frontend.AbstractGoal_c;
import polyglot.frontend.Globals;
import polyglot.frontend.Goal;
import polyglot.types.ClassDef;
import polyglot.types.Context;
import polyglot.types.FieldDef;
import polyglot.types.Flags;
import polyglot.types.InitializerDef;
import polyglot.types.LazyRef;
import polyglot.types.Name;
import polyglot.types.QName;
import polyglot.types.Ref;
import polyglot.types.SemanticException;
import polyglot.types.ContainerType;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.types.Types;
import polyglot.types.VarDef_c.ConstantValue;
import polyglot.util.CodeWriter;
import polyglot.util.CollectionUtil; import x10.util.CollectionFactory;
import polyglot.util.Position;
import polyglot.visit.ContextVisitor;
import polyglot.visit.NodeVisitor;
import polyglot.visit.PrettyPrinter;
import polyglot.visit.TypeBuilder;
import polyglot.visit.TypeCheckPreparer;
import polyglot.visit.TypeChecker;
import x10.constraint.XTerm;
import x10.errors.Errors;
import x10.extension.X10Del;
import x10.extension.X10Del_c;
import x10.extension.X10Ext;
import x10.types.ParameterType;
import x10.types.X10ClassDef;
import x10.types.X10ClassType;
import polyglot.types.Context;
import x10.types.X10Def;
import x10.types.X10FieldDef;
import x10.types.X10InitializerDef;
import x10.types.X10FieldDef_c;
import x10.types.X10ParsedClassType;
import x10.types.X10ParsedClassType_c;
import x10.types.X10ClassDef_c;
import polyglot.types.TypeSystem;
import polyglot.types.FieldInstance;
import x10.types.checker.Checker;
import x10.types.checker.Converter;
import x10.types.checker.PlaceChecker;
import x10.types.constraints.CConstraint;
import x10.types.constraints.TypeConstraint;
import x10.types.constraints.XConstrainedTerm;
import x10.visit.X10TypeChecker;
public class X10FieldDecl_c extends FieldDecl_c implements X10FieldDecl {
TypeNode hasType;
public Type hasType() {
return hasType==null ? null : hasType.type();
}
public X10FieldDecl_c(NodeFactory nf, Position pos, FlagsNode flags, TypeNode type,
Id name, Expr init)
{
super(pos, flags,
type instanceof HasTypeNode_c
? nf.UnknownTypeNode(type.position())
: type, name, init);
if (type instanceof HasTypeNode_c)
hasType = ((HasTypeNode_c) type).typeNode();
}
@Override
public Context enterScope(Context c) {
c = super.enterScope(c);
if (!c.inStaticContext() && fieldDef().thisDef() != null)
c.addVariable(fieldDef().thisDef().asInstance());
return c;
}
@Override
public X10FieldDecl_c flags(FlagsNode flags) {
return (X10FieldDecl_c) super.flags(flags);
}
@Override
public X10FieldDecl_c type(TypeNode type) {
return (X10FieldDecl_c) super.type(type);
}
@Override
public X10FieldDecl_c name(Id name) {
return (X10FieldDecl_c) super.name(name);
}
@Override
public X10FieldDecl_c init(Expr init) {
return (X10FieldDecl_c) super.init(init);
}
@Override
public X10FieldDecl_c fieldDef(FieldDef mi) {
return (X10FieldDecl_c) super.fieldDef(mi);
}
@Override
public X10FieldDef fieldDef() {
return (X10FieldDef) super.fieldDef();
}
protected X10FieldDecl_c reconstruct(TypeNode hasType) {
if (this.hasType != hasType) {
X10FieldDecl_c n = (X10FieldDecl_c) copy();
n.hasType = hasType;
return n;
}
return this;
}
public Context enterChildScope(Node child, Context c) {
Context oldC=c;
if (child == this.type || child==this.hasType) {
c = c.pushBlock();
FieldDef fi = fieldDef();
c.addVariable(fi.asInstance());
c.setVarWhoseTypeIsBeingElaborated(fi);
addInClassInvariantIfNeeded(c);
//PlaceChecker.setHereTerm(fieldDef(), c);
}
if (child == this.init) {
c = c.pushBlock();
addInClassInvariantIfNeeded(c);
PlaceChecker.setHereTerm(fieldDef(), c);
}
c = super.enterChildScope(child, c);
return c;
}
public void addInClassInvariantIfNeeded(Context c) {
if (!fieldDef().flags().isStatic()) {
// this call occurs in the body of an instance method for T.
// Pick up the real clause for T -- that information is known
// statically about "this"
Ref<? extends ContainerType> container = fieldDef().container();
if (container.known()) {
X10ClassType type = (X10ClassType) Types.get(container);
Ref<CConstraint> rc = type.x10Def().realClause();
c.addConstraint(rc);
Ref<TypeConstraint> tc = type.x10Def().typeBounds();
if (tc != null) {
c.setTypeConstraintWithContextTerms(tc);
}
}
}
}
@Override
public void setResolver(final Node parent, TypeCheckPreparer v) {
final FieldDef def = fieldDef();
Ref<ConstantValue> rx = def.constantValueRef();
if (rx instanceof LazyRef<?>) {
LazyRef<ConstantValue> r = (LazyRef<ConstantValue>) rx;
TypeChecker tc0 = new X10TypeChecker(v.job(), v.typeSystem(), v.nodeFactory(), v.getMemo());
final TypeChecker tc = (TypeChecker) tc0.context(v.context().freeze());
final Node n = this;
r.setResolver(new AbstractGoal_c("ConstantValue") {
private static final long serialVersionUID = -4839673421806815982L;
{ this.scheduler = tc.job().extensionInfo().scheduler(); }
public boolean runTask() {
if (state() == Goal.Status.RUNNING_RECURSIVE || state() == Goal.Status.RUNNING_WILL_FAIL) {
// The field is not constant if the initializer is recursive.
//
// But, we could be checking if the field is constant for another
// reference in the same file:
//
// m() { use x; }
// final int x = 1;
//
// So this is incorrect. The goal below needs to be refined to only visit the initializer.
def.setNotConstant();
}
else {
Node m = parent.visitChild(n, tc);
tc.job().nodeMemo().put(n, m);
tc.job().nodeMemo().put(m, m);
}
return true;
}
});
}
}
public Node conformanceCheck(ContextVisitor tc) {
Node result = super.conformanceCheck(tc);
// Any occurrence of a non-final static field in X10
// should be reported as an error.
if (flags().flags().isStatic() && (!flags().flags().isFinal())) {
Errors.issue(tc.job(),
new Errors.CannotDeclareStaticNonFinalField(position()));
}
FieldDef fi = fieldDef();
ContainerType ref = fi.container().get();
TypeSystem xts = (TypeSystem) ref.typeSystem();
Context context = (Context) tc.context();
if (Types.isX10Struct(ref) && !isMutable(xts, ref)) {
Flags x10flags = fi.flags();
if (! x10flags.isFinal())
Errors.issue(tc.job(),
new Errors.IllegalFieldDefinition(fi, position()));
}
checkVariance(tc);
X10MethodDecl_c.checkVisibility(tc, this);
return result;
}
protected boolean isMutable(TypeSystem xts, Type t) {
if (!(t instanceof X10ClassType)) return false;
X10ClassType ct = (X10ClassType) t;
try {
Type m = xts.systemResolver().findOne(QName.make("x10.compiler.Mutable"));
return ct.annotations().contains(m);
} catch (SemanticException e) {
return false;
}
}
protected void checkVariance(ContextVisitor tc) {
Context c = (Context) tc.context();
X10ClassDef cd;
if (c.inSuperTypeDeclaration())
cd = c.supertypeDeclarationType();
else
cd = (X10ClassDef) c.currentClassDef();
final Map<Name,ParameterType.Variance> vars = CollectionFactory.newHashMap();
for (int i = 0; i < cd.typeParameters().size(); i++) {
ParameterType pt = cd.typeParameters().get(i);
ParameterType.Variance v = cd.variances().get(i);
vars.put(pt.name(), v);
}
/*try {
if (flags().flags().isFinal()) {
Checker.checkVariancesOfType(type.position(), type.type(), ParameterType.Variance.COVARIANT, "as the type of a final field", vars, tc);
}
else {
Checker.checkVariancesOfType(type.position(), type.type(), ParameterType.Variance.INVARIANT, "as the type of a non-final field", vars, tc);
}
} catch (SemanticException e) {
Errors.issue(tc.job(), e, this);
}*/
}
protected FieldDef createFieldDef(TypeSystem ts, ClassDef ct, Flags xFlags) {
X10FieldDef fi = (X10FieldDef) ts.fieldDef(position(), Types.ref(ct.asType()), xFlags, type.typeRef(), name.id());
fi.setThisDef(((X10ClassDef) ct).thisDef());
return fi;
}
protected InitializerDef createInitializerDef(TypeSystem ts, ClassDef ct, Flags iflags) {
X10InitializerDef ii;
ii = (X10InitializerDef) super.createInitializerDef(ts, ct , iflags);
ii.setThisDef(((X10ClassDef) ct).thisDef());
return ii;
}
@Override
public Node buildTypesOverride(TypeBuilder tb) {
TypeSystem ts = (TypeSystem) tb.typeSystem();
X10FieldDecl_c n = (X10FieldDecl_c) super.buildTypesOverride(tb);
X10FieldDef fi = (X10FieldDef) n.fieldDef();
final ClassDef container = tb.currentClass();
n = (X10FieldDecl_c) X10Del_c.visitAnnotations(n, tb);
List<AnnotationNode> as = ((X10Del) n.del()).annotations();
if (as != null) {
List<Ref<? extends Type>> ats = new ArrayList<Ref<? extends Type>>(as.size());
for (AnnotationNode an : as) {
ats.add(an.annotationType().typeRef());
}
fi.setDefAnnotations(ats);
}
// Clear the static bit on properties
if (this instanceof PropertyDecl) {
Flags flags = flags().flags().clearStatic();
n = (X10FieldDecl_c) n.flags(n.flags.flags(flags));
fi.setFlags(flags);
}
// vj - shortcut and initialize the field instance if the decl has an initializer
// This is the hack to permit reading the list of properties from the StringLit initializer
// of a field, without waiting for a ConstantsChecked pass to run.
if (init instanceof StringLit) {
String val = ((StringLit) init).value();
fi.setConstantValue(val);
}
// TODO: Could infer type of final fields as LCA of types assigned in the constructor.
if (type instanceof UnknownTypeNode && init == null)
Errors.issue(tb.job(), new Errors.CannotInferFieldType(position()));
// Do not infer types of mutable fields, since there could be more than one assignment and the compiler might not see them all.
if (type instanceof UnknownTypeNode && ! flags.flags().isFinal())
Errors.issue(tb.job(), new Errors.CannotInferNonFinalFieldType(position()));
return n;
}
public static boolean shouldInferType(Node n, TypeSystem ts) {
try {
Type at = ts.systemResolver().findOne(QName.make("x10.compiler.NoInferType"));
boolean res = ((X10Ext)n.ext()).annotationMatching(at).isEmpty();
if (res == true) return true;
return res;
} catch (SemanticException e) {
return false;
}
}
@Override
public Node setResolverOverride(Node parent, TypeCheckPreparer v) {
if (type() instanceof UnknownTypeNode && init != null) {
UnknownTypeNode tn = (UnknownTypeNode) type();
NodeVisitor childv = v.enter(parent, this);
childv = childv.enter(this, init);
if (childv instanceof TypeCheckPreparer) {
TypeCheckPreparer tcp = (TypeCheckPreparer) childv;
final LazyRef<Type> r = (LazyRef<Type>) tn.typeRef();
TypeChecker tc = new X10TypeChecker(v.job(), v.typeSystem(), v.nodeFactory(), v.getMemo());
tc = (TypeChecker) tc.context(tcp.context().freeze());
r.setResolver(new TypeCheckExprGoal(this, init, tc, r));
}
}
return super.setResolverOverride(parent, v);
}
@Override
public Node typeCheckOverride(Node parent, ContextVisitor tc) {
NodeVisitor childtc = tc.enter(parent, this);
List<AnnotationNode> oldAnnotations = ((X10Ext) ext()).annotations();
List<AnnotationNode> newAnnotations = node().visitList(oldAnnotations, childtc);
// Do not infer types of native fields
if (type instanceof UnknownTypeNode && ! shouldInferType(this, tc.typeSystem()))
Errors.issue(tc.job(), new Errors.CannotInferNativeFieldType(position()));
if (hasType != null && ! flags().flags().isFinal()) {
Errors.issue(tc.job(), new Errors.OnlyValMayHaveHasType(this));
}
if (type() instanceof UnknownTypeNode && shouldInferType(this, tc.typeSystem())) {
Expr init = (Expr) this.visitChild(init(), childtc);
if (init != null) {
Type t = init.type();
if (t instanceof X10ClassType) {
X10ClassType ct = (X10ClassType) t;
if (ct.isAnonymous()) {
if (ct.interfaces().size() > 0)
t = ct.interfaces().get(0);
else
t = ct.superClass();
}
}
Context xc = enterChildScope(type(), tc.context());
t = PlaceChecker.ReplaceHereByPlaceTerm(t, xc);
LazyRef<Type> r = (LazyRef<Type>) type().typeRef();
r.update(t);
TypeNode htn = null;
{
TypeNode tn = (TypeNode) this.visitChild(type(), childtc);
if (hasType != null) {
htn = (TypeNode) visitChild(hasType, childtc);
boolean checkSubType = true;
try {
Types.checkMissingParameters(htn);
} catch (SemanticException e) {
Errors.issue(tc.job(), e, htn);
checkSubType = false;
}
if (checkSubType && ! htn.type().typeSystem().isSubtype(type().type(), htn.type(),tc.context())) {
xc = (Context) enterChildScope(init, tc.context());
Expr newInit = Converter.attemptCoercion(tc.context(xc), init, htn.type());
if (newInit == null) {
Errors.issue(tc.job(),
new Errors.TypeIsNotASubtypeOfTypeBound(type().type(),
htn.type(),
position()));
} else {
init = newInit;
r.update(newInit.type());
}
}
}
}
FlagsNode flags = (FlagsNode) this.visitChild(flags(), childtc);
Id name = (Id) this.visitChild(name(), childtc);
TypeNode tn = (TypeNode) this.visitChild(type(), childtc);
Node n = tc.leave(parent, this, reconstruct(flags, tn, name, init, htn), childtc);
if (oldAnnotations == null || oldAnnotations.isEmpty()) {
return n;
}
if (! CollectionUtil.allEqual(oldAnnotations, newAnnotations)) {
return ((X10Del) n.del()).annotations(newAnnotations);
}
return n;
}
}
return null;
}
/** Reconstruct the declaration. */
protected X10FieldDecl_c reconstruct(FlagsNode flags, TypeNode type, Id name, Expr init, TypeNode hasType) {
X10FieldDecl_c n = (X10FieldDecl_c) super.reconstruct(flags, type, name, init);
if (n.hasType != hasType) {
n.hasType = hasType;
}
return n;
}
@Override
public Node typeCheck(ContextVisitor tc) {
final TypeNode typeNode = this.type();
Type type = typeNode.type();
Type oldType = (Type)type.copy();
Context xc = (Context) enterChildScope(type(), tc.context());
Flags f = flags.flags();
try {
Types.checkMissingParameters(typeNode);
} catch (SemanticException e) {
Errors.issue(tc.job(), e, this);
}
// Need to replace here by current placeTerm in type,
// since the field of this type can be referenced across
// a place shift. So here must be bound to the current placeTerm.
type = PlaceChecker.ReplaceHereByPlaceTerm(type, xc);
TypeSystem ts = (TypeSystem) tc.typeSystem();
if (type.isVoid()) {
Errors.issue(tc.job(), new Errors.FieldCannotHaveType(typeNode.type(), position()));
type = ts.unknownType(position());
}
if (Types.isX10Struct(fieldDef().container().get()) &&
!isMutable(ts, fieldDef().container().get()) &&
! f.isFinal())
{
Errors.issue(tc.job(), new Errors.StructMayNotHaveVarFields(position()));
}
final boolean noInit = init() == null;
if (f.isStatic() && noInit) {
Errors.issue(tc.job(), new Errors.StaticFieldMustHaveInitializer(name, position()));
}
NodeFactory nf = (NodeFactory) tc.nodeFactory();
X10FieldDecl_c n = (X10FieldDecl_c) this.type((CanonicalTypeNode) nf.CanonicalTypeNode(type().position(), type).ext(type().ext().copy()));
// Add an initializer to uninitialized var field unless field is annotated @Uninitialized.
final X10FieldDef fieldDef = (X10FieldDef) n.fieldDef();
final boolean needsInit = !f.isFinal() && noInit && !Types.isUninitializedField(fieldDef, ts);
final boolean isTransient = f.isTransient() && !Types.isSuppressTransientErrorField(fieldDef,ts);
if (needsInit || isTransient) {
final boolean hasZero = Types.isHaszero(type, xc);
// creating an init.
- Expr e = Types.getZeroVal(typeNode,position().markCompilerGenerated(),tc);
+ ContextVisitor tcWithNewContext = tc.context(xc);
+ Expr e = Types.getZeroVal(typeNode,position().markCompilerGenerated(),tcWithNewContext);
if (needsInit) {
if (e != null) {
n = (X10FieldDecl_c) n.init(e);
}
}
if (isTransient) {
// transient fields (not annotated with @SuppressTransientError) must have a default value
if (!hasZero)
Errors.issue(tc.job(), new Errors.TransientFieldMustHaveTypeWithDefaultValue(n.name(), position()));
}
}
if (n.init != null) {
xc = (Context) n.enterChildScope(n.init, tc.context());
ContextVisitor childtc = tc.context(xc);
Expr newInit = Converter.attemptCoercion(childtc, n.init, oldType); // use the oldType. The type of n.init may have "here".
if (newInit == null)
Errors.issue(tc.job(),
new Errors.FieldInitTypeWrong(n.init, type, n.init.position()),
this);
else
n = n.init(newInit);
}
// Types.checkVariance(n.type(), f.isFinal() ? ParameterType.Variance.COVARIANT : ParameterType.Variance.INVARIANT,tc.job());
// check cycles in struct declaration that will cause a field of infinite size, e.g.,
// struct Z(@ERR u:Z) {}
// struct Box[T](t:T) { }
// struct InfiniteSize(@ERR x:Box[Box[InfiniteSize]]) {}
final ContainerType containerType = fieldDef.container().get();
X10ClassDef_c goalDef = Types.getDef(containerType);
if (ts.isStruct(containerType)) {
Set<X10ClassDef_c> otherStructsUsed = CollectionFactory.newHashSet();
ArrayList<X10ParsedClassType> toExamine = new ArrayList<X10ParsedClassType>();
final X10ParsedClassType_c goal = Types.myBaseType(type);
if (goal!=null) {
toExamine.add(goal);
boolean isFirstTime = true;
while (toExamine.size()>0) {
final X10ParsedClassType curr = toExamine.remove(toExamine.size() - 1);
if (!isFirstTime && Types.getDef(curr)==goalDef) {
Errors.issue(tc.job(),new Errors.StructsCircularity(position),this);
break;
}
isFirstTime = false;
if (!ts.isStruct(curr)) continue;
X10ClassDef_c def = Types.getDef(curr);
if (otherStructsUsed.contains(def)) {
continue;
}
otherStructsUsed.add(def);
toExamine.addAll(getAllTypeArgs(curr));
for (FieldDef fi : def.fields()) {
if (fi.flags().isStatic()) continue;
X10ParsedClassType fiType = Types.myBaseType(fi.type().get());
if (fiType!=null) {
toExamine.add(fiType);
toExamine.addAll(getAllTypeArgs(fiType));
}
}
}
}
}
if (f.isProperty()) {
// you cannot write: class A[T](b:T) {...}
// i.e., property base type must be a class
Type t = Types.baseType(n.type().type());
if (!(t instanceof X10ParsedClassType))
Errors.issue(tc.job(),new SemanticException("A property type cannot be a type parameter.",position),this);
}
return n;
}
public ArrayList<X10ParsedClassType> getAllTypeArgs(X10ParsedClassType curr) {
final List<Type> typeArgs = curr.typeArguments();
ArrayList<X10ParsedClassType> res = new ArrayList<X10ParsedClassType>();
if (typeArgs!=null) {
// consider: struct InfiniteSize(x:Box[Box[InfiniteSize]]) {}
// if I just add Box[InfiniteSize] to toExamine, then when I pop it and check "if (otherStructsUsed.contains(def))" then I'll ignore it.
// therefore I must also add InfiniteSize (i.e., all the type args found recursively in the type.)
ArrayList<Type> toExamineArgs = new ArrayList<Type>(typeArgs);
while (toExamineArgs.size()>0) {
Type ta = toExamineArgs.remove(toExamineArgs.size()-1);
final X10ParsedClassType_c baseTa = Types.myBaseType(ta);
if (baseTa!=null) {
res.add(baseTa);
List<Type> typeArgs2 = baseTa.typeArguments();
if (typeArgs2!=null) toExamineArgs.addAll(typeArgs2);
}
}
}
return res;
}
/** Visit the children of the declaration. */
public Node visitChildren(NodeVisitor v) {
X10FieldDecl_c n = (X10FieldDecl_c) super.visitChildren(v);
TypeNode hasType = (TypeNode) visitChild(n.hasType, v);
return n.reconstruct(hasType);
}
public Node visitSignature(NodeVisitor v) {
X10FieldDecl_c n = (X10FieldDecl_c) super.visitSignature(v);
TypeNode hasType = (TypeNode) visitChild(n.hasType, v);
return n.reconstruct(hasType);
}
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
boolean isInterface = fi != null && fi.container() != null &&
fi.container().get().toClass().flags().isInterface();
Flags fs = flags.flags();
Boolean f = fs.isFinal();
if (isInterface) {
fs = fs.clearPublic();
fs = fs.clearStatic();
}
fs = fs.clearFinal();
w.write(fs.translate());
for (Iterator<AnnotationNode> i = (((X10Ext) this.ext()).annotations()).iterator(); i.hasNext(); ) {
AnnotationNode an = i.next();
an.prettyPrint(w, tr);
w.allowBreak(0, " ");
}
if (f)
w.write("val ");
else
w.write("var ");
tr.print(this, name, w);
w.allowBreak(2, 2, ":", 1);
print(type, w, tr);
if (init != null) {
w.write(" =");
w.allowBreak(2, " ");
print(init, w, tr);
}
w.write(";");
}
public Node checkConstants(ContextVisitor tc) {
Type native_annotation_type = tc.typeSystem().NativeType();
if (!((X10Ext)ext).annotationMatching(native_annotation_type).isEmpty()) {
fi.setNotConstant();
return this;
} else {
return super.checkConstants(tc);
}
}
}
| true | true | public Node typeCheck(ContextVisitor tc) {
final TypeNode typeNode = this.type();
Type type = typeNode.type();
Type oldType = (Type)type.copy();
Context xc = (Context) enterChildScope(type(), tc.context());
Flags f = flags.flags();
try {
Types.checkMissingParameters(typeNode);
} catch (SemanticException e) {
Errors.issue(tc.job(), e, this);
}
// Need to replace here by current placeTerm in type,
// since the field of this type can be referenced across
// a place shift. So here must be bound to the current placeTerm.
type = PlaceChecker.ReplaceHereByPlaceTerm(type, xc);
TypeSystem ts = (TypeSystem) tc.typeSystem();
if (type.isVoid()) {
Errors.issue(tc.job(), new Errors.FieldCannotHaveType(typeNode.type(), position()));
type = ts.unknownType(position());
}
if (Types.isX10Struct(fieldDef().container().get()) &&
!isMutable(ts, fieldDef().container().get()) &&
! f.isFinal())
{
Errors.issue(tc.job(), new Errors.StructMayNotHaveVarFields(position()));
}
final boolean noInit = init() == null;
if (f.isStatic() && noInit) {
Errors.issue(tc.job(), new Errors.StaticFieldMustHaveInitializer(name, position()));
}
NodeFactory nf = (NodeFactory) tc.nodeFactory();
X10FieldDecl_c n = (X10FieldDecl_c) this.type((CanonicalTypeNode) nf.CanonicalTypeNode(type().position(), type).ext(type().ext().copy()));
// Add an initializer to uninitialized var field unless field is annotated @Uninitialized.
final X10FieldDef fieldDef = (X10FieldDef) n.fieldDef();
final boolean needsInit = !f.isFinal() && noInit && !Types.isUninitializedField(fieldDef, ts);
final boolean isTransient = f.isTransient() && !Types.isSuppressTransientErrorField(fieldDef,ts);
if (needsInit || isTransient) {
final boolean hasZero = Types.isHaszero(type, xc);
// creating an init.
Expr e = Types.getZeroVal(typeNode,position().markCompilerGenerated(),tc);
if (needsInit) {
if (e != null) {
n = (X10FieldDecl_c) n.init(e);
}
}
if (isTransient) {
// transient fields (not annotated with @SuppressTransientError) must have a default value
if (!hasZero)
Errors.issue(tc.job(), new Errors.TransientFieldMustHaveTypeWithDefaultValue(n.name(), position()));
}
}
if (n.init != null) {
xc = (Context) n.enterChildScope(n.init, tc.context());
ContextVisitor childtc = tc.context(xc);
Expr newInit = Converter.attemptCoercion(childtc, n.init, oldType); // use the oldType. The type of n.init may have "here".
if (newInit == null)
Errors.issue(tc.job(),
new Errors.FieldInitTypeWrong(n.init, type, n.init.position()),
this);
else
n = n.init(newInit);
}
// Types.checkVariance(n.type(), f.isFinal() ? ParameterType.Variance.COVARIANT : ParameterType.Variance.INVARIANT,tc.job());
// check cycles in struct declaration that will cause a field of infinite size, e.g.,
// struct Z(@ERR u:Z) {}
// struct Box[T](t:T) { }
// struct InfiniteSize(@ERR x:Box[Box[InfiniteSize]]) {}
final ContainerType containerType = fieldDef.container().get();
X10ClassDef_c goalDef = Types.getDef(containerType);
if (ts.isStruct(containerType)) {
Set<X10ClassDef_c> otherStructsUsed = CollectionFactory.newHashSet();
ArrayList<X10ParsedClassType> toExamine = new ArrayList<X10ParsedClassType>();
final X10ParsedClassType_c goal = Types.myBaseType(type);
if (goal!=null) {
toExamine.add(goal);
boolean isFirstTime = true;
while (toExamine.size()>0) {
final X10ParsedClassType curr = toExamine.remove(toExamine.size() - 1);
if (!isFirstTime && Types.getDef(curr)==goalDef) {
Errors.issue(tc.job(),new Errors.StructsCircularity(position),this);
break;
}
isFirstTime = false;
if (!ts.isStruct(curr)) continue;
X10ClassDef_c def = Types.getDef(curr);
if (otherStructsUsed.contains(def)) {
continue;
}
otherStructsUsed.add(def);
toExamine.addAll(getAllTypeArgs(curr));
for (FieldDef fi : def.fields()) {
if (fi.flags().isStatic()) continue;
X10ParsedClassType fiType = Types.myBaseType(fi.type().get());
if (fiType!=null) {
toExamine.add(fiType);
toExamine.addAll(getAllTypeArgs(fiType));
}
}
}
}
}
if (f.isProperty()) {
// you cannot write: class A[T](b:T) {...}
// i.e., property base type must be a class
Type t = Types.baseType(n.type().type());
if (!(t instanceof X10ParsedClassType))
Errors.issue(tc.job(),new SemanticException("A property type cannot be a type parameter.",position),this);
}
return n;
}
| public Node typeCheck(ContextVisitor tc) {
final TypeNode typeNode = this.type();
Type type = typeNode.type();
Type oldType = (Type)type.copy();
Context xc = (Context) enterChildScope(type(), tc.context());
Flags f = flags.flags();
try {
Types.checkMissingParameters(typeNode);
} catch (SemanticException e) {
Errors.issue(tc.job(), e, this);
}
// Need to replace here by current placeTerm in type,
// since the field of this type can be referenced across
// a place shift. So here must be bound to the current placeTerm.
type = PlaceChecker.ReplaceHereByPlaceTerm(type, xc);
TypeSystem ts = (TypeSystem) tc.typeSystem();
if (type.isVoid()) {
Errors.issue(tc.job(), new Errors.FieldCannotHaveType(typeNode.type(), position()));
type = ts.unknownType(position());
}
if (Types.isX10Struct(fieldDef().container().get()) &&
!isMutable(ts, fieldDef().container().get()) &&
! f.isFinal())
{
Errors.issue(tc.job(), new Errors.StructMayNotHaveVarFields(position()));
}
final boolean noInit = init() == null;
if (f.isStatic() && noInit) {
Errors.issue(tc.job(), new Errors.StaticFieldMustHaveInitializer(name, position()));
}
NodeFactory nf = (NodeFactory) tc.nodeFactory();
X10FieldDecl_c n = (X10FieldDecl_c) this.type((CanonicalTypeNode) nf.CanonicalTypeNode(type().position(), type).ext(type().ext().copy()));
// Add an initializer to uninitialized var field unless field is annotated @Uninitialized.
final X10FieldDef fieldDef = (X10FieldDef) n.fieldDef();
final boolean needsInit = !f.isFinal() && noInit && !Types.isUninitializedField(fieldDef, ts);
final boolean isTransient = f.isTransient() && !Types.isSuppressTransientErrorField(fieldDef,ts);
if (needsInit || isTransient) {
final boolean hasZero = Types.isHaszero(type, xc);
// creating an init.
ContextVisitor tcWithNewContext = tc.context(xc);
Expr e = Types.getZeroVal(typeNode,position().markCompilerGenerated(),tcWithNewContext);
if (needsInit) {
if (e != null) {
n = (X10FieldDecl_c) n.init(e);
}
}
if (isTransient) {
// transient fields (not annotated with @SuppressTransientError) must have a default value
if (!hasZero)
Errors.issue(tc.job(), new Errors.TransientFieldMustHaveTypeWithDefaultValue(n.name(), position()));
}
}
if (n.init != null) {
xc = (Context) n.enterChildScope(n.init, tc.context());
ContextVisitor childtc = tc.context(xc);
Expr newInit = Converter.attemptCoercion(childtc, n.init, oldType); // use the oldType. The type of n.init may have "here".
if (newInit == null)
Errors.issue(tc.job(),
new Errors.FieldInitTypeWrong(n.init, type, n.init.position()),
this);
else
n = n.init(newInit);
}
// Types.checkVariance(n.type(), f.isFinal() ? ParameterType.Variance.COVARIANT : ParameterType.Variance.INVARIANT,tc.job());
// check cycles in struct declaration that will cause a field of infinite size, e.g.,
// struct Z(@ERR u:Z) {}
// struct Box[T](t:T) { }
// struct InfiniteSize(@ERR x:Box[Box[InfiniteSize]]) {}
final ContainerType containerType = fieldDef.container().get();
X10ClassDef_c goalDef = Types.getDef(containerType);
if (ts.isStruct(containerType)) {
Set<X10ClassDef_c> otherStructsUsed = CollectionFactory.newHashSet();
ArrayList<X10ParsedClassType> toExamine = new ArrayList<X10ParsedClassType>();
final X10ParsedClassType_c goal = Types.myBaseType(type);
if (goal!=null) {
toExamine.add(goal);
boolean isFirstTime = true;
while (toExamine.size()>0) {
final X10ParsedClassType curr = toExamine.remove(toExamine.size() - 1);
if (!isFirstTime && Types.getDef(curr)==goalDef) {
Errors.issue(tc.job(),new Errors.StructsCircularity(position),this);
break;
}
isFirstTime = false;
if (!ts.isStruct(curr)) continue;
X10ClassDef_c def = Types.getDef(curr);
if (otherStructsUsed.contains(def)) {
continue;
}
otherStructsUsed.add(def);
toExamine.addAll(getAllTypeArgs(curr));
for (FieldDef fi : def.fields()) {
if (fi.flags().isStatic()) continue;
X10ParsedClassType fiType = Types.myBaseType(fi.type().get());
if (fiType!=null) {
toExamine.add(fiType);
toExamine.addAll(getAllTypeArgs(fiType));
}
}
}
}
}
if (f.isProperty()) {
// you cannot write: class A[T](b:T) {...}
// i.e., property base type must be a class
Type t = Types.baseType(n.type().type());
if (!(t instanceof X10ParsedClassType))
Errors.issue(tc.job(),new SemanticException("A property type cannot be a type parameter.",position),this);
}
return n;
}
|
diff --git a/app/src/com/trovebox/android/app/service/UploaderService.java b/app/src/com/trovebox/android/app/service/UploaderService.java
index bda0e8d..0c0983f 100644
--- a/app/src/com/trovebox/android/app/service/UploaderService.java
+++ b/app/src/com/trovebox/android/app/service/UploaderService.java
@@ -1,595 +1,603 @@
package com.trovebox.android.app.service;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import twitter4j.Twitter;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import com.facebook.android.Facebook;
import com.trovebox.android.app.FacebookFragment;
import com.trovebox.android.app.MainActivity;
import com.trovebox.android.app.PhotoDetailsActivity;
import com.trovebox.android.app.Preferences;
import com.trovebox.android.app.R;
import com.trovebox.android.app.TwitterFragment;
import com.trovebox.android.app.UploadActivity;
import com.trovebox.android.app.facebook.FacebookProvider;
import com.trovebox.android.app.model.Photo;
import com.trovebox.android.app.model.utils.PhotoUtils;
import com.trovebox.android.app.net.HttpEntityWithProgress.ProgressListener;
import com.trovebox.android.app.net.ITroveboxApi;
import com.trovebox.android.app.net.PhotosResponse;
import com.trovebox.android.app.net.ReturnSizes;
import com.trovebox.android.app.net.UploadResponse;
import com.trovebox.android.app.net.account.AccountLimitUtils;
import com.trovebox.android.app.provider.PhotoUpload;
import com.trovebox.android.app.provider.UploadsProviderAccessor;
import com.trovebox.android.app.twitter.TwitterProvider;
import com.trovebox.android.app.util.CommonUtils;
import com.trovebox.android.app.util.GuiUtils;
import com.trovebox.android.app.util.ImageUtils;
import com.trovebox.android.app.util.SHA1Utils;
import com.trovebox.android.app.util.TrackerUtils;
import com.trovebox.android.app.util.Utils;
public class UploaderService extends Service {
private static final int NOTIFICATION_UPLOAD_PROGRESS = 1;
private static final String TAG = UploaderService.class.getSimpleName();
private ITroveboxApi mApi;
private static ArrayList<NewPhotoObserver> sNewPhotoObservers;
private static ConnectivityChangeReceiver sReceiver;
private static MediaMountedReceiver mediaMountedReceiver;
private static Set<String> alreadyObservingPaths;
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private NotificationManager mNotificationManager;
private long mNotificationLastUpdateTime;
/**
* According to this http://stackoverflow.com/a/7370448/527759 need so send
* different request codes each time we put some extra data into intent, or
* it will not be recreated
*/
int requestCounter = 0;
/**
* Now it is static and uses weak reference
* http://stackoverflow.com/a/11408340/527759
*/
private static final class ServiceHandler extends Handler
{
private final WeakReference<UploaderService> mService;
public ServiceHandler(Looper looper, UploaderService service) {
super(looper);
mService = new WeakReference<UploaderService>(service);
}
@Override
public void handleMessage(Message msg) {
UploaderService service = mService.get();
if (service != null)
{
service.handleIntent((Intent) msg.obj);
}
}
}
@Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
HandlerThread thread = new HandlerThread(TAG);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper, this);
mApi = Preferences.getApi(this);
startFileObserver();
setUpConnectivityWatcher();
setUpMediaWatcher();
CommonUtils.debug(TAG, "Service created");
}
@Override
public void onDestroy() {
unregisterReceiver(sReceiver);
unregisterReceiver(mediaMountedReceiver);
for (NewPhotoObserver observer : sNewPhotoObservers) {
observer.stopWatching();
}
CommonUtils.debug(TAG, "Service destroyed");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
return START_STICKY;
}
private void handleIntent(Intent intent) {
if (!CommonUtils.checkLoggedInAndOnline(true))
{
return;
}
UploadsProviderAccessor uploads = new UploadsProviderAccessor(this);
List<PhotoUpload> pendingUploads = uploads.getPendingUploads();
+ boolean hasSuccessfulUploads = false;
for (PhotoUpload photoUpload : pendingUploads) {
if (!CommonUtils.checkLoggedInAndOnline(true))
{
return;
}
Log.i(TAG, "Starting upload to Trovebox: " + photoUpload.getPhotoUri());
String filePath = ImageUtils.getRealPathFromURI(this, photoUpload.getPhotoUri());
if (filePath == null || !(new File(filePath).exists())) {
uploads.delete(photoUpload.getId());
// TODO: Maybe set error, and set as "do not try again"
CommonUtils.info(TAG, "Upload canceled, because file does not exist anymore.");
continue;
}
boolean wifiOnlyUpload = Preferences
.isWiFiOnlyUploadActive(getBaseContext());
if (wifiOnlyUpload && !Utils.isWiFiActive(getBaseContext()))
{
CommonUtils.info(TAG, "Upload canceled because WiFi is not active anymore");
break;
}
File file = new File(filePath);
stopErrorNotification(file);
try {
String hash = SHA1Utils.computeSha1ForFile(filePath);
PhotosResponse photos = mApi.getPhotos(hash);
if(!photos.isSuccess())
{
uploads.setError(photoUpload.getId(),
photos.getAlertMessage());
showErrorNotification(photoUpload, file);
continue;
}
Photo photo = null;
boolean skipped = false;
if (photos.getPhotos().size() > 0)
{
CommonUtils.debug(TAG, "The photo " + filePath
+ " with hash " + hash
+ " already found on the server. Skip uploading");
skipped = true;
photo = photos.getPhotos().get(0);
} else
{
long start = System.currentTimeMillis();
final Notification notification = CommonUtils.isIceCreamSandwichOrHigher() ? null
: showUploadNotification(file);
final NotificationCompat.Builder builder = CommonUtils
.isIceCreamSandwichOrHigher() ? getStandardUploadNotification(file)
: null;
UploadResponse uploadResponse = mApi.uploadPhoto(file,
photoUpload.getMetaData(),
new ProgressListener()
{
private int mLastProgress = -1;
@Override
public void transferred(long transferedBytes,
long totalBytes)
{
int newProgress = (int) (transferedBytes * 100 / totalBytes);
if (mLastProgress < newProgress)
{
mLastProgress = newProgress;
if (builder != null)
{
updateUploadNotification(builder,
mLastProgress, 100);
} else
{
updateUploadNotification(notification, mLastProgress,
100);
}
}
}
});
if(uploadResponse.isSuccess())
{
Log.i(TAG, "Upload to Trovebox completed for: "
+ photoUpload.getPhotoUri());
photo = uploadResponse.getPhoto();
TrackerUtils.trackDataLoadTiming(System.currentTimeMillis() - start,
"photoUpload", TAG);
} else
{
photoUpload.setError(uploadResponse.getAlertMessage());
showErrorNotification(photoUpload, file);
continue;
}
}
Preferences.adjustRemainingUploadingLimit(-1);
+ hasSuccessfulUploads = true;
uploads.setUploaded(photoUpload.getId());
showSuccessNotification(photoUpload, file,
photo, skipped);
shareIfRequested(photoUpload, photo, true);
if (!skipped)
{
TrackerUtils.trackServiceEvent("photo_upload", TAG);
UploaderServiceUtils.sendPhotoUploadedBroadcast();
} else
{
TrackerUtils.trackServiceEvent("photo_upload_skip", TAG);
}
} catch (Exception e) {
uploads.setError(photoUpload.getId(),
e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
showErrorNotification(photoUpload, file);
GuiUtils.processError(TAG,
R.string.errorCouldNotUploadTakenPhoto,
e,
getApplicationContext(), !photoUpload.isAutoUpload());
}
stopUploadNotification();
}
- AccountLimitUtils.updateLimitInformationCacheIfNecessary(true);
+ // to avoid so many invalid json response errors at unauthorised wi-fi
+ // networks we need to
+ // update limit information only in case we had successful uploads
+ if (hasSuccessfulUploads)
+ {
+ AccountLimitUtils.updateLimitInformationCacheIfNecessary(true);
+ }
}
public void shareIfRequested(PhotoUpload photoUpload,
Photo photo, boolean silent)
{
if (photo != null && !photo.isPrivate())
{
if (photoUpload.isShareOnTwitter())
{
shareOnTwitter(photo, silent);
}
if (photoUpload.isShareOnFacebook())
{
shareOnFacebook(photo, silent);
}
}
}
private void shareOnFacebook(Photo photo, boolean silent)
{
try
{
Facebook facebook = FacebookProvider.getFacebook();
if (facebook.isSessionValid())
{
ReturnSizes thumbSize = FacebookFragment.thumbSize;
photo = PhotoUtils.validateUrlForSizeExistAndReturn(photo, thumbSize);
FacebookFragment.sharePhoto(null, photo, thumbSize,
getApplicationContext());
}
} catch (Exception ex)
{
GuiUtils.processError(TAG, R.string.errorCouldNotSendFacebookPhoto,
ex,
getApplicationContext(),
!silent);
}
}
private void shareOnTwitter(Photo photo, boolean silent)
{
try
{
Twitter twitter = TwitterProvider
.getTwitter(getApplicationContext());
if (twitter != null)
{
String message = TwitterFragment.getDefaultTweetMessage(getApplicationContext(),
photo);
TwitterFragment.sendTweet(message, twitter);
}
} catch (Exception ex)
{
GuiUtils.processError(TAG, R.string.errorCouldNotSendTweet, ex,
getApplicationContext(),
!silent);
}
}
/**
* This is used for the devices with android version >= 4.x
*/
private NotificationCompat.Builder getStandardUploadNotification(File file)
{
int icon = R.drawable.icon;
CharSequence tickerText = getString(R.string.notification_uploading_photo, file.getName());
long when = System.currentTimeMillis();
CharSequence contentMessageTitle = getString(R.string.notification_uploading_photo,
file.getName());
// TODO adjust this to show the upload manager
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
builder
.setTicker(tickerText)
.setWhen(when)
.setSmallIcon(icon)
.setContentTitle(contentMessageTitle)
.setProgress(100, 0, true)
.setContentIntent(contentIntent);
return builder;
}
private Notification showUploadNotification(File file)
{
int icon = R.drawable.icon;
CharSequence tickerText = getString(R.string.notification_uploading_photo, file.getName());
long when = System.currentTimeMillis();
CharSequence contentMessageTitle = getString(R.string.notification_uploading_photo,
file.getName());
// TODO adjust this to show the upload manager
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_upload);
contentView.setImageViewResource(R.id.image, icon);
contentView.setTextViewText(R.id.title, contentMessageTitle);
contentView.setProgressBar(R.id.progress, 100, 0, true);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
Notification notification = builder
.setTicker(tickerText)
.setWhen(when)
.setSmallIcon(icon)
.setContentIntent(contentIntent)
.setContent(contentView)
.build();
CommonUtils.debug(TAG, "Is notification content view null: "
+ (notification.contentView == null));
// need to explicitly set contentView again because of bug in compat
// library. Solution found here
// http://stackoverflow.com/a/12574534/527759
notification.contentView = contentView;
mNotificationManager.notify(NOTIFICATION_UPLOAD_PROGRESS, notification);
return notification;
}
protected void updateUploadNotification(final Notification notification, int progress, int max) {
if (progress < max) {
long now = System.currentTimeMillis();
if (now - mNotificationLastUpdateTime < 500) {
return;
}
mNotificationLastUpdateTime = now;
notification.contentView.setProgressBar(R.id.progress, max, progress, false);
} else {
notification.contentView.setProgressBar(R.id.progress, 0, 0, true);
}
mNotificationManager.notify(NOTIFICATION_UPLOAD_PROGRESS, notification);
}
/**
* This is used to update progress in the notification message for the
* platform version >= 4.x
*/
protected void updateUploadNotification(final NotificationCompat.Builder builder, int progress,
int max) {
if (progress < max) {
long now = System.currentTimeMillis();
if (now - mNotificationLastUpdateTime < 500) {
return;
}
mNotificationLastUpdateTime = now;
builder.setProgress(max, progress, false);
} else {
builder.setProgress(0, 0, true);
}
mNotificationManager.notify(NOTIFICATION_UPLOAD_PROGRESS, builder.build());
}
private void stopUploadNotification() {
mNotificationManager.cancel(NOTIFICATION_UPLOAD_PROGRESS);
}
private void showErrorNotification(PhotoUpload photoUpload, File file) {
int icon = R.drawable.icon;
CharSequence titleText = photoUpload.getError() == null ?
getString(R.string.notification_upload_failed_title)
:getString(R.string.notification_upload_failed_title_with_reason, photoUpload.getError());
long when = System.currentTimeMillis();
CharSequence contentMessageTitle = getString(R.string.notification_upload_failed_text,
file.getName());
Intent notificationIntent = new Intent(this, UploadActivity.class);
notificationIntent.putExtra(UploadActivity.EXTRA_PENDING_UPLOAD_URI, photoUpload.getUri());
PendingIntent contentIntent = PendingIntent.getActivity(this,
requestCounter++, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
Notification notification = builder
.setContentTitle(titleText)
.setContentText(contentMessageTitle)
.setWhen(when)
.setSmallIcon(icon)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.build();
// Notification notification = new Notification(icon, titleText, when);
// notification.flags |= Notification.FLAG_AUTO_CANCEL;
// notification.setLatestEventInfo(this, titleText, contentMessageTitle,
// contentIntent);
mNotificationManager.notify(file.hashCode(), notification);
}
private void stopErrorNotification(File file) {
mNotificationManager.cancel(file.hashCode());
}
private void showSuccessNotification(PhotoUpload photoUpload, File file,
Photo photo,
boolean skipped)
{
int icon = R.drawable.icon;
CharSequence titleText = getString(
skipped ?
R.string.notification_upload_skipped_title :
R.string.notification_upload_success_title);
long when = System.currentTimeMillis();
String imageName = file.getName();
if (!TextUtils.isEmpty(photoUpload.getMetaData().getTitle())) {
imageName = photoUpload.getMetaData().getTitle();
}
CharSequence contentMessageTitle = getString(R.string.notification_upload_success_text,
imageName);
Intent notificationIntent;
if (photo != null)
{
notificationIntent = new Intent(this, PhotoDetailsActivity.class);
notificationIntent
.putExtra(PhotoDetailsActivity.EXTRA_PHOTO, photo);
} else {
notificationIntent = new Intent(this, MainActivity.class);
}
PendingIntent contentIntent = PendingIntent.getActivity(this,
requestCounter++, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
Notification notification = builder
.setContentTitle(titleText)
.setContentText(contentMessageTitle)
.setWhen(when)
.setSmallIcon(icon)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.build();
// Notification notification = new Notification(icon, titleText, when);
// notification.flags |= Notification.FLAG_AUTO_CANCEL;
// notification.setLatestEventInfo(this, titleText, contentMessageTitle,
// contentIntent);
mNotificationManager.notify(file.hashCode(), notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void setUpConnectivityWatcher() {
sReceiver = new ConnectivityChangeReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(sReceiver, filter);
}
private void setUpMediaWatcher() {
mediaMountedReceiver = new MediaMountedReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addDataScheme("file");
registerReceiver(mediaMountedReceiver, filter);
}
private synchronized void startFileObserver() {
if (sNewPhotoObservers == null)
{
sNewPhotoObservers = new ArrayList<NewPhotoObserver>();
alreadyObservingPaths = new HashSet<String>();
}
Set<String> externalMounts = Utils.getExternalMounts();
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage != null)
{
externalMounts.add(externalStorage.getAbsolutePath());
}
for (String path : externalMounts)
{
File dcim = new File(path, "DCIM");
if (dcim.isDirectory()) {
String[] dirNames = dcim.list();
if (dirNames != null)
{
for (String dir : dirNames) {
if (!dir.startsWith(".")) {
dir = dcim.getAbsolutePath() + "/" + dir;
if (alreadyObservingPaths.contains(dir))
{
CommonUtils.debug(TAG, "Directory " + dir
+ " is already observing, skipping");
continue;
}
alreadyObservingPaths.add(dir);
NewPhotoObserver observer = new NewPhotoObserver(this, dir);
sNewPhotoObservers.add(observer);
observer.startWatching();
CommonUtils.debug(TAG, "Started watching " + dir);
}
}
}
} else
{
CommonUtils.debug(TAG, "Can't find camera storage folder in " + path);
}
}
}
private class ConnectivityChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean online = Utils.isOnline(context);
boolean wifiOnlyUpload = Preferences
.isWiFiOnlyUploadActive(getBaseContext());
CommonUtils.debug(TAG, "Connectivity changed to " + (online ? "online" : "offline"));
if (online
&& (!wifiOnlyUpload || (wifiOnlyUpload && Utils
.isWiFiActive(context))))
{
context.startService(new Intent(context, UploaderService.class));
}
}
}
private class MediaMountedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
CommonUtils.debug(TAG, "Received media mounted intent");
startFileObserver();
}
}
}
| false | true | private void handleIntent(Intent intent) {
if (!CommonUtils.checkLoggedInAndOnline(true))
{
return;
}
UploadsProviderAccessor uploads = new UploadsProviderAccessor(this);
List<PhotoUpload> pendingUploads = uploads.getPendingUploads();
for (PhotoUpload photoUpload : pendingUploads) {
if (!CommonUtils.checkLoggedInAndOnline(true))
{
return;
}
Log.i(TAG, "Starting upload to Trovebox: " + photoUpload.getPhotoUri());
String filePath = ImageUtils.getRealPathFromURI(this, photoUpload.getPhotoUri());
if (filePath == null || !(new File(filePath).exists())) {
uploads.delete(photoUpload.getId());
// TODO: Maybe set error, and set as "do not try again"
CommonUtils.info(TAG, "Upload canceled, because file does not exist anymore.");
continue;
}
boolean wifiOnlyUpload = Preferences
.isWiFiOnlyUploadActive(getBaseContext());
if (wifiOnlyUpload && !Utils.isWiFiActive(getBaseContext()))
{
CommonUtils.info(TAG, "Upload canceled because WiFi is not active anymore");
break;
}
File file = new File(filePath);
stopErrorNotification(file);
try {
String hash = SHA1Utils.computeSha1ForFile(filePath);
PhotosResponse photos = mApi.getPhotos(hash);
if(!photos.isSuccess())
{
uploads.setError(photoUpload.getId(),
photos.getAlertMessage());
showErrorNotification(photoUpload, file);
continue;
}
Photo photo = null;
boolean skipped = false;
if (photos.getPhotos().size() > 0)
{
CommonUtils.debug(TAG, "The photo " + filePath
+ " with hash " + hash
+ " already found on the server. Skip uploading");
skipped = true;
photo = photos.getPhotos().get(0);
} else
{
long start = System.currentTimeMillis();
final Notification notification = CommonUtils.isIceCreamSandwichOrHigher() ? null
: showUploadNotification(file);
final NotificationCompat.Builder builder = CommonUtils
.isIceCreamSandwichOrHigher() ? getStandardUploadNotification(file)
: null;
UploadResponse uploadResponse = mApi.uploadPhoto(file,
photoUpload.getMetaData(),
new ProgressListener()
{
private int mLastProgress = -1;
@Override
public void transferred(long transferedBytes,
long totalBytes)
{
int newProgress = (int) (transferedBytes * 100 / totalBytes);
if (mLastProgress < newProgress)
{
mLastProgress = newProgress;
if (builder != null)
{
updateUploadNotification(builder,
mLastProgress, 100);
} else
{
updateUploadNotification(notification, mLastProgress,
100);
}
}
}
});
if(uploadResponse.isSuccess())
{
Log.i(TAG, "Upload to Trovebox completed for: "
+ photoUpload.getPhotoUri());
photo = uploadResponse.getPhoto();
TrackerUtils.trackDataLoadTiming(System.currentTimeMillis() - start,
"photoUpload", TAG);
} else
{
photoUpload.setError(uploadResponse.getAlertMessage());
showErrorNotification(photoUpload, file);
continue;
}
}
Preferences.adjustRemainingUploadingLimit(-1);
uploads.setUploaded(photoUpload.getId());
showSuccessNotification(photoUpload, file,
photo, skipped);
shareIfRequested(photoUpload, photo, true);
if (!skipped)
{
TrackerUtils.trackServiceEvent("photo_upload", TAG);
UploaderServiceUtils.sendPhotoUploadedBroadcast();
} else
{
TrackerUtils.trackServiceEvent("photo_upload_skip", TAG);
}
} catch (Exception e) {
uploads.setError(photoUpload.getId(),
e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
showErrorNotification(photoUpload, file);
GuiUtils.processError(TAG,
R.string.errorCouldNotUploadTakenPhoto,
e,
getApplicationContext(), !photoUpload.isAutoUpload());
}
stopUploadNotification();
}
AccountLimitUtils.updateLimitInformationCacheIfNecessary(true);
}
| private void handleIntent(Intent intent) {
if (!CommonUtils.checkLoggedInAndOnline(true))
{
return;
}
UploadsProviderAccessor uploads = new UploadsProviderAccessor(this);
List<PhotoUpload> pendingUploads = uploads.getPendingUploads();
boolean hasSuccessfulUploads = false;
for (PhotoUpload photoUpload : pendingUploads) {
if (!CommonUtils.checkLoggedInAndOnline(true))
{
return;
}
Log.i(TAG, "Starting upload to Trovebox: " + photoUpload.getPhotoUri());
String filePath = ImageUtils.getRealPathFromURI(this, photoUpload.getPhotoUri());
if (filePath == null || !(new File(filePath).exists())) {
uploads.delete(photoUpload.getId());
// TODO: Maybe set error, and set as "do not try again"
CommonUtils.info(TAG, "Upload canceled, because file does not exist anymore.");
continue;
}
boolean wifiOnlyUpload = Preferences
.isWiFiOnlyUploadActive(getBaseContext());
if (wifiOnlyUpload && !Utils.isWiFiActive(getBaseContext()))
{
CommonUtils.info(TAG, "Upload canceled because WiFi is not active anymore");
break;
}
File file = new File(filePath);
stopErrorNotification(file);
try {
String hash = SHA1Utils.computeSha1ForFile(filePath);
PhotosResponse photos = mApi.getPhotos(hash);
if(!photos.isSuccess())
{
uploads.setError(photoUpload.getId(),
photos.getAlertMessage());
showErrorNotification(photoUpload, file);
continue;
}
Photo photo = null;
boolean skipped = false;
if (photos.getPhotos().size() > 0)
{
CommonUtils.debug(TAG, "The photo " + filePath
+ " with hash " + hash
+ " already found on the server. Skip uploading");
skipped = true;
photo = photos.getPhotos().get(0);
} else
{
long start = System.currentTimeMillis();
final Notification notification = CommonUtils.isIceCreamSandwichOrHigher() ? null
: showUploadNotification(file);
final NotificationCompat.Builder builder = CommonUtils
.isIceCreamSandwichOrHigher() ? getStandardUploadNotification(file)
: null;
UploadResponse uploadResponse = mApi.uploadPhoto(file,
photoUpload.getMetaData(),
new ProgressListener()
{
private int mLastProgress = -1;
@Override
public void transferred(long transferedBytes,
long totalBytes)
{
int newProgress = (int) (transferedBytes * 100 / totalBytes);
if (mLastProgress < newProgress)
{
mLastProgress = newProgress;
if (builder != null)
{
updateUploadNotification(builder,
mLastProgress, 100);
} else
{
updateUploadNotification(notification, mLastProgress,
100);
}
}
}
});
if(uploadResponse.isSuccess())
{
Log.i(TAG, "Upload to Trovebox completed for: "
+ photoUpload.getPhotoUri());
photo = uploadResponse.getPhoto();
TrackerUtils.trackDataLoadTiming(System.currentTimeMillis() - start,
"photoUpload", TAG);
} else
{
photoUpload.setError(uploadResponse.getAlertMessage());
showErrorNotification(photoUpload, file);
continue;
}
}
Preferences.adjustRemainingUploadingLimit(-1);
hasSuccessfulUploads = true;
uploads.setUploaded(photoUpload.getId());
showSuccessNotification(photoUpload, file,
photo, skipped);
shareIfRequested(photoUpload, photo, true);
if (!skipped)
{
TrackerUtils.trackServiceEvent("photo_upload", TAG);
UploaderServiceUtils.sendPhotoUploadedBroadcast();
} else
{
TrackerUtils.trackServiceEvent("photo_upload_skip", TAG);
}
} catch (Exception e) {
uploads.setError(photoUpload.getId(),
e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
showErrorNotification(photoUpload, file);
GuiUtils.processError(TAG,
R.string.errorCouldNotUploadTakenPhoto,
e,
getApplicationContext(), !photoUpload.isAutoUpload());
}
stopUploadNotification();
}
// to avoid so many invalid json response errors at unauthorised wi-fi
// networks we need to
// update limit information only in case we had successful uploads
if (hasSuccessfulUploads)
{
AccountLimitUtils.updateLimitInformationCacheIfNecessary(true);
}
}
|
diff --git a/src/main/java/echode/api/Echode.java b/src/main/java/echode/api/Echode.java
index 7255572..b089543 100644
--- a/src/main/java/echode/api/Echode.java
+++ b/src/main/java/echode/api/Echode.java
@@ -1,254 +1,253 @@
package echode.api;
import com.google.common.eventbus.EventBus;
import echode.Test;
import echode.Time;
import echode.test.TestListener;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.UnknownHostException;
import java.util.*;
public class Echode {
Scanner scan;
private String in;
private List<Class> loaded = new ArrayList<>();
Class<?> c;
boolean started = false;
private PrintStream out;
public final EventBus EVENT_BUS = new EventBus();
public UUID uuid;
//begin eventbus-specific stuff
public abstract class ProgramLoadedEvent {
public Class program;
public String name;
public ProgramLoadedEvent(Class program, String name) {
this.program = program;
this.name = name;
}
}
public abstract class ExecEvent {
public Class program;
public String[] args;
public ExecEvent(Class program, String[] args) {
this.program = program;
this.args = args;
}
}
public Echode(PrintStream out ) {
this.out = out;
}
// welcome message
public void intro() throws ReflectiveOperationException, MalformedURLException, IOException {
EVENT_BUS.register(new TestListener());
out.println("Welcome to ECHODE version " + getAPIVersion());
reportRunAnalytic();
resetLoaded();
load();
}
private void load() throws ReflectiveOperationException, MalformedURLException {
String currentDir = System.getProperty("user.dir");
out.println("Loading programs...");
loadBuiltins();
File dir = new File(currentDir + "\\programs\\");
if (!dir.isDirectory()) {
boolean mkdir = dir.mkdir();
if (!mkdir) {
throw new RuntimeException("Making the directory failed.");
}
}
URL url = new URL("file", currentDir, "programs/");
//out.println(dir);
URL[] urls = new URL[1];
urls[0] = url;
URLClassLoader loader = new URLClassLoader(urls);
for (File f: dir.listFiles()) {
//out.println(f); Debugging
if (f.getName().trim().endsWith(".class")) {
String name = f.getName();
name = name.replaceAll(".class", "");
name = name.replace(dir.getAbsolutePath(), "");
name = name.replaceAll("/", ".");
name = name.replaceAll("\\\\", ".");
//out.println();
//out.println(name);
Class c = loader.loadClass(name);
//System.err.println(c);
//System.err.println(c);
if (c.getSuperclass().equals(Program.class)) {
add(c);
}
}
}
}
public void parse(String in2) throws ReflectiveOperationException {
/**
* Commented this out, in case needed.
*
* if (in2.equalsIgnoreCase("about")) { out.println(
* "Echode version 0.2.2\nMade by Erik Konijn and Marks Polakovs"); }
* else { if (in2.equalsIgnoreCase("kill")){
* out.println("Echode shut down successfully."); System.exit(0);
* } else{ out.println("Not implemented yet."); } }
**/
String[] result = in2.split(" ");
if (!(result.length == 0)) {
//System.err.println(result[0]);
switch (result[0]) {
case "about":
- out
- .println("Echode version " + getApiVersion()+"\nMade by Erik Konijn and Marks Polakovs");
+ out.println("Echode version " + getAPIVersion()+"\nMade by Erik Konijn and Marks Polakovs");
break;
case "kill": case "exit": case "quit":
out.println("Echode terminated succesfully.");
System.exit(0);
break;
//Help may be reimplemented at a later date
case "version":
out.println("0.3");
break;
default:
Class noparams[] = {};
for (Class ct:loaded) {
//System.err.println(ct);
String checkingName = getProgramName(ct);
if (checkingName.equalsIgnoreCase(result[0])) {
out.println("Starting program " + checkingName);
//System.err.println("equals");
String[] argv = new String[result.length - 1];
for(int i = 0;i<result.length;i++) {
if (!(i == 0)) {
argv[i-1] = result[i];
}
}
EVENT_BUS.post(new ExecEvent(ct, argv) {});
ct.getDeclaredMethod("run", PrintStream.class, String[].class).invoke(ct.getConstructors()[0].newInstance((Object[]) noparams), out, argv);
break;
} else {
}
out.println("No program found with name " + result[0]);
}
}
}
}
private void resetLoaded() {
loaded.clear();
}
private void add(Class c) throws ReflectiveOperationException {
loaded.add(c);
EVENT_BUS.post(new ProgramLoadedEvent(c, c.getName()) {
});
out.println("Loaded " + getProgramName(c));
}
private void loadBuiltins() throws ReflectiveOperationException {
add(Test.class);
add(Time.class);
}
private void reportRunAnalytic() throws IOException, ClassNotFoundException {
out.println("Beginning Google analytics report:");
writeUuidToFile();
String url = "https://ssl.google-analytics.com/collect";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Java/1.6.0_26");
String urlParameters1 = "v=1&tid=UA-44877650-2&cid=" + uuid.toString() + "&t=event&ec=echode&ea=run&el=Run&ev=300";
// Send post request
con.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters1);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
out.println("Response Code from Google Analytics: "
+ responseCode);
} catch (UnknownHostException e) {
out.println("Google Analytics reporting failed (if this"
+ " persists, contact the devs and attach the"
+ " following:\n" + e);
}
//print result
}
public void writeUuidToFile() throws IOException, ClassNotFoundException {
File file = new File("echode_uuid.ser");
if (!file.exists()) {
file.createNewFile();
FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fout);
if (uuid == null) {
uuid = UUID.randomUUID();
//System.err.println(uuid);
}
oos.writeObject(uuid);
oos.flush();
oos.close();
} else {
FileInputStream fin = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fin);
uuid = (UUID) ois.readObject();
//System.err.println(uuid);
}
out.println("Google Analytics tracking ID: " + uuid);
}
public String getAPIVersion() {
String path = "/version.prop";
InputStream stream = getClass().getResourceAsStream(path);
if (stream == null) return "UNKNOWN";
Properties props = new Properties();
try {
props.load(stream);
stream.close();
return (String)props.get("version");
} catch (IOException e) {
return "UNKNOWN";
}
}
public String getProgramName(Class<? extends Program> ct) throws ReflectiveOperationException {
Program checking = ct.getConstructor(null).newInstance(null);
return checking.getName();
}
}
| true | true | public void parse(String in2) throws ReflectiveOperationException {
/**
* Commented this out, in case needed.
*
* if (in2.equalsIgnoreCase("about")) { out.println(
* "Echode version 0.2.2\nMade by Erik Konijn and Marks Polakovs"); }
* else { if (in2.equalsIgnoreCase("kill")){
* out.println("Echode shut down successfully."); System.exit(0);
* } else{ out.println("Not implemented yet."); } }
**/
String[] result = in2.split(" ");
if (!(result.length == 0)) {
//System.err.println(result[0]);
switch (result[0]) {
case "about":
out
.println("Echode version " + getApiVersion()+"\nMade by Erik Konijn and Marks Polakovs");
break;
case "kill": case "exit": case "quit":
out.println("Echode terminated succesfully.");
System.exit(0);
break;
//Help may be reimplemented at a later date
case "version":
out.println("0.3");
break;
default:
Class noparams[] = {};
for (Class ct:loaded) {
//System.err.println(ct);
String checkingName = getProgramName(ct);
if (checkingName.equalsIgnoreCase(result[0])) {
out.println("Starting program " + checkingName);
//System.err.println("equals");
String[] argv = new String[result.length - 1];
for(int i = 0;i<result.length;i++) {
if (!(i == 0)) {
argv[i-1] = result[i];
}
}
EVENT_BUS.post(new ExecEvent(ct, argv) {});
ct.getDeclaredMethod("run", PrintStream.class, String[].class).invoke(ct.getConstructors()[0].newInstance((Object[]) noparams), out, argv);
break;
} else {
}
out.println("No program found with name " + result[0]);
}
}
}
}
| public void parse(String in2) throws ReflectiveOperationException {
/**
* Commented this out, in case needed.
*
* if (in2.equalsIgnoreCase("about")) { out.println(
* "Echode version 0.2.2\nMade by Erik Konijn and Marks Polakovs"); }
* else { if (in2.equalsIgnoreCase("kill")){
* out.println("Echode shut down successfully."); System.exit(0);
* } else{ out.println("Not implemented yet."); } }
**/
String[] result = in2.split(" ");
if (!(result.length == 0)) {
//System.err.println(result[0]);
switch (result[0]) {
case "about":
out.println("Echode version " + getAPIVersion()+"\nMade by Erik Konijn and Marks Polakovs");
break;
case "kill": case "exit": case "quit":
out.println("Echode terminated succesfully.");
System.exit(0);
break;
//Help may be reimplemented at a later date
case "version":
out.println("0.3");
break;
default:
Class noparams[] = {};
for (Class ct:loaded) {
//System.err.println(ct);
String checkingName = getProgramName(ct);
if (checkingName.equalsIgnoreCase(result[0])) {
out.println("Starting program " + checkingName);
//System.err.println("equals");
String[] argv = new String[result.length - 1];
for(int i = 0;i<result.length;i++) {
if (!(i == 0)) {
argv[i-1] = result[i];
}
}
EVENT_BUS.post(new ExecEvent(ct, argv) {});
ct.getDeclaredMethod("run", PrintStream.class, String[].class).invoke(ct.getConstructors()[0].newInstance((Object[]) noparams), out, argv);
break;
} else {
}
out.println("No program found with name " + result[0]);
}
}
}
}
|
diff --git a/src/org/biojava/bio/SmallAnnotation.java b/src/org/biojava/bio/SmallAnnotation.java
index b740a0883..761c6ea35 100644
--- a/src/org/biojava/bio/SmallAnnotation.java
+++ b/src/org/biojava/bio/SmallAnnotation.java
@@ -1,305 +1,305 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio;
import java.util.*;
import java.io.*;
import org.biojava.utils.*;
/**
* Annotation that is optimized for memory usage. Access time
* is linear, so SmallAnnotations are not recommended when
* the number of entries is large. However, they are fine for
* small numbers of keys.
*
* @author Thomas Down
* @since 1.2
*/
public class SmallAnnotation implements Annotation {
private Object[] mappings;
private int numMappings = 0;
protected transient ChangeSupport changeSupport = null;
public SmallAnnotation() {
}
public SmallAnnotation(int size) {
mappings = new Object[size * 2];
}
public Object getProperty(Object key) {
int keyHash = key.hashCode();
if (mappings != null) {
for (int i = 0; i < numMappings * 2; i += 2) {
if (keyHash == mappings[i].hashCode() && key.equals(mappings[i])) {
return mappings[i + 1];
}
}
}
throw new NoSuchElementException("Key " + key.toString() + " has no mapping");
}
public boolean containsProperty(Object key) {
int keyHash = key.hashCode();
if (mappings != null) {
for (int i = 0; i < numMappings * 2; i += 2) {
if (keyHash == mappings[i].hashCode() && key.equals(mappings[i])) {
return true;
}
}
}
return false;
}
public void setProperty(Object key, Object value)
throws ChangeVetoException
{
if (changeSupport != null) {
Object oldValue = null;
if (containsProperty(key)) {
oldValue = getProperty(key);
}
ChangeEvent ce = new ChangeEvent(
this,
Annotation.PROPERTY,
new Object[] { key, value },
new Object[] { key, oldValue}
);
synchronized (changeSupport) {
changeSupport.firePreChangeEvent(ce);
_setProperty(key, value);
changeSupport.firePostChangeEvent(ce);
}
} else {
_setProperty(key, value);
}
}
private void _setProperty(Object key, Object value) {
if (mappings == null) {
mappings = new Object[4];
} else {
int keyHash = key.hashCode();
for (int i = 0; i < numMappings * 2; i += 2) {
if (keyHash == mappings[i].hashCode() && key.equals(mappings[i])) {
- mappings[i] = value;
+ mappings[i+1] = value;
return;
}
}
}
int newPos = numMappings * 2;
if (newPos + 1 >= mappings.length) {
Object[] newMappings = new Object[mappings.length + 6];
System.arraycopy(mappings, 0, newMappings, 0, mappings.length);
mappings = newMappings;
}
mappings[newPos] = key;
mappings[newPos + 1] = value;
numMappings++;
}
public Set keys() {
return new KeySet();
}
public Map asMap() {
return new EntryMap();
}
//
// Changeable
//
public void addChangeListener(ChangeListener cl) {
if(changeSupport == null) {
changeSupport = new ChangeSupport();
}
synchronized(changeSupport) {
changeSupport.addChangeListener(cl);
}
}
public void addChangeListener(ChangeListener cl, ChangeType ct) {
if(changeSupport == null) {
changeSupport = new ChangeSupport();
}
synchronized(changeSupport) {
changeSupport.addChangeListener(cl, ct);
}
}
public void removeChangeListener(ChangeListener cl) {
if(changeSupport != null) {
synchronized(changeSupport) {
changeSupport.removeChangeListener(cl);
}
}
}
public void removeChangeListener(ChangeListener cl, ChangeType ct) {
if(changeSupport != null) {
synchronized(changeSupport) {
changeSupport.removeChangeListener(cl, ct);
}
}
}
//
// Support classes for our collection views
//
private class KeySet extends AbstractSet {
public Iterator iterator() {
return new KeyIterator();
}
public int size() {
return numMappings;
}
public boolean contains(Object o) {
return containsProperty(o);
}
}
private class KeyIterator implements Iterator {
int pos = 0;
public boolean hasNext() {
return pos < numMappings;
}
public Object next() {
if (pos >= numMappings) {
throw new NoSuchElementException();
}
int offset = pos * 2;
++pos;
return mappings[offset];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
private class EntryMap extends AbstractMap {
public Set entrySet() {
return new EntrySet();
}
public Set keySet() {
return new KeySet();
}
public boolean containsKey(Object key) {
return containsProperty(key);
}
public Object get(Object key) {
if (containsProperty(key)) {
return getProperty(key);
}
return null;
}
public int size() {
return numMappings;
}
}
private class EntrySet extends AbstractSet {
public Iterator iterator() {
return new EntryIterator();
}
public int size() {
return numMappings;
}
}
private class EntryIterator implements Iterator {
int pos = 0;
public boolean hasNext() {
return pos < numMappings;
}
public Object next() {
if (pos >= numMappings) {
throw new NoSuchElementException();
}
int offset = pos * 2;
++pos;
return new MapEntry(offset);
}
public void remove() {
throw new UnsupportedOperationException();
}
}
private class MapEntry implements Map.Entry {
private int offset;
private MapEntry(int offset) {
this.offset = offset;
}
public Object getKey() {
return mappings[offset];
}
public Object getValue() {
return mappings[offset + 1];
}
public Object setValue(Object v) {
throw new UnsupportedOperationException();
}
public boolean equals(Object o) {
if (! (o instanceof Map.Entry)) {
return false;
}
Map.Entry mo = (Map.Entry) o;
return ((getKey() == null ? mo.getKey() == null : getKey().equals(mo.getKey())) &&
(getValue() == null ? mo.getValue() == null : getValue().equals(mo.getValue())));
}
public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode());
}
}
}
| true | true | private void _setProperty(Object key, Object value) {
if (mappings == null) {
mappings = new Object[4];
} else {
int keyHash = key.hashCode();
for (int i = 0; i < numMappings * 2; i += 2) {
if (keyHash == mappings[i].hashCode() && key.equals(mappings[i])) {
mappings[i] = value;
return;
}
}
}
int newPos = numMappings * 2;
if (newPos + 1 >= mappings.length) {
Object[] newMappings = new Object[mappings.length + 6];
System.arraycopy(mappings, 0, newMappings, 0, mappings.length);
mappings = newMappings;
}
mappings[newPos] = key;
mappings[newPos + 1] = value;
numMappings++;
}
| private void _setProperty(Object key, Object value) {
if (mappings == null) {
mappings = new Object[4];
} else {
int keyHash = key.hashCode();
for (int i = 0; i < numMappings * 2; i += 2) {
if (keyHash == mappings[i].hashCode() && key.equals(mappings[i])) {
mappings[i+1] = value;
return;
}
}
}
int newPos = numMappings * 2;
if (newPos + 1 >= mappings.length) {
Object[] newMappings = new Object[mappings.length + 6];
System.arraycopy(mappings, 0, newMappings, 0, mappings.length);
mappings = newMappings;
}
mappings[newPos] = key;
mappings[newPos + 1] = value;
numMappings++;
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayout.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayout.java
index 681341c34..f19e0829c 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayout.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayout.java
@@ -1,278 +1,282 @@
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Caption;
import com.itmill.toolkit.terminal.gwt.client.Container;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
/**
* Abstract base class for ordered layouts.
* Use either vertical or horizontal subclass.
* @author IT Mill Ltd
*/
public abstract class IOrderedLayout extends ComplexPanel implements Container {
public static final String CLASSNAME = "i-orderedlayout";
public static final int ORIENTATION_VERTICAL = 0;
public static final int ORIENTATION_HORIZONTAL = 1;
int orientationMode = ORIENTATION_VERTICAL;
private HashMap componentToCaption = new HashMap();
private ApplicationConnection client;
/**
* Contains reference to Element where Paintables are wrapped. For horizontal
* layout this is TR and for vertical DIV.
*/
private Element childContainer;
public IOrderedLayout(int orientation) {
orientationMode = orientation;
constructDOM();
setStyleName(CLASSNAME);
}
private void constructDOM() {
switch (orientationMode) {
case ORIENTATION_HORIZONTAL:
Element table = DOM.createTable();
Element tBody = DOM.createTBody();
childContainer = DOM.createTR();
DOM.appendChild(table, tBody);
DOM.appendChild(tBody, childContainer);
setElement(table);
break;
default:
childContainer = DOM.createDiv();
setElement(childContainer);
break;
}
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
// Ensure correct implementation
if (client.updateComponent(this, uidl, false))
return;
ArrayList uidlWidgets = new ArrayList();
for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
UIDL uidlForChild = (UIDL) it.next();
Widget child = client.getWidget(uidlForChild);
uidlWidgets.add(child);
}
ArrayList oldWidgets = getPaintables();
Iterator oldIt = oldWidgets.iterator();
Iterator newIt = uidlWidgets.iterator();
Iterator newUidl = uidl.getChildIterator();
Widget oldChild = null;
while(newIt.hasNext()) {
Widget child = (Widget) newIt.next();
UIDL childUidl = (UIDL) newUidl.next();
if(oldChild == null && oldIt.hasNext()) {
// search for next old Paintable which still exists in layout
// and delete others
while(oldIt.hasNext()) {
oldChild = (Widget) oldIt.next();
// now oldChild is an instance of Paintable
if(uidlWidgets.contains(oldChild))
break;
else {
removePaintable((Paintable) oldChild);
oldChild = null;
}
}
}
if(oldChild == null) {
// we are adding components to layout
add(child);
} else if(child == oldChild) {
// child already attached and updated
oldChild = null;
} else if(hasChildComponent(child)) {
// current child has been moved, re-insert before current oldChild
- // TODO this might be optimized by movin only container element
+ // TODO this might be optimized by moving only container element
// to correct position
removeCaption(child);
int index = getWidgetIndex(oldChild);
if(componentToCaption.containsKey(oldChild))
index--;
remove(child);
this.insert(child, index);
+ } else {
+ // insert new child before old one
+ int index = getWidgetIndex(oldChild);
+ insert(child,index);
}
((Paintable)child).updateFromUIDL(childUidl, client);
}
// remove possibly remaining old Paintable object which were not updated
while(oldIt.hasNext()) {
oldChild = (Widget) oldIt.next();
Paintable p = (Paintable) oldChild;
if(!uidlWidgets.contains(p))
removePaintable(p);
}
}
/**
* Retuns a list of Paintables currently rendered in layout
*
* @return list of Paintable objects
*/
private ArrayList getPaintables() {
ArrayList al = new ArrayList();
Iterator it = iterator();
while (it.hasNext()) {
Widget w = (Widget) it.next();
if (w instanceof Paintable)
al.add(w);
}
return al;
}
/**
* Removes Paintable from DOM and its reference from ApplicationConnection.
*
* Also removes Paintable's Caption if one exists
*
* @param p Paintable to be removed
*/
public boolean removePaintable(Paintable p) {
Caption c = (Caption) componentToCaption.get(p);
if(c != null) {
componentToCaption.remove(c);
remove(c);
}
client.unregisterPaintable(p);
return remove((Widget) p);
}
/* (non-Javadoc)
* @see com.itmill.toolkit.terminal.gwt.client.Layout#replaceChildComponent(com.google.gwt.user.client.ui.Widget, com.google.gwt.user.client.ui.Widget)
*/
public void replaceChildComponent(Widget from, Widget to) {
client.unregisterPaintable((Paintable) from);
Caption c = (Caption) componentToCaption.get(from);
if (c != null) {
remove(c);
componentToCaption.remove(c);
}
int index = getWidgetIndex(from);
if (index >= 0) {
remove(index);
insert(to, index);
}
}
private void insert(Widget w, int beforeIndex) {
if (w instanceof Caption) {
Caption c = (Caption) w;
// captions go into same container element as their
// owners
Element container = DOM.getParent(((UIObject) c.getOwner()).getElement());
Element captionContainer = DOM.createDiv();
DOM.insertChild(container, captionContainer, 0);
insert(w, captionContainer, beforeIndex, false);
} else {
Element container = createWidgetWrappper();
DOM.insertChild(childContainer, container, beforeIndex);
insert(w, container, beforeIndex, false);
}
}
/**
* creates an Element which will contain child widget
*/
private Element createWidgetWrappper() {
switch (orientationMode) {
case ORIENTATION_HORIZONTAL:
return DOM.createTD();
default:
return DOM.createDiv();
}
}
public boolean hasChildComponent(Widget component) {
return getWidgetIndex(component) >= 0;
}
public void updateCaption(Paintable component, UIDL uidl) {
Caption c = (Caption) componentToCaption.get(component);
if (Caption.isNeeded(uidl)) {
if (c == null) {
int index = getWidgetIndex((Widget) component);
c = new Caption(component);
insert(c, index);
componentToCaption.put(component, c);
}
c.updateCaption(uidl);
} else {
if (c != null) {
remove(c);
componentToCaption.remove(component);
}
}
}
public void removeCaption(Widget w) {
Caption c = (Caption) componentToCaption.get(w);
if(c != null) {
this.remove(c);
componentToCaption.remove(w);
}
}
public void add(Widget w) {
Element wrapper = createWidgetWrappper();
DOM.appendChild(childContainer, wrapper);
super.add(w,wrapper);
}
public boolean remove(int index) {
return remove(getWidget(index));
}
public boolean remove(Widget w) {
Element wrapper = DOM.getParent(w.getElement());
boolean removed = super.remove(w);
if(removed) {
if (! (w instanceof Caption)) {
DOM.removeChild(childContainer, wrapper);
}
return true;
}
return false;
}
public Widget getWidget(int index) {
return getChildren().get(index);
}
public int getWidgetCount() {
return getChildren().size();
}
public int getWidgetIndex(Widget child) {
return getChildren().indexOf(child);
}
}
| false | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
// Ensure correct implementation
if (client.updateComponent(this, uidl, false))
return;
ArrayList uidlWidgets = new ArrayList();
for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
UIDL uidlForChild = (UIDL) it.next();
Widget child = client.getWidget(uidlForChild);
uidlWidgets.add(child);
}
ArrayList oldWidgets = getPaintables();
Iterator oldIt = oldWidgets.iterator();
Iterator newIt = uidlWidgets.iterator();
Iterator newUidl = uidl.getChildIterator();
Widget oldChild = null;
while(newIt.hasNext()) {
Widget child = (Widget) newIt.next();
UIDL childUidl = (UIDL) newUidl.next();
if(oldChild == null && oldIt.hasNext()) {
// search for next old Paintable which still exists in layout
// and delete others
while(oldIt.hasNext()) {
oldChild = (Widget) oldIt.next();
// now oldChild is an instance of Paintable
if(uidlWidgets.contains(oldChild))
break;
else {
removePaintable((Paintable) oldChild);
oldChild = null;
}
}
}
if(oldChild == null) {
// we are adding components to layout
add(child);
} else if(child == oldChild) {
// child already attached and updated
oldChild = null;
} else if(hasChildComponent(child)) {
// current child has been moved, re-insert before current oldChild
// TODO this might be optimized by movin only container element
// to correct position
removeCaption(child);
int index = getWidgetIndex(oldChild);
if(componentToCaption.containsKey(oldChild))
index--;
remove(child);
this.insert(child, index);
}
((Paintable)child).updateFromUIDL(childUidl, client);
}
// remove possibly remaining old Paintable object which were not updated
while(oldIt.hasNext()) {
oldChild = (Widget) oldIt.next();
Paintable p = (Paintable) oldChild;
if(!uidlWidgets.contains(p))
removePaintable(p);
}
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
// Ensure correct implementation
if (client.updateComponent(this, uidl, false))
return;
ArrayList uidlWidgets = new ArrayList();
for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
UIDL uidlForChild = (UIDL) it.next();
Widget child = client.getWidget(uidlForChild);
uidlWidgets.add(child);
}
ArrayList oldWidgets = getPaintables();
Iterator oldIt = oldWidgets.iterator();
Iterator newIt = uidlWidgets.iterator();
Iterator newUidl = uidl.getChildIterator();
Widget oldChild = null;
while(newIt.hasNext()) {
Widget child = (Widget) newIt.next();
UIDL childUidl = (UIDL) newUidl.next();
if(oldChild == null && oldIt.hasNext()) {
// search for next old Paintable which still exists in layout
// and delete others
while(oldIt.hasNext()) {
oldChild = (Widget) oldIt.next();
// now oldChild is an instance of Paintable
if(uidlWidgets.contains(oldChild))
break;
else {
removePaintable((Paintable) oldChild);
oldChild = null;
}
}
}
if(oldChild == null) {
// we are adding components to layout
add(child);
} else if(child == oldChild) {
// child already attached and updated
oldChild = null;
} else if(hasChildComponent(child)) {
// current child has been moved, re-insert before current oldChild
// TODO this might be optimized by moving only container element
// to correct position
removeCaption(child);
int index = getWidgetIndex(oldChild);
if(componentToCaption.containsKey(oldChild))
index--;
remove(child);
this.insert(child, index);
} else {
// insert new child before old one
int index = getWidgetIndex(oldChild);
insert(child,index);
}
((Paintable)child).updateFromUIDL(childUidl, client);
}
// remove possibly remaining old Paintable object which were not updated
while(oldIt.hasNext()) {
oldChild = (Widget) oldIt.next();
Paintable p = (Paintable) oldChild;
if(!uidlWidgets.contains(p))
removePaintable(p);
}
}
|
diff --git a/src/java/packageController/ServletCart.java b/src/java/packageController/ServletCart.java
index c420032..b479eb8 100644
--- a/src/java/packageController/ServletCart.java
+++ b/src/java/packageController/ServletCart.java
@@ -1,120 +1,120 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package packageController;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import packageException.CommandeException;
import packageModel.AlbumCart;
import packageModel.Utilisateur;
/**
*
* @author Emilien
*/
public class ServletCart extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
double tot = 0;
HttpSession sess = request.getSession();
Utilisateur util = (Utilisateur)sess.getAttribute("user");
for (Iterator iter = util.getHasmMapPanier().entrySet().iterator(); iter.hasNext();) //Vérification des quantités dans la hashmap
{
- Map.Entry data = (Map.Entry)iter.next();
- AlbumCart album = (AlbumCart)data.getValue();
- if(album.getQte()<1)
- {
- throw new CommandeException("qteInvalid");
+ Map.Entry data = (Map.Entry)iter.next();
+ AlbumCart album = (AlbumCart)data.getValue();
+ if(album.getQte()<1)
+ {
+ throw new CommandeException("qteInvalid");
+ }
+ else
+ {
+ if(album.getPromo()) {
+ tot+= album.getQte() * album.getPrixPromo();
}
- else
- {
- if(album.getPromo()) {
- tot+= album.getQte() * album.getPrixPromo();
- }
- else {
- tot+=album.getQte() * album.getPrix();
- }
+ else {
+ tot+=album.getQte() * album.getPrix();
}
+ }
}
DecimalFormat myFormatter = new DecimalFormat("#.##");
String outputTot = myFormatter.format(tot);
RequestDispatcher rd = request.getRequestDispatcher("cart.jsp");
request.setAttribute("total",outputTot);
rd.forward(request, response);
}
catch(CommandeException ex)
{
RequestDispatcher rd = request.getRequestDispatcher("erreur.jsp");
request.setAttribute("reponse",ex);
rd.forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| false | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
double tot = 0;
HttpSession sess = request.getSession();
Utilisateur util = (Utilisateur)sess.getAttribute("user");
for (Iterator iter = util.getHasmMapPanier().entrySet().iterator(); iter.hasNext();) //Vérification des quantités dans la hashmap
{
Map.Entry data = (Map.Entry)iter.next();
AlbumCart album = (AlbumCart)data.getValue();
if(album.getQte()<1)
{
throw new CommandeException("qteInvalid");
}
else
{
if(album.getPromo()) {
tot+= album.getQte() * album.getPrixPromo();
}
else {
tot+=album.getQte() * album.getPrix();
}
}
}
DecimalFormat myFormatter = new DecimalFormat("#.##");
String outputTot = myFormatter.format(tot);
RequestDispatcher rd = request.getRequestDispatcher("cart.jsp");
request.setAttribute("total",outputTot);
rd.forward(request, response);
}
catch(CommandeException ex)
{
RequestDispatcher rd = request.getRequestDispatcher("erreur.jsp");
request.setAttribute("reponse",ex);
rd.forward(request, response);
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
double tot = 0;
HttpSession sess = request.getSession();
Utilisateur util = (Utilisateur)sess.getAttribute("user");
for (Iterator iter = util.getHasmMapPanier().entrySet().iterator(); iter.hasNext();) //Vérification des quantités dans la hashmap
{
Map.Entry data = (Map.Entry)iter.next();
AlbumCart album = (AlbumCart)data.getValue();
if(album.getQte()<1)
{
throw new CommandeException("qteInvalid");
}
else
{
if(album.getPromo()) {
tot+= album.getQte() * album.getPrixPromo();
}
else {
tot+=album.getQte() * album.getPrix();
}
}
}
DecimalFormat myFormatter = new DecimalFormat("#.##");
String outputTot = myFormatter.format(tot);
RequestDispatcher rd = request.getRequestDispatcher("cart.jsp");
request.setAttribute("total",outputTot);
rd.forward(request, response);
}
catch(CommandeException ex)
{
RequestDispatcher rd = request.getRequestDispatcher("erreur.jsp");
request.setAttribute("reponse",ex);
rd.forward(request, response);
}
}
|
diff --git a/src/main/java/eu/europeana/portal2/web/presentation/model/SeeAlsoSuggestions.java b/src/main/java/eu/europeana/portal2/web/presentation/model/SeeAlsoSuggestions.java
index 9e0650aa..bb5b5cb4 100644
--- a/src/main/java/eu/europeana/portal2/web/presentation/model/SeeAlsoSuggestions.java
+++ b/src/main/java/eu/europeana/portal2/web/presentation/model/SeeAlsoSuggestions.java
@@ -1,131 +1,131 @@
package eu.europeana.portal2.web.presentation.model;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import eu.europeana.portal2.web.util.ControllerUtil;
public class SeeAlsoSuggestions {
private Map<String, String> seeAlsoTranslations;
private Map<String, String> seeAlsoAggregations;
private Map<String, Field> fields = new LinkedHashMap<String, Field>();
public SeeAlsoSuggestions(Map<String, String> seeAlsoTranslations, Map<String, String> seeAlsoAggregations) {
this.seeAlsoTranslations = seeAlsoTranslations;
this.seeAlsoAggregations = seeAlsoAggregations;
}
public void add(String query, Integer count) {
String[] parts = query.split(":", 2);
String fieldName = parts[0];
String fieldValue = parts[1]
.replaceAll("^\"", "")
.replaceAll("\"$", "");
String aggregatedFieldName = (seeAlsoAggregations.containsKey(fieldName))
? seeAlsoAggregations.get(fieldName)
: fieldName;
Field field;
if (fields.containsKey(aggregatedFieldName)) {
field = fields.get(aggregatedFieldName);
} else {
field = new Field(aggregatedFieldName, seeAlsoTranslations.get(aggregatedFieldName));
fields.put(aggregatedFieldName, field);
}
String extendedQuery;
- if (fieldName.equals("PROVIDER") || fieldName.equals("DATA_PROVIDER")) {
+ if (fieldName.equals("title") || fieldName.equals("PROVIDER") || fieldName.equals("DATA_PROVIDER")) {
extendedQuery = query;
} else {
extendedQuery = fieldName + ":(" + ControllerUtil.clearSeeAlso(fieldValue) + ")";
}
field.addSuggestion(new Suggestion(extendedQuery, fieldValue, count));
}
public Map<String, Field> getFields() {
return fields;
}
public String toString() {
StringBuffer sb = new StringBuffer("SeeAlsoSuggestions [");
for (Entry<String, Field> entry : fields.entrySet()) {
sb.append(entry.getValue()).append(": ");
sb.append(entry.getValue().toString());
sb.append(",");
}
sb.append("]");
return sb.toString();
}
public class Field {
private String fieldName;
private String translationKey;
private List<Suggestion> suggestions = new LinkedList<Suggestion>();
public Field(String fieldName, String translationKey) {
this.fieldName = fieldName;
this.translationKey = translationKey;
}
public void addSuggestion(Suggestion suggestion) {
suggestions.add(suggestion);
}
public String getFieldName() {
return fieldName;
}
public String getTranslationKey() {
return translationKey;
}
public List<Suggestion> getSuggestions() {
return suggestions;
}
@Override
public String toString() {
return "Field [fieldName=" + fieldName
+ ", translationKey=" + translationKey
+ ", suggestions=" + suggestions + "]";
}
}
public class Suggestion {
private String query;
private String value;
private Integer count;
public Suggestion(String query, String value, Integer count) {
this.query = query;
this.value = value;
this.count = count;
}
public String getQuery() {
return query;
}
public String getValue() {
return value;
}
public Integer getCount() {
return count;
}
@Override
public String toString() {
return "Suggestion [query=" + query + ", value=" + value + ", count=" + count + "]";
}
}
}
| true | true | public void add(String query, Integer count) {
String[] parts = query.split(":", 2);
String fieldName = parts[0];
String fieldValue = parts[1]
.replaceAll("^\"", "")
.replaceAll("\"$", "");
String aggregatedFieldName = (seeAlsoAggregations.containsKey(fieldName))
? seeAlsoAggregations.get(fieldName)
: fieldName;
Field field;
if (fields.containsKey(aggregatedFieldName)) {
field = fields.get(aggregatedFieldName);
} else {
field = new Field(aggregatedFieldName, seeAlsoTranslations.get(aggregatedFieldName));
fields.put(aggregatedFieldName, field);
}
String extendedQuery;
if (fieldName.equals("PROVIDER") || fieldName.equals("DATA_PROVIDER")) {
extendedQuery = query;
} else {
extendedQuery = fieldName + ":(" + ControllerUtil.clearSeeAlso(fieldValue) + ")";
}
field.addSuggestion(new Suggestion(extendedQuery, fieldValue, count));
}
| public void add(String query, Integer count) {
String[] parts = query.split(":", 2);
String fieldName = parts[0];
String fieldValue = parts[1]
.replaceAll("^\"", "")
.replaceAll("\"$", "");
String aggregatedFieldName = (seeAlsoAggregations.containsKey(fieldName))
? seeAlsoAggregations.get(fieldName)
: fieldName;
Field field;
if (fields.containsKey(aggregatedFieldName)) {
field = fields.get(aggregatedFieldName);
} else {
field = new Field(aggregatedFieldName, seeAlsoTranslations.get(aggregatedFieldName));
fields.put(aggregatedFieldName, field);
}
String extendedQuery;
if (fieldName.equals("title") || fieldName.equals("PROVIDER") || fieldName.equals("DATA_PROVIDER")) {
extendedQuery = query;
} else {
extendedQuery = fieldName + ":(" + ControllerUtil.clearSeeAlso(fieldValue) + ")";
}
field.addSuggestion(new Suggestion(extendedQuery, fieldValue, count));
}
|
diff --git a/tests/src/com/android/music/MusicPlayerStability.java b/tests/src/com/android/music/MusicPlayerStability.java
index 5654adb..d84d2f8 100644
--- a/tests/src/com/android/music/MusicPlayerStability.java
+++ b/tests/src/com/android/music/MusicPlayerStability.java
@@ -1,88 +1,90 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.music.tests;
import android.app.Instrumentation;
import com.android.music.TrackBrowserActivity;
import android.view.KeyEvent;
import android.widget.ListView;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
/**
* Junit / Instrumentation test case for the Music Player
*/
public class MusicPlayerStability extends ActivityInstrumentationTestCase2 <TrackBrowserActivity>{
private static String TAG = "musicplayerstability";
private static int PLAY_TIME = 30000;
private ListView mTrackList;
public MusicPlayerStability() {
super("com.android.music",TrackBrowserActivity.class);
}
@Override
protected void setUp() throws Exception {
getActivity();
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test case 1: This test case is for the power and general stability
* measurment. We don't need to do the validation. This test case simply
* play the mp3 for 30 seconds then stop.
* The sdcard should have the target mp3 files.
*/
@LargeTest
public void testPlay30sMP3() throws Exception {
// Launch the songs list. Pick the fisrt song and play
try {
Instrumentation inst = getInstrumentation();
+ //Make sure the song list shown up
+ Thread.sleep(2000);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
mTrackList = getActivity().getListView();
- int viewCount = mTrackList.getSelectedItemPosition();
+ int scrollCount = mTrackList.getMaxScrollAmount();
//Make sure there is at least one song in the sdcard
- if (viewCount != -1) {
+ if (scrollCount != -1) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
} else {
assertTrue("testPlayMP3", false);
}
Thread.sleep(PLAY_TIME);
} catch (Exception e) {
assertTrue("testPlayMP3", false);
}
}
@LargeTest
public void testLaunchMusicPlayer() throws Exception {
// Launch music player and sleep for 30 seconds to capture
// the music player power usage base line.
try {
Thread.sleep(PLAY_TIME);
} catch (Exception e) {
assertTrue("MusicPlayer Do Nothing", false);
}
assertTrue("MusicPlayer Do Nothing", true);
}
}
| false | true | public void testPlay30sMP3() throws Exception {
// Launch the songs list. Pick the fisrt song and play
try {
Instrumentation inst = getInstrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
mTrackList = getActivity().getListView();
int viewCount = mTrackList.getSelectedItemPosition();
//Make sure there is at least one song in the sdcard
if (viewCount != -1) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
} else {
assertTrue("testPlayMP3", false);
}
Thread.sleep(PLAY_TIME);
} catch (Exception e) {
assertTrue("testPlayMP3", false);
}
}
| public void testPlay30sMP3() throws Exception {
// Launch the songs list. Pick the fisrt song and play
try {
Instrumentation inst = getInstrumentation();
//Make sure the song list shown up
Thread.sleep(2000);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
mTrackList = getActivity().getListView();
int scrollCount = mTrackList.getMaxScrollAmount();
//Make sure there is at least one song in the sdcard
if (scrollCount != -1) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
} else {
assertTrue("testPlayMP3", false);
}
Thread.sleep(PLAY_TIME);
} catch (Exception e) {
assertTrue("testPlayMP3", false);
}
}
|
diff --git a/src/main/java/javabot/operations/TellOperation.java b/src/main/java/javabot/operations/TellOperation.java
index 64404db2..ea6f1047 100644
--- a/src/main/java/javabot/operations/TellOperation.java
+++ b/src/main/java/javabot/operations/TellOperation.java
@@ -1,194 +1,196 @@
package javabot.operations;
import javabot.BotEvent;
import javabot.Javabot;
import javabot.Message;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @author ricky_clarkson
* @author ernimril - Throttle patch
*/
public class TellOperation implements BotOperation {
private static final Log log = LogFactory.getLog(TellOperation.class);
private final String ownNick;
private final Javabot javabot;
private static final int MAX_TELL_MEMORY = 100;
private static final int THROTTLE_TIME = 10 * 1000; // 10 secs.
private final List<TellInfo> lastTells = new ArrayList<TellInfo>(MAX_TELL_MEMORY);
public TellOperation(final String myNick, final Javabot bot) {
ownNick = myNick;
javabot = bot;
}
private static final class TellInfo {
private final long when;
private final String nick;
private final String msg;
public TellInfo(String nick, String msg) {
this.nick = nick;
this.msg = msg;
when = System.currentTimeMillis();
}
public long getWhen() {
return when;
}
public boolean match(String nick, String msg) {
return this.nick.equals(nick) && this.msg.equals(msg);
}
}
private static final class TellSubject {
private final String target;
private final String subject;
public TellSubject (String target, String subject) {
this.target = target;
this.subject = subject;
}
public String getTarget () {
return target;
}
public String getSubject () {
return subject;
}
}
/**
* @see BotOperation#handleMessage(BotEvent)
*/
public List<Message> handleMessage(BotEvent event) {
List<Message> messages = new ArrayList<Message>();
String message = event.getMessage();
String channel = event.getChannel();
String login = event.getLogin();
String hostname = event.getHostname();
String sender = event.getSender();
boolean isPrivateMessage = sender.equals(channel);
if (!isTellCommand (message)) {
return messages;
}
TellSubject tellSubject = parseTellSubject (message);
if (tellSubject == null) {
messages.add(new Message(channel, "The syntax is: tell nick about factoid - you missed out the 'about', "
+ sender, false));
return messages;
}
String nick = tellSubject.getTarget ();
if ("me".equals(nick)) {
nick = sender;
}
String thing = tellSubject.getSubject ();
if (nick.equals(ownNick)) {
messages.add(new Message(channel, "I don't want to talk to myself", false));
} else if (alreadyTold(nick, thing)) {
log.debug("skipping tell of " + thing + " to " + nick + ", already told " + nick + " about " + thing);
messages.add(new Message(channel, sender + ", Slow down, Speedy Gonzalez!", false));
} else if (!javabot.userIsOnChannel(nick, channel)) {
messages.add(new Message(channel, "The user " + nick + " is not on " + channel, false));
} else if (isPrivateMessage && !javabot.isOnSameChannelAs (nick)) {
messages.add(new Message(sender, "I will not send a message to someone who is not on any"
+ " of my channels.", false));
+ } else if (thing.endsWith("++") || thing.endsWith("--")) {
+ messages.add(new Message(channel, "I'm afraid I can't let you do that, Dave.", false));
} else {
List<Message> responses = javabot.getResponses(nick, nick, login, hostname, thing);
addTold(nick, thing);
if (isPrivateMessage) {
messages.add(new Message(nick, sender + " wants to tell you the following:", false));
messages.addAll(responses);
messages.add(new Message(sender, "I told " + nick + " about " + thing + ".", false));
} else {
log.debug(sender + " is telling " + nick + " about " + thing);
for (Message response : responses) {
messages.add(prependNickToReply (channel, nick,
response));
}
}
}
return messages;
}
private Message prependNickToReply (String channel, String nick,
Message response) {
String reply = response.getMessage ();
if (!reply.startsWith(nick)) {
if (response.isAction()) {
reply = MessageFormat.format ("{0}, {1} {2}", nick, javabot.getNick (), reply);
} else {
reply = MessageFormat.format ("{0}, {1}", nick, reply);
}
}
return new Message(channel, reply, false);
}
private TellSubject parseTellSubject(String message) {
if (message.startsWith ("tell "))
return parseLonghand (message);
return parseShorthand (message);
}
private TellSubject parseLonghand (String message) {
message = message.substring("tell ".length());
String nick = message.substring(0, message.indexOf(" "));
int about = message.indexOf("about ");
if (about < 0)
return null;
String thing = message.substring(about + "about ".length());
return new TellSubject (nick, thing);
}
private TellSubject parseShorthand (String message) {
int space = message.indexOf (' ');
if (space < 0)
return null;
return new TellSubject (message.substring (1, space), message.substring (space + 1));
}
private boolean isTellCommand(String message) {
return message.startsWith("tell ") || message.startsWith("~");
}
private boolean alreadyTold(String nick, String msg) {
long now = System.currentTimeMillis();
log.debug("alreadyTold: " + nick + " " + msg);
for (int i = 0, j = lastTells.size(); i < j; i++) {
TellInfo ti = lastTells.get(i);
log.debug(ti.nick + " " + ti.msg);
if (now - ti.getWhen() < THROTTLE_TIME && ti.match(nick, msg))
return true;
}
return false;
}
private void addTold(String nick, String msg) {
TellInfo ti = new TellInfo(nick, msg);
lastTells.add(ti);
if (lastTells.size() > MAX_TELL_MEMORY)
lastTells.remove(0);
}
public List<Message> handleChannelMessage(BotEvent event) {
return new ArrayList<Message>();
}
}
| true | true | public List<Message> handleMessage(BotEvent event) {
List<Message> messages = new ArrayList<Message>();
String message = event.getMessage();
String channel = event.getChannel();
String login = event.getLogin();
String hostname = event.getHostname();
String sender = event.getSender();
boolean isPrivateMessage = sender.equals(channel);
if (!isTellCommand (message)) {
return messages;
}
TellSubject tellSubject = parseTellSubject (message);
if (tellSubject == null) {
messages.add(new Message(channel, "The syntax is: tell nick about factoid - you missed out the 'about', "
+ sender, false));
return messages;
}
String nick = tellSubject.getTarget ();
if ("me".equals(nick)) {
nick = sender;
}
String thing = tellSubject.getSubject ();
if (nick.equals(ownNick)) {
messages.add(new Message(channel, "I don't want to talk to myself", false));
} else if (alreadyTold(nick, thing)) {
log.debug("skipping tell of " + thing + " to " + nick + ", already told " + nick + " about " + thing);
messages.add(new Message(channel, sender + ", Slow down, Speedy Gonzalez!", false));
} else if (!javabot.userIsOnChannel(nick, channel)) {
messages.add(new Message(channel, "The user " + nick + " is not on " + channel, false));
} else if (isPrivateMessage && !javabot.isOnSameChannelAs (nick)) {
messages.add(new Message(sender, "I will not send a message to someone who is not on any"
+ " of my channels.", false));
} else {
List<Message> responses = javabot.getResponses(nick, nick, login, hostname, thing);
addTold(nick, thing);
if (isPrivateMessage) {
messages.add(new Message(nick, sender + " wants to tell you the following:", false));
messages.addAll(responses);
messages.add(new Message(sender, "I told " + nick + " about " + thing + ".", false));
} else {
log.debug(sender + " is telling " + nick + " about " + thing);
for (Message response : responses) {
messages.add(prependNickToReply (channel, nick,
response));
}
}
}
return messages;
}
| public List<Message> handleMessage(BotEvent event) {
List<Message> messages = new ArrayList<Message>();
String message = event.getMessage();
String channel = event.getChannel();
String login = event.getLogin();
String hostname = event.getHostname();
String sender = event.getSender();
boolean isPrivateMessage = sender.equals(channel);
if (!isTellCommand (message)) {
return messages;
}
TellSubject tellSubject = parseTellSubject (message);
if (tellSubject == null) {
messages.add(new Message(channel, "The syntax is: tell nick about factoid - you missed out the 'about', "
+ sender, false));
return messages;
}
String nick = tellSubject.getTarget ();
if ("me".equals(nick)) {
nick = sender;
}
String thing = tellSubject.getSubject ();
if (nick.equals(ownNick)) {
messages.add(new Message(channel, "I don't want to talk to myself", false));
} else if (alreadyTold(nick, thing)) {
log.debug("skipping tell of " + thing + " to " + nick + ", already told " + nick + " about " + thing);
messages.add(new Message(channel, sender + ", Slow down, Speedy Gonzalez!", false));
} else if (!javabot.userIsOnChannel(nick, channel)) {
messages.add(new Message(channel, "The user " + nick + " is not on " + channel, false));
} else if (isPrivateMessage && !javabot.isOnSameChannelAs (nick)) {
messages.add(new Message(sender, "I will not send a message to someone who is not on any"
+ " of my channels.", false));
} else if (thing.endsWith("++") || thing.endsWith("--")) {
messages.add(new Message(channel, "I'm afraid I can't let you do that, Dave.", false));
} else {
List<Message> responses = javabot.getResponses(nick, nick, login, hostname, thing);
addTold(nick, thing);
if (isPrivateMessage) {
messages.add(new Message(nick, sender + " wants to tell you the following:", false));
messages.addAll(responses);
messages.add(new Message(sender, "I told " + nick + " about " + thing + ".", false));
} else {
log.debug(sender + " is telling " + nick + " about " + thing);
for (Message response : responses) {
messages.add(prependNickToReply (channel, nick,
response));
}
}
}
return messages;
}
|
diff --git a/src/org/openprince/dat/ImageResource.java b/src/org/openprince/dat/ImageResource.java
index 54a0945..8153084 100644
--- a/src/org/openprince/dat/ImageResource.java
+++ b/src/org/openprince/dat/ImageResource.java
@@ -1,235 +1,235 @@
package org.openprince.dat;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.openprince.graphics.SpriteSheet;
public class ImageResource extends Resource {
public int width;
public int height;
public int bpp;
public ImageCompression compression;
public ImageDirection direction;
public List<Byte> decompressed;
public SpriteSheet sheet = null;
public int sheetX = 0;
public int sheetY = 0;
public ImageResource(ByteBuffer buffer, IndexItem index) {
super(buffer, index);
getHeader();
decompress();
}
public ImageResource(Resource res) {
super(res);
getHeader();
decompress();
}
@Override
public ResourceType getType() {
return ResourceType.IMAGE;
}
private void getHeader() {
buffer.rewind();
height = buffer.getChar();
width = buffer.getChar();
buffer.get();
int info = buffer.get();
bpp = ((info & 0x30) >> 4) + 1;
switch (info & 0x0F) {
case 0:
compression = ImageCompression.RAW;
direction = ImageDirection.LEFT_RIGHT;
break;
case 1:
compression = ImageCompression.RLE;
direction = ImageDirection.LEFT_RIGHT;
break;
case 2:
compression = ImageCompression.RLE;
direction = ImageDirection.UP_DOWN;
break;
case 3:
compression = ImageCompression.LZG;
direction = ImageDirection.LEFT_RIGHT;
break;
case 4:
compression = ImageCompression.LZG;
direction = ImageDirection.UP_DOWN;
break;
default:
width = 0;
height = 0;
compression = ImageCompression.UNKNOWN;
direction = ImageDirection.LEFT_RIGHT;
}
}
private void decompress() {
decompressed = new ArrayList<Byte>();
switch (compression) {
case RLE:
buffer.position(6);
byte control;
while (buffer.remaining() > 0) {
control = buffer.get();
if (control < 0) {
byte value = buffer.get();
while (control < 0) {
decompressed.add(value);
control++;
}
} else {
while (control >= 0 && buffer.remaining() > 0) {
decompressed.add(buffer.get());
control--;
}
}
}
break;
case LZG:
final int LZG_WINDOW_SIZE = 1024;
int oCursor;
int iCursor = 0;
int maskbyte = 0;
int loc,
rep,
k;
for (oCursor = 0; oCursor < LZG_WINDOW_SIZE; oCursor++) {
decompressed.add((byte) 0);
}
buffer.position(6);
while (iCursor < buffer.limit() - 6) {
maskbyte = buffer.get(6 + iCursor);
iCursor++;
for (k = 8; k != 0 && (iCursor < buffer.limit() - 6); k--) {
int bit = maskbyte & 1;
maskbyte >>= 1;
if (bit == 1) {
decompressed.add(buffer.get(6 + iCursor++));
oCursor++;
} else {
loc = 66 + ((buffer.get(6 + iCursor) & 0x03) << 8)
+ (buffer.get(6 + iCursor + 1) & 0xff);
rep = 3 + ((buffer.get(6 + iCursor) & 0xfc) >> 2);
iCursor += 2;
loc = (oCursor - loc) & 0x3ff;
while (rep-- > 0) {
decompressed.add(decompressed
.get(oCursor - loc));
oCursor++;
}
}
}
}
for (k = 0; k < LZG_WINDOW_SIZE; k++) {
decompressed.remove(0);
}
break;
default:
break;
}
}
public void renderToSheet(SpriteSheet sheet, PaletteResource pal, int sx,
int sy) {
this.sheet = sheet;
sheetX = sx;
sheetY = sy;
try {
int bits = 0;
int val = 0;
int pos = 0;
int pixel = 0;
if (direction == ImageDirection.LEFT_RIGHT) {
int xoffs = 8 / bpp - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x += 8 / bpp) {
val = decompressed.get(pos) & 0xff;
xoffs = 8 / bpp - 1;
bits = 8;
while (x + xoffs >= width) {
xoffs--;
val >>= bpp;
bits -= bpp;
}
while (bits > 0) {
pixel = val & ((1 << bpp) - 1);
val >>= bpp;
bits -= bpp;
sheet.drawPixel(xoffs + sx + x, sy + y,
pal.r.get(pixel)
.byteValue(), pal.g.get(pixel)
.byteValue(),
pal.b.get(pixel).byteValue());
xoffs--;
}
pos++;
}
}
} else {
int xoffs = 8 / bpp - 1;
for (int x = 0; x < width; x += 8 / bpp) {
val = decompressed.get(pos) & 0xff;
bits = 8;
for (int y = 0; y < height && xoffs >= 0;) {
while (x + xoffs >= width) {
xoffs--;
val >>= bpp;
bits -= bpp;
}
pixel = val & ((1 << bpp) - 1);
val >>= bpp;
bits -= bpp;
sheet.drawPixel(xoffs + sx + x, sy + y, pal.r
.get(pixel)
.byteValue(), pal.g.get(pixel).byteValue(),
pal.b.get(pixel).byteValue());
xoffs--;
if (bits == 0) {
+ pos++;
val = decompressed.get(pos) & 0xff;
bits = 8;
- pos++;
y++;
xoffs = 8 / bpp - 1;
}
}
}
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
System.out.println("Allocated at " + sx + ", " + sy);
}
}
| false | true | public void renderToSheet(SpriteSheet sheet, PaletteResource pal, int sx,
int sy) {
this.sheet = sheet;
sheetX = sx;
sheetY = sy;
try {
int bits = 0;
int val = 0;
int pos = 0;
int pixel = 0;
if (direction == ImageDirection.LEFT_RIGHT) {
int xoffs = 8 / bpp - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x += 8 / bpp) {
val = decompressed.get(pos) & 0xff;
xoffs = 8 / bpp - 1;
bits = 8;
while (x + xoffs >= width) {
xoffs--;
val >>= bpp;
bits -= bpp;
}
while (bits > 0) {
pixel = val & ((1 << bpp) - 1);
val >>= bpp;
bits -= bpp;
sheet.drawPixel(xoffs + sx + x, sy + y,
pal.r.get(pixel)
.byteValue(), pal.g.get(pixel)
.byteValue(),
pal.b.get(pixel).byteValue());
xoffs--;
}
pos++;
}
}
} else {
int xoffs = 8 / bpp - 1;
for (int x = 0; x < width; x += 8 / bpp) {
val = decompressed.get(pos) & 0xff;
bits = 8;
for (int y = 0; y < height && xoffs >= 0;) {
while (x + xoffs >= width) {
xoffs--;
val >>= bpp;
bits -= bpp;
}
pixel = val & ((1 << bpp) - 1);
val >>= bpp;
bits -= bpp;
sheet.drawPixel(xoffs + sx + x, sy + y, pal.r
.get(pixel)
.byteValue(), pal.g.get(pixel).byteValue(),
pal.b.get(pixel).byteValue());
xoffs--;
if (bits == 0) {
val = decompressed.get(pos) & 0xff;
bits = 8;
pos++;
y++;
xoffs = 8 / bpp - 1;
}
}
}
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
System.out.println("Allocated at " + sx + ", " + sy);
}
| public void renderToSheet(SpriteSheet sheet, PaletteResource pal, int sx,
int sy) {
this.sheet = sheet;
sheetX = sx;
sheetY = sy;
try {
int bits = 0;
int val = 0;
int pos = 0;
int pixel = 0;
if (direction == ImageDirection.LEFT_RIGHT) {
int xoffs = 8 / bpp - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x += 8 / bpp) {
val = decompressed.get(pos) & 0xff;
xoffs = 8 / bpp - 1;
bits = 8;
while (x + xoffs >= width) {
xoffs--;
val >>= bpp;
bits -= bpp;
}
while (bits > 0) {
pixel = val & ((1 << bpp) - 1);
val >>= bpp;
bits -= bpp;
sheet.drawPixel(xoffs + sx + x, sy + y,
pal.r.get(pixel)
.byteValue(), pal.g.get(pixel)
.byteValue(),
pal.b.get(pixel).byteValue());
xoffs--;
}
pos++;
}
}
} else {
int xoffs = 8 / bpp - 1;
for (int x = 0; x < width; x += 8 / bpp) {
val = decompressed.get(pos) & 0xff;
bits = 8;
for (int y = 0; y < height && xoffs >= 0;) {
while (x + xoffs >= width) {
xoffs--;
val >>= bpp;
bits -= bpp;
}
pixel = val & ((1 << bpp) - 1);
val >>= bpp;
bits -= bpp;
sheet.drawPixel(xoffs + sx + x, sy + y, pal.r
.get(pixel)
.byteValue(), pal.g.get(pixel).byteValue(),
pal.b.get(pixel).byteValue());
xoffs--;
if (bits == 0) {
pos++;
val = decompressed.get(pos) & 0xff;
bits = 8;
y++;
xoffs = 8 / bpp - 1;
}
}
}
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
System.out.println("Allocated at " + sx + ", " + sy);
}
|
diff --git a/src/main/java/com/geNAZt/RegionShop/Data/Tasks/PriceRecalculateTask.java b/src/main/java/com/geNAZt/RegionShop/Data/Tasks/PriceRecalculateTask.java
index 334abd2..8fb3d90 100644
--- a/src/main/java/com/geNAZt/RegionShop/Data/Tasks/PriceRecalculateTask.java
+++ b/src/main/java/com/geNAZt/RegionShop/Data/Tasks/PriceRecalculateTask.java
@@ -1,127 +1,127 @@
package com.geNAZt.RegionShop.Data.Tasks;
import com.geNAZt.RegionShop.Config.ConfigManager;
import com.geNAZt.RegionShop.Config.Sub.Item;
import com.geNAZt.RegionShop.Config.Sub.ServerShop;
import com.geNAZt.RegionShop.Database.Database;
import com.geNAZt.RegionShop.Database.Table.CustomerSign;
import com.geNAZt.RegionShop.Database.Table.Items;
import com.geNAZt.RegionShop.RegionShopPlugin;
import com.geNAZt.RegionShop.Util.ItemName;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
/**
* Created for YEAHWH.AT
* User: geNAZt ([email protected])
* Date: 16.06.13
*/
public class PriceRecalculateTask extends BukkitRunnable {
@Override
public void run() {
for (ServerShop shop : ConfigManager.servershop.ServerShops) {
for (Item item : shop.Items) {
Items itemInShop = Database.getServer().find(Items.class).
setUseCache(false).
setReadOnly(false).
setUseQueryCache(false).
where().
eq("meta.id.itemID", item.itemID).
eq("meta.id.dataValue", item.dataValue).
eq("itemStorage.regions.region", shop.Region).
findUnique();
if (itemInShop == null) continue;
Integer sold = (itemInShop.getSold() * 4) * 60;
Integer bought = (itemInShop.getBought() * 4) * 60;
Float sellPriceDiff = (float) sold / item.maxItemRecalc;
Float buyPriceDiff;
if (bought > 0) {
buyPriceDiff = (float) item.maxItemRecalc / bought;
} else {
buyPriceDiff = 2.0F;
}
if (sellPriceDiff > 1.0) {
//Preis geht rauf
if (sellPriceDiff > item.limitSellPriceFactor) {
sellPriceDiff = item.limitSellPriceFactor;
}
} else {
//Preis geht runter
if (sellPriceDiff < item.limitSellPriceUnderFactor) {
sellPriceDiff = item.limitSellPriceUnderFactor;
}
}
if (buyPriceDiff > 1.0) {
//Abgabe geht rauf
buyPriceDiff = buyPriceDiff * item.limitBuyPriceFactor;
} else {
//Abgabe geht runter
if (buyPriceDiff < item.limitBuyPriceUnderFactor) {
buyPriceDiff = item.limitBuyPriceUnderFactor;
}
}
- Float newSellPrice = Math.round(item.sell * sellPriceDiff / 100) * 100.0F;
- Float newBuyPrice = Math.round(item.buy * buyPriceDiff / 100) * 100.0F;
+ Float newSellPrice = Math.round(item.sell * sellPriceDiff * 100) / 100.0F;
+ Float newBuyPrice = Math.round(item.buy * buyPriceDiff * 100) / 100.0F;
itemInShop.setBuy(newBuyPrice);
itemInShop.setSell(newSellPrice);
itemInShop.setCurrentAmount(99999);
itemInShop.setBought(0);
itemInShop.setSold(0);
Database.getServer().update(itemInShop);
//Check if Item has a Sign
final CustomerSign customerSign = Database.getServer().find(CustomerSign.class).
where().
conjunction().
eq("item", itemInShop).
endJunction().
findUnique();
final Items items = itemInShop;
if (customerSign != null) {
RegionShopPlugin.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(RegionShopPlugin.getInstance(), new Runnable() {
@Override
public void run() {
Block block = RegionShopPlugin.getInstance().getServer().getWorld(customerSign.getRegion().getWorld()).getBlockAt(customerSign.getX(), customerSign.getY(), customerSign.getZ());
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
Sign sign = (Sign) block.getState();
//Get the nice name
ItemStack itemStack = com.geNAZt.RegionShop.Database.Model.Item.fromDBItem(items);
String itemName = ItemName.getDataName(itemStack) + itemStack.getType().toString();
if (itemStack.getItemMeta().hasDisplayName()) {
itemName = "(" + itemStack.getItemMeta().getDisplayName() + ")";
}
for (Integer line = 0; line < 4; line++) {
sign.setLine(line, ConfigManager.language.Sign_Customer_SignText.get(line).
replace("%id", items.getId().toString()).
replace("%itemname", ItemName.nicer(itemName)).
replace("%amount", items.getUnitAmount().toString()).
replace("%sell", items.getSell().toString()).
replace("%buy", items.getBuy().toString()));
}
sign.update();
}
}
});
}
}
}
}
}
| true | true | public void run() {
for (ServerShop shop : ConfigManager.servershop.ServerShops) {
for (Item item : shop.Items) {
Items itemInShop = Database.getServer().find(Items.class).
setUseCache(false).
setReadOnly(false).
setUseQueryCache(false).
where().
eq("meta.id.itemID", item.itemID).
eq("meta.id.dataValue", item.dataValue).
eq("itemStorage.regions.region", shop.Region).
findUnique();
if (itemInShop == null) continue;
Integer sold = (itemInShop.getSold() * 4) * 60;
Integer bought = (itemInShop.getBought() * 4) * 60;
Float sellPriceDiff = (float) sold / item.maxItemRecalc;
Float buyPriceDiff;
if (bought > 0) {
buyPriceDiff = (float) item.maxItemRecalc / bought;
} else {
buyPriceDiff = 2.0F;
}
if (sellPriceDiff > 1.0) {
//Preis geht rauf
if (sellPriceDiff > item.limitSellPriceFactor) {
sellPriceDiff = item.limitSellPriceFactor;
}
} else {
//Preis geht runter
if (sellPriceDiff < item.limitSellPriceUnderFactor) {
sellPriceDiff = item.limitSellPriceUnderFactor;
}
}
if (buyPriceDiff > 1.0) {
//Abgabe geht rauf
buyPriceDiff = buyPriceDiff * item.limitBuyPriceFactor;
} else {
//Abgabe geht runter
if (buyPriceDiff < item.limitBuyPriceUnderFactor) {
buyPriceDiff = item.limitBuyPriceUnderFactor;
}
}
Float newSellPrice = Math.round(item.sell * sellPriceDiff / 100) * 100.0F;
Float newBuyPrice = Math.round(item.buy * buyPriceDiff / 100) * 100.0F;
itemInShop.setBuy(newBuyPrice);
itemInShop.setSell(newSellPrice);
itemInShop.setCurrentAmount(99999);
itemInShop.setBought(0);
itemInShop.setSold(0);
Database.getServer().update(itemInShop);
//Check if Item has a Sign
final CustomerSign customerSign = Database.getServer().find(CustomerSign.class).
where().
conjunction().
eq("item", itemInShop).
endJunction().
findUnique();
final Items items = itemInShop;
if (customerSign != null) {
RegionShopPlugin.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(RegionShopPlugin.getInstance(), new Runnable() {
@Override
public void run() {
Block block = RegionShopPlugin.getInstance().getServer().getWorld(customerSign.getRegion().getWorld()).getBlockAt(customerSign.getX(), customerSign.getY(), customerSign.getZ());
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
Sign sign = (Sign) block.getState();
//Get the nice name
ItemStack itemStack = com.geNAZt.RegionShop.Database.Model.Item.fromDBItem(items);
String itemName = ItemName.getDataName(itemStack) + itemStack.getType().toString();
if (itemStack.getItemMeta().hasDisplayName()) {
itemName = "(" + itemStack.getItemMeta().getDisplayName() + ")";
}
for (Integer line = 0; line < 4; line++) {
sign.setLine(line, ConfigManager.language.Sign_Customer_SignText.get(line).
replace("%id", items.getId().toString()).
replace("%itemname", ItemName.nicer(itemName)).
replace("%amount", items.getUnitAmount().toString()).
replace("%sell", items.getSell().toString()).
replace("%buy", items.getBuy().toString()));
}
sign.update();
}
}
});
}
}
}
}
| public void run() {
for (ServerShop shop : ConfigManager.servershop.ServerShops) {
for (Item item : shop.Items) {
Items itemInShop = Database.getServer().find(Items.class).
setUseCache(false).
setReadOnly(false).
setUseQueryCache(false).
where().
eq("meta.id.itemID", item.itemID).
eq("meta.id.dataValue", item.dataValue).
eq("itemStorage.regions.region", shop.Region).
findUnique();
if (itemInShop == null) continue;
Integer sold = (itemInShop.getSold() * 4) * 60;
Integer bought = (itemInShop.getBought() * 4) * 60;
Float sellPriceDiff = (float) sold / item.maxItemRecalc;
Float buyPriceDiff;
if (bought > 0) {
buyPriceDiff = (float) item.maxItemRecalc / bought;
} else {
buyPriceDiff = 2.0F;
}
if (sellPriceDiff > 1.0) {
//Preis geht rauf
if (sellPriceDiff > item.limitSellPriceFactor) {
sellPriceDiff = item.limitSellPriceFactor;
}
} else {
//Preis geht runter
if (sellPriceDiff < item.limitSellPriceUnderFactor) {
sellPriceDiff = item.limitSellPriceUnderFactor;
}
}
if (buyPriceDiff > 1.0) {
//Abgabe geht rauf
buyPriceDiff = buyPriceDiff * item.limitBuyPriceFactor;
} else {
//Abgabe geht runter
if (buyPriceDiff < item.limitBuyPriceUnderFactor) {
buyPriceDiff = item.limitBuyPriceUnderFactor;
}
}
Float newSellPrice = Math.round(item.sell * sellPriceDiff * 100) / 100.0F;
Float newBuyPrice = Math.round(item.buy * buyPriceDiff * 100) / 100.0F;
itemInShop.setBuy(newBuyPrice);
itemInShop.setSell(newSellPrice);
itemInShop.setCurrentAmount(99999);
itemInShop.setBought(0);
itemInShop.setSold(0);
Database.getServer().update(itemInShop);
//Check if Item has a Sign
final CustomerSign customerSign = Database.getServer().find(CustomerSign.class).
where().
conjunction().
eq("item", itemInShop).
endJunction().
findUnique();
final Items items = itemInShop;
if (customerSign != null) {
RegionShopPlugin.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(RegionShopPlugin.getInstance(), new Runnable() {
@Override
public void run() {
Block block = RegionShopPlugin.getInstance().getServer().getWorld(customerSign.getRegion().getWorld()).getBlockAt(customerSign.getX(), customerSign.getY(), customerSign.getZ());
if (block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN)) {
Sign sign = (Sign) block.getState();
//Get the nice name
ItemStack itemStack = com.geNAZt.RegionShop.Database.Model.Item.fromDBItem(items);
String itemName = ItemName.getDataName(itemStack) + itemStack.getType().toString();
if (itemStack.getItemMeta().hasDisplayName()) {
itemName = "(" + itemStack.getItemMeta().getDisplayName() + ")";
}
for (Integer line = 0; line < 4; line++) {
sign.setLine(line, ConfigManager.language.Sign_Customer_SignText.get(line).
replace("%id", items.getId().toString()).
replace("%itemname", ItemName.nicer(itemName)).
replace("%amount", items.getUnitAmount().toString()).
replace("%sell", items.getSell().toString()).
replace("%buy", items.getBuy().toString()));
}
sign.update();
}
}
});
}
}
}
}
|
diff --git a/src/com/android/phone/CallNotifier.java b/src/com/android/phone/CallNotifier.java
index 3fb3df7c..babaefcb 100755
--- a/src/com/android/phone/CallNotifier.java
+++ b/src/com/android/phone/CallNotifier.java
@@ -1,1558 +1,1561 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.CallerInfo;
import com.android.internal.telephony.CallerInfoAsyncQuery;
import com.android.internal.telephony.cdma.CdmaCallWaitingNotification;
import com.android.internal.telephony.cdma.SignalToneUtil;
import com.android.internal.telephony.cdma.CdmaInformationRecords.CdmaDisplayInfoRec;
import com.android.internal.telephony.cdma.CdmaInformationRecords.CdmaSignalInfoRec;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.gsm.GSMPhone;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Vibrator;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.provider.Checkin;
import android.provider.Settings;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* Stub which listens for phone state changes and decides whether it is worth
* telling the user what just happened.
*/
public class CallNotifier extends Handler
implements CallerInfoAsyncQuery.OnQueryCompleteListener {
private static final String LOG_TAG = "CallNotifier";
private static final boolean DBG =
(PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2);
// Strings used with Checkin.logEvent().
private static final String PHONE_UI_EVENT_RINGER_QUERY_ELAPSED =
"using default incoming call behavior";
private static final String PHONE_UI_EVENT_MULTIPLE_QUERY =
"multiple incoming call queries attempted";
// Maximum time we allow the CallerInfo query to run,
// before giving up and falling back to the default ringtone.
private static final int RINGTONE_QUERY_WAIT_TIME = 500; // msec
// Timers related to CDMA Call Waiting
// 1) For displaying Caller Info
// 2) For disabling "Add Call" menu option once User selects Ignore or CW Timeout occures
private static final int CALLWAITING_CALLERINFO_DISPLAY_TIME = 20000; // msec
private static final int CALLWAITING_ADDCALL_DISABLE_TIME = 60000; // msec
// Time to display the DisplayInfo Record sent by CDMA network
private static final int DISPLAYINFO_NOTIFICATION_TIME = 2000; // msec
// Boolean to store information if a Call Waiting timed out
private boolean mCallWaitingTimeOut = false;
// values used to track the query state
private static final int CALLERINFO_QUERY_READY = 0;
private static final int CALLERINFO_QUERYING = -1;
// the state of the CallerInfo Query.
private int mCallerInfoQueryState;
// object used to synchronize access to mCallerInfoQueryState
private Object mCallerInfoQueryStateGuard = new Object();
// Event used to indicate a query timeout.
private static final int RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT = 100;
// Events from the Phone object:
private static final int PHONE_STATE_CHANGED = 1;
private static final int PHONE_NEW_RINGING_CONNECTION = 2;
private static final int PHONE_DISCONNECT = 3;
private static final int PHONE_UNKNOWN_CONNECTION_APPEARED = 4;
private static final int PHONE_INCOMING_RING = 5;
private static final int PHONE_STATE_DISPLAYINFO = 6;
private static final int PHONE_STATE_SIGNALINFO = 7;
private static final int PHONE_CDMA_CALL_WAITING = 8;
private static final int PHONE_ENHANCED_VP_ON = 9;
private static final int PHONE_ENHANCED_VP_OFF = 10;
// Events generated internally:
private static final int PHONE_MWI_CHANGED = 11;
private static final int PHONE_BATTERY_LOW = 12;
private static final int CALLWAITING_CALLERINFO_DISPLAY_DONE = 13;
private static final int CALLWAITING_ADDCALL_DISABLE_TIMEOUT = 14;
private static final int DISPLAYINFO_NOTIFICATION_DONE = 15;
private static final int EVENT_OTA_PROVISION_CHANGE = 16;
// Emergency call related defines:
private static final int EMERGENCY_TONE_OFF = 0;
private static final int EMERGENCY_TONE_ALERT = 1;
private static final int EMERGENCY_TONE_VIBRATE = 2;
private PhoneApp mApplication;
private Phone mPhone;
private Ringer mRinger;
private BluetoothHandsfree mBluetoothHandsfree;
private boolean mSilentRingerRequested;
// ToneGenerator instance for playing SignalInfo tones
private ToneGenerator mSignalInfoToneGenerator;
// The tone volume relative to other sounds in the stream SignalInfo
private static final int TONE_RELATIVE_VOLUME_LOPRI_SIGNALINFO = 50;
// Additional members for CDMA
private Call.State mPreviousCdmaCallState;
private boolean mCdmaVoicePrivacyState = false;
private boolean mIsCdmaRedialCall = false;
// Emergency call tone and vibrate:
private int mIsEmergencyToneOn;
private int mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
private EmergencyTonePlayerVibrator mEmergencyTonePlayerVibrator;
public CallNotifier(PhoneApp app, Phone phone, Ringer ringer,
BluetoothHandsfree btMgr) {
mApplication = app;
mPhone = phone;
mPhone.registerForNewRingingConnection(this, PHONE_NEW_RINGING_CONNECTION, null);
mPhone.registerForPreciseCallStateChanged(this, PHONE_STATE_CHANGED, null);
mPhone.registerForDisconnect(this, PHONE_DISCONNECT, null);
mPhone.registerForUnknownConnection(this, PHONE_UNKNOWN_CONNECTION_APPEARED, null);
mPhone.registerForIncomingRing(this, PHONE_INCOMING_RING, null);
if (mPhone.getPhoneName().equals("CDMA")) {
mPhone.registerForCdmaOtaStatusChange(this, EVENT_OTA_PROVISION_CHANGE, null);
}
if (mPhone.getPhoneName().equals("CDMA")) {
if (DBG) log("Registering for Call Waiting, Signal and Display Info.");
mPhone.registerForCallWaiting(this, PHONE_CDMA_CALL_WAITING, null);
mPhone.registerForDisplayInfo(this, PHONE_STATE_DISPLAYINFO, null);
mPhone.registerForSignalInfo(this, PHONE_STATE_SIGNALINFO, null);
mPhone.registerForInCallVoicePrivacyOn(this, PHONE_ENHANCED_VP_ON, null);
mPhone.registerForInCallVoicePrivacyOff(this, PHONE_ENHANCED_VP_OFF, null);
// Instantiate the ToneGenerator for SignalInfo and CallWaiting
// TODO(Moto): We probably dont need the mSignalInfoToneGenerator instance
// around forever. Need to change it so as to create a ToneGenerator instance only
// when a tone is being played and releases it after its done playing.
try {
mSignalInfoToneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION,
TONE_RELATIVE_VOLUME_LOPRI_SIGNALINFO);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "CallNotifier: Exception caught while creating " +
"mSignalInfoToneGenerator: " + e);
mSignalInfoToneGenerator = null;
}
}
mRinger = ringer;
mBluetoothHandsfree = btMgr;
TelephonyManager telephonyManager = (TelephonyManager)app.getSystemService(
Context.TELEPHONY_SERVICE);
telephonyManager.listen(mPhoneStateListener,
PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR
| PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PHONE_NEW_RINGING_CONNECTION:
if (DBG) log("RINGING... (new)");
onNewRingingConnection((AsyncResult) msg.obj);
mSilentRingerRequested = false;
break;
case PHONE_INCOMING_RING:
// repeat the ring when requested by the RIL, and when the user has NOT
// specifically requested silence.
if (msg.obj != null && ((AsyncResult) msg.obj).result != null &&
((GSMPhone)((AsyncResult) msg.obj).result).getState() == Phone.State.RINGING
&& mSilentRingerRequested == false) {
if (DBG) log("RINGING... (PHONE_INCOMING_RING event)");
mRinger.ring();
} else {
if (DBG) log("RING before NEW_RING, skipping");
}
break;
case PHONE_STATE_CHANGED:
onPhoneStateChanged((AsyncResult) msg.obj);
break;
case PHONE_DISCONNECT:
if (DBG) log("DISCONNECT");
onDisconnect((AsyncResult) msg.obj);
break;
case PHONE_UNKNOWN_CONNECTION_APPEARED:
onUnknownConnectionAppeared((AsyncResult) msg.obj);
break;
case RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT:
// CallerInfo query is taking too long! But we can't wait
// any more, so start ringing NOW even if it means we won't
// use the correct custom ringtone.
Log.w(LOG_TAG, "CallerInfo query took too long; manually starting ringer");
// In this case we call onCustomRingQueryComplete(), just
// like if the query had completed normally. (But we're
// going to get the default ringtone, since we never got
// the chance to call Ringer.setCustomRingtoneUri()).
onCustomRingQueryComplete();
break;
case PHONE_MWI_CHANGED:
onMwiChanged(mPhone.getMessageWaitingIndicator());
break;
case PHONE_BATTERY_LOW:
onBatteryLow();
break;
case PHONE_CDMA_CALL_WAITING:
if (DBG) log("Received PHONE_CDMA_CALL_WAITING event");
onCdmaCallWaiting((AsyncResult) msg.obj);
break;
case CALLWAITING_CALLERINFO_DISPLAY_DONE:
if (DBG) log("Received CALLWAITING_CALLERINFO_DISPLAY_DONE event ...");
mCallWaitingTimeOut = true;
onCdmaCallWaitingReject();
break;
case CALLWAITING_ADDCALL_DISABLE_TIMEOUT:
if (DBG) log("Received CALLWAITING_ADDCALL_DISABLE_TIMEOUT event ...");
// Set the mAddCallMenuStateAfterCW state to true
mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true);
break;
case PHONE_STATE_DISPLAYINFO:
if (DBG) log("Received PHONE_STATE_DISPLAYINFO event");
onDisplayInfo((AsyncResult) msg.obj);
break;
case PHONE_STATE_SIGNALINFO:
if (DBG) log("Received PHONE_STATE_SIGNALINFO event");
onSignalInfo((AsyncResult) msg.obj);
break;
case DISPLAYINFO_NOTIFICATION_DONE:
if (DBG) log("Received Display Info notification done event ...");
CdmaDisplayInfo.dismissDisplayInfoRecord();
break;
case EVENT_OTA_PROVISION_CHANGE:
mApplication.handleOtaEvents(msg);
break;
case PHONE_ENHANCED_VP_ON:
if (DBG) log("PHONE_ENHANCED_VP_ON...");
if (!mCdmaVoicePrivacyState) {
int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY;
new InCallTonePlayer(toneToPlay).start();
mCdmaVoicePrivacyState = true;
}
break;
case PHONE_ENHANCED_VP_OFF:
if (DBG) log("PHONE_ENHANCED_VP_OFF...");
if (mCdmaVoicePrivacyState) {
int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY;
new InCallTonePlayer(toneToPlay).start();
mCdmaVoicePrivacyState = false;
}
break;
default:
// super.handleMessage(msg);
}
}
PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onMessageWaitingIndicatorChanged(boolean mwi) {
onMwiChanged(mwi);
}
@Override
public void onCallForwardingIndicatorChanged(boolean cfi) {
onCfiChanged(cfi);
}
};
private void onNewRingingConnection(AsyncResult r) {
Connection c = (Connection) r.result;
if (DBG) log("onNewRingingConnection(): " + c);
// Incoming calls are totally ignored if the device isn't provisioned yet
boolean provisioned = Settings.Secure.getInt(mPhone.getContext().getContentResolver(),
Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
if (!provisioned) {
Log.i(LOG_TAG, "CallNotifier: rejecting incoming call: device isn't provisioned");
// Send the caller straight to voicemail, just like
// "rejecting" an incoming call.
PhoneUtils.hangupRingingCall(mPhone);
return;
}
if (c != null && c.isRinging()) {
// Stop any signalInfo tone being played on receiving a Call
if (mPhone.getPhoneName().equals("CDMA")) {
stopSignalInfoTone();
}
Call.State state = c.getState();
// State will be either INCOMING or WAITING.
if (VDBG) log("- connection is ringing! state = " + state);
// if (DBG) PhoneUtils.dumpCallState(mPhone);
// No need to do any service state checks here (like for
// "emergency mode"), since in those states the SIM won't let
// us get incoming connections in the first place.
// TODO: Consider sending out a serialized broadcast Intent here
// (maybe "ACTION_NEW_INCOMING_CALL"), *before* starting the
// ringer and going to the in-call UI. The intent should contain
// the caller-id info for the current connection, and say whether
// it would be a "call waiting" call or a regular ringing call.
// If anybody consumed the broadcast, we'd bail out without
// ringing or bringing up the in-call UI.
//
// This would give 3rd party apps a chance to listen for (and
// intercept) new ringing connections. An app could reject the
// incoming call by consuming the broadcast and doing nothing, or
// it could "pick up" the call (without any action by the user!)
// by firing off an ACTION_ANSWER intent.
//
// We'd need to protect this with a new "intercept incoming calls"
// system permission.
// - don't ring for call waiting connections
// - do this before showing the incoming call panel
if (state == Call.State.INCOMING) {
PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_RINGING);
startIncomingCallQuery(c);
} else {
if (VDBG) log("- starting call waiting tone...");
new InCallTonePlayer(InCallTonePlayer.TONE_CALL_WAITING).start();
// The InCallTonePlayer will automatically stop playing (and
// clean itself up) after playing the tone.
// TODO: alternatively, consider starting an
// InCallTonePlayer with an "unlimited" tone length, and
// manually stop it later when the ringing call either (a)
// gets answered, or (b) gets disconnected.
// in this case, just fall through like before, and call
// PhoneUtils.showIncomingCallUi
PhoneUtils.showIncomingCallUi();
}
}
// Obtain a partial wake lock to make sure the CPU doesn't go to
// sleep before we finish bringing up the InCallScreen.
// (This will be upgraded soon to a full wake lock; see
// PhoneUtils.showIncomingCallUi().)
if (VDBG) log("Holding wake lock on new incoming connection.");
mApplication.requestWakeState(PhoneApp.WakeState.PARTIAL);
if (VDBG) log("- onNewRingingConnection() done.");
}
/**
* Helper method to manage the start of incoming call queries
*/
private void startIncomingCallQuery(Connection c) {
// TODO: cache the custom ringer object so that subsequent
// calls will not need to do this query work. We can keep
// the MRU ringtones in memory. We'll still need to hit
// the database to get the callerinfo to act as a key,
// but at least we can save the time required for the
// Media player setup. The only issue with this is that
// we may need to keep an eye on the resources the Media
// player uses to keep these ringtones around.
// make sure we're in a state where we can be ready to
// query a ringtone uri.
boolean shouldStartQuery = false;
synchronized (mCallerInfoQueryStateGuard) {
if (mCallerInfoQueryState == CALLERINFO_QUERY_READY) {
mCallerInfoQueryState = CALLERINFO_QUERYING;
shouldStartQuery = true;
}
}
if (shouldStartQuery) {
// create a custom ringer using the default ringer first
mRinger.setCustomRingtoneUri(Settings.System.DEFAULT_RINGTONE_URI);
// query the callerinfo to try to get the ringer.
PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(
mPhone.getContext(), c, this, this);
// if this has already been queried then just ring, otherwise
// we wait for the alloted time before ringing.
if (cit.isFinal) {
if (VDBG) log("- CallerInfo already up to date, using available data");
onQueryComplete(0, this, cit.currentInfo);
} else {
if (VDBG) log("- Starting query, posting timeout message.");
sendEmptyMessageDelayed(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT,
RINGTONE_QUERY_WAIT_TIME);
}
// calls to PhoneUtils.showIncomingCallUi will come after the
// queries are complete (or timeout).
} else {
// This should never happen; its the case where an incoming call
// arrives at the same time that the query is still being run,
// and before the timeout window has closed.
Checkin.logEvent(mPhone.getContext().getContentResolver(),
Checkin.Events.Tag.PHONE_UI,
PHONE_UI_EVENT_MULTIPLE_QUERY);
// In this case, just log the request and ring.
if (VDBG) log("RINGING... (request to ring arrived while query is running)");
mRinger.ring();
// in this case, just fall through like before, and call
// PhoneUtils.showIncomingCallUi
PhoneUtils.showIncomingCallUi();
}
}
/**
* Performs the final steps of the onNewRingingConnection sequence:
* starts the ringer, and launches the InCallScreen to show the
* "incoming call" UI.
*
* Normally, this is called when the CallerInfo query completes (see
* onQueryComplete()). In this case, onQueryComplete() has already
* configured the Ringer object to use the custom ringtone (if there
* is one) for this caller. So we just tell the Ringer to start, and
* proceed to the InCallScreen.
*
* But this method can *also* be called if the
* RINGTONE_QUERY_WAIT_TIME timeout expires, which means that the
* CallerInfo query is taking too long. In that case, we log a
* warning but otherwise we behave the same as in the normal case.
* (We still tell the Ringer to start, but it's going to use the
* default ringtone.)
*/
private void onCustomRingQueryComplete() {
boolean isQueryExecutionTimeExpired = false;
synchronized (mCallerInfoQueryStateGuard) {
if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
mCallerInfoQueryState = CALLERINFO_QUERY_READY;
isQueryExecutionTimeExpired = true;
}
}
if (isQueryExecutionTimeExpired) {
// There may be a problem with the query here, since the
// default ringtone is playing instead of the custom one.
Log.w(LOG_TAG, "CallerInfo query took too long; falling back to default ringtone");
Checkin.logEvent(mPhone.getContext().getContentResolver(),
Checkin.Events.Tag.PHONE_UI,
PHONE_UI_EVENT_RINGER_QUERY_ELAPSED);
}
// Make sure we still have an incoming call!
//
// (It's possible for the incoming call to have been disconnected
// while we were running the query. In that case we better not
// start the ringer here, since there won't be any future
// DISCONNECT event to stop it!)
//
// Note we don't have to worry about the incoming call going away
// *after* this check but before we call mRinger.ring() below,
// since in that case we *will* still get a DISCONNECT message sent
// to our handler. (And we will correctly stop the ringer when we
// process that event.)
if (mPhone.getState() != Phone.State.RINGING) {
Log.i(LOG_TAG, "onCustomRingQueryComplete: No incoming call! Bailing out...");
// Don't start the ringer *or* bring up the "incoming call" UI.
// Just bail out.
return;
}
// Ring, either with the queried ringtone or default one.
if (VDBG) log("RINGING... (onCustomRingQueryComplete)");
mRinger.ring();
// ...and show the InCallScreen.
PhoneUtils.showIncomingCallUi();
}
private void onUnknownConnectionAppeared(AsyncResult r) {
Phone.State state = mPhone.getState();
if (state == Phone.State.OFFHOOK) {
// basically do onPhoneStateChanged + displayCallScreen
onPhoneStateChanged(r);
PhoneUtils.showIncomingCallUi();
}
}
private void onPhoneStateChanged(AsyncResult r) {
Phone.State state = mPhone.getState();
// Turn status bar notifications on or off depending upon the state
// of the phone. Notification Alerts (audible or vibrating) should
// be on if and only if the phone is IDLE.
NotificationMgr.getDefault().getStatusBarMgr()
.enableNotificationAlerts(state == Phone.State.IDLE);
if (mPhone.getPhoneName().equals("CDMA")) {
if ((mPhone.getForegroundCall().getState() == Call.State.ACTIVE)
&& ((mPreviousCdmaCallState == Call.State.DIALING)
|| (mPreviousCdmaCallState == Call.State.ALERTING))) {
if (mIsCdmaRedialCall) {
int toneToPlay = InCallTonePlayer.TONE_REDIAL;
new InCallTonePlayer(toneToPlay).start();
}
}
mPreviousCdmaCallState = mPhone.getForegroundCall().getState();
}
// Have the PhoneApp recompute its mShowBluetoothIndication
// flag based on the (new) telephony state.
// There's no need to force a UI update since we update the
// in-call notification ourselves (below), and the InCallScreen
// listens for phone state changes itself.
mApplication.updateBluetoothIndication(false);
// Update the proximity sensor mode (on devices that have a
// proximity sensor).
mApplication.updateProximitySensorMode(state);
if (state == Phone.State.OFFHOOK) {
PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
if (VDBG) log("onPhoneStateChanged: OFF HOOK");
// if the call screen is showing, let it handle the event,
// otherwise handle it here.
if (!mApplication.isShowingCallScreen()) {
mApplication.setScreenTimeout(PhoneApp.ScreenTimeoutDuration.DEFAULT);
mApplication.requestWakeState(PhoneApp.WakeState.SLEEP);
}
// Since we're now in-call, the Ringer should definitely *not*
// be ringing any more. (This is just a sanity-check; we
// already stopped the ringer explicitly back in
// PhoneUtils.answerCall(), before the call to phone.acceptCall().)
// TODO: Confirm that this call really *is* unnecessary, and if so,
// remove it!
if (DBG) log("stopRing()... (OFFHOOK state)");
mRinger.stopRing();
// put a icon in the status bar
NotificationMgr.getDefault().updateInCallNotification();
}
if (mPhone.getPhoneName().equals("CDMA")) {
Connection c = mPhone.getForegroundCall().getLatestConnection();
if ((c != null) && (PhoneNumberUtils.isEmergencyNumber(c.getAddress()))) {
if (VDBG) log("onPhoneStateChanged: it is an emergency call.");
Call.State callState = mPhone.getForegroundCall().getState();
if (mEmergencyTonePlayerVibrator == null) {
mEmergencyTonePlayerVibrator = new EmergencyTonePlayerVibrator();
}
if (callState == Call.State.DIALING || callState == Call.State.ALERTING) {
mIsEmergencyToneOn = Settings.System.getInt(
mPhone.getContext().getContentResolver(),
Settings.System.EMERGENCY_TONE, EMERGENCY_TONE_OFF);
if (mIsEmergencyToneOn != EMERGENCY_TONE_OFF &&
mCurrentEmergencyToneState == EMERGENCY_TONE_OFF) {
if (mEmergencyTonePlayerVibrator != null) {
mEmergencyTonePlayerVibrator.start();
}
}
} else if (callState == Call.State.ACTIVE) {
if (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF) {
if (mEmergencyTonePlayerVibrator != null) {
mEmergencyTonePlayerVibrator.stop();
}
}
}
}
}
}
void updateCallNotifierRegistrationsAfterRadioTechnologyChange() {
if (DBG) Log.d(LOG_TAG, "updateCallNotifierRegistrationsAfterRadioTechnologyChange...");
// Unregister all events from the old obsolete phone
mPhone.unregisterForNewRingingConnection(this);
mPhone.unregisterForPreciseCallStateChanged(this);
mPhone.unregisterForDisconnect(this);
mPhone.unregisterForUnknownConnection(this);
mPhone.unregisterForIncomingRing(this);
mPhone.unregisterForCallWaiting(this);
mPhone.unregisterForDisplayInfo(this);
mPhone.unregisterForSignalInfo(this);
mPhone.unregisterForCdmaOtaStatusChange(this);
// Release the ToneGenerator used for playing SignalInfo and CallWaiting
if (mSignalInfoToneGenerator != null) {
mSignalInfoToneGenerator.release();
}
mPhone.unregisterForInCallVoicePrivacyOn(this);
mPhone.unregisterForInCallVoicePrivacyOff(this);
// Register all events new to the new active phone
mPhone.registerForNewRingingConnection(this, PHONE_NEW_RINGING_CONNECTION, null);
mPhone.registerForPreciseCallStateChanged(this, PHONE_STATE_CHANGED, null);
mPhone.registerForDisconnect(this, PHONE_DISCONNECT, null);
mPhone.registerForUnknownConnection(this, PHONE_UNKNOWN_CONNECTION_APPEARED, null);
mPhone.registerForIncomingRing(this, PHONE_INCOMING_RING, null);
if (mPhone.getPhoneName().equals("CDMA")) {
if (DBG) log("Registering for Call Waiting, Signal and Display Info.");
mPhone.registerForCallWaiting(this, PHONE_CDMA_CALL_WAITING, null);
mPhone.registerForDisplayInfo(this, PHONE_STATE_DISPLAYINFO, null);
mPhone.registerForSignalInfo(this, PHONE_STATE_SIGNALINFO, null);
mPhone.registerForCdmaOtaStatusChange(this, EVENT_OTA_PROVISION_CHANGE, null);
// Instantiate the ToneGenerator for SignalInfo
try {
mSignalInfoToneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION,
TONE_RELATIVE_VOLUME_LOPRI_SIGNALINFO);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "CallNotifier: Exception caught while creating " +
"mSignalInfoToneGenerator: " + e);
mSignalInfoToneGenerator = null;
}
mPhone.registerForInCallVoicePrivacyOn(this, PHONE_ENHANCED_VP_ON, null);
mPhone.registerForInCallVoicePrivacyOff(this, PHONE_ENHANCED_VP_OFF, null);
}
}
/**
* Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
* refreshes the CallCard data when it called. If called with this
* class itself, it is assumed that we have been waiting for the ringtone
* and direct to voicemail settings to update.
*/
public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
if (cookie instanceof Long) {
if (VDBG) log("CallerInfo query complete, posting missed call notification");
NotificationMgr.getDefault().notifyMissedCall(ci.name, ci.phoneNumber,
ci.phoneLabel, ((Long) cookie).longValue());
} else if (cookie instanceof CallNotifier) {
if (VDBG) log("CallerInfo query complete, updating data");
// get rid of the timeout messages
removeMessages(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT);
boolean isQueryExecutionTimeOK = false;
synchronized (mCallerInfoQueryStateGuard) {
if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
mCallerInfoQueryState = CALLERINFO_QUERY_READY;
isQueryExecutionTimeOK = true;
}
}
//if we're in the right state
if (isQueryExecutionTimeOK) {
// send directly to voicemail.
if (ci.shouldSendToVoicemail) {
if (DBG) log("send to voicemail flag detected. hanging up.");
PhoneUtils.hangupRingingCall(mPhone);
return;
}
// set the ringtone uri to prepare for the ring.
if (ci.contactRingtoneUri != null) {
if (DBG) log("custom ringtone found, setting up ringer.");
Ringer r = ((CallNotifier) cookie).mRinger;
r.setCustomRingtoneUri(ci.contactRingtoneUri);
}
// ring, and other post-ring actions.
onCustomRingQueryComplete();
}
}
}
private void onDisconnect(AsyncResult r) {
if (VDBG) log("onDisconnect()... phone state: " + mPhone.getState());
mCdmaVoicePrivacyState = false;
int autoretrySetting = 0;
if (mPhone.getPhoneName().equals("CDMA")) {
autoretrySetting = android.provider.Settings.System.getInt(mPhone.getContext().
getContentResolver(),android.provider.Settings.System.CALL_AUTO_RETRY, 0);
}
if (mPhone.getState() == Phone.State.IDLE) {
PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_IDLE);
}
if (mPhone.getPhoneName().equals("CDMA")) {
// Stop any signalInfo tone being played when a call gets ended
stopSignalInfoTone();
}
Connection c = (Connection) r.result;
if (DBG && c != null) {
log("- onDisconnect: cause = " + c.getDisconnectCause()
+ ", incoming = " + c.isIncoming()
+ ", date = " + c.getCreateTime());
}
// Stop the ringer if it was ringing (for an incoming call that
// either disconnected by itself, or was rejected by the user.)
//
// TODO: We technically *shouldn't* stop the ringer if the
// foreground or background call disconnects while an incoming call
// is still ringing, but that's a really rare corner case.
// It's safest to just unconditionally stop the ringer here.
if (DBG) log("stopRing()... (onDisconnect)");
mRinger.stopRing();
// Check for the various tones we might need to play (thru the
// earpiece) after a call disconnects.
int toneToPlay = InCallTonePlayer.TONE_NONE;
// The "Busy" or "Congestion" tone is the highest priority:
if (c != null) {
Connection.DisconnectCause cause = c.getDisconnectCause();
if (cause == Connection.DisconnectCause.BUSY) {
if (DBG) log("- need to play BUSY tone!");
toneToPlay = InCallTonePlayer.TONE_BUSY;
} else if (cause == Connection.DisconnectCause.CONGESTION) {
if (DBG) log("- need to play CONGESTION tone!");
toneToPlay = InCallTonePlayer.TONE_CONGESTION;
} else if (((cause == Connection.DisconnectCause.NORMAL)
|| (cause == Connection.DisconnectCause.LOCAL))
&& (mApplication.isOtaCallInActiveState())) {
if (DBG) log("- need to play OTA_CALL_END tone!");
toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
} else if (cause == Connection.DisconnectCause.CDMA_REORDER) {
if (DBG) log("- need to play CDMA_REORDER tone!");
toneToPlay = InCallTonePlayer.TONE_REORDER;
} else if (cause == Connection.DisconnectCause.CDMA_INTERCEPT) {
if (DBG) log("- need to play CDMA_INTERCEPT tone!");
toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
} else if (cause == Connection.DisconnectCause.CDMA_DROP) {
if (DBG) log("- need to play CDMA_DROP tone!");
toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
} else if (cause == Connection.DisconnectCause.OUT_OF_SERVICE) {
if (DBG) log("- need to play OUT OF SERVICE tone!");
toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
+ } else if (cause == Connection.DisconnectCause.ERROR_UNSPECIFIED) {
+ if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!");
+ toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
}
}
// If we don't need to play BUSY or CONGESTION, then play the
// "call ended" tone if this was a "regular disconnect" (i.e. a
// normal call where one end or the other hung up) *and* this
// disconnect event caused the phone to become idle. (In other
// words, we *don't* play the sound if one call hangs up but
// there's still an active call on the other line.)
// TODO: We may eventually want to disable this via a preference.
if ((toneToPlay == InCallTonePlayer.TONE_NONE)
&& (mPhone.getState() == Phone.State.IDLE)
&& (c != null)) {
Connection.DisconnectCause cause = c.getDisconnectCause();
if ((cause == Connection.DisconnectCause.NORMAL) // remote hangup
|| (cause == Connection.DisconnectCause.LOCAL)) { // local hangup
if (VDBG) log("- need to play CALL_ENDED tone!");
toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
mIsCdmaRedialCall = false;
}
}
if (mPhone.getState() == Phone.State.IDLE) {
// Don't reset the audio mode or bluetooth/speakerphone state
// if we still need to let the user hear a tone through the earpiece.
if (toneToPlay == InCallTonePlayer.TONE_NONE) {
resetAudioStateAfterDisconnect();
}
NotificationMgr.getDefault().cancelCallInProgressNotification();
// If the InCallScreen is *not* in the foreground, forcibly
// dismiss it to make sure it won't still be in the activity
// history. (But if it *is* in the foreground, don't mess
// with it; it needs to be visible, displaying the "Call
// ended" state.)
if (!mApplication.isShowingCallScreen()) {
if (VDBG) log("onDisconnect: force InCallScreen to finish()");
mApplication.dismissCallScreen();
}
}
if (c != null) {
final String number = c.getAddress();
final int presentation = c.getNumberPresentation();
if (DBG) log("- onDisconnect: presentation=" + presentation);
final long date = c.getCreateTime();
final long duration = c.getDurationMillis();
final Connection.DisconnectCause cause = c.getDisconnectCause();
// For international calls, 011 needs to be logged as +
final String cdmaLogNumber = c.isIncoming()? number : c.getOrigDialString();
// Set the "type" to be displayed in the call log (see constants in CallLog.Calls)
final int callLogType;
if (c.isIncoming()) {
callLogType = (cause == Connection.DisconnectCause.INCOMING_MISSED ?
CallLog.Calls.MISSED_TYPE :
CallLog.Calls.INCOMING_TYPE);
} else {
callLogType = CallLog.Calls.OUTGOING_TYPE;
}
if (VDBG) log("- callLogType: " + callLogType + ", UserData: " + c.getUserData());
// Get the CallerInfo object and then log the call with it.
{
Object o = c.getUserData();
final CallerInfo ci;
if ((o == null) || (o instanceof CallerInfo)) {
ci = (CallerInfo) o;
} else {
ci = ((PhoneUtils.CallerInfoToken) o).currentInfo;
}
final String eNumber = c.getAddress();
if (mPhone.getPhoneName().equals("CDMA")) {
if ((PhoneNumberUtils.isEmergencyNumber(eNumber))
&& (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
if (mEmergencyTonePlayerVibrator != null) {
mEmergencyTonePlayerVibrator.stop();
}
}
}
// Watch out: Calls.addCall() hits the Contacts database,
// so we shouldn't call it from the main thread.
Thread t = new Thread() {
public void run() {
if (mPhone.getPhoneName().equals("CDMA")) {
// Don't put OTA or Emergency calls into call log
if (!mApplication.isOtaCallInActiveState()
&& !PhoneNumberUtils.isEmergencyNumber(eNumber)) {
Calls.addCall(ci, mApplication, number, presentation,
callLogType, date, (int) duration / 1000);
}
} else {
Calls.addCall(ci, mApplication, number, presentation,
callLogType, date, (int) duration / 1000);
// if (DBG) log("onDisconnect helper thread: Calls.addCall() done.");
}
}
};
t.start();
}
if (callLogType == CallLog.Calls.MISSED_TYPE) {
// Show the "Missed call" notification.
// (Note we *don't* do this if this was an incoming call that
// the user deliberately rejected.)
showMissedCallNotification(c, date);
}
// Possibly play a "post-disconnect tone" thru the earpiece.
// We do this here, rather than from the InCallScreen
// activity, since we need to do this even if you're not in
// the Phone UI at the moment the connection ends.
if (toneToPlay != InCallTonePlayer.TONE_NONE) {
if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
new InCallTonePlayer(toneToPlay).start();
// TODO: alternatively, we could start an InCallTonePlayer
// here with an "unlimited" tone length,
// and manually stop it later when this connection truly goes
// away. (The real connection over the network was closed as soon
// as we got the BUSY message. But our telephony layer keeps the
// connection open for a few extra seconds so we can show the
// "busy" indication to the user. We could stop the busy tone
// when *that* connection's "disconnect" event comes in.)
}
if (mPhone.getState() == Phone.State.IDLE) {
// Release screen wake locks if the in-call screen is not
// showing. Otherwise, let the in-call screen handle this because
// it needs to show the call ended screen for a couple of
// seconds.
if (!mApplication.isShowingCallScreen()) {
if (VDBG) log("- NOT showing in-call screen; releasing wake locks!");
mApplication.setScreenTimeout(PhoneApp.ScreenTimeoutDuration.DEFAULT);
mApplication.requestWakeState(PhoneApp.WakeState.SLEEP);
} else {
if (VDBG) log("- still showing in-call screen; not releasing wake locks.");
}
} else {
if (VDBG) log("- phone still in use; not releasing wake locks.");
}
if (((mPreviousCdmaCallState == Call.State.DIALING)
|| (mPreviousCdmaCallState == Call.State.ALERTING))
&& (!PhoneNumberUtils.isEmergencyNumber(number))
&& (cause != Connection.DisconnectCause.INCOMING_MISSED )
&& (cause != Connection.DisconnectCause.NORMAL)
&& (cause != Connection.DisconnectCause.LOCAL)
&& (cause != Connection.DisconnectCause.INCOMING_REJECTED)) {
if (!mIsCdmaRedialCall) {
if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
// TODO: (Moto): The contact reference data may need to be stored and use
// here when redialing a call. For now, pass in NULL as the URI parameter.
PhoneUtils.placeCall(mPhone, number, null);
mIsCdmaRedialCall = true;
} else {
mIsCdmaRedialCall = false;
}
} else {
mIsCdmaRedialCall = false;
}
}
}
if (mPhone.getPhoneName().equals("CDMA")) {
// Resetting the CdmaPhoneCallState members
mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
// Remove Call waiting timers
removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
}
}
/**
* Resets the audio mode and speaker state when a call ends.
*/
private void resetAudioStateAfterDisconnect() {
if (VDBG) log("resetAudioStateAfterDisconnect()...");
if (mBluetoothHandsfree != null) {
mBluetoothHandsfree.audioOff();
}
if (PhoneUtils.isSpeakerOn(mPhone.getContext())) {
PhoneUtils.turnOnSpeaker(mPhone.getContext(), false);
}
PhoneUtils.setAudioMode(mPhone.getContext(), AudioManager.MODE_NORMAL);
}
private void onMwiChanged(boolean visible) {
if (VDBG) log("onMwiChanged(): " + visible);
NotificationMgr.getDefault().updateMwi(visible);
}
/**
* Posts a delayed PHONE_MWI_CHANGED event, to schedule a "retry" for a
* failed NotificationMgr.updateMwi() call.
*/
/* package */ void sendMwiChangedDelayed(long delayMillis) {
Message message = Message.obtain(this, PHONE_MWI_CHANGED);
sendMessageDelayed(message, delayMillis);
}
private void onCfiChanged(boolean visible) {
if (VDBG) log("onCfiChanged(): " + visible);
NotificationMgr.getDefault().updateCfi(visible);
}
/**
* Indicates whether or not this ringer is ringing.
*/
boolean isRinging() {
return mRinger.isRinging();
}
/**
* Stops the current ring, and tells the notifier that future
* ring requests should be ignored.
*/
void silenceRinger() {
mSilentRingerRequested = true;
if (DBG) log("stopRing()... (silenceRinger)");
mRinger.stopRing();
}
/**
* Posts a PHONE_BATTERY_LOW event, causing us to play a warning
* tone if the user is in-call.
*/
/* package */ void sendBatteryLow() {
Message message = Message.obtain(this, PHONE_BATTERY_LOW);
sendMessage(message);
}
private void onBatteryLow() {
if (DBG) log("onBatteryLow()...");
// Play the "low battery" warning tone, only if the user is
// in-call. (The test here is exactly the opposite of the test in
// StatusBarPolicy.updateBattery(), where we bring up the "low
// battery warning" dialog only if the user is NOT in-call.)
if (mPhone.getState() != Phone.State.IDLE) {
new InCallTonePlayer(InCallTonePlayer.TONE_BATTERY_LOW).start();
}
}
/**
* Helper class to play tones through the earpiece (or speaker / BT)
* during a call, using the ToneGenerator.
*
* To use, just instantiate a new InCallTonePlayer
* (passing in the TONE_* constant for the tone you want)
* and start() it.
*
* When we're done playing the tone, if the phone is idle at that
* point, we'll reset the audio routing and speaker state.
* (That means that for tones that get played *after* a call
* disconnects, like "busy" or "congestion" or "call ended", you
* should NOT call resetAudioStateAfterDisconnect() yourself.
* Instead, just start the InCallTonePlayer, which will automatically
* defer the resetAudioStateAfterDisconnect() call until the tone
* finishes playing.)
*/
private class InCallTonePlayer extends Thread {
private int mToneId;
// The possible tones we can play.
public static final int TONE_NONE = 0;
public static final int TONE_CALL_WAITING = 1;
public static final int TONE_BUSY = 2;
public static final int TONE_CONGESTION = 3;
public static final int TONE_BATTERY_LOW = 4;
public static final int TONE_CALL_ENDED = 5;
public static final int TONE_VOICE_PRIVACY = 6;
public static final int TONE_REORDER = 7;
public static final int TONE_INTERCEPT = 8;
public static final int TONE_CDMA_DROP = 9;
public static final int TONE_OUT_OF_SERVICE = 10;
public static final int TONE_REDIAL = 11;
public static final int TONE_OTA_CALL_END = 12;
// The tone volume relative to other sounds in the stream
private static final int TONE_RELATIVE_VOLUME_HIPRI = 80;
private static final int TONE_RELATIVE_VOLUME_LOPRI = 50;
InCallTonePlayer(int toneId) {
super();
mToneId = toneId;
}
@Override
public void run() {
if (VDBG) log("InCallTonePlayer.run(toneId = " + mToneId + ")...");
int toneType = 0; // passed to ToneGenerator.startTone()
int toneVolume; // passed to the ToneGenerator constructor
int toneLengthMillis;
AudioManager audioManager = (AudioManager) mPhone.getContext()
.getSystemService(Context.AUDIO_SERVICE);
switch (mToneId) {
case TONE_CALL_WAITING:
toneType = ToneGenerator.TONE_SUP_CALL_WAITING;
toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
toneLengthMillis = 5000;
break;
case TONE_BUSY:
if (mPhone.getPhoneName().equals("CDMA")) {
toneType = ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT;
toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
toneLengthMillis = 5000;
} else {
toneType = ToneGenerator.TONE_SUP_BUSY;
toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
toneLengthMillis = 4000;
}
break;
case TONE_CONGESTION:
toneType = ToneGenerator.TONE_SUP_CONGESTION;
toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
toneLengthMillis = 4000;
break;
case TONE_BATTERY_LOW:
// For now, use ToneGenerator.TONE_PROP_ACK (two quick
// beeps). TODO: is there some other ToneGenerator
// tone that would be more appropriate here? Or
// should we consider adding a new custom tone?
toneType = ToneGenerator.TONE_PROP_ACK;
toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
toneLengthMillis = 1000;
break;
case TONE_CALL_ENDED:
toneType = ToneGenerator.TONE_PROP_PROMPT;
toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
toneLengthMillis = 2000;
break;
case TONE_OTA_CALL_END:
if (mApplication.cdmaOtaConfigData.otaPlaySuccessFailureTone ==
OtaUtils.OTA_PLAY_SUCCESS_FAILURE_TONE_ON) {
toneType = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD;
toneVolume = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
toneLengthMillis = 5000;
} else {
toneType = ToneGenerator.TONE_PROP_PROMPT;
toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
toneLengthMillis = 2000;
}
break;
case TONE_VOICE_PRIVACY:
toneType = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE;
toneVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
toneLengthMillis = 5000;
break;
case TONE_REORDER:
toneType = ToneGenerator.TONE_CDMA_ABBR_REORDER;
toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
toneLengthMillis = 5000;
break;
case TONE_INTERCEPT:
toneType = ToneGenerator.TONE_CDMA_ABBR_INTERCEPT;
toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
toneLengthMillis = 5000;
break;
case TONE_CDMA_DROP:
case TONE_OUT_OF_SERVICE:
toneType = ToneGenerator.TONE_CDMA_CALLDROP_LITE;
toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
toneLengthMillis = 5000;
break;
case TONE_REDIAL:
toneType = ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE;
toneVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
toneLengthMillis = 5000;
break;
default:
throw new IllegalArgumentException("Bad toneId: " + mToneId);
}
// If the mToneGenerator creation fails, just continue without it. It is
// a local audio signal, and is not as important.
ToneGenerator toneGenerator;
try {
int stream;
if (mBluetoothHandsfree != null) {
stream = mBluetoothHandsfree.isAudioOn() ? AudioManager.STREAM_BLUETOOTH_SCO:
AudioManager.STREAM_VOICE_CALL;
} else {
stream = AudioManager.STREAM_VOICE_CALL;
}
toneGenerator = new ToneGenerator(stream, toneVolume);
// if (DBG) log("- created toneGenerator: " + toneGenerator);
} catch (RuntimeException e) {
Log.w(LOG_TAG,
"InCallTonePlayer: Exception caught while creating ToneGenerator: " + e);
toneGenerator = null;
}
// Using the ToneGenerator (with the CALL_WAITING / BUSY /
// CONGESTION tones at least), the ToneGenerator itself knows
// the right pattern of tones to play; we do NOT need to
// manually start/stop each individual tone, or manually
// insert the correct delay between tones. (We just start it
// and let it run for however long we want the tone pattern to
// continue.)
//
// TODO: When we stop the ToneGenerator in the middle of a
// "tone pattern", it sounds bad if we cut if off while the
// tone is actually playing. Consider adding API to the
// ToneGenerator to say "stop at the next silent part of the
// pattern", or simply "play the pattern N times and then
// stop."
boolean needToStopTone = true;
boolean okToPlayTone = false;
if (toneGenerator != null) {
if (mPhone.getPhoneName().equals("CDMA")) {
if (toneType == ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD) {
if ((audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) &&
(audioManager.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE)) {
if (DBG) log("- InCallTonePlayer: start playing call tone=" + toneType);
okToPlayTone = true;
needToStopTone = false;
}
} else if ((toneType == ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT) ||
(toneType == ToneGenerator.TONE_CDMA_ABBR_REORDER) ||
(toneType == ToneGenerator.TONE_CDMA_ABBR_INTERCEPT) ||
(toneType == ToneGenerator.TONE_CDMA_CALLDROP_LITE)) {
if (audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
if (DBG) log("InCallTonePlayer:playing call fail tone:" + toneType);
okToPlayTone = true;
needToStopTone = false;
}
} else if ((toneType == ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE) ||
(toneType == ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE)) {
if ((audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) &&
(audioManager.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE)) {
if (DBG) log("InCallTonePlayer:playing tone for toneType=" + toneType);
okToPlayTone = true;
needToStopTone = false;
}
}
} else {
okToPlayTone = true;
}
if (okToPlayTone) {
toneGenerator.startTone(toneType);
SystemClock.sleep(toneLengthMillis);
if (needToStopTone) {
toneGenerator.stopTone();
}
}
// if (DBG) log("- InCallTonePlayer: done playing.");
toneGenerator.release();
}
// Finally, do the same cleanup we otherwise would have done
// in onDisconnect().
//
// (But watch out: do NOT do this if the phone is in use,
// since some of our tones get played *during* a call (like
// CALL_WAITING and BATTERY_LOW) and we definitely *don't*
// want to reset the audio mode / speaker / bluetooth after
// playing those!
// This call is really here for use with tones that get played
// *after* a call disconnects, like "busy" or "congestion" or
// "call ended", where the phone has already become idle but
// we need to defer the resetAudioStateAfterDisconnect() call
// till the tone finishes playing.)
if (mPhone.getState() == Phone.State.IDLE) {
resetAudioStateAfterDisconnect();
}
}
}
/**
* Displays a notification when the phone receives a DisplayInfo record.
*/
private void onDisplayInfo(AsyncResult r) {
// Extract the DisplayInfo String from the message
CdmaDisplayInfoRec displayInfoRec = (CdmaDisplayInfoRec)(r.result);
if (displayInfoRec != null) {
String displayInfo = displayInfoRec.alpha;
if (DBG) log("onDisplayInfo: displayInfo=" + displayInfo);
CdmaDisplayInfo.displayInfoRecord(mApplication, displayInfo);
// start a 2 second timer
sendEmptyMessageDelayed(DISPLAYINFO_NOTIFICATION_DONE,
DISPLAYINFO_NOTIFICATION_TIME);
}
}
/**
* Helper class to play SignalInfo tones using the ToneGenerator.
*
* To use, just instantiate a new SignalInfoTonePlayer
* (passing in the ToneID constant for the tone you want)
* and start() it.
*/
private class SignalInfoTonePlayer extends Thread {
private int mToneId;
SignalInfoTonePlayer(int toneId) {
super();
mToneId = toneId;
}
@Override
public void run() {
if (DBG) log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")...");
if (mSignalInfoToneGenerator != null) {
//First stop any ongoing SignalInfo tone
mSignalInfoToneGenerator.stopTone();
//Start playing the new tone if its a valid tone
mSignalInfoToneGenerator.startTone(mToneId);
}
}
}
/**
* Plays a tone when the phone receives a SignalInfo record.
*/
private void onSignalInfo(AsyncResult r) {
if (mPhone.getRingingCall().getState() == Call.State.INCOMING) {
// Do not start any new SignalInfo tone when Call state is INCOMING
// and stop any previous SignalInfo tone which is being played
stopSignalInfoTone();
} else {
// Extract the SignalInfo String from the message
CdmaSignalInfoRec signalInfoRec = (CdmaSignalInfoRec)(r.result);
// Only proceed if a Signal info is present.
if (signalInfoRec != null) {
boolean isPresent = signalInfoRec.isPresent;
if (DBG) log("onSignalInfo: isPresent=" + isPresent);
if (isPresent) {// if tone is valid
int uSignalType = signalInfoRec.signalType;
int uAlertPitch = signalInfoRec.alertPitch;
int uSignal = signalInfoRec.signal;
if (DBG) log("onSignalInfo: uSignalType=" + uSignalType + ", uAlertPitch=" +
uAlertPitch + ", uSignal=" + uSignal);
//Map the Signal to a ToneGenerator ToneID only if Signal info is present
int toneID = SignalToneUtil.getAudioToneFromSignalInfo
(uSignalType, uAlertPitch, uSignal);
//Create the SignalInfo tone player and pass the ToneID
new SignalInfoTonePlayer(toneID).start();
}
}
}
}
/**
* Stops a SignalInfo tone in the following condition
* 1 - On receiving a New Ringing Call
* 2 - On disconnecting a call
* 3 - On answering a Call Waiting Call
*/
/* package */ void stopSignalInfoTone() {
if (DBG) log("stopSignalInfoTone: Stopping SignalInfo tone player");
new SignalInfoTonePlayer(ToneGenerator.TONE_CDMA_SIGNAL_OFF).start();
}
/**
* Plays a Call waiting tone if it is present in the second incoming call.
*/
private void onCdmaCallWaiting(AsyncResult r) {
// Start the InCallScreen Activity if its not on foreground
if (!mApplication.isShowingCallScreen()) {
PhoneUtils.showIncomingCallUi();
}
// Start timer for CW display
mCallWaitingTimeOut = false;
sendEmptyMessageDelayed(CALLWAITING_CALLERINFO_DISPLAY_DONE,
CALLWAITING_CALLERINFO_DISPLAY_TIME);
// Set the mAddCallMenuStateAfterCW state to false
mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(false);
// Start the timer for disabling "Add Call" menu option
sendEmptyMessageDelayed(CALLWAITING_ADDCALL_DISABLE_TIMEOUT,
CALLWAITING_ADDCALL_DISABLE_TIME);
// Extract the Call waiting information
CdmaCallWaitingNotification infoCW = (CdmaCallWaitingNotification) r.result;
int isPresent = infoCW.isPresent;
if (DBG) log("onCdmaCallWaiting: isPresent=" + isPresent);
if (isPresent == 1 ) {//'1' if tone is valid
int uSignalType = infoCW.signalType;
int uAlertPitch = infoCW.alertPitch;
int uSignal = infoCW.signal;
if (DBG) log("onCdmaCallWaiting: uSignalType=" + uSignalType + ", uAlertPitch="
+ uAlertPitch + ", uSignal=" + uSignal);
//Map the Signal to a ToneGenerator ToneID only if Signal info is present
int toneID =
SignalToneUtil.getAudioToneFromSignalInfo(uSignalType, uAlertPitch, uSignal);
//Create the SignalInfo tone player and pass the ToneID
new SignalInfoTonePlayer(toneID).start();
}
}
/**
* Performs Call logging based on Timeout or Ignore Call Waiting Call for CDMA,
* and finally calls Hangup on the Call Waiting connection.
*/
/* package */ void onCdmaCallWaitingReject() {
final Call ringingCall = mPhone.getRingingCall();
// Call waiting timeout scenario
if (ringingCall.getState() == Call.State.WAITING) {
// Code for perform Call logging and missed call notification
Connection c = ringingCall.getLatestConnection();
if (c != null) {
final String number = c.getAddress();
final int presentation = c.getNumberPresentation();
final long date = c.getCreateTime();
final long duration = c.getDurationMillis();
final int callLogType = mCallWaitingTimeOut ?
CallLog.Calls.MISSED_TYPE : CallLog.Calls.INCOMING_TYPE;
// get the callerinfo object and then log the call with it.
Object o = c.getUserData();
final CallerInfo ci;
if ((o == null) || (o instanceof CallerInfo)) {
ci = (CallerInfo) o;
} else {
ci = ((PhoneUtils.CallerInfoToken) o).currentInfo;
}
// Watch out: Calls.addCall() hits the Contacts database,
// so we shouldn't call it from the main thread.
Thread t = new Thread() {
public void run() {
Calls.addCall(ci, mApplication, number, presentation,
callLogType, date, (int) duration / 1000);
if (DBG) log("onCdmaCallWaitingReject helper thread: Calls.addCall() done.");
}
};
t.start();
if (callLogType == CallLog.Calls.MISSED_TYPE) {
// Add missed call notification
showMissedCallNotification(c, date);
}
// Set the Phone Call State to SINGLE_ACTIVE as there is only one connection
mApplication.cdmaPhoneCallState.setCurrentCallState(
CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
// Hangup the RingingCall connection for CW
PhoneUtils.hangup(c);
}
//Reset the mCallWaitingTimeOut boolean
mCallWaitingTimeOut = false;
}
}
/**
* Return the private variable mPreviousCdmaCallState.
*/
/* package */ Call.State getPreviousCdmaCallState() {
return mPreviousCdmaCallState;
}
/**
* Return the private variable mCdmaVoicePrivacyState.
*/
/* package */ boolean getCdmaVoicePrivacyState() {
return mCdmaVoicePrivacyState;
}
/**
* Return the private variable mIsCdmaRedialCall.
*/
/* package */ boolean getIsCdmaRedialCall() {
return mIsCdmaRedialCall;
}
/**
* Helper function used to show a missed call notification.
*/
private void showMissedCallNotification(Connection c, final long date) {
PhoneUtils.CallerInfoToken info =
PhoneUtils.startGetCallerInfo(mApplication, c, this, Long.valueOf(date));
if (info != null) {
// at this point, we've requested to start a query, but it makes no
// sense to log this missed call until the query comes back.
if (VDBG) log("showMissedCallNotification: Querying for CallerInfo on missed call...");
if (info.isFinal) {
// it seems that the query we have actually is up to date.
// send the notification then.
CallerInfo ci = info.currentInfo;
NotificationMgr.getDefault().notifyMissedCall(ci.name, ci.phoneNumber,
ci.phoneLabel, date);
}
} else {
// getCallerInfo() can return null in rare cases, like if we weren't
// able to get a valid phone number out of the specified Connection.
Log.w(LOG_TAG, "showMissedCallNotification: got null CallerInfo for Connection " + c);
}
}
/**
* Inner class to handle emergency call tone and vibrator
*/
private class EmergencyTonePlayerVibrator {
private final int EMG_VIBRATE_LENGTH = 1000; // ms.
private final int EMG_VIBRATE_PAUSE = 1000; // ms.
private final long[] mVibratePattern =
new long[] { EMG_VIBRATE_LENGTH, EMG_VIBRATE_PAUSE };
private ToneGenerator mToneGenerator;
private AudioManager mAudioManager;
private Vibrator mEmgVibrator;
/**
* constructor
*/
public EmergencyTonePlayerVibrator() {
Context context = mApplication.getApplicationContext();
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
/**
* Start the emergency tone or vibrator.
*/
private void start() {
if (VDBG) log("call startEmergencyToneOrVibrate.");
int ringerMode = mAudioManager.getRingerMode();
if ((mIsEmergencyToneOn == EMERGENCY_TONE_ALERT) &&
(ringerMode == AudioManager.RINGER_MODE_NORMAL)) {
if (VDBG) log("Play Emergency Tone.");
mToneGenerator = new ToneGenerator (AudioManager.STREAM_VOICE_CALL,
mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL));
if (mToneGenerator != null) {
mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK);
mCurrentEmergencyToneState = EMERGENCY_TONE_ALERT;
}
} else if (mIsEmergencyToneOn == EMERGENCY_TONE_VIBRATE) {
if (VDBG) log("Play Emergency Vibrate.");
mEmgVibrator = new Vibrator();
if (mEmgVibrator != null) {
mEmgVibrator.vibrate(mVibratePattern, 0);
mCurrentEmergencyToneState = EMERGENCY_TONE_VIBRATE;
}
}
}
/**
* If the emergency tone is active, stop the tone or vibrator accordingly.
*/
private void stop() {
if (VDBG) log("call stopEmergencyToneOrVibrate.");
if ((mCurrentEmergencyToneState == EMERGENCY_TONE_ALERT)
&& (mToneGenerator != null)) {
mToneGenerator.stopTone();
mToneGenerator.release();
} else if ((mCurrentEmergencyToneState == EMERGENCY_TONE_VIBRATE)
&& (mEmgVibrator != null)) {
mEmgVibrator.cancel();
}
mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
}
}
private void log(String msg) {
Log.d(LOG_TAG, msg);
}
}
| true | true | private void onDisconnect(AsyncResult r) {
if (VDBG) log("onDisconnect()... phone state: " + mPhone.getState());
mCdmaVoicePrivacyState = false;
int autoretrySetting = 0;
if (mPhone.getPhoneName().equals("CDMA")) {
autoretrySetting = android.provider.Settings.System.getInt(mPhone.getContext().
getContentResolver(),android.provider.Settings.System.CALL_AUTO_RETRY, 0);
}
if (mPhone.getState() == Phone.State.IDLE) {
PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_IDLE);
}
if (mPhone.getPhoneName().equals("CDMA")) {
// Stop any signalInfo tone being played when a call gets ended
stopSignalInfoTone();
}
Connection c = (Connection) r.result;
if (DBG && c != null) {
log("- onDisconnect: cause = " + c.getDisconnectCause()
+ ", incoming = " + c.isIncoming()
+ ", date = " + c.getCreateTime());
}
// Stop the ringer if it was ringing (for an incoming call that
// either disconnected by itself, or was rejected by the user.)
//
// TODO: We technically *shouldn't* stop the ringer if the
// foreground or background call disconnects while an incoming call
// is still ringing, but that's a really rare corner case.
// It's safest to just unconditionally stop the ringer here.
if (DBG) log("stopRing()... (onDisconnect)");
mRinger.stopRing();
// Check for the various tones we might need to play (thru the
// earpiece) after a call disconnects.
int toneToPlay = InCallTonePlayer.TONE_NONE;
// The "Busy" or "Congestion" tone is the highest priority:
if (c != null) {
Connection.DisconnectCause cause = c.getDisconnectCause();
if (cause == Connection.DisconnectCause.BUSY) {
if (DBG) log("- need to play BUSY tone!");
toneToPlay = InCallTonePlayer.TONE_BUSY;
} else if (cause == Connection.DisconnectCause.CONGESTION) {
if (DBG) log("- need to play CONGESTION tone!");
toneToPlay = InCallTonePlayer.TONE_CONGESTION;
} else if (((cause == Connection.DisconnectCause.NORMAL)
|| (cause == Connection.DisconnectCause.LOCAL))
&& (mApplication.isOtaCallInActiveState())) {
if (DBG) log("- need to play OTA_CALL_END tone!");
toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
} else if (cause == Connection.DisconnectCause.CDMA_REORDER) {
if (DBG) log("- need to play CDMA_REORDER tone!");
toneToPlay = InCallTonePlayer.TONE_REORDER;
} else if (cause == Connection.DisconnectCause.CDMA_INTERCEPT) {
if (DBG) log("- need to play CDMA_INTERCEPT tone!");
toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
} else if (cause == Connection.DisconnectCause.CDMA_DROP) {
if (DBG) log("- need to play CDMA_DROP tone!");
toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
} else if (cause == Connection.DisconnectCause.OUT_OF_SERVICE) {
if (DBG) log("- need to play OUT OF SERVICE tone!");
toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
}
}
// If we don't need to play BUSY or CONGESTION, then play the
// "call ended" tone if this was a "regular disconnect" (i.e. a
// normal call where one end or the other hung up) *and* this
// disconnect event caused the phone to become idle. (In other
// words, we *don't* play the sound if one call hangs up but
// there's still an active call on the other line.)
// TODO: We may eventually want to disable this via a preference.
if ((toneToPlay == InCallTonePlayer.TONE_NONE)
&& (mPhone.getState() == Phone.State.IDLE)
&& (c != null)) {
Connection.DisconnectCause cause = c.getDisconnectCause();
if ((cause == Connection.DisconnectCause.NORMAL) // remote hangup
|| (cause == Connection.DisconnectCause.LOCAL)) { // local hangup
if (VDBG) log("- need to play CALL_ENDED tone!");
toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
mIsCdmaRedialCall = false;
}
}
if (mPhone.getState() == Phone.State.IDLE) {
// Don't reset the audio mode or bluetooth/speakerphone state
// if we still need to let the user hear a tone through the earpiece.
if (toneToPlay == InCallTonePlayer.TONE_NONE) {
resetAudioStateAfterDisconnect();
}
NotificationMgr.getDefault().cancelCallInProgressNotification();
// If the InCallScreen is *not* in the foreground, forcibly
// dismiss it to make sure it won't still be in the activity
// history. (But if it *is* in the foreground, don't mess
// with it; it needs to be visible, displaying the "Call
// ended" state.)
if (!mApplication.isShowingCallScreen()) {
if (VDBG) log("onDisconnect: force InCallScreen to finish()");
mApplication.dismissCallScreen();
}
}
if (c != null) {
final String number = c.getAddress();
final int presentation = c.getNumberPresentation();
if (DBG) log("- onDisconnect: presentation=" + presentation);
final long date = c.getCreateTime();
final long duration = c.getDurationMillis();
final Connection.DisconnectCause cause = c.getDisconnectCause();
// For international calls, 011 needs to be logged as +
final String cdmaLogNumber = c.isIncoming()? number : c.getOrigDialString();
// Set the "type" to be displayed in the call log (see constants in CallLog.Calls)
final int callLogType;
if (c.isIncoming()) {
callLogType = (cause == Connection.DisconnectCause.INCOMING_MISSED ?
CallLog.Calls.MISSED_TYPE :
CallLog.Calls.INCOMING_TYPE);
} else {
callLogType = CallLog.Calls.OUTGOING_TYPE;
}
if (VDBG) log("- callLogType: " + callLogType + ", UserData: " + c.getUserData());
// Get the CallerInfo object and then log the call with it.
{
Object o = c.getUserData();
final CallerInfo ci;
if ((o == null) || (o instanceof CallerInfo)) {
ci = (CallerInfo) o;
} else {
ci = ((PhoneUtils.CallerInfoToken) o).currentInfo;
}
final String eNumber = c.getAddress();
if (mPhone.getPhoneName().equals("CDMA")) {
if ((PhoneNumberUtils.isEmergencyNumber(eNumber))
&& (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
if (mEmergencyTonePlayerVibrator != null) {
mEmergencyTonePlayerVibrator.stop();
}
}
}
// Watch out: Calls.addCall() hits the Contacts database,
// so we shouldn't call it from the main thread.
Thread t = new Thread() {
public void run() {
if (mPhone.getPhoneName().equals("CDMA")) {
// Don't put OTA or Emergency calls into call log
if (!mApplication.isOtaCallInActiveState()
&& !PhoneNumberUtils.isEmergencyNumber(eNumber)) {
Calls.addCall(ci, mApplication, number, presentation,
callLogType, date, (int) duration / 1000);
}
} else {
Calls.addCall(ci, mApplication, number, presentation,
callLogType, date, (int) duration / 1000);
// if (DBG) log("onDisconnect helper thread: Calls.addCall() done.");
}
}
};
t.start();
}
if (callLogType == CallLog.Calls.MISSED_TYPE) {
// Show the "Missed call" notification.
// (Note we *don't* do this if this was an incoming call that
// the user deliberately rejected.)
showMissedCallNotification(c, date);
}
// Possibly play a "post-disconnect tone" thru the earpiece.
// We do this here, rather than from the InCallScreen
// activity, since we need to do this even if you're not in
// the Phone UI at the moment the connection ends.
if (toneToPlay != InCallTonePlayer.TONE_NONE) {
if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
new InCallTonePlayer(toneToPlay).start();
// TODO: alternatively, we could start an InCallTonePlayer
// here with an "unlimited" tone length,
// and manually stop it later when this connection truly goes
// away. (The real connection over the network was closed as soon
// as we got the BUSY message. But our telephony layer keeps the
// connection open for a few extra seconds so we can show the
// "busy" indication to the user. We could stop the busy tone
// when *that* connection's "disconnect" event comes in.)
}
if (mPhone.getState() == Phone.State.IDLE) {
// Release screen wake locks if the in-call screen is not
// showing. Otherwise, let the in-call screen handle this because
// it needs to show the call ended screen for a couple of
// seconds.
if (!mApplication.isShowingCallScreen()) {
if (VDBG) log("- NOT showing in-call screen; releasing wake locks!");
mApplication.setScreenTimeout(PhoneApp.ScreenTimeoutDuration.DEFAULT);
mApplication.requestWakeState(PhoneApp.WakeState.SLEEP);
} else {
if (VDBG) log("- still showing in-call screen; not releasing wake locks.");
}
} else {
if (VDBG) log("- phone still in use; not releasing wake locks.");
}
if (((mPreviousCdmaCallState == Call.State.DIALING)
|| (mPreviousCdmaCallState == Call.State.ALERTING))
&& (!PhoneNumberUtils.isEmergencyNumber(number))
&& (cause != Connection.DisconnectCause.INCOMING_MISSED )
&& (cause != Connection.DisconnectCause.NORMAL)
&& (cause != Connection.DisconnectCause.LOCAL)
&& (cause != Connection.DisconnectCause.INCOMING_REJECTED)) {
if (!mIsCdmaRedialCall) {
if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
// TODO: (Moto): The contact reference data may need to be stored and use
// here when redialing a call. For now, pass in NULL as the URI parameter.
PhoneUtils.placeCall(mPhone, number, null);
mIsCdmaRedialCall = true;
} else {
mIsCdmaRedialCall = false;
}
} else {
mIsCdmaRedialCall = false;
}
}
}
if (mPhone.getPhoneName().equals("CDMA")) {
// Resetting the CdmaPhoneCallState members
mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
// Remove Call waiting timers
removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
}
}
| private void onDisconnect(AsyncResult r) {
if (VDBG) log("onDisconnect()... phone state: " + mPhone.getState());
mCdmaVoicePrivacyState = false;
int autoretrySetting = 0;
if (mPhone.getPhoneName().equals("CDMA")) {
autoretrySetting = android.provider.Settings.System.getInt(mPhone.getContext().
getContentResolver(),android.provider.Settings.System.CALL_AUTO_RETRY, 0);
}
if (mPhone.getState() == Phone.State.IDLE) {
PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_IDLE);
}
if (mPhone.getPhoneName().equals("CDMA")) {
// Stop any signalInfo tone being played when a call gets ended
stopSignalInfoTone();
}
Connection c = (Connection) r.result;
if (DBG && c != null) {
log("- onDisconnect: cause = " + c.getDisconnectCause()
+ ", incoming = " + c.isIncoming()
+ ", date = " + c.getCreateTime());
}
// Stop the ringer if it was ringing (for an incoming call that
// either disconnected by itself, or was rejected by the user.)
//
// TODO: We technically *shouldn't* stop the ringer if the
// foreground or background call disconnects while an incoming call
// is still ringing, but that's a really rare corner case.
// It's safest to just unconditionally stop the ringer here.
if (DBG) log("stopRing()... (onDisconnect)");
mRinger.stopRing();
// Check for the various tones we might need to play (thru the
// earpiece) after a call disconnects.
int toneToPlay = InCallTonePlayer.TONE_NONE;
// The "Busy" or "Congestion" tone is the highest priority:
if (c != null) {
Connection.DisconnectCause cause = c.getDisconnectCause();
if (cause == Connection.DisconnectCause.BUSY) {
if (DBG) log("- need to play BUSY tone!");
toneToPlay = InCallTonePlayer.TONE_BUSY;
} else if (cause == Connection.DisconnectCause.CONGESTION) {
if (DBG) log("- need to play CONGESTION tone!");
toneToPlay = InCallTonePlayer.TONE_CONGESTION;
} else if (((cause == Connection.DisconnectCause.NORMAL)
|| (cause == Connection.DisconnectCause.LOCAL))
&& (mApplication.isOtaCallInActiveState())) {
if (DBG) log("- need to play OTA_CALL_END tone!");
toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
} else if (cause == Connection.DisconnectCause.CDMA_REORDER) {
if (DBG) log("- need to play CDMA_REORDER tone!");
toneToPlay = InCallTonePlayer.TONE_REORDER;
} else if (cause == Connection.DisconnectCause.CDMA_INTERCEPT) {
if (DBG) log("- need to play CDMA_INTERCEPT tone!");
toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
} else if (cause == Connection.DisconnectCause.CDMA_DROP) {
if (DBG) log("- need to play CDMA_DROP tone!");
toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
} else if (cause == Connection.DisconnectCause.OUT_OF_SERVICE) {
if (DBG) log("- need to play OUT OF SERVICE tone!");
toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
} else if (cause == Connection.DisconnectCause.ERROR_UNSPECIFIED) {
if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!");
toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
}
}
// If we don't need to play BUSY or CONGESTION, then play the
// "call ended" tone if this was a "regular disconnect" (i.e. a
// normal call where one end or the other hung up) *and* this
// disconnect event caused the phone to become idle. (In other
// words, we *don't* play the sound if one call hangs up but
// there's still an active call on the other line.)
// TODO: We may eventually want to disable this via a preference.
if ((toneToPlay == InCallTonePlayer.TONE_NONE)
&& (mPhone.getState() == Phone.State.IDLE)
&& (c != null)) {
Connection.DisconnectCause cause = c.getDisconnectCause();
if ((cause == Connection.DisconnectCause.NORMAL) // remote hangup
|| (cause == Connection.DisconnectCause.LOCAL)) { // local hangup
if (VDBG) log("- need to play CALL_ENDED tone!");
toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
mIsCdmaRedialCall = false;
}
}
if (mPhone.getState() == Phone.State.IDLE) {
// Don't reset the audio mode or bluetooth/speakerphone state
// if we still need to let the user hear a tone through the earpiece.
if (toneToPlay == InCallTonePlayer.TONE_NONE) {
resetAudioStateAfterDisconnect();
}
NotificationMgr.getDefault().cancelCallInProgressNotification();
// If the InCallScreen is *not* in the foreground, forcibly
// dismiss it to make sure it won't still be in the activity
// history. (But if it *is* in the foreground, don't mess
// with it; it needs to be visible, displaying the "Call
// ended" state.)
if (!mApplication.isShowingCallScreen()) {
if (VDBG) log("onDisconnect: force InCallScreen to finish()");
mApplication.dismissCallScreen();
}
}
if (c != null) {
final String number = c.getAddress();
final int presentation = c.getNumberPresentation();
if (DBG) log("- onDisconnect: presentation=" + presentation);
final long date = c.getCreateTime();
final long duration = c.getDurationMillis();
final Connection.DisconnectCause cause = c.getDisconnectCause();
// For international calls, 011 needs to be logged as +
final String cdmaLogNumber = c.isIncoming()? number : c.getOrigDialString();
// Set the "type" to be displayed in the call log (see constants in CallLog.Calls)
final int callLogType;
if (c.isIncoming()) {
callLogType = (cause == Connection.DisconnectCause.INCOMING_MISSED ?
CallLog.Calls.MISSED_TYPE :
CallLog.Calls.INCOMING_TYPE);
} else {
callLogType = CallLog.Calls.OUTGOING_TYPE;
}
if (VDBG) log("- callLogType: " + callLogType + ", UserData: " + c.getUserData());
// Get the CallerInfo object and then log the call with it.
{
Object o = c.getUserData();
final CallerInfo ci;
if ((o == null) || (o instanceof CallerInfo)) {
ci = (CallerInfo) o;
} else {
ci = ((PhoneUtils.CallerInfoToken) o).currentInfo;
}
final String eNumber = c.getAddress();
if (mPhone.getPhoneName().equals("CDMA")) {
if ((PhoneNumberUtils.isEmergencyNumber(eNumber))
&& (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
if (mEmergencyTonePlayerVibrator != null) {
mEmergencyTonePlayerVibrator.stop();
}
}
}
// Watch out: Calls.addCall() hits the Contacts database,
// so we shouldn't call it from the main thread.
Thread t = new Thread() {
public void run() {
if (mPhone.getPhoneName().equals("CDMA")) {
// Don't put OTA or Emergency calls into call log
if (!mApplication.isOtaCallInActiveState()
&& !PhoneNumberUtils.isEmergencyNumber(eNumber)) {
Calls.addCall(ci, mApplication, number, presentation,
callLogType, date, (int) duration / 1000);
}
} else {
Calls.addCall(ci, mApplication, number, presentation,
callLogType, date, (int) duration / 1000);
// if (DBG) log("onDisconnect helper thread: Calls.addCall() done.");
}
}
};
t.start();
}
if (callLogType == CallLog.Calls.MISSED_TYPE) {
// Show the "Missed call" notification.
// (Note we *don't* do this if this was an incoming call that
// the user deliberately rejected.)
showMissedCallNotification(c, date);
}
// Possibly play a "post-disconnect tone" thru the earpiece.
// We do this here, rather than from the InCallScreen
// activity, since we need to do this even if you're not in
// the Phone UI at the moment the connection ends.
if (toneToPlay != InCallTonePlayer.TONE_NONE) {
if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
new InCallTonePlayer(toneToPlay).start();
// TODO: alternatively, we could start an InCallTonePlayer
// here with an "unlimited" tone length,
// and manually stop it later when this connection truly goes
// away. (The real connection over the network was closed as soon
// as we got the BUSY message. But our telephony layer keeps the
// connection open for a few extra seconds so we can show the
// "busy" indication to the user. We could stop the busy tone
// when *that* connection's "disconnect" event comes in.)
}
if (mPhone.getState() == Phone.State.IDLE) {
// Release screen wake locks if the in-call screen is not
// showing. Otherwise, let the in-call screen handle this because
// it needs to show the call ended screen for a couple of
// seconds.
if (!mApplication.isShowingCallScreen()) {
if (VDBG) log("- NOT showing in-call screen; releasing wake locks!");
mApplication.setScreenTimeout(PhoneApp.ScreenTimeoutDuration.DEFAULT);
mApplication.requestWakeState(PhoneApp.WakeState.SLEEP);
} else {
if (VDBG) log("- still showing in-call screen; not releasing wake locks.");
}
} else {
if (VDBG) log("- phone still in use; not releasing wake locks.");
}
if (((mPreviousCdmaCallState == Call.State.DIALING)
|| (mPreviousCdmaCallState == Call.State.ALERTING))
&& (!PhoneNumberUtils.isEmergencyNumber(number))
&& (cause != Connection.DisconnectCause.INCOMING_MISSED )
&& (cause != Connection.DisconnectCause.NORMAL)
&& (cause != Connection.DisconnectCause.LOCAL)
&& (cause != Connection.DisconnectCause.INCOMING_REJECTED)) {
if (!mIsCdmaRedialCall) {
if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
// TODO: (Moto): The contact reference data may need to be stored and use
// here when redialing a call. For now, pass in NULL as the URI parameter.
PhoneUtils.placeCall(mPhone, number, null);
mIsCdmaRedialCall = true;
} else {
mIsCdmaRedialCall = false;
}
} else {
mIsCdmaRedialCall = false;
}
}
}
if (mPhone.getPhoneName().equals("CDMA")) {
// Resetting the CdmaPhoneCallState members
mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
// Remove Call waiting timers
removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
}
}
|
diff --git a/chris-geometric-correction/src/main/java/org/esa/beam/chris/operators/GeometryCalculator.java b/chris-geometric-correction/src/main/java/org/esa/beam/chris/operators/GeometryCalculator.java
index 6c3c1bd..9e476b2 100644
--- a/chris-geometric-correction/src/main/java/org/esa/beam/chris/operators/GeometryCalculator.java
+++ b/chris-geometric-correction/src/main/java/org/esa/beam/chris/operators/GeometryCalculator.java
@@ -1,721 +1,721 @@
package org.esa.beam.chris.operators;
import org.esa.beam.chris.util.math.internal.Pow;
import org.esa.beam.framework.datamodel.RationalFunctionModel;
import java.util.Arrays;
import java.util.List;
class GeometryCalculator {
private static final int SLOW_DOWN_FACTOR = 5;
private static final double JD2001 = TimeConverter.julianDate(2001, 0, 1);
// constants used for array indexes, so the code is more readable.
private static final int X = 0;
private static final int Y = 1;
private static final int Z = 2;
// five images for each acquisition
private static final int IMAGE_COUNT = 5;
final AcquisitionInfo acquisitionInfo;
final double[][] lats;
final double[][] lons;
final double[][] vaas;
final double[][] vzas;
final double[][] pitchAngles;
final double[][] rollAngles;
public GeometryCalculator(AcquisitionInfo acquisitionInfo) {
this.acquisitionInfo = acquisitionInfo;
final ModeCharacteristics modeCharacteristics = ModeCharacteristics.get(acquisitionInfo.getMode());
final int rowCount = modeCharacteristics.getRowCount();
final int colCount = modeCharacteristics.getColCount();
lats = new double[rowCount][colCount];
lons = new double[rowCount][colCount];
vaas = new double[rowCount][colCount];
vzas = new double[rowCount][colCount];
pitchAngles = new double[rowCount][colCount];
rollAngles = new double[rowCount][colCount];
}
void calculate(IctDataRecord ictData, List<GpsDataRecord> gpsData, GCP[] gcps, boolean useTargetAltitude) {
//////////////////////////
// Prepare Time Frames
//////////////////////////
// The last element of ict_njd corresponds to the acquisition setup time, that occurs 390s before the start of acquisition.
final ModeCharacteristics modeCharacteristics = ModeCharacteristics.get(acquisitionInfo.getMode());
final double acquisitionSetupTime = ictData.ict1 - (10.0 + 390.0) / TimeConverter.SECONDS_PER_DAY - JD2001;
double[] ict_njd = {
ictData.ict1 - JD2001,
ictData.ict2 - JD2001,
ictData.ict3 - JD2001,
ictData.ict4 - JD2001,
ictData.ict5 - JD2001,
acquisitionSetupTime
};
double[] T_ict = Arrays.copyOfRange(ict_njd, 0, IMAGE_COUNT);
//---- Nos quedamos con todos los elementos de GPS menos el ultimo ----------------
//---- ya q es donde se almacena la AngVel media, y perder un dato --------------
//---- de GPS no es un problema. ------------------------------------------------
// We are left with all elements but the last GPS
// and q is where stores AngVel half, and losing data
// GPS is not a problem.
final int numGPS = gpsData.size() - 2;
double[] gps_njd = new double[numGPS];
for (int i = 0; i < gps_njd.length; i++) {
gps_njd[i] = gpsData.get(i).jd - JD2001;
}
// ---- Critical Times ---------------------------------------------
double[] T_ini = new double[IMAGE_COUNT]; // imaging start time (imaging lasts ~9.5s in every mode)
double[] T_end = new double[IMAGE_COUNT]; // imaging stop time
for (int i = 0; i < T_ini.length; i++) {
T_ini[i] = ict_njd[i] - (modeCharacteristics.getTimePerImage() / 2.0) / TimeConverter.SECONDS_PER_DAY;
T_end[i] = ict_njd[i] + (modeCharacteristics.getTimePerImage() / 2.0) / TimeConverter.SECONDS_PER_DAY;
}
// double T_i = ict_njd[0] - 10 / Conversions.SECONDS_PER_DAY; // "imaging mode" start time
// double T_e = ict_njd[4] + 10 / Conversions.SECONDS_PER_DAY; // "imaging mode" stop time
// Searches the closest values in the telemetry to the Critical Times (just for plotting purposses)
// skipped
//---- determine per-Line Time Frame -----------------------------------
// Time elapsed since imaging start at each image line
double[] T_lin = new double[modeCharacteristics.getRowCount()];
for (int line = 0; line < T_lin.length; line++) {
T_lin[line] = (line * modeCharacteristics.getTotalTimePerLine() + modeCharacteristics.getIntegrationTimePerLine() / 2) / TimeConverter.SECONDS_PER_DAY;
// +TpL/2 is added to set the time at the middle of the integration time, i.e. pixel center
}
double[][] T_img = new double[modeCharacteristics.getRowCount()][IMAGE_COUNT];
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
for (int img = 0; img < IMAGE_COUNT; img++) {
T_img[line][img] = T_ini[img] + T_lin[line];
}
}
double[] T = new double[1 + IMAGE_COUNT * modeCharacteristics.getRowCount()];
T[0] = ict_njd[5];
int Tindex = 1;
for (int img = 0; img < IMAGE_COUNT; img++) {
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
T[Tindex] = T_img[line][img];
Tindex++;
}
}
// Set the indices of T that correspond to critical times (integration start and stop) for each image
// The first element of T corresponds to the acquisition-setup time, so Tini[0] must skip element 0 of T
int[] Tini = new int[IMAGE_COUNT];
int[] Tend = new int[IMAGE_COUNT];
for (int img = 0; img < IMAGE_COUNT; img++) {
Tini[img] = modeCharacteristics.getRowCount() * img + 1;
Tend[img] = Tini[img] + modeCharacteristics.getRowCount() - 1;
}
final int Tfix = 0; // Index corresponding to the time of fixing the orbit
// ========================================================================
// === Inertial Coordinates ===
// ==v==v== ==v== Converts coordinates from ECEF to ECI ==v==v== ==v==v== =
// Pos/Vel with Time from Telemetry
double[][] eci = new double[gpsData.size()][6];
for (int i = 0; i < gpsData.size(); i++) {
GpsDataRecord gpsDataRecord = gpsData.get(i);
// position and velocity is given in meters,
// we transform to km in order to keep the values smaller. from now all distances in Km
double[] ecef = {
gpsDataRecord.posX / 1000.0, gpsDataRecord.posY / 1000.0, gpsDataRecord.posZ / 1000.0,
gpsDataRecord.velX / 1000.0, gpsDataRecord.velY / 1000.0, gpsDataRecord.velZ / 1000.0
};
double gst = TimeConverter.jdToGST(gpsDataRecord.jd);
CoordinateConverter.ecefToEci(gst, ecef, eci[i]);
}
// =======================================================================
// === Data to per-Line Time Frame ===
// =======================================================================
// ---- Interpolate GPS ECI position/velocity to per-line time -------
double[] iX = interpolate(gps_njd, get2ndDim(eci, 0, numGPS), T);
double[] iY = interpolate(gps_njd, get2ndDim(eci, 1, numGPS), T);
double[] iZ = interpolate(gps_njd, get2ndDim(eci, 2, numGPS), T);
double[] iVX = interpolate(gps_njd, get2ndDim(eci, 3, numGPS), T);
double[] iVY = interpolate(gps_njd, get2ndDim(eci, 4, numGPS), T);
double[] iVZ = interpolate(gps_njd, get2ndDim(eci, 5, numGPS), T);
double[] iR = new double[T.length];
for (int i = 0; i < iR.length; i++) {
iR[i] = Math.sqrt(iX[i] * iX[i] + iY[i] * iY[i] + iZ[i] * iZ[i]);
}
// ==v==v== Get Orbital Plane Vector ==================================================
// ---- Calculates normal vector to orbital plane --------------------------
double[][] uWop = toUnitVectors(vectorProducts(iX, iY, iZ, iVX, iVY, iVZ));
// Fixes orbital plane vector to the corresponding point on earth at the time of acquistion setup
double gst_opv = TimeConverter.jdToGST(T[Tfix] + JD2001);
double[] uWecf = CoordinateConverter.eciToEcef(gst_opv, uWop[Tfix], new double[3]);
double[][] uW = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, uWecf, uW[i]);
}
// ==v==v== Get Angular Velocity ======================================================
// Angular velocity is not really used in the model, except the AngVel at orbit fixation time (iAngVel[0])
final double[] gpsSecs = new double[gpsData.size()];
final double[] eciX = new double[gpsData.size()];
final double[] eciY = new double[gpsData.size()];
final double[] eciZ = new double[gpsData.size()];
for (int i = 0; i < gpsData.size(); i++) {
gpsSecs[i] = gpsData.get(i).secs;
eciX[i] = eci[i][X];
eciY[i] = eci[i][Y];
eciZ[i] = eci[i][Z];
}
final double[] AngVelRaw = VectorMath.angularVelocity(gpsSecs, eciX, eciY, eciZ);
final double[] AngVelRawSubset = Arrays.copyOfRange(AngVelRaw, 0, numGPS);
SimpleSmoother smoother = new SimpleSmoother(5);
final double[] AngVel = new double[AngVelRawSubset.length];
smoother.smooth(AngVelRawSubset, AngVel);
double[] iAngVel = interpolate(gps_njd, AngVel, T);
// ===== Process the correct image ==========================================
final int img = acquisitionInfo.getChronologicalImageNumber();
// ---- Target Coordinates in ECI using per-Line Time -------------------
- final double targetAltitude = acquisitionInfo.getTargetAlt() / 1000;
+ final double targetAltitude = acquisitionInfo.getTargetAlt();
final double[] TGTecf = CoordinateConverter.wgsToEcef(acquisitionInfo.getTargetLon(),
acquisitionInfo.getTargetLat(), targetAltitude,
new double[3]);
// Case with Moving Target for imaging time
double[][] iTGT0 = new double[T.length][3];
for (int i = 0; i < iTGT0.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, TGTecf, iTGT0[i]);
}
// ==v==v== Rotates TGT to perform scanning ======================================
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
final double x = uW[Tini[img] + i][X];
final double y = uW[Tini[img] + i][Y];
final double z = uW[Tini[img] + i][Z];
final double a = Math.pow(-1.0,
img) * iAngVel[0] / SLOW_DOWN_FACTOR * (T_img[i][img] - T_ict[img]) * TimeConverter.SECONDS_PER_DAY;
Quaternion.createQuaternion(x, y, z, a).transform(iTGT0[Tini[img] + i], iTGT0[Tini[img] + i]);
}
final int bestGcpIndex = findBestGCP(modeCharacteristics.getColCount() / 2,
modeCharacteristics.getRowCount() / 2, gcps);
if (bestGcpIndex != -1) {
final GCP gcp = gcps[bestGcpIndex];
/**
* 0. Calculate GCP position in ECEF
*/
final double[] GCP_ecf = new double[3];
CoordinateConverter.wgsToEcef(gcp.getLon(), gcp.getLat(), gcp.getAlt(), GCP_ecf);
final double[] wgs = CoordinateConverter.ecefToWgs(GCP_ecf[0], GCP_ecf[1], GCP_ecf[2], new double[3]);
System.out.println("lon = " + wgs[X]);
System.out.println("lat = " + wgs[Y]);
/**
* 1. Transform nominal Moving Target to ECEF
*/
// Transform Moving Target to ECF in order to find the point closest to GCP0
// iTGT0_ecf = eci2ecf(T+jd0, iTGT0[X,*], iTGT0[Y,*], iTGT0[Z,*])
final double[][] iTGT0_ecf = new double[iTGT0.length][3];
for (int i = 0; i < iTGT0.length; i++) {
final double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.eciToEcef(gst, iTGT0[i], iTGT0_ecf[i]);
}
/**
* 2. Find time offset dT
*/
double minDiff = Double.MAX_VALUE;
double tmin = Double.MAX_VALUE;
int wmin = -1;
for (int i = Tini[img]; i <= Tend[img]; i++) {
double[] pos = iTGT0_ecf[i];
final double diff = Math.sqrt(
Pow.pow2(pos[X] - GCP_ecf[X]) + Pow.pow2(pos[Y] - GCP_ecf[Y]) + Pow.pow2(
pos[Z] - GCP_ecf[Z]));
if (diff < minDiff) {
minDiff = diff;
tmin = T[i];
wmin = i; // This is necessary in order to recompute the times more easily
}
}
final double dY;
if (acquisitionInfo.isBackscanning()) {
dY = (wmin % modeCharacteristics.getRowCount()) - (modeCharacteristics.getRowCount() - gcp.getY() + 0.5);
} else {
dY = (wmin % modeCharacteristics.getRowCount()) - (gcp.getY() + 0.5);
}
final double dT = (dY * modeCharacteristics.getTotalTimePerLine()) / TimeConverter.SECONDS_PER_DAY;
System.out.println("dT = " + dT);
/**
* 3. Update T[]: add dT to all times in T[].
*/
for (int i = 0; i < T.length; i++) {
final double newT = T[i] + dT; //tmin + (mode.getDt() * (i - wmin)) / TimeConverter.SECONDS_PER_DAY;
T[i] = newT;
}
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
T_img[line][img] += dT;
}
/**
* 4. Calculate GCP position in ECI for updated times T[]
*/
// T_GCP = T[wmin] ; Assigns the acquisition time to the GCP
// GCP_eci = ecf2eci(T+jd0, GCP_ecf.X, GCP_ecf.Y, GCP_ecf.Z, units = GCP_ecf.units) ; Transform GCP coords to ECI for every time in the acquisition
final double[][] GCP_eci = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
final double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, GCP_ecf, GCP_eci[i]);
}
//// COPIED FROM ABOVE
/**
* 5. Interpolate satellite positions & velocities for updated times T[]
*/
iX = interpolate(gps_njd, get2ndDim(eci, 0, numGPS), T);
iY = interpolate(gps_njd, get2ndDim(eci, 1, numGPS), T);
iZ = interpolate(gps_njd, get2ndDim(eci, 2, numGPS), T);
iVX = interpolate(gps_njd, get2ndDim(eci, 3, numGPS), T);
iVY = interpolate(gps_njd, get2ndDim(eci, 4, numGPS), T);
iVZ = interpolate(gps_njd, get2ndDim(eci, 5, numGPS), T);
iR = new double[T.length];
for (int i = 0; i < iR.length; i++) {
iR[i] = Math.sqrt(iX[i] * iX[i] + iY[i] * iY[i] + iZ[i] * iZ[i]);
}
// ==v==v== Get Orbital Plane Vector ==================================================
// ---- Calculates normal vector to orbital plane --------------------------
uWop = toUnitVectors(vectorProducts(iX, iY, iZ, iVX, iVY, iVZ));
// Fixes orbital plane vector to the corresponding point on earth at the time of acquistion setup
gst_opv = TimeConverter.jdToGST(T[Tfix] + JD2001);
uWecf = new double[3];
CoordinateConverter.eciToEcef(gst_opv, uWop[Tfix], uWecf);
uW = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, uWecf, uW[i]);
}
// ==v==v== Get Angular Velocity ======================================================
// Angular velocity is not really used in the model, except the AngVel at orbit fixation time (iAngVel[0])
iAngVel = interpolate(gps_njd, AngVel, T);
//// EVOBA MORF DEIPOC
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
final double x = uW[Tini[img] + i][X];
final double y = uW[Tini[img] + i][Y];
final double z = uW[Tini[img] + i][Z];
final double a = Math.pow(-1.0,
img) * iAngVel[0] / SLOW_DOWN_FACTOR * (T_img[i][img] - tmin) * TimeConverter.SECONDS_PER_DAY;
Quaternion.createQuaternion(x, y, z, a).transform(GCP_eci[Tini[img] + i], GCP_eci[Tini[img] + i]);
System.out.println("i = " + i);
final double gst = TimeConverter.jdToGST(T[Tini[img] + i] + JD2001);
final double[] ecef = new double[3];
CoordinateConverter.eciToEcef(gst, GCP_eci[Tini[img] + i], ecef);
final double[] p = CoordinateConverter.ecefToWgs(ecef[0], ecef[1], ecef[2], new double[3]);
System.out.println("lon = " + p[X]);
System.out.println("lat = " + p[Y]);
System.out.println();
}
iTGT0 = GCP_eci;
} // gcpCount > 0;
// Once GCP and TT are used iTGT0 will be subsetted to the corrected T, but in the nominal case iTGT0 matches already T
double[][] iTGT = iTGT0;
// Determine the roll offset due to GCP not being in the middle of the CCD
// IF info.Mode NE 5 THEN nC2 = nCols/2 ELSE nC2 = nCols-1 ; Determine the column number of the middle of the CCD
// dRoll = (nC2-GCP[X])*IFOV ; calculates the IFOV angle difference from GCP0's pixel column to the image central pixel (the nominal target)
double dRoll = 0.0;
if (bestGcpIndex != -1) {
final int nC2;
if (acquisitionInfo.getMode() != 5) {
nC2 = modeCharacteristics.getColCount() / 2;
} else {
nC2 = modeCharacteristics.getColCount() - 1;
}
final GCP gcp = gcps[bestGcpIndex];
dRoll = (nC2 - gcp.getX()) * modeCharacteristics.getIfov();
}
//==== Calculates View Angles ==============================================
// ViewingGeometry[] viewAngs = new ViewingGeometry[mode.getNLines()];
double[][] viewRange = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
double TgtX = iTGT[Tini[img] + i][X];
double TgtY = iTGT[Tini[img] + i][Y];
double TgtZ = iTGT[Tini[img] + i][Z];
double SatX = iX[Tini[img] + i];
double SatY = iY[Tini[img] + i];
double SatZ = iZ[Tini[img] + i];
ViewingGeometry viewingGeometry = ViewingGeometry.create(TgtX, TgtY, TgtZ, SatX, SatY, SatZ);
viewRange[i][X] = viewingGeometry.x;
viewRange[i][Y] = viewingGeometry.y;
viewRange[i][Z] = viewingGeometry.z;
}
// Observation angles are not needed for the geometric correction but they are used for research. They are a by-product.
// But ViewAngs provides also the range from the target to the satellite, which is needed later (Range, of course could be calculated independently).
// ==== Satellite Rotation Axes ==============================================
double[][] yawAxes = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
yawAxes[i][X] = iX[Tini[img] + i];
yawAxes[i][Y] = iY[Tini[img] + i];
yawAxes[i][Z] = iZ[Tini[img] + i];
}
yawAxes = toUnitVectors(yawAxes);
double[][] pitchAxes = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
pitchAxes[i][X] = uWop[Tini[img] + i][X];
pitchAxes[i][Y] = uWop[Tini[img] + i][Y];
pitchAxes[i][Z] = uWop[Tini[img] + i][Z];
}
double[][] rollAxes = vectorProducts(pitchAxes, yawAxes, new double[modeCharacteristics.getRowCount()][3]);
double[][] uRange = toUnitVectors(viewRange);
// RollSign:
int[] uRollSign = new int[modeCharacteristics.getRowCount()];
double[][] uSP = vectorProducts(uRange, pitchAxes, new double[modeCharacteristics.getRowCount()][3]);
double[][] uSL = vectorProducts(pitchAxes, uSP, new double[modeCharacteristics.getRowCount()][3]);
double[][] uRoll = toUnitVectors(
vectorProducts(uSL, uRange, new double[modeCharacteristics.getRowCount()][3]));
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
double total = 0;
total += uRoll[i][X] / uSP[i][X];
total += uRoll[i][Y] / uSP[i][Y];
total += uRoll[i][Z] / uSP[i][Z];
uRollSign[i] = (int) Math.signum(total);
}
double[] centerPitchAngles = new double[modeCharacteristics.getRowCount()];
double[] centerRollAngles = new double[modeCharacteristics.getRowCount()];
System.out.println("dRoll = " + dRoll);
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
centerPitchAngles[i] = Math.PI / 2.0 - VectorMath.angle(uSP[i][X],
uSP[i][Y],
uSP[i][Z],
yawAxes[i][X],
yawAxes[i][Y],
yawAxes[i][Z]);
centerRollAngles[i] = uRollSign[i] * VectorMath.angle(uSL[i][X],
uSL[i][Y],
uSL[i][Z],
uRange[i][X],
uRange[i][Y],
uRange[i][Z]);
centerRollAngles[i] += dRoll;
}
// ==== Rotate the Line of Sight and intercept with Earth ==============================================
double[] ixSubset = new double[modeCharacteristics.getRowCount()];
double[] iySubset = new double[modeCharacteristics.getRowCount()];
double[] izSubset = new double[modeCharacteristics.getRowCount()];
double[] timeSubset = new double[modeCharacteristics.getRowCount()];
for (int i = 0; i < timeSubset.length; i++) {
ixSubset[i] = iX[Tini[img] + i];
iySubset[i] = iY[Tini[img] + i];
izSubset[i] = iZ[Tini[img] + i];
timeSubset[i] = T[Tini[img] + i];
}
calculatePitchAndRollAngles(acquisitionInfo.getMode(),
modeCharacteristics.getFov(),
modeCharacteristics.getIfov(), centerPitchAngles, centerRollAngles,
pitchAngles,
rollAngles);
// a. if there ar more than 2 GCPs we can calculate deltas for the pointing angle
if (gcps.length > 2) {
refinePitchAndRollAngles(gcps, timeSubset, ixSubset, iySubset, izSubset, pitchAxes, yawAxes,
pitchAngles, rollAngles);
}
final PositionCalculator positionCalculator = new PositionCalculator(
useTargetAltitude ? targetAltitude : 0.0);
positionCalculator.calculatePositions(
timeSubset, ixSubset, iySubset, izSubset, pitchAxes, rollAxes, yawAxes, pitchAngles,
rollAngles,
lons,
lats,
vaas,
vzas);
}
final double getLon(int y, int x) {
return lons[y][x];
}
final double getLat(int y, int x) {
return lats[y][x];
}
final double getVaa(int y, int x) {
return vaas[y][x];
}
final double getVza(int y, int x) {
return vzas[y][x];
}
final double getPitchAngle(int y, int x) {
return pitchAngles[y][x];
}
final double getRollAngle(int y, int x) {
return rollAngles[y][x];
}
private static double[] toUnitVector(double[] vector) {
final double norm = Math.sqrt(vector[X] * vector[X] + vector[Y] * vector[Y] + vector[Z] * vector[Z]);
vector[X] /= norm;
vector[Y] /= norm;
vector[Z] /= norm;
return vector;
}
private static double[][] toUnitVectors(double[][] vectors) {
for (final double[] vector : vectors) {
toUnitVector(vector);
}
return vectors;
}
private static double[] vectorProduct(double[] u, double[] v, double[] w) {
w[X] = u[Y] * v[Z] - u[Z] * v[Y];
w[Y] = u[Z] * v[X] - u[X] * v[Z];
w[Z] = u[X] * v[Y] - u[Y] * v[X];
return w;
}
private static double[][] vectorProducts(double[][] u, double[][] v, double[][] w) {
for (int i = 0; i < u.length; i++) {
vectorProduct(u[i], v[i], w[i]);
}
return w;
}
private static double[][] vectorProducts(double[] x, double[] y, double[] z, double[] u, double[] v, double[] w) {
final double[][] products = new double[x.length][3];
for (int i = 0; i < x.length; i++) {
final double[] product = products[i];
product[X] = y[i] * w[i] - z[i] * v[i];
product[Y] = z[i] * u[i] - x[i] * w[i];
product[Z] = x[i] * v[i] - y[i] * u[i];
}
return products;
}
private static double[] get2ndDim(double[][] twoDimArray, int secondDimIndex, int numElems) {
double[] secondDim = new double[numElems];
for (int i = 0; i < numElems; i++) {
secondDim[i] = twoDimArray[i][secondDimIndex];
}
return secondDim;
}
private static void refinePitchAndRollAngles(GCP[] gcps, double[] timeSubset, double[] ixSubset, double[] iySubset,
double[] izSubset,
double[][] pitchAxes, double[][] yawAxes, double[][] pitchAngles,
double[][] rollAngles) {
final int gcpCount = gcps.length;
final double[] x = new double[gcpCount];
final double[] y = new double[gcpCount];
final double[] deltaPitch = new double[gcpCount];
final double[] deltaRoll = new double[gcpCount];
final double[] pitchRoll = new double[2];
for (int i = 0; i < gcpCount; i++) {
final GCP gcp = gcps[i];
final int row = gcp.getRow();
final int col = gcp.getCol();
final double satT = timeSubset[row];
final double satX = ixSubset[row];
final double satY = iySubset[row];
final double satZ = izSubset[row];
final double[] pitchAxis = pitchAxes[row];
final double[] yawAxis = yawAxes[row];
calculatePitchRoll(satT, satX, satY, satZ, gcp, pitchAxis, yawAxis, pitchRoll);
x[i] = gcp.getX();
y[i] = gcp.getY();
deltaPitch[i] = pitchRoll[0] - pitchAngles[row][col];
deltaRoll[i] = pitchRoll[1] - rollAngles[row][col];
}
final RationalFunctionModel deltaPitchModel = new RationalFunctionModel(2, 0, x, y, deltaPitch);
final RationalFunctionModel deltaRollModel = new RationalFunctionModel(2, 0, x, y, deltaRoll);
for (int k = 0; k < pitchAngles.length; k++) {
final double[] rowPitchAngles = pitchAngles[k];
final double[] rowRollAngles = rollAngles[k];
for (int l = 0; l < rowPitchAngles.length; l++) {
rowPitchAngles[l] += deltaPitchModel.getValue(l + 0.5, k + 0.5);
rowRollAngles[l] += deltaRollModel.getValue(l + 0.5, k + 0.5);
}
}
}
private static void calculatePitchRoll(
double satT,
double satX,
double satY,
double satZ,
GCP gcp,
double[] pitchAxis,
double[] yawAxis,
double[] angles) {
final double[] gcpPos = CoordinateConverter.wgsToEcef(gcp.getLon(), gcp.getLat(), gcp.getAlt(), new double[3]);
CoordinateConverter.ecefToEci(TimeConverter.jdToGST(satT + JD2001), gcpPos, gcpPos);
final double dx = gcpPos[X] - satX;
final double dy = gcpPos[Y] - satY;
final double dz = gcpPos[Z] - satZ;
final double[] pointing = toUnitVector(new double[]{dx, dy, dz});
final double[] sp = vectorProduct(pointing, pitchAxis, new double[3]);
final double[] sl = vectorProduct(pitchAxis, sp, new double[3]);
final double[] rollAxis = toUnitVector(vectorProduct(sl, pointing, new double[3]));
final double total = rollAxis[X] / sp[X] + rollAxis[Y] / sp[Y] + rollAxis[Z] / sp[Z];
final double pitchAngle = Math.PI / 2.0 - VectorMath.angle(sp[X],
sp[Y],
sp[Z],
yawAxis[X],
yawAxis[Y],
yawAxis[Z]);
final double rollSign = Math.signum(total);
final double rollAngle = rollSign * VectorMath.angle(sl[X],
sl[Y],
sl[Z],
pointing[X],
pointing[Y],
pointing[Z]);
angles[0] = pitchAngle;
angles[1] = rollAngle;
}
private static void calculatePitchAndRollAngles(int mode,
double fov,
double ifov,
double[] centerPitchAngles,
double[] centerRollAngles,
double[][] pitchAngles,
double[][] rollAngles) {
final int rowCount = pitchAngles.length;
final int colCount = pitchAngles[0].length;
final double[] deltas = new double[colCount];
if (mode == 5) {
// for Mode 5 the last pixel points to the target, i.e. delta is zero for the last pixel
for (int i = 0; i < deltas.length; i++) {
deltas[i] = (i + 0.5) * ifov - fov;
}
} else {
final double halfFov = fov / 2.0;
for (int i = 0; i < deltas.length; i++) {
deltas[i] = (i + 0.5) * ifov - halfFov;
}
}
for (int l = 0; l < rowCount; l++) {
for (int c = 0; c < colCount; c++) {
pitchAngles[l][c] = centerPitchAngles[l];
rollAngles[l][c] = centerRollAngles[l] + deltas[c];
}
}
}
/**
* Finds the GCP which is nearest to some given pixel coordinates (x, y).
*
* @param x the x pixel coordinate.
* @param y the y pixel coordinate.
* @param gcps the ground control points being searched.
*
* @return the index of the GCP nearest to ({@code x}, {@code y}) or {@code -1},
* if no such GCP could be found.
*/
private static int findBestGCP(double x, double y, GCP[] gcps) {
int bestIndex = -1;
double bestDelta = Double.POSITIVE_INFINITY;
for (int i = 0; i < gcps.length; i++) {
final double dx = gcps[i].getX() - x;
final double dy = gcps[i].getY() - y;
final double delta = dx * dx + dy * dy;
if (delta < bestDelta) {
bestDelta = delta;
bestIndex = i;
}
}
return bestIndex;
}
/**
* Interpolates a set of values y(x) using a natural spline.
*
* @param x the original x values.
* @param y the original y values.
* @param x2 the x values used for interpolation.
*
* @return the interpolated y values, which is an array of length {@code x2.length}.
*/
private static double[] interpolate(double[] x, double[] y, double[] x2) {
final PolynomialSplineFunction splineFunction = new SplineInterpolator().interpolate(x, y);
final double[] y2 = new double[x2.length];
for (int i = 0; i < x2.length; i++) {
y2[i] = splineFunction.value(x2[i]);
}
return y2;
}
}
| true | true | void calculate(IctDataRecord ictData, List<GpsDataRecord> gpsData, GCP[] gcps, boolean useTargetAltitude) {
//////////////////////////
// Prepare Time Frames
//////////////////////////
// The last element of ict_njd corresponds to the acquisition setup time, that occurs 390s before the start of acquisition.
final ModeCharacteristics modeCharacteristics = ModeCharacteristics.get(acquisitionInfo.getMode());
final double acquisitionSetupTime = ictData.ict1 - (10.0 + 390.0) / TimeConverter.SECONDS_PER_DAY - JD2001;
double[] ict_njd = {
ictData.ict1 - JD2001,
ictData.ict2 - JD2001,
ictData.ict3 - JD2001,
ictData.ict4 - JD2001,
ictData.ict5 - JD2001,
acquisitionSetupTime
};
double[] T_ict = Arrays.copyOfRange(ict_njd, 0, IMAGE_COUNT);
//---- Nos quedamos con todos los elementos de GPS menos el ultimo ----------------
//---- ya q es donde se almacena la AngVel media, y perder un dato --------------
//---- de GPS no es un problema. ------------------------------------------------
// We are left with all elements but the last GPS
// and q is where stores AngVel half, and losing data
// GPS is not a problem.
final int numGPS = gpsData.size() - 2;
double[] gps_njd = new double[numGPS];
for (int i = 0; i < gps_njd.length; i++) {
gps_njd[i] = gpsData.get(i).jd - JD2001;
}
// ---- Critical Times ---------------------------------------------
double[] T_ini = new double[IMAGE_COUNT]; // imaging start time (imaging lasts ~9.5s in every mode)
double[] T_end = new double[IMAGE_COUNT]; // imaging stop time
for (int i = 0; i < T_ini.length; i++) {
T_ini[i] = ict_njd[i] - (modeCharacteristics.getTimePerImage() / 2.0) / TimeConverter.SECONDS_PER_DAY;
T_end[i] = ict_njd[i] + (modeCharacteristics.getTimePerImage() / 2.0) / TimeConverter.SECONDS_PER_DAY;
}
// double T_i = ict_njd[0] - 10 / Conversions.SECONDS_PER_DAY; // "imaging mode" start time
// double T_e = ict_njd[4] + 10 / Conversions.SECONDS_PER_DAY; // "imaging mode" stop time
// Searches the closest values in the telemetry to the Critical Times (just for plotting purposses)
// skipped
//---- determine per-Line Time Frame -----------------------------------
// Time elapsed since imaging start at each image line
double[] T_lin = new double[modeCharacteristics.getRowCount()];
for (int line = 0; line < T_lin.length; line++) {
T_lin[line] = (line * modeCharacteristics.getTotalTimePerLine() + modeCharacteristics.getIntegrationTimePerLine() / 2) / TimeConverter.SECONDS_PER_DAY;
// +TpL/2 is added to set the time at the middle of the integration time, i.e. pixel center
}
double[][] T_img = new double[modeCharacteristics.getRowCount()][IMAGE_COUNT];
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
for (int img = 0; img < IMAGE_COUNT; img++) {
T_img[line][img] = T_ini[img] + T_lin[line];
}
}
double[] T = new double[1 + IMAGE_COUNT * modeCharacteristics.getRowCount()];
T[0] = ict_njd[5];
int Tindex = 1;
for (int img = 0; img < IMAGE_COUNT; img++) {
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
T[Tindex] = T_img[line][img];
Tindex++;
}
}
// Set the indices of T that correspond to critical times (integration start and stop) for each image
// The first element of T corresponds to the acquisition-setup time, so Tini[0] must skip element 0 of T
int[] Tini = new int[IMAGE_COUNT];
int[] Tend = new int[IMAGE_COUNT];
for (int img = 0; img < IMAGE_COUNT; img++) {
Tini[img] = modeCharacteristics.getRowCount() * img + 1;
Tend[img] = Tini[img] + modeCharacteristics.getRowCount() - 1;
}
final int Tfix = 0; // Index corresponding to the time of fixing the orbit
// ========================================================================
// === Inertial Coordinates ===
// ==v==v== ==v== Converts coordinates from ECEF to ECI ==v==v== ==v==v== =
// Pos/Vel with Time from Telemetry
double[][] eci = new double[gpsData.size()][6];
for (int i = 0; i < gpsData.size(); i++) {
GpsDataRecord gpsDataRecord = gpsData.get(i);
// position and velocity is given in meters,
// we transform to km in order to keep the values smaller. from now all distances in Km
double[] ecef = {
gpsDataRecord.posX / 1000.0, gpsDataRecord.posY / 1000.0, gpsDataRecord.posZ / 1000.0,
gpsDataRecord.velX / 1000.0, gpsDataRecord.velY / 1000.0, gpsDataRecord.velZ / 1000.0
};
double gst = TimeConverter.jdToGST(gpsDataRecord.jd);
CoordinateConverter.ecefToEci(gst, ecef, eci[i]);
}
// =======================================================================
// === Data to per-Line Time Frame ===
// =======================================================================
// ---- Interpolate GPS ECI position/velocity to per-line time -------
double[] iX = interpolate(gps_njd, get2ndDim(eci, 0, numGPS), T);
double[] iY = interpolate(gps_njd, get2ndDim(eci, 1, numGPS), T);
double[] iZ = interpolate(gps_njd, get2ndDim(eci, 2, numGPS), T);
double[] iVX = interpolate(gps_njd, get2ndDim(eci, 3, numGPS), T);
double[] iVY = interpolate(gps_njd, get2ndDim(eci, 4, numGPS), T);
double[] iVZ = interpolate(gps_njd, get2ndDim(eci, 5, numGPS), T);
double[] iR = new double[T.length];
for (int i = 0; i < iR.length; i++) {
iR[i] = Math.sqrt(iX[i] * iX[i] + iY[i] * iY[i] + iZ[i] * iZ[i]);
}
// ==v==v== Get Orbital Plane Vector ==================================================
// ---- Calculates normal vector to orbital plane --------------------------
double[][] uWop = toUnitVectors(vectorProducts(iX, iY, iZ, iVX, iVY, iVZ));
// Fixes orbital plane vector to the corresponding point on earth at the time of acquistion setup
double gst_opv = TimeConverter.jdToGST(T[Tfix] + JD2001);
double[] uWecf = CoordinateConverter.eciToEcef(gst_opv, uWop[Tfix], new double[3]);
double[][] uW = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, uWecf, uW[i]);
}
// ==v==v== Get Angular Velocity ======================================================
// Angular velocity is not really used in the model, except the AngVel at orbit fixation time (iAngVel[0])
final double[] gpsSecs = new double[gpsData.size()];
final double[] eciX = new double[gpsData.size()];
final double[] eciY = new double[gpsData.size()];
final double[] eciZ = new double[gpsData.size()];
for (int i = 0; i < gpsData.size(); i++) {
gpsSecs[i] = gpsData.get(i).secs;
eciX[i] = eci[i][X];
eciY[i] = eci[i][Y];
eciZ[i] = eci[i][Z];
}
final double[] AngVelRaw = VectorMath.angularVelocity(gpsSecs, eciX, eciY, eciZ);
final double[] AngVelRawSubset = Arrays.copyOfRange(AngVelRaw, 0, numGPS);
SimpleSmoother smoother = new SimpleSmoother(5);
final double[] AngVel = new double[AngVelRawSubset.length];
smoother.smooth(AngVelRawSubset, AngVel);
double[] iAngVel = interpolate(gps_njd, AngVel, T);
// ===== Process the correct image ==========================================
final int img = acquisitionInfo.getChronologicalImageNumber();
// ---- Target Coordinates in ECI using per-Line Time -------------------
final double targetAltitude = acquisitionInfo.getTargetAlt() / 1000;
final double[] TGTecf = CoordinateConverter.wgsToEcef(acquisitionInfo.getTargetLon(),
acquisitionInfo.getTargetLat(), targetAltitude,
new double[3]);
// Case with Moving Target for imaging time
double[][] iTGT0 = new double[T.length][3];
for (int i = 0; i < iTGT0.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, TGTecf, iTGT0[i]);
}
// ==v==v== Rotates TGT to perform scanning ======================================
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
final double x = uW[Tini[img] + i][X];
final double y = uW[Tini[img] + i][Y];
final double z = uW[Tini[img] + i][Z];
final double a = Math.pow(-1.0,
img) * iAngVel[0] / SLOW_DOWN_FACTOR * (T_img[i][img] - T_ict[img]) * TimeConverter.SECONDS_PER_DAY;
Quaternion.createQuaternion(x, y, z, a).transform(iTGT0[Tini[img] + i], iTGT0[Tini[img] + i]);
}
final int bestGcpIndex = findBestGCP(modeCharacteristics.getColCount() / 2,
modeCharacteristics.getRowCount() / 2, gcps);
if (bestGcpIndex != -1) {
final GCP gcp = gcps[bestGcpIndex];
/**
* 0. Calculate GCP position in ECEF
*/
final double[] GCP_ecf = new double[3];
CoordinateConverter.wgsToEcef(gcp.getLon(), gcp.getLat(), gcp.getAlt(), GCP_ecf);
final double[] wgs = CoordinateConverter.ecefToWgs(GCP_ecf[0], GCP_ecf[1], GCP_ecf[2], new double[3]);
System.out.println("lon = " + wgs[X]);
System.out.println("lat = " + wgs[Y]);
/**
* 1. Transform nominal Moving Target to ECEF
*/
// Transform Moving Target to ECF in order to find the point closest to GCP0
// iTGT0_ecf = eci2ecf(T+jd0, iTGT0[X,*], iTGT0[Y,*], iTGT0[Z,*])
final double[][] iTGT0_ecf = new double[iTGT0.length][3];
for (int i = 0; i < iTGT0.length; i++) {
final double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.eciToEcef(gst, iTGT0[i], iTGT0_ecf[i]);
}
/**
* 2. Find time offset dT
*/
double minDiff = Double.MAX_VALUE;
double tmin = Double.MAX_VALUE;
int wmin = -1;
for (int i = Tini[img]; i <= Tend[img]; i++) {
double[] pos = iTGT0_ecf[i];
final double diff = Math.sqrt(
Pow.pow2(pos[X] - GCP_ecf[X]) + Pow.pow2(pos[Y] - GCP_ecf[Y]) + Pow.pow2(
pos[Z] - GCP_ecf[Z]));
if (diff < minDiff) {
minDiff = diff;
tmin = T[i];
wmin = i; // This is necessary in order to recompute the times more easily
}
}
final double dY;
if (acquisitionInfo.isBackscanning()) {
dY = (wmin % modeCharacteristics.getRowCount()) - (modeCharacteristics.getRowCount() - gcp.getY() + 0.5);
} else {
dY = (wmin % modeCharacteristics.getRowCount()) - (gcp.getY() + 0.5);
}
final double dT = (dY * modeCharacteristics.getTotalTimePerLine()) / TimeConverter.SECONDS_PER_DAY;
System.out.println("dT = " + dT);
/**
* 3. Update T[]: add dT to all times in T[].
*/
for (int i = 0; i < T.length; i++) {
final double newT = T[i] + dT; //tmin + (mode.getDt() * (i - wmin)) / TimeConverter.SECONDS_PER_DAY;
T[i] = newT;
}
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
T_img[line][img] += dT;
}
/**
* 4. Calculate GCP position in ECI for updated times T[]
*/
// T_GCP = T[wmin] ; Assigns the acquisition time to the GCP
// GCP_eci = ecf2eci(T+jd0, GCP_ecf.X, GCP_ecf.Y, GCP_ecf.Z, units = GCP_ecf.units) ; Transform GCP coords to ECI for every time in the acquisition
final double[][] GCP_eci = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
final double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, GCP_ecf, GCP_eci[i]);
}
//// COPIED FROM ABOVE
/**
* 5. Interpolate satellite positions & velocities for updated times T[]
*/
iX = interpolate(gps_njd, get2ndDim(eci, 0, numGPS), T);
iY = interpolate(gps_njd, get2ndDim(eci, 1, numGPS), T);
iZ = interpolate(gps_njd, get2ndDim(eci, 2, numGPS), T);
iVX = interpolate(gps_njd, get2ndDim(eci, 3, numGPS), T);
iVY = interpolate(gps_njd, get2ndDim(eci, 4, numGPS), T);
iVZ = interpolate(gps_njd, get2ndDim(eci, 5, numGPS), T);
iR = new double[T.length];
for (int i = 0; i < iR.length; i++) {
iR[i] = Math.sqrt(iX[i] * iX[i] + iY[i] * iY[i] + iZ[i] * iZ[i]);
}
// ==v==v== Get Orbital Plane Vector ==================================================
// ---- Calculates normal vector to orbital plane --------------------------
uWop = toUnitVectors(vectorProducts(iX, iY, iZ, iVX, iVY, iVZ));
// Fixes orbital plane vector to the corresponding point on earth at the time of acquistion setup
gst_opv = TimeConverter.jdToGST(T[Tfix] + JD2001);
uWecf = new double[3];
CoordinateConverter.eciToEcef(gst_opv, uWop[Tfix], uWecf);
uW = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, uWecf, uW[i]);
}
// ==v==v== Get Angular Velocity ======================================================
// Angular velocity is not really used in the model, except the AngVel at orbit fixation time (iAngVel[0])
iAngVel = interpolate(gps_njd, AngVel, T);
//// EVOBA MORF DEIPOC
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
final double x = uW[Tini[img] + i][X];
final double y = uW[Tini[img] + i][Y];
final double z = uW[Tini[img] + i][Z];
final double a = Math.pow(-1.0,
img) * iAngVel[0] / SLOW_DOWN_FACTOR * (T_img[i][img] - tmin) * TimeConverter.SECONDS_PER_DAY;
Quaternion.createQuaternion(x, y, z, a).transform(GCP_eci[Tini[img] + i], GCP_eci[Tini[img] + i]);
System.out.println("i = " + i);
final double gst = TimeConverter.jdToGST(T[Tini[img] + i] + JD2001);
final double[] ecef = new double[3];
CoordinateConverter.eciToEcef(gst, GCP_eci[Tini[img] + i], ecef);
final double[] p = CoordinateConverter.ecefToWgs(ecef[0], ecef[1], ecef[2], new double[3]);
System.out.println("lon = " + p[X]);
System.out.println("lat = " + p[Y]);
System.out.println();
}
iTGT0 = GCP_eci;
} // gcpCount > 0;
// Once GCP and TT are used iTGT0 will be subsetted to the corrected T, but in the nominal case iTGT0 matches already T
double[][] iTGT = iTGT0;
// Determine the roll offset due to GCP not being in the middle of the CCD
// IF info.Mode NE 5 THEN nC2 = nCols/2 ELSE nC2 = nCols-1 ; Determine the column number of the middle of the CCD
// dRoll = (nC2-GCP[X])*IFOV ; calculates the IFOV angle difference from GCP0's pixel column to the image central pixel (the nominal target)
double dRoll = 0.0;
if (bestGcpIndex != -1) {
final int nC2;
if (acquisitionInfo.getMode() != 5) {
nC2 = modeCharacteristics.getColCount() / 2;
} else {
nC2 = modeCharacteristics.getColCount() - 1;
}
final GCP gcp = gcps[bestGcpIndex];
dRoll = (nC2 - gcp.getX()) * modeCharacteristics.getIfov();
}
//==== Calculates View Angles ==============================================
// ViewingGeometry[] viewAngs = new ViewingGeometry[mode.getNLines()];
double[][] viewRange = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
double TgtX = iTGT[Tini[img] + i][X];
double TgtY = iTGT[Tini[img] + i][Y];
double TgtZ = iTGT[Tini[img] + i][Z];
double SatX = iX[Tini[img] + i];
double SatY = iY[Tini[img] + i];
double SatZ = iZ[Tini[img] + i];
ViewingGeometry viewingGeometry = ViewingGeometry.create(TgtX, TgtY, TgtZ, SatX, SatY, SatZ);
viewRange[i][X] = viewingGeometry.x;
viewRange[i][Y] = viewingGeometry.y;
viewRange[i][Z] = viewingGeometry.z;
}
// Observation angles are not needed for the geometric correction but they are used for research. They are a by-product.
// But ViewAngs provides also the range from the target to the satellite, which is needed later (Range, of course could be calculated independently).
// ==== Satellite Rotation Axes ==============================================
double[][] yawAxes = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
yawAxes[i][X] = iX[Tini[img] + i];
yawAxes[i][Y] = iY[Tini[img] + i];
yawAxes[i][Z] = iZ[Tini[img] + i];
}
yawAxes = toUnitVectors(yawAxes);
double[][] pitchAxes = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
pitchAxes[i][X] = uWop[Tini[img] + i][X];
pitchAxes[i][Y] = uWop[Tini[img] + i][Y];
pitchAxes[i][Z] = uWop[Tini[img] + i][Z];
}
double[][] rollAxes = vectorProducts(pitchAxes, yawAxes, new double[modeCharacteristics.getRowCount()][3]);
double[][] uRange = toUnitVectors(viewRange);
// RollSign:
int[] uRollSign = new int[modeCharacteristics.getRowCount()];
double[][] uSP = vectorProducts(uRange, pitchAxes, new double[modeCharacteristics.getRowCount()][3]);
double[][] uSL = vectorProducts(pitchAxes, uSP, new double[modeCharacteristics.getRowCount()][3]);
double[][] uRoll = toUnitVectors(
vectorProducts(uSL, uRange, new double[modeCharacteristics.getRowCount()][3]));
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
double total = 0;
total += uRoll[i][X] / uSP[i][X];
total += uRoll[i][Y] / uSP[i][Y];
total += uRoll[i][Z] / uSP[i][Z];
uRollSign[i] = (int) Math.signum(total);
}
double[] centerPitchAngles = new double[modeCharacteristics.getRowCount()];
double[] centerRollAngles = new double[modeCharacteristics.getRowCount()];
System.out.println("dRoll = " + dRoll);
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
centerPitchAngles[i] = Math.PI / 2.0 - VectorMath.angle(uSP[i][X],
uSP[i][Y],
uSP[i][Z],
yawAxes[i][X],
yawAxes[i][Y],
yawAxes[i][Z]);
centerRollAngles[i] = uRollSign[i] * VectorMath.angle(uSL[i][X],
uSL[i][Y],
uSL[i][Z],
uRange[i][X],
uRange[i][Y],
uRange[i][Z]);
centerRollAngles[i] += dRoll;
}
// ==== Rotate the Line of Sight and intercept with Earth ==============================================
double[] ixSubset = new double[modeCharacteristics.getRowCount()];
double[] iySubset = new double[modeCharacteristics.getRowCount()];
double[] izSubset = new double[modeCharacteristics.getRowCount()];
double[] timeSubset = new double[modeCharacteristics.getRowCount()];
for (int i = 0; i < timeSubset.length; i++) {
ixSubset[i] = iX[Tini[img] + i];
iySubset[i] = iY[Tini[img] + i];
izSubset[i] = iZ[Tini[img] + i];
timeSubset[i] = T[Tini[img] + i];
}
calculatePitchAndRollAngles(acquisitionInfo.getMode(),
modeCharacteristics.getFov(),
modeCharacteristics.getIfov(), centerPitchAngles, centerRollAngles,
pitchAngles,
rollAngles);
// a. if there ar more than 2 GCPs we can calculate deltas for the pointing angle
if (gcps.length > 2) {
refinePitchAndRollAngles(gcps, timeSubset, ixSubset, iySubset, izSubset, pitchAxes, yawAxes,
pitchAngles, rollAngles);
}
final PositionCalculator positionCalculator = new PositionCalculator(
useTargetAltitude ? targetAltitude : 0.0);
positionCalculator.calculatePositions(
timeSubset, ixSubset, iySubset, izSubset, pitchAxes, rollAxes, yawAxes, pitchAngles,
rollAngles,
lons,
lats,
vaas,
vzas);
}
| void calculate(IctDataRecord ictData, List<GpsDataRecord> gpsData, GCP[] gcps, boolean useTargetAltitude) {
//////////////////////////
// Prepare Time Frames
//////////////////////////
// The last element of ict_njd corresponds to the acquisition setup time, that occurs 390s before the start of acquisition.
final ModeCharacteristics modeCharacteristics = ModeCharacteristics.get(acquisitionInfo.getMode());
final double acquisitionSetupTime = ictData.ict1 - (10.0 + 390.0) / TimeConverter.SECONDS_PER_DAY - JD2001;
double[] ict_njd = {
ictData.ict1 - JD2001,
ictData.ict2 - JD2001,
ictData.ict3 - JD2001,
ictData.ict4 - JD2001,
ictData.ict5 - JD2001,
acquisitionSetupTime
};
double[] T_ict = Arrays.copyOfRange(ict_njd, 0, IMAGE_COUNT);
//---- Nos quedamos con todos los elementos de GPS menos el ultimo ----------------
//---- ya q es donde se almacena la AngVel media, y perder un dato --------------
//---- de GPS no es un problema. ------------------------------------------------
// We are left with all elements but the last GPS
// and q is where stores AngVel half, and losing data
// GPS is not a problem.
final int numGPS = gpsData.size() - 2;
double[] gps_njd = new double[numGPS];
for (int i = 0; i < gps_njd.length; i++) {
gps_njd[i] = gpsData.get(i).jd - JD2001;
}
// ---- Critical Times ---------------------------------------------
double[] T_ini = new double[IMAGE_COUNT]; // imaging start time (imaging lasts ~9.5s in every mode)
double[] T_end = new double[IMAGE_COUNT]; // imaging stop time
for (int i = 0; i < T_ini.length; i++) {
T_ini[i] = ict_njd[i] - (modeCharacteristics.getTimePerImage() / 2.0) / TimeConverter.SECONDS_PER_DAY;
T_end[i] = ict_njd[i] + (modeCharacteristics.getTimePerImage() / 2.0) / TimeConverter.SECONDS_PER_DAY;
}
// double T_i = ict_njd[0] - 10 / Conversions.SECONDS_PER_DAY; // "imaging mode" start time
// double T_e = ict_njd[4] + 10 / Conversions.SECONDS_PER_DAY; // "imaging mode" stop time
// Searches the closest values in the telemetry to the Critical Times (just for plotting purposses)
// skipped
//---- determine per-Line Time Frame -----------------------------------
// Time elapsed since imaging start at each image line
double[] T_lin = new double[modeCharacteristics.getRowCount()];
for (int line = 0; line < T_lin.length; line++) {
T_lin[line] = (line * modeCharacteristics.getTotalTimePerLine() + modeCharacteristics.getIntegrationTimePerLine() / 2) / TimeConverter.SECONDS_PER_DAY;
// +TpL/2 is added to set the time at the middle of the integration time, i.e. pixel center
}
double[][] T_img = new double[modeCharacteristics.getRowCount()][IMAGE_COUNT];
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
for (int img = 0; img < IMAGE_COUNT; img++) {
T_img[line][img] = T_ini[img] + T_lin[line];
}
}
double[] T = new double[1 + IMAGE_COUNT * modeCharacteristics.getRowCount()];
T[0] = ict_njd[5];
int Tindex = 1;
for (int img = 0; img < IMAGE_COUNT; img++) {
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
T[Tindex] = T_img[line][img];
Tindex++;
}
}
// Set the indices of T that correspond to critical times (integration start and stop) for each image
// The first element of T corresponds to the acquisition-setup time, so Tini[0] must skip element 0 of T
int[] Tini = new int[IMAGE_COUNT];
int[] Tend = new int[IMAGE_COUNT];
for (int img = 0; img < IMAGE_COUNT; img++) {
Tini[img] = modeCharacteristics.getRowCount() * img + 1;
Tend[img] = Tini[img] + modeCharacteristics.getRowCount() - 1;
}
final int Tfix = 0; // Index corresponding to the time of fixing the orbit
// ========================================================================
// === Inertial Coordinates ===
// ==v==v== ==v== Converts coordinates from ECEF to ECI ==v==v== ==v==v== =
// Pos/Vel with Time from Telemetry
double[][] eci = new double[gpsData.size()][6];
for (int i = 0; i < gpsData.size(); i++) {
GpsDataRecord gpsDataRecord = gpsData.get(i);
// position and velocity is given in meters,
// we transform to km in order to keep the values smaller. from now all distances in Km
double[] ecef = {
gpsDataRecord.posX / 1000.0, gpsDataRecord.posY / 1000.0, gpsDataRecord.posZ / 1000.0,
gpsDataRecord.velX / 1000.0, gpsDataRecord.velY / 1000.0, gpsDataRecord.velZ / 1000.0
};
double gst = TimeConverter.jdToGST(gpsDataRecord.jd);
CoordinateConverter.ecefToEci(gst, ecef, eci[i]);
}
// =======================================================================
// === Data to per-Line Time Frame ===
// =======================================================================
// ---- Interpolate GPS ECI position/velocity to per-line time -------
double[] iX = interpolate(gps_njd, get2ndDim(eci, 0, numGPS), T);
double[] iY = interpolate(gps_njd, get2ndDim(eci, 1, numGPS), T);
double[] iZ = interpolate(gps_njd, get2ndDim(eci, 2, numGPS), T);
double[] iVX = interpolate(gps_njd, get2ndDim(eci, 3, numGPS), T);
double[] iVY = interpolate(gps_njd, get2ndDim(eci, 4, numGPS), T);
double[] iVZ = interpolate(gps_njd, get2ndDim(eci, 5, numGPS), T);
double[] iR = new double[T.length];
for (int i = 0; i < iR.length; i++) {
iR[i] = Math.sqrt(iX[i] * iX[i] + iY[i] * iY[i] + iZ[i] * iZ[i]);
}
// ==v==v== Get Orbital Plane Vector ==================================================
// ---- Calculates normal vector to orbital plane --------------------------
double[][] uWop = toUnitVectors(vectorProducts(iX, iY, iZ, iVX, iVY, iVZ));
// Fixes orbital plane vector to the corresponding point on earth at the time of acquistion setup
double gst_opv = TimeConverter.jdToGST(T[Tfix] + JD2001);
double[] uWecf = CoordinateConverter.eciToEcef(gst_opv, uWop[Tfix], new double[3]);
double[][] uW = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, uWecf, uW[i]);
}
// ==v==v== Get Angular Velocity ======================================================
// Angular velocity is not really used in the model, except the AngVel at orbit fixation time (iAngVel[0])
final double[] gpsSecs = new double[gpsData.size()];
final double[] eciX = new double[gpsData.size()];
final double[] eciY = new double[gpsData.size()];
final double[] eciZ = new double[gpsData.size()];
for (int i = 0; i < gpsData.size(); i++) {
gpsSecs[i] = gpsData.get(i).secs;
eciX[i] = eci[i][X];
eciY[i] = eci[i][Y];
eciZ[i] = eci[i][Z];
}
final double[] AngVelRaw = VectorMath.angularVelocity(gpsSecs, eciX, eciY, eciZ);
final double[] AngVelRawSubset = Arrays.copyOfRange(AngVelRaw, 0, numGPS);
SimpleSmoother smoother = new SimpleSmoother(5);
final double[] AngVel = new double[AngVelRawSubset.length];
smoother.smooth(AngVelRawSubset, AngVel);
double[] iAngVel = interpolate(gps_njd, AngVel, T);
// ===== Process the correct image ==========================================
final int img = acquisitionInfo.getChronologicalImageNumber();
// ---- Target Coordinates in ECI using per-Line Time -------------------
final double targetAltitude = acquisitionInfo.getTargetAlt();
final double[] TGTecf = CoordinateConverter.wgsToEcef(acquisitionInfo.getTargetLon(),
acquisitionInfo.getTargetLat(), targetAltitude,
new double[3]);
// Case with Moving Target for imaging time
double[][] iTGT0 = new double[T.length][3];
for (int i = 0; i < iTGT0.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, TGTecf, iTGT0[i]);
}
// ==v==v== Rotates TGT to perform scanning ======================================
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
final double x = uW[Tini[img] + i][X];
final double y = uW[Tini[img] + i][Y];
final double z = uW[Tini[img] + i][Z];
final double a = Math.pow(-1.0,
img) * iAngVel[0] / SLOW_DOWN_FACTOR * (T_img[i][img] - T_ict[img]) * TimeConverter.SECONDS_PER_DAY;
Quaternion.createQuaternion(x, y, z, a).transform(iTGT0[Tini[img] + i], iTGT0[Tini[img] + i]);
}
final int bestGcpIndex = findBestGCP(modeCharacteristics.getColCount() / 2,
modeCharacteristics.getRowCount() / 2, gcps);
if (bestGcpIndex != -1) {
final GCP gcp = gcps[bestGcpIndex];
/**
* 0. Calculate GCP position in ECEF
*/
final double[] GCP_ecf = new double[3];
CoordinateConverter.wgsToEcef(gcp.getLon(), gcp.getLat(), gcp.getAlt(), GCP_ecf);
final double[] wgs = CoordinateConverter.ecefToWgs(GCP_ecf[0], GCP_ecf[1], GCP_ecf[2], new double[3]);
System.out.println("lon = " + wgs[X]);
System.out.println("lat = " + wgs[Y]);
/**
* 1. Transform nominal Moving Target to ECEF
*/
// Transform Moving Target to ECF in order to find the point closest to GCP0
// iTGT0_ecf = eci2ecf(T+jd0, iTGT0[X,*], iTGT0[Y,*], iTGT0[Z,*])
final double[][] iTGT0_ecf = new double[iTGT0.length][3];
for (int i = 0; i < iTGT0.length; i++) {
final double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.eciToEcef(gst, iTGT0[i], iTGT0_ecf[i]);
}
/**
* 2. Find time offset dT
*/
double minDiff = Double.MAX_VALUE;
double tmin = Double.MAX_VALUE;
int wmin = -1;
for (int i = Tini[img]; i <= Tend[img]; i++) {
double[] pos = iTGT0_ecf[i];
final double diff = Math.sqrt(
Pow.pow2(pos[X] - GCP_ecf[X]) + Pow.pow2(pos[Y] - GCP_ecf[Y]) + Pow.pow2(
pos[Z] - GCP_ecf[Z]));
if (diff < minDiff) {
minDiff = diff;
tmin = T[i];
wmin = i; // This is necessary in order to recompute the times more easily
}
}
final double dY;
if (acquisitionInfo.isBackscanning()) {
dY = (wmin % modeCharacteristics.getRowCount()) - (modeCharacteristics.getRowCount() - gcp.getY() + 0.5);
} else {
dY = (wmin % modeCharacteristics.getRowCount()) - (gcp.getY() + 0.5);
}
final double dT = (dY * modeCharacteristics.getTotalTimePerLine()) / TimeConverter.SECONDS_PER_DAY;
System.out.println("dT = " + dT);
/**
* 3. Update T[]: add dT to all times in T[].
*/
for (int i = 0; i < T.length; i++) {
final double newT = T[i] + dT; //tmin + (mode.getDt() * (i - wmin)) / TimeConverter.SECONDS_PER_DAY;
T[i] = newT;
}
for (int line = 0; line < modeCharacteristics.getRowCount(); line++) {
T_img[line][img] += dT;
}
/**
* 4. Calculate GCP position in ECI for updated times T[]
*/
// T_GCP = T[wmin] ; Assigns the acquisition time to the GCP
// GCP_eci = ecf2eci(T+jd0, GCP_ecf.X, GCP_ecf.Y, GCP_ecf.Z, units = GCP_ecf.units) ; Transform GCP coords to ECI for every time in the acquisition
final double[][] GCP_eci = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
final double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, GCP_ecf, GCP_eci[i]);
}
//// COPIED FROM ABOVE
/**
* 5. Interpolate satellite positions & velocities for updated times T[]
*/
iX = interpolate(gps_njd, get2ndDim(eci, 0, numGPS), T);
iY = interpolate(gps_njd, get2ndDim(eci, 1, numGPS), T);
iZ = interpolate(gps_njd, get2ndDim(eci, 2, numGPS), T);
iVX = interpolate(gps_njd, get2ndDim(eci, 3, numGPS), T);
iVY = interpolate(gps_njd, get2ndDim(eci, 4, numGPS), T);
iVZ = interpolate(gps_njd, get2ndDim(eci, 5, numGPS), T);
iR = new double[T.length];
for (int i = 0; i < iR.length; i++) {
iR[i] = Math.sqrt(iX[i] * iX[i] + iY[i] * iY[i] + iZ[i] * iZ[i]);
}
// ==v==v== Get Orbital Plane Vector ==================================================
// ---- Calculates normal vector to orbital plane --------------------------
uWop = toUnitVectors(vectorProducts(iX, iY, iZ, iVX, iVY, iVZ));
// Fixes orbital plane vector to the corresponding point on earth at the time of acquistion setup
gst_opv = TimeConverter.jdToGST(T[Tfix] + JD2001);
uWecf = new double[3];
CoordinateConverter.eciToEcef(gst_opv, uWop[Tfix], uWecf);
uW = new double[T.length][3];
for (int i = 0; i < T.length; i++) {
double gst = TimeConverter.jdToGST(T[i] + JD2001);
CoordinateConverter.ecefToEci(gst, uWecf, uW[i]);
}
// ==v==v== Get Angular Velocity ======================================================
// Angular velocity is not really used in the model, except the AngVel at orbit fixation time (iAngVel[0])
iAngVel = interpolate(gps_njd, AngVel, T);
//// EVOBA MORF DEIPOC
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
final double x = uW[Tini[img] + i][X];
final double y = uW[Tini[img] + i][Y];
final double z = uW[Tini[img] + i][Z];
final double a = Math.pow(-1.0,
img) * iAngVel[0] / SLOW_DOWN_FACTOR * (T_img[i][img] - tmin) * TimeConverter.SECONDS_PER_DAY;
Quaternion.createQuaternion(x, y, z, a).transform(GCP_eci[Tini[img] + i], GCP_eci[Tini[img] + i]);
System.out.println("i = " + i);
final double gst = TimeConverter.jdToGST(T[Tini[img] + i] + JD2001);
final double[] ecef = new double[3];
CoordinateConverter.eciToEcef(gst, GCP_eci[Tini[img] + i], ecef);
final double[] p = CoordinateConverter.ecefToWgs(ecef[0], ecef[1], ecef[2], new double[3]);
System.out.println("lon = " + p[X]);
System.out.println("lat = " + p[Y]);
System.out.println();
}
iTGT0 = GCP_eci;
} // gcpCount > 0;
// Once GCP and TT are used iTGT0 will be subsetted to the corrected T, but in the nominal case iTGT0 matches already T
double[][] iTGT = iTGT0;
// Determine the roll offset due to GCP not being in the middle of the CCD
// IF info.Mode NE 5 THEN nC2 = nCols/2 ELSE nC2 = nCols-1 ; Determine the column number of the middle of the CCD
// dRoll = (nC2-GCP[X])*IFOV ; calculates the IFOV angle difference from GCP0's pixel column to the image central pixel (the nominal target)
double dRoll = 0.0;
if (bestGcpIndex != -1) {
final int nC2;
if (acquisitionInfo.getMode() != 5) {
nC2 = modeCharacteristics.getColCount() / 2;
} else {
nC2 = modeCharacteristics.getColCount() - 1;
}
final GCP gcp = gcps[bestGcpIndex];
dRoll = (nC2 - gcp.getX()) * modeCharacteristics.getIfov();
}
//==== Calculates View Angles ==============================================
// ViewingGeometry[] viewAngs = new ViewingGeometry[mode.getNLines()];
double[][] viewRange = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
double TgtX = iTGT[Tini[img] + i][X];
double TgtY = iTGT[Tini[img] + i][Y];
double TgtZ = iTGT[Tini[img] + i][Z];
double SatX = iX[Tini[img] + i];
double SatY = iY[Tini[img] + i];
double SatZ = iZ[Tini[img] + i];
ViewingGeometry viewingGeometry = ViewingGeometry.create(TgtX, TgtY, TgtZ, SatX, SatY, SatZ);
viewRange[i][X] = viewingGeometry.x;
viewRange[i][Y] = viewingGeometry.y;
viewRange[i][Z] = viewingGeometry.z;
}
// Observation angles are not needed for the geometric correction but they are used for research. They are a by-product.
// But ViewAngs provides also the range from the target to the satellite, which is needed later (Range, of course could be calculated independently).
// ==== Satellite Rotation Axes ==============================================
double[][] yawAxes = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
yawAxes[i][X] = iX[Tini[img] + i];
yawAxes[i][Y] = iY[Tini[img] + i];
yawAxes[i][Z] = iZ[Tini[img] + i];
}
yawAxes = toUnitVectors(yawAxes);
double[][] pitchAxes = new double[modeCharacteristics.getRowCount()][3];
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
pitchAxes[i][X] = uWop[Tini[img] + i][X];
pitchAxes[i][Y] = uWop[Tini[img] + i][Y];
pitchAxes[i][Z] = uWop[Tini[img] + i][Z];
}
double[][] rollAxes = vectorProducts(pitchAxes, yawAxes, new double[modeCharacteristics.getRowCount()][3]);
double[][] uRange = toUnitVectors(viewRange);
// RollSign:
int[] uRollSign = new int[modeCharacteristics.getRowCount()];
double[][] uSP = vectorProducts(uRange, pitchAxes, new double[modeCharacteristics.getRowCount()][3]);
double[][] uSL = vectorProducts(pitchAxes, uSP, new double[modeCharacteristics.getRowCount()][3]);
double[][] uRoll = toUnitVectors(
vectorProducts(uSL, uRange, new double[modeCharacteristics.getRowCount()][3]));
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
double total = 0;
total += uRoll[i][X] / uSP[i][X];
total += uRoll[i][Y] / uSP[i][Y];
total += uRoll[i][Z] / uSP[i][Z];
uRollSign[i] = (int) Math.signum(total);
}
double[] centerPitchAngles = new double[modeCharacteristics.getRowCount()];
double[] centerRollAngles = new double[modeCharacteristics.getRowCount()];
System.out.println("dRoll = " + dRoll);
for (int i = 0; i < modeCharacteristics.getRowCount(); i++) {
centerPitchAngles[i] = Math.PI / 2.0 - VectorMath.angle(uSP[i][X],
uSP[i][Y],
uSP[i][Z],
yawAxes[i][X],
yawAxes[i][Y],
yawAxes[i][Z]);
centerRollAngles[i] = uRollSign[i] * VectorMath.angle(uSL[i][X],
uSL[i][Y],
uSL[i][Z],
uRange[i][X],
uRange[i][Y],
uRange[i][Z]);
centerRollAngles[i] += dRoll;
}
// ==== Rotate the Line of Sight and intercept with Earth ==============================================
double[] ixSubset = new double[modeCharacteristics.getRowCount()];
double[] iySubset = new double[modeCharacteristics.getRowCount()];
double[] izSubset = new double[modeCharacteristics.getRowCount()];
double[] timeSubset = new double[modeCharacteristics.getRowCount()];
for (int i = 0; i < timeSubset.length; i++) {
ixSubset[i] = iX[Tini[img] + i];
iySubset[i] = iY[Tini[img] + i];
izSubset[i] = iZ[Tini[img] + i];
timeSubset[i] = T[Tini[img] + i];
}
calculatePitchAndRollAngles(acquisitionInfo.getMode(),
modeCharacteristics.getFov(),
modeCharacteristics.getIfov(), centerPitchAngles, centerRollAngles,
pitchAngles,
rollAngles);
// a. if there ar more than 2 GCPs we can calculate deltas for the pointing angle
if (gcps.length > 2) {
refinePitchAndRollAngles(gcps, timeSubset, ixSubset, iySubset, izSubset, pitchAxes, yawAxes,
pitchAngles, rollAngles);
}
final PositionCalculator positionCalculator = new PositionCalculator(
useTargetAltitude ? targetAltitude : 0.0);
positionCalculator.calculatePositions(
timeSubset, ixSubset, iySubset, izSubset, pitchAxes, rollAxes, yawAxes, pitchAngles,
rollAngles,
lons,
lats,
vaas,
vzas);
}
|
diff --git a/subprojects/demo-javafx/server/src/main/groovy/com/canoo/dolphin/demo/PerformanceAction.java b/subprojects/demo-javafx/server/src/main/groovy/com/canoo/dolphin/demo/PerformanceAction.java
index 5e4118fc..08b9341b 100644
--- a/subprojects/demo-javafx/server/src/main/groovy/com/canoo/dolphin/demo/PerformanceAction.java
+++ b/subprojects/demo-javafx/server/src/main/groovy/com/canoo/dolphin/demo/PerformanceAction.java
@@ -1,67 +1,67 @@
/*
* Copyright 2012 Canoo Engineering AG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.canoo.dolphin.demo;
import com.canoo.dolphin.core.Attribute;
import com.canoo.dolphin.core.PresentationModel;
import com.canoo.dolphin.core.comm.Command;
import com.canoo.dolphin.core.server.DTO;
import com.canoo.dolphin.core.server.Slot;
import com.canoo.dolphin.core.server.action.DolphinServerAction;
import com.canoo.dolphin.core.server.comm.ActionRegistry;
import com.canoo.dolphin.core.server.comm.CommandHandler;
import java.util.LinkedList;
import java.util.List;
public class PerformanceAction extends DolphinServerAction {
static long id = 0;
public void registerIn(final ActionRegistry registry) {
registry.register("sync", new CommandHandler() {
public void handleCommand(Command command, List response) {
// do nothing
// this is only for synchronizing the timer after "clear"
}
});
registry.register("stressTest", new CommandHandler() {
public void handleCommand(Command command, List response) {
PresentationModel pm = getServerDolphin().findPresentationModelById("input");
if (pm == null) {
throw new IllegalStateException("No input criteria known on the server!");
}
Attribute countAtt = pm.findAttributeByPropertyName("count");
Object countValue = (countAtt == null) ? null : countAtt.getValue();
int count = (countValue == null) ? 1 : Integer.parseInt(countValue.toString());
Attribute attCountAtt = pm.findAttributeByPropertyName("attCount");
Object attCountValue = (attCountAtt == null) ? null : attCountAtt.getValue();
int attCount = (attCountValue == null) ? 1 : Integer.parseInt(attCountValue.toString());
for (int pmCount = 0; pmCount < count; pmCount++) {
- LinkedList<Slot> slots = new LinkedList<>();
+ LinkedList<Slot> slots = new LinkedList();
for (int attI = 0; attI < attCount; attI++) {
slots.add(new Slot("att" + Long.toString(id++), "val" + Long.toString(id++)));
}
presentationModel(Long.toString(id++), "all", new DTO(slots));
}
}
});
}
}
| true | true | public void registerIn(final ActionRegistry registry) {
registry.register("sync", new CommandHandler() {
public void handleCommand(Command command, List response) {
// do nothing
// this is only for synchronizing the timer after "clear"
}
});
registry.register("stressTest", new CommandHandler() {
public void handleCommand(Command command, List response) {
PresentationModel pm = getServerDolphin().findPresentationModelById("input");
if (pm == null) {
throw new IllegalStateException("No input criteria known on the server!");
}
Attribute countAtt = pm.findAttributeByPropertyName("count");
Object countValue = (countAtt == null) ? null : countAtt.getValue();
int count = (countValue == null) ? 1 : Integer.parseInt(countValue.toString());
Attribute attCountAtt = pm.findAttributeByPropertyName("attCount");
Object attCountValue = (attCountAtt == null) ? null : attCountAtt.getValue();
int attCount = (attCountValue == null) ? 1 : Integer.parseInt(attCountValue.toString());
for (int pmCount = 0; pmCount < count; pmCount++) {
LinkedList<Slot> slots = new LinkedList<>();
for (int attI = 0; attI < attCount; attI++) {
slots.add(new Slot("att" + Long.toString(id++), "val" + Long.toString(id++)));
}
presentationModel(Long.toString(id++), "all", new DTO(slots));
}
}
});
}
| public void registerIn(final ActionRegistry registry) {
registry.register("sync", new CommandHandler() {
public void handleCommand(Command command, List response) {
// do nothing
// this is only for synchronizing the timer after "clear"
}
});
registry.register("stressTest", new CommandHandler() {
public void handleCommand(Command command, List response) {
PresentationModel pm = getServerDolphin().findPresentationModelById("input");
if (pm == null) {
throw new IllegalStateException("No input criteria known on the server!");
}
Attribute countAtt = pm.findAttributeByPropertyName("count");
Object countValue = (countAtt == null) ? null : countAtt.getValue();
int count = (countValue == null) ? 1 : Integer.parseInt(countValue.toString());
Attribute attCountAtt = pm.findAttributeByPropertyName("attCount");
Object attCountValue = (attCountAtt == null) ? null : attCountAtt.getValue();
int attCount = (attCountValue == null) ? 1 : Integer.parseInt(attCountValue.toString());
for (int pmCount = 0; pmCount < count; pmCount++) {
LinkedList<Slot> slots = new LinkedList();
for (int attI = 0; attI < attCount; attI++) {
slots.add(new Slot("att" + Long.toString(id++), "val" + Long.toString(id++)));
}
presentationModel(Long.toString(id++), "all", new DTO(slots));
}
}
});
}
|
diff --git a/src/org/apache/xerces/validators/schema/TraverseSchema.java b/src/org/apache/xerces/validators/schema/TraverseSchema.java
index 4be46357..68cc4418 100644
--- a/src/org/apache/xerces/validators/schema/TraverseSchema.java
+++ b/src/org/apache/xerces/validators/schema/TraverseSchema.java
@@ -1,4499 +1,4499 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.validators.schema;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.validators.common.Grammar;
import org.apache.xerces.validators.common.GrammarResolver;
import org.apache.xerces.validators.common.GrammarResolverImpl;
import org.apache.xerces.validators.common.XMLElementDecl;
import org.apache.xerces.validators.common.XMLAttributeDecl;
import org.apache.xerces.validators.schema.SchemaSymbols;
import org.apache.xerces.validators.schema.XUtil;
import org.apache.xerces.validators.datatype.DatatypeValidator;
import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.utils.StringPool;
import org.w3c.dom.Element;
//REVISIT: for now, import everything in the DOM package
import org.w3c.dom.*;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
//Unit Test
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.validators.common.XMLValidator;
import org.apache.xerces.validators.datatype.DatatypeValidator.*;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.framework.XMLContentSpec;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.framework.XMLParser;
import org.apache.xerces.framework.XMLDocumentScanner;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import java.io.IOException;
import org.w3c.dom.Document;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xerces.validators.schema.SchemaSymbols;
/**
* Instances of this class get delegated to Traverse the Schema and
* to populate the Grammar internal representation by
* instances of Grammar objects.
* Traverse a Schema Grammar:
* As of April 07, 2000 the following is the
* XML Representation of Schemas and Schema components,
* Chapter 4 of W3C Working Draft.
* <schema
* attributeFormDefault = qualified | unqualified
* blockDefault = #all or (possibly empty) subset of {equivClass, extension, restriction}
* elementFormDefault = qualified | unqualified
* finalDefault = #all or (possibly empty) subset of {extension, restriction}
* id = ID
* targetNamespace = uriReference
* version = string>
* Content: ((include | import | annotation)* , ((simpleType | complexType | element | group | attribute | attributeGroup | notation) , annotation*)+)
* </schema>
*
*
* <attribute
* form = qualified | unqualified
* id = ID
* name = NCName
* ref = QName
* type = QName
* use = default | fixed | optional | prohibited | required
* value = string>
* Content: (annotation? , simpleType?)
* </>
*
* <element
* abstract = boolean
* block = #all or (possibly empty) subset of {equivClass, extension, restriction}
* default = string
* equivClass = QName
* final = #all or (possibly empty) subset of {extension, restriction}
* fixed = string
* form = qualified | unqualified
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* nullable = boolean
* ref = QName
* type = QName>
* Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*)
* </>
*
*
* <complexType
* abstract = boolean
* base = QName
* block = #all or (possibly empty) subset of {extension, restriction}
* content = elementOnly | empty | mixed | textOnly
* derivedBy = extension | restriction
* final = #all or (possibly empty) subset of {extension, restriction}
* id = ID
* name = NCName>
* Content: (annotation? , (((minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern)* | (element | group | all | choice | sequence | any)*) , ((attribute | attributeGroup)* , anyAttribute?)))
* </>
*
*
* <attributeGroup
* id = ID
* name = NCName
* ref = QName>
* Content: (annotation?, (attribute|attributeGroup), anyAttribute?)
* </>
*
* <anyAttribute
* id = ID
* namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}>
* Content: (annotation?)
* </anyAttribute>
*
* <group
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* ref = QName>
* Content: (annotation? , (element | group | all | choice | sequence | any)*)
* </>
*
* <all
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </all>
*
* <choice
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </choice>
*
* <sequence
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </sequence>
*
*
* <any
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}
* processContents = lax | skip | strict>
* Content: (annotation?)
* </any>
*
* <unique
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </unique>
*
* <key
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </key>
*
* <keyref
* id = ID
* name = NCName
* refer = QName>
* Content: (annotation? , (selector , field+))
* </keyref>
*
* <selector>
* Content: XPathExprApprox : An XPath expression
* </selector>
*
* <field>
* Content: XPathExprApprox : An XPath expression
* </field>
*
*
* <notation
* id = ID
* name = NCName
* public = A public identifier, per ISO 8879
* system = uriReference>
* Content: (annotation?)
* </notation>
*
* <annotation>
* Content: (appinfo | documentation)*
* </annotation>
*
* <include
* id = ID
* schemaLocation = uriReference>
* Content: (annotation?)
* </include>
*
* <import
* id = ID
* namespace = uriReference
* schemaLocation = uriReference>
* Content: (annotation?)
* </import>
*
* <simpleType
* abstract = boolean
* base = QName
* derivedBy = | list | restriction : restriction
* id = ID
* name = NCName>
* Content: ( annotation? , ( minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern )* )
* </simpleType>
*
* <length
* id = ID
* value = nonNegativeInteger>
* Content: ( annotation? )
* </length>
*
* <minLength
* id = ID
* value = nonNegativeInteger>
* Content: ( annotation? )
* </minLength>
*
* <maxLength
* id = ID
* value = nonNegativeInteger>
* Content: ( annotation? )
* </maxLength>
*
*
* <pattern
* id = ID
* value = string>
* Content: ( annotation? )
* </pattern>
*
*
* <enumeration
* id = ID
* value = string>
* Content: ( annotation? )
* </enumeration>
*
* <maxInclusive
* id = ID
* value = string>
* Content: ( annotation? )
* </maxInclusive>
*
* <maxExclusive
* id = ID
* value = string>
* Content: ( annotation? )
* </maxExclusive>
*
* <minInclusive
* id = ID
* value = string>
* Content: ( annotation? )
* </minInclusive>
*
*
* <minExclusive
* id = ID
* value = string>
* Content: ( annotation? )
* </minExclusive>
*
* <precision
* id = ID
* value = nonNegativeInteger>
* Content: ( annotation? )
* </precision>
*
* <scale
* id = ID
* value = nonNegativeInteger>
* Content: ( annotation? )
* </scale>
*
* <encoding
* id = ID
* value = | hex | base64 >
* Content: ( annotation? )
* </encoding>
*
*
* <duration
* id = ID
* value = timeDuration>
* Content: ( annotation? )
* </duration>
*
* <period
* id = ID
* value = timeDuration>
* Content: ( annotation? )
* </period>
*
*
* @author Eric Ye, Jeffrey Rodriguez, Andy Clark
*
* @see org.apache.xerces.validators.common.Grammar
*
* @version $Id$
*/
public class TraverseSchema implements
NamespacesScope.NamespacesHandler{
//CONSTANTS
private static final int TOP_LEVEL_SCOPE = -1;
//debuggin
private static boolean DEBUGGING = false;
//private data members
private XMLErrorReporter fErrorReporter = null;
private StringPool fStringPool = null;
private GrammarResolver fGrammarResolver = null;
private SchemaGrammar fSchemaGrammar = null;
private Element fSchemaRootElement;
private DatatypeValidatorFactoryImpl fDatatypeRegistry =
DatatypeValidatorFactoryImpl.getDatatypeRegistry();
private Hashtable fComplexTypeRegistry = new Hashtable();
private Hashtable fAttributeDeclRegistry = new Hashtable();
private Vector fIncludeLocations = new Vector();
private Vector fImportLocations = new Vector();
private int fAnonTypeCount =0;
private int fScopeCount=0;
private int fCurrentScope=TOP_LEVEL_SCOPE;
private int fSimpleTypeAnonCount = 0;
private Stack fCurrentTypeNameStack = new Stack();
private Hashtable fElementRecurseComplex = new Hashtable();
private boolean fElementDefaultQualified = false;
private boolean fAttributeDefaultQualified = false;
private int fTargetNSURI;
private String fTargetNSURIString = "";
private NamespacesScope fNamespacesScope = null;
private String fCurrentSchemaURL = "";
private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl();
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
// REVISIT: maybe need to be moved into SchemaGrammar class
public class ComplexTypeInfo {
public String typeName;
public DatatypeValidator baseDataTypeValidator;
public ComplexTypeInfo baseComplexTypeInfo;
public int derivedBy = 0;
public int blockSet = 0;
public int finalSet = 0;
public boolean isAbstract = false;
public int scopeDefined = -1;
public int contentType;
public int contentSpecHandle = -1;
public int templateElementIndex = -1;
public int attlistHead = -1;
public DatatypeValidator datatypeValidator;
}
//REVISIT: verify the URI.
public final static String SchemaForSchemaURI = "http://www.w3.org/TR-1/Schema";
private TraverseSchema( ) {
// new TraverseSchema() is forbidden;
}
public void setGrammarResolver(GrammarResolver grammarResolver){
fGrammarResolver = grammarResolver;
}
public void startNamespaceDeclScope(int prefix, int uri){
//TO DO
}
public void endNamespaceDeclScope(int prefix){
//TO DO, do we need to do anything here?
}
private String resolvePrefixToURI (String prefix) throws Exception {
String uriStr = fStringPool.toString(fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix)));
if (uriStr == null) {
// REVISIT: Localize
reportGenericSchemaError("prefix : [" + prefix +"] can not be resolved to a URI");
return "";
}
//REVISIT, !!!! a hack: needs to be updated later, cause now we only use localpart to key build-in datatype.
if ( prefix.length()==0 && uriStr.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& fTargetNSURIString.length() == 0) {
uriStr = "";
}
return uriStr;
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
XMLErrorReporter errorReporter,
String schemaURL
) throws Exception {
fErrorReporter = errorReporter;
fCurrentSchemaURL = schemaURL;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver
) throws Exception {
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public void doTraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver) throws Exception {
fNamespacesScope = new NamespacesScope(this);
fSchemaRootElement = root;
fStringPool = stringPool;
fSchemaGrammar = schemaGrammar;
fGrammarResolver = grammarResolver;
if (root == null) {
// REVISIT: Anything to do?
return;
}
//Make sure namespace binding is defaulted
String rootPrefix = root.getPrefix();
if( rootPrefix == null || rootPrefix.length() == 0 ){
String xmlns = root.getAttribute("xmlns");
if( xmlns.length() == 0 )
root.setAttribute("xmlns", SchemaSymbols.URI_SCHEMAFORSCHEMA );
}
//Retrieve the targetnamespace URI information
fTargetNSURIString = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE);
if (fTargetNSURIString==null) {
fTargetNSURIString="";
}
fTargetNSURI = fStringPool.addSymbol(fTargetNSURIString);
if (fGrammarResolver == null) {
// REVISIT: Localize
reportGenericSchemaError("Internal error: don't have a GrammarResolver for TraverseSchema");
}
else{
fSchemaGrammar.setComplexTypeRegistry(fComplexTypeRegistry);
fSchemaGrammar.setDatatypeRegistry(fDatatypeRegistry);
fSchemaGrammar.setAttributeDeclRegistry(fAttributeDeclRegistry);
fSchemaGrammar.setNamespacesScope(fNamespacesScope);
fSchemaGrammar.setTargetNamespaceURI(fTargetNSURIString);
fGrammarResolver.putGrammar(fTargetNSURIString, fSchemaGrammar);
}
// Retrived the Namespace mapping from the schema element.
NamedNodeMap schemaEltAttrs = root.getAttributes();
int i = 0;
Attr sattr = null;
boolean seenXMLNS = false;
while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) {
String attName = sattr.getName();
if (attName.startsWith("xmlns:")) {
String attValue = sattr.getValue();
String prefix = attName.substring(attName.indexOf(":")+1);
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix),
fStringPool.addSymbol(attValue) );
}
if (attName.equals("xmlns")) {
String attValue = sattr.getValue();
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(attValue) );
seenXMLNS = true;
}
}
if (!seenXMLNS && fTargetNSURIString.length() == 0 ) {
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol("") );
}
fElementDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
fAttributeDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
//REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space);
if (fTargetNSURI == StringPool.EMPTY_STRING) {
fElementDefaultQualified = true;
//fAttributeDefaultQualified = true;
}
//fScopeCount++;
fCurrentScope = -1;
checkTopLevelDuplicateNames(root);
//extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar.
extractTopLevel3Components(root);
for (Element child = XUtil.getFirstChildElement(root); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getNodeName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ELEMENT )) {
traverseElementDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
//traverseAttributeGroupDecl(child);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
traverseAttributeDecl( child, null );
} else if (name.equals( SchemaSymbols.ELT_WILDCARD) ) {
traverseWildcardDecl( child);
} else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) {
//traverseGroupDecl(child);
} else if (name.equals(SchemaSymbols.ELT_NOTATION)) {
; //TO DO
}
else if (name.equals(SchemaSymbols.ELT_INCLUDE)) {
traverseInclude(child);
}
else if (name.equals(SchemaSymbols.ELT_IMPORT)) {
traverseImport(child);
}
} // for each child node
} // traverseSchema(Element)
private void checkTopLevelDuplicateNames(Element root) {
//TO DO : !!!
}
private void extractTopLevel3Components(Element root){
for (Element child = XUtil.getFirstChildElement(root); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getNodeName();
if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
fSchemaGrammar.topLevelAttrGrpDecls.put(name, child);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
fSchemaGrammar.topLevelAttrDecls.put(name, child);
} else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) {
fSchemaGrammar.topLevelGroupDecls.put(name, child);
}
} // for each child node
}
/**
* Expands a system id and returns the system id as a URL, if
* it can be expanded. A return value of null means that the
* identifier is already expanded. An exception thrown
* indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
*
* @return Returns the URL object representing the expanded system
* identifier. A null value indicates that the given
* system identifier is already expanded.
*
*/
private String expandSystemId(String systemId, String currentSystemId) throws Exception{
String id = systemId;
// check for bad parameters id
if (id == null || id.length() == 0) {
return systemId;
}
// if id already expanded, return
try {
URL url = new URL(id);
if (url != null) {
return systemId;
}
}
catch (MalformedURLException e) {
// continue on...
}
// normalize id
id = fixURI(id);
// normalize base
URL base = null;
URL url = null;
try {
if (currentSystemId == null) {
String dir;
try {
dir = fixURI(System.getProperty("user.dir"));
}
catch (SecurityException se) {
dir = "";
}
if (!dir.endsWith("/")) {
dir = dir + "/";
}
base = new URL("file", "", dir);
}
else {
base = new URL(currentSystemId);
}
// expand id
url = new URL(base, id);
}
catch (Exception e) {
// let it go through
}
if (url == null) {
return systemId;
}
return url.toString();
}
/**
* Fixes a platform dependent filename to standard URI form.
*
* @param str The string to fix.
*
* @return Returns the fixed URI string.
*/
private static String fixURI(String str) {
// handle platform dependent strings
str = str.replace(java.io.File.separatorChar, '/');
// Windows fix
if (str.length() >= 2) {
char ch1 = str.charAt(1);
if (ch1 == ':') {
char ch0 = Character.toUpperCase(str.charAt(0));
if (ch0 >= 'A' && ch0 <= 'Z') {
str = "/" + str;
}
}
}
// done
return str;
}
private void traverseInclude(Element includeDecl) throws Exception {
//TO DO: !!!!! location needs to be resolved first.
String location = includeDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION);
location = expandSystemId(location, fCurrentSchemaURL);
if (fIncludeLocations.contains((Object)location)) {
return;
}
fIncludeLocations.addElement((Object)location);
DOMParser parser = new DOMParser() {
public void ignorableWhitespace(char ch[], int start, int length) {}
public void ignorableWhitespace(int dataIdx) {}
};
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( location);
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
//e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root != null) {
String targetNSURI = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE);
if (targetNSURI.length() > 0 && !targetNSURI.equals(fTargetNSURIString) ) {
// REVISIT: Localize
reportGenericSchemaError("included schema '"+location+"' has a different targetNameSpace '"
+targetNSURI+"'");
}
else {
boolean saveElementDefaultQualified = fElementDefaultQualified;
boolean saveAttributeDefaultQualified = fAttributeDefaultQualified;
int saveScope = fCurrentScope;
String savedSchemaURL = fCurrentSchemaURL;
Element saveRoot = fSchemaRootElement;
fSchemaRootElement = root;
fCurrentSchemaURL = location;
traverseIncludedSchema(root);
fCurrentSchemaURL = savedSchemaURL;
fCurrentScope = saveScope;
fElementDefaultQualified = saveElementDefaultQualified;
fAttributeDefaultQualified = saveAttributeDefaultQualified;
fSchemaRootElement = saveRoot;
}
}
}
private void traverseIncludedSchema(Element root) throws Exception {
// Retrived the Namespace mapping from the schema element.
NamedNodeMap schemaEltAttrs = root.getAttributes();
int i = 0;
Attr sattr = null;
boolean seenXMLNS = false;
while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) {
String attName = sattr.getName();
if (attName.startsWith("xmlns:")) {
String attValue = sattr.getValue();
String prefix = attName.substring(attName.indexOf(":")+1);
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix),
fStringPool.addSymbol(attValue) );
}
if (attName.equals("xmlns")) {
String attValue = sattr.getValue();
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(attValue) );
seenXMLNS = true;
}
}
if (!seenXMLNS && fTargetNSURIString.length() == 0 ) {
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol("") );
}
fElementDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
fAttributeDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
//REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space);
if (fTargetNSURI == StringPool.EMPTY_STRING) {
fElementDefaultQualified = true;
//fAttributeDefaultQualified = true;
}
//fScopeCount++;
fCurrentScope = -1;
checkTopLevelDuplicateNames(root);
//extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar.
extractTopLevel3Components(root);
for (Element child = XUtil.getFirstChildElement(root); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getNodeName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ELEMENT )) {
traverseElementDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
//traverseAttributeGroupDecl(child);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
traverseAttributeDecl( child, null );
} else if (name.equals( SchemaSymbols.ELT_WILDCARD) ) {
traverseWildcardDecl( child);
} else if (name.equals(SchemaSymbols.ELT_GROUP) && child.getAttribute(SchemaSymbols.ATT_REF).equals("")) {
//traverseGroupDecl(child);
} else if (name.equals(SchemaSymbols.ELT_NOTATION)) {
; //TO DO
}
else if (name.equals(SchemaSymbols.ELT_INCLUDE)) {
traverseInclude(child);
}
else if (name.equals(SchemaSymbols.ELT_IMPORT)) {
traverseImport(child);
}
} // for each child node
}
private void traverseImport(Element importDecl) throws Exception {
String location = importDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION);
location = expandSystemId(location, fCurrentSchemaURL);
String namespaceString = importDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE);
SchemaGrammar importedGrammar = new SchemaGrammar();
if (fGrammarResolver.getGrammar(namespaceString) != null) {
importedGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(namespaceString);
}
if (fImportLocations.contains((Object)location)) {
return;
}
fImportLocations.addElement((Object)location);
DOMParser parser = new DOMParser() {
public void ignorableWhitespace(char ch[], int start, int length) {}
public void ignorableWhitespace(int dataIdx) {}
};
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( location);
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root != null) {
String targetNSURI = root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE);
if (!targetNSURI.equals(namespaceString) ) {
// REVISIT: Localize
reportGenericSchemaError("imported schema '"+location+"' has a different targetNameSpace '"
+targetNSURI+"' from what is declared '"+namespaceString+"'.");
}
else
new TraverseSchema(root, fStringPool, importedGrammar, fGrammarResolver, fErrorReporter, location);
}
else {
reportGenericSchemaError("Could not get the doc root for imported Schema file: "+location);
}
}
/**
* No-op - Traverse Annotation Declaration
*
* @param comment
*/
private void traverseAnnotationDecl(Element comment) {
//TO DO
return ;
}
/**
* Traverse SimpleType declaration:
* <simpleType
* abstract = boolean
* base = QName
* derivedBy = | list | restriction : restriction
* id = ID
* name = NCName>
* Content: ( annotation? , ( minExclusive | minInclusive | maxExclusive | maxInclusive | precision | scale | length | minLength | maxLength | encoding | period | duration | enumeration | pattern )* )
* </simpleType>
*
* @param simpleTypeDecl
* @return
*/
private int traverseSimpleTypeDecl( Element simpleTypeDecl ) throws Exception {
String varietyProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY );
if (varietyProperty.length() == 0) {
varietyProperty = SchemaSymbols.ATTVAL_RESTRICTION;
}
String nameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME );
String baseTypeQNameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE );
String abstractProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT );
int newSimpleTypeName = -1;
if ( nameProperty.equals("")) { // anonymous simpleType
newSimpleTypeName = fStringPool.addSymbol(
"#S#"+fSimpleTypeAnonCount++ );
//"http://www.apache.org/xml/xerces/internalDatatype"+fSimpleTypeAnonCount++ );
} else
newSimpleTypeName = fStringPool.addSymbol( nameProperty );
int basetype;
DatatypeValidator baseValidator = null;
if( baseTypeQNameProperty!= null ) {
basetype = fStringPool.addSymbol( baseTypeQNameProperty );
String prefix = "";
String localpart = baseTypeQNameProperty;
int colonptr = baseTypeQNameProperty.indexOf(":");
if ( colonptr > 0) {
prefix = baseTypeQNameProperty.substring(0,colonptr);
localpart = baseTypeQNameProperty.substring(colonptr+1);
}
String uri = resolvePrefixToURI(prefix);
baseValidator = getDatatypeValidator(uri, localpart);
if (baseValidator == null) {
Element baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
traverseSimpleTypeDecl( baseTypeNode );
baseValidator = getDatatypeValidator(uri, localpart);
if (baseValidator == null) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ),
simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME) });
return -1;
//reportGenericSchemaError("Base type could not be found : " + baseTypeQNameProperty);
}
}
else {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ),
simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME) });
return -1;
//reportGenericSchemaError("Base type could not be found : " + baseTypeQNameProperty);
}
}
}
// Any Children if so then check Content otherwise bail out
Element content = XUtil.getFirstChildElement( simpleTypeDecl );
int numFacets = 0;
Hashtable facetData = null;
if( content != null ) {
//Content follows: ( annotation? , facets* )
//annotation ? ( 0 or 1 )
if( content.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){
traverseAnnotationDecl( content );
content = XUtil.getNextSiblingElement(content);
}
//TODO: If content is annotation again should raise validation error
// if( content.getNodeName().equal( SchemaSymbols.ELT_ANNOTATIO ) {
// throw ValidationException(); }
//
//facets * ( 0 or more )
int numEnumerationLiterals = 0;
facetData = new Hashtable();
Vector enumData = new Vector();
while (content != null) {
if (content.getNodeType() == Node.ELEMENT_NODE) {
Element facetElt = (Element) content;
numFacets++;
if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
String enumVal = facetElt.getAttribute(SchemaSymbols.ATT_VALUE);
enumData.addElement(enumVal);
//Enumerations can have annotations ? ( 0 | 1 )
Element enumContent = XUtil.getFirstChildElement( facetElt );
if( enumContent != null && enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){
traverseAnnotationDecl( content );
}
//TODO: If enumContent is encounter again should raise validation error
// enumContent.getNextSibling();
// if( enumContent.getNodeName().equal( SchemaSymbols.ELT_ANNOTATIO ) {
// throw ValidationException(); }
//
} else {
facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE ));
}
}
//content = (Element) content.getNextSibling();
content = XUtil.getNextSiblingElement(content);
}
if (numEnumerationLiterals > 0) {
facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
}
// create & register validator for "generated" type if it doesn't exist
String nameOfType = fStringPool.toString( newSimpleTypeName);
if (fTargetNSURIString.length () != 0) {
nameOfType = fTargetNSURIString+","+nameOfType;
}
try {
DatatypeValidator newValidator =
fDatatypeRegistry.getDatatypeValidator( nameOfType );
if( newValidator == null ) { // not previously registered
boolean derivedByList =
varietyProperty.equals( SchemaSymbols.ATTVAL_LIST ) ? true:false;
fDatatypeRegistry.createDatatypeValidator( nameOfType, baseValidator,
facetData, derivedByList );
}
} catch (Exception e) {
//e.printStackTrace(System.err);
reportSchemaError(SchemaMessageProvider.DatatypeError,new Object [] { e.getMessage() });
}
return fStringPool.addSymbol(nameOfType);
}
/*
* <any
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}
* processContents = lax | skip | strict>
* Content: (annotation?)
* </any>
*/
private int traverseAny(Element child) throws Exception {
int anyIndex = -1;
String namespace = child.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim();
String processContents = child.getAttribute("processContents").trim();
int processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY;
int processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER;
int processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL;
if (processContents.length() > 0 && !processContents.equals("strict")) {
if (processContents.equals("lax")) {
processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_LAX;
processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX;
processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX;
}
else if (processContents.equals("skip")) {
processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_SKIP;
processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP;
processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP;
}
}
if (namespace.length() == 0 || namespace.equals("##any")) {
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, -1, false);
}
else if (namespace.equals("##other")) {
String uri = child.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace");
int uriIndex = fStringPool.addSymbol(uri);
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyOther, -1, uriIndex, false);
}
else if (namespace.equals("##local")) {
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, -1, false);
}
else if (namespace.length() > 0) {
StringTokenizer tokenizer = new StringTokenizer(namespace);
Vector tokens = new Vector();
while (tokenizer.hasMoreElements()) {
String token = tokenizer.nextToken();
if (token.equals("##targetNamespace")) {
token = child.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace");
}
tokens.addElement(token);
}
String uri = (String)tokens.elementAt(0);
int uriIndex = fStringPool.addSymbol(uri);
int leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false);
int valueIndex = leafIndex;
int count = tokens.size();
if (count > 1) {
uri = (String)tokens.elementAt(1);
uriIndex = fStringPool.addSymbol(uri);
leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false);
int otherValueIndex = leafIndex;
int choiceIndex = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, valueIndex, otherValueIndex, false);
for (int i = 2; i < count; i++) {
uri = (String)tokens.elementAt(i);
uriIndex = fStringPool.addSymbol(uri);
leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, uriIndex, false);
otherValueIndex = leafIndex;
choiceIndex = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, choiceIndex, otherValueIndex, false);
}
anyIndex = choiceIndex;
}
else {
anyIndex = leafIndex;
}
}
else {
// REVISIT: Localize
reportGenericSchemaError("Empty namespace attribute for any element");
}
return anyIndex;
}
public DatatypeValidator getDatatypeValidator(String uri, String localpart) {
DatatypeValidator dv = null;
if (uri.length()==0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) {
dv = fDatatypeRegistry.getDatatypeValidator( localpart );
}
else {
dv = fDatatypeRegistry.getDatatypeValidator( uri+","+localpart );
}
return dv;
}
/*
* <anyAttribute
* id = ID
* namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}>
* Content: (annotation?)
* </anyAttribute>
*/
private XMLAttributeDecl traverseAnyAttribute(Element anyAttributeDecl) throws Exception {
XMLAttributeDecl anyAttDecl = new XMLAttributeDecl();
String processContents = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_PROCESSCONTENTS).trim();
String namespace = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim();
String curTargetUri = anyAttributeDecl.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace");
if ( namespace.length() == 0 || namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDANY) ) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_ANY;
}
else if (namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDOTHER)) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_OTHER;
anyAttDecl.name.uri = fStringPool.addSymbol(curTargetUri);
}
else if (namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_LOCAL;
}
else if (namespace.length() > 0){
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_LIST;
StringTokenizer tokenizer = new StringTokenizer(namespace);
int aStringList = fStringPool.startStringList();
Vector tokens = new Vector();
while (tokenizer.hasMoreElements()) {
String token = tokenizer.nextToken();
if (token.equals("##targetNamespace")) {
token = curTargetUri;
}
if (!fStringPool.addStringToList(aStringList, fStringPool.addSymbol(token))){
reportGenericSchemaError("Internal StringPool error when reading the "+
"namespace attribute for anyattribute declaration");
}
}
fStringPool.finishStringList(aStringList);
anyAttDecl.enumeration = aStringList;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Empty namespace attribute for anyattribute declaration");
}
// default processContents is "strict";
anyAttDecl.defaultType = XMLAttributeDecl.PROCESSCONTENTS_STRICT;
if (processContents.equals(SchemaSymbols.ATTVAL_SKIP)){
anyAttDecl.defaultType = XMLAttributeDecl.PROCESSCONTENTS_SKIP;
}
else if (processContents.equals(SchemaSymbols.ATTVAL_LAX)) {
anyAttDecl.defaultType = XMLAttributeDecl.PROCESSCONTENTS_LAX;
}
return anyAttDecl;
}
private XMLAttributeDecl mergeTwoAnyAttribute(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) {
if (oneAny.type == -1) {
return oneAny;
}
if (anotherAny.type == -1) {
return anotherAny;
}
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return anotherAny;
}
if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return oneAny;
}
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if ( anotherAny.name.uri == oneAny.name.uri ) {
return oneAny;
}
else {
oneAny.type = -1;
return oneAny;
}
}
else if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_LOCAL) {
return anotherAny;
}
else if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
if (!fStringPool.stringInList(anotherAny.enumeration, oneAny.name.uri) ) {
return anotherAny;
}
else {
int[] anotherAnyURIs = fStringPool.stringListAsIntArray(anotherAny.enumeration);
int newList = fStringPool.startStringList();
for (int i=0; i< anotherAnyURIs.length; i++) {
if (anotherAnyURIs[i] != oneAny.name.uri ) {
fStringPool.addStringToList(newList, anotherAnyURIs[i]);
}
}
fStringPool.finishStringList(newList);
anotherAny.enumeration = newList;
return anotherAny;
}
}
}
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LOCAL) {
if ( anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER
|| anotherAny.type == XMLAttributeDecl.TYPE_ANY_LOCAL) {
return oneAny;
}
else if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
oneAny.type = -1;
return oneAny;
}
}
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
if ( anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER){
if (!fStringPool.stringInList(oneAny.enumeration, anotherAny.name.uri) ) {
return oneAny;
}
else {
int[] oneAnyURIs = fStringPool.stringListAsIntArray(oneAny.enumeration);
int newList = fStringPool.startStringList();
for (int i=0; i< oneAnyURIs.length; i++) {
if (oneAnyURIs[i] != anotherAny.name.uri ) {
fStringPool.addStringToList(newList, oneAnyURIs[i]);
}
}
fStringPool.finishStringList(newList);
oneAny.enumeration = newList;
return oneAny;
}
}
else if ( anotherAny.type == XMLAttributeDecl.TYPE_ANY_LOCAL) {
oneAny.type = -1;
return oneAny;
}
else if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
int[] result = intersect2sets( fStringPool.stringListAsIntArray(oneAny.enumeration),
fStringPool.stringListAsIntArray(anotherAny.enumeration));
int newList = fStringPool.startStringList();
for (int i=0; i<result.length; i++) {
fStringPool.addStringToList(newList, result[i]);
}
fStringPool.finishStringList(newList);
oneAny.enumeration = newList;
return oneAny;
}
}
// should never go there;
return oneAny;
}
int[] intersect2sets(int[] one, int[] theOther){
int[] result = new int[(one.length>theOther.length?one.length:theOther.length)];
// simple implemention,
int count = 0;
for (int i=0; i<one.length; i++) {
for(int j=0; j<theOther.length; j++) {
if (one[i]==theOther[j]) {
result[count++] = one[i];
}
}
}
int[] result2 = new int[count];
System.arraycopy(result, 0, result2, 0, count);
return result2;
}
/**
* Traverse ComplexType Declaration.
*
* <complexType
* abstract = boolean
* base = QName
* block = #all or (possibly empty) subset of {extension, restriction}
* content = elementOnly | empty | mixed | textOnly
* derivedBy = extension | restriction
* final = #all or (possibly empty) subset of {extension, restriction}
* id = ID
* name = NCName>
* Content: (annotation? , (((minExclusive | minInclusive | maxExclusive
* | maxInclusive | precision | scale | length | minLength
* | maxLength | encoding | period | duration | enumeration
* | pattern)* | (element | group | all | choice | sequence | any)*) ,
* ((attribute | attributeGroup)* , anyAttribute?)))
* </complexType>
* @param complexTypeDecl
* @return
*/
//REVISIT: TO DO, base and derivation ???
private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception {
String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT );
String base = complexTypeDecl.getAttribute(SchemaSymbols.ATT_BASE);
String blockSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_BLOCK );
String content = complexTypeDecl.getAttribute(SchemaSymbols.ATT_CONTENT);
String derivedBy = complexTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY );
String finalSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_FINAL );
String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID );
String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME);
boolean isNamedType = false;
if ( DEBUGGING )
System.out.println("traversing complex Type : " + typeName +","+base+","+content+".");
if (typeName.equals("")) { // gensym a unique name
//typeName = "http://www.apache.org/xml/xerces/internalType"+fTypeCount++;
typeName = "#"+fAnonTypeCount++;
}
else {
fCurrentTypeNameStack.push(typeName);
isNamedType = true;
}
if (isTopLevel(complexTypeDecl)) {
String fullName = fTargetNSURIString+","+typeName;
ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName);
if (temp != null ) {
return fStringPool.addSymbol(fullName);
}
}
int scopeDefined = fScopeCount++;
int previousScope = fCurrentScope;
fCurrentScope = scopeDefined;
Element child = null;
int contentSpecType = -1;
int csnType = 0;
int left = -2;
int right = -2;
ComplexTypeInfo baseTypeInfo = null; //if base is a complexType;
DatatypeValidator baseTypeValidator = null; //if base is a simple type or a complex type derived from a simpleType
DatatypeValidator simpleTypeValidator = null;
int baseTypeSymbol = -1;
String fullBaseName = "";
boolean baseIsSimpleSimple = false;
boolean baseIsComplexSimple = false;
boolean derivedByRestriction = true;
boolean derivedByExtension = false;
int baseContentSpecHandle = -1;
Element baseTypeNode = null;
//int parsedderivedBy = parseComplexDerivedBy(derivedBy);
//handle the inhreitance here.
if (base.length()>0) {
//first check if derivedBy is present
if (derivedBy.length() == 0) {
// REVISIT: Localize
reportGenericSchemaError("derivedBy must be present when base is present in "
+SchemaSymbols.ELT_COMPLEXTYPE
+" "+ typeName);
}
else {
if (derivedBy.equals(SchemaSymbols.ATTVAL_EXTENSION)) {
derivedByRestriction = false;
}
String prefix = "";
String localpart = base;
int colonptr = base.indexOf(":");
if ( colonptr > 0) {
prefix = base.substring(0,colonptr);
localpart = base.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String typeURI = resolvePrefixToURI(prefix);
// check if the base type is from the same Schema;
if ( ! typeURI.equals(fTargetNSURIString)
&& ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0 ) /*REVISIT, !!!! a hack: for schema that has no target namespace, e.g. personal-schema.xml*/{
baseTypeInfo = getTypeInfoFromNS(typeURI, localpart);
if (baseTypeInfo == null) {
baseTypeValidator = getTypeValidatorFromNS(typeURI, localpart);
if (baseTypeValidator == null) {
//TO DO: report error here;
System.out.println("Could not find base type " +localpart
+ " in schema " + typeURI);
}
else{
baseIsSimpleSimple = true;
}
}
}
else {
fullBaseName = typeURI+","+localpart;
// assume the base is a complexType and try to locate the base type first
baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName);
// if not found, 2 possibilities: 1: ComplexType in question has not been compiled yet;
// 2: base is SimpleTYpe;
if (baseTypeInfo == null) {
baseTypeValidator = getDatatypeValidator(typeURI, localpart);
if (baseTypeValidator == null) {
baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode );
baseTypeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol)); //REVISIT: should it be fullBaseName;
}
else {
baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode );
simpleTypeValidator = baseTypeValidator = getDatatypeValidator(typeURI, localpart);
if (simpleTypeValidator == null) {
//TO DO: signal error here.
}
baseIsSimpleSimple = true;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Base type could not be found : " + base);
}
}
}
else {
simpleTypeValidator = baseTypeValidator;
baseIsSimpleSimple = true;
}
}
}
//Schema Spec : 5.11: Complex Type Definition Properties Correct : 2
if (baseIsSimpleSimple && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("base is a simpledType, can't derive by restriction in " + typeName);
}
//if the base is a complexType
if (baseTypeInfo != null ) {
//Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1
// 5.11: Derivation Valid ( Restriction, Complex ) 1.2.1
if (derivedByRestriction) {
//REVISIT: check base Type's finalset does not include "restriction"
}
else {
//REVISIT: check base Type's finalset doest not include "extension"
}
if ( baseTypeInfo.contentSpecHandle > -1) {
if (derivedByRestriction) {
//REVISIT: !!! really hairy staff to check the particle derivation OK in 5.10
checkParticleDerivationOK(complexTypeDecl, baseTypeNode);
}
baseContentSpecHandle = baseTypeInfo.contentSpecHandle;
}
else if ( baseTypeInfo.datatypeValidator != null ) {
baseTypeValidator = baseTypeInfo.datatypeValidator;
baseIsComplexSimple = true;
}
}
//Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1
if (baseIsComplexSimple && !derivedByRestriction ) {
// REVISIT: Localize
reportGenericSchemaError("base is ComplexSimple, can't derive by extension in " + typeName);
}
} // END of if (derivedBy.length() == 0) {} else {}
} // END of if (base.length() > 0) {}
// skip refinement and annotations
child = null;
if (baseIsComplexSimple) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
int numEnumerationLiterals = 0;
int numFacets = 0;
Hashtable facetData = new Hashtable();
Vector enumData = new Vector();
//REVISIT: there is a better way to do this,
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null && (child.getNodeName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MININCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_PRECISION) ||
child.getNodeName().equals(SchemaSymbols.ELT_SCALE) ||
child.getNodeName().equals(SchemaSymbols.ELT_LENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_MINLENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXLENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_ENCODING) ||
child.getNodeName().equals(SchemaSymbols.ELT_PERIOD) ||
child.getNodeName().equals(SchemaSymbols.ELT_DURATION) ||
child.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION) ||
child.getNodeName().equals(SchemaSymbols.ELT_PATTERN) ||
child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION));
child = XUtil.getNextSiblingElement(child))
{
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element facetElt = (Element) child;
numFacets++;
if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE));
//Enumerations can have annotations ? ( 0 | 1 )
Element enumContent = XUtil.getFirstChildElement( facetElt );
if( enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){
traverseAnnotationDecl( child );
}
// TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over
} else {
facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE ));
}
}
}
if (numEnumerationLiterals > 0) {
facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
//if (numFacets > 0)
// baseTypeValidator.setFacets(facetData, derivedBy );
if (numFacets > 0) {
simpleTypeValidator = fDatatypeRegistry.createDatatypeValidator( typeName, baseTypeValidator,
facetData, false );
}
else
simpleTypeValidator = baseTypeValidator;
if (child != null) {
// REVISIT: Localize
reportGenericSchemaError("Invalid child '"+child.getNodeName()+"' in complexType : '" + typeName
+ "', because it restricts another complexSimpleType");
}
}
// if content = textonly, base is a datatype
if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) {
//TO DO
if (base.length() == 0) {
simpleTypeValidator = baseTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING);
}
else if ( baseTypeValidator == null
&& baseTypeInfo != null && baseTypeInfo.datatypeValidator==null ) // must be datatype
reportSchemaError(SchemaMessageProvider.NotADatatype,
new Object [] { base }); //REVISIT check forward refs
//handle datatypes
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
/****
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF,
fStringPool.addSymbol(base),
-1, false);
/****/
}
else {
if (!baseIsComplexSimple) {
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
}
csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
boolean mixedContent = false;
//REVISIT: is the default content " elementOnly"
boolean elementContent = true;
boolean textContent = false;
boolean emptyContent = false;
left = -2;
right = -2;
boolean hadContent = false;
if (content.equals(SchemaSymbols.ATTVAL_EMPTY)) {
contentSpecType = XMLElementDecl.TYPE_EMPTY;
emptyContent = true;
elementContent = false;
left = -1; // no contentSpecNode needed
} else if (content.equals(SchemaSymbols.ATTVAL_MIXED) ) {
contentSpecType = XMLElementDecl.TYPE_MIXED;
mixedContent = true;
elementContent = false;
csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
} else if (content.equals(SchemaSymbols.ATTVAL_ELEMENTONLY) || content.equals("")) {
elementContent = true;
} else if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) {
textContent = true;
elementContent = false;
}
if (mixedContent) {
// add #PCDATA leaf
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF,
-1, // -1 means "#PCDATA" is name
-1, false);
csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
}
boolean seeParticle = false;
boolean seeOtherParticle = false;
boolean seeAll = false;
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2; // to save the particle's contentSpec handle
hadContent = true;
seeParticle = false;
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
if (mixedContent || elementContent) {
if ( DEBUGGING )
System.out.println(" child element name " + child.getAttribute(SchemaSymbols.ATT_NAME));
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
seeOtherParticle = true;
}
else {
reportSchemaError(SchemaMessageProvider.EltRefOnlyInMixedElemOnly, null);
}
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
seeParticle = true;
seeAll = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE) ||
childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
break; // attr processing is done later on in this method
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANNOTATION)) {
//REVISIT, do nothing for annotation for now.
}
else if (childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE)) {
break;
//REVISIT, do nothing for attribute wildcard for now.
}
else { // datatype qual
if (!baseIsComplexSimple )
if (base.equals(""))
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "unrecogized child '"+childName+"' in compelx type "+typeName });
else
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "unrecogized child '"+childName+"' in compelx type '"+typeName+"' with base "+base });
}
// if base is complextype with simpleType content, can't have any particle children at all.
if (baseIsComplexSimple && seeParticle) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+", base type is complextype with simpleType content, can't have any particle children at all");
hadContent = false;
left = index = -2;
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
break;
}
// check the minOccurs and maxOccurs of the particle, and fix the
// contentspec accordingly
if (seeParticle) {
index = expandContentModel(index, child);
} //end of if (seeParticle)
if (seeAll && seeOtherParticle) {
// REVISIT: Localize
reportGenericSchemaError ( " 'All' group needs to be the only child in Complextype : " + typeName);
}
if (seeAll) {
//TO DO: REVISIT
//check the minOccurs = 1 and maxOccurs = 1
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
} //end looping through the children
if ( ! ( seeOtherParticle || seeAll ) && (elementContent || mixedContent)
- && (base.length() == 0 || ( base.length() > 0 && derivedByRestriction)) ) {
+ && (base.length() == 0 || ( base.length() > 0 && derivedByRestriction && !baseIsComplexSimple)) ) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
simpleTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING);
// REVISIT: Localize
reportGenericSchemaError ( " complexType '"+typeName+"' with a elementOnly or mixed content "
+"need to have at least one particle child");
}
if (hadContent && right != -2)
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
if (mixedContent && hadContent) {
// set occurrence count
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE,
left, -1, false);
}
}
// if derived by extension and base complextype has a content model,
// compose the final content model by concatenating the base and the
// current in sequence.
if (!derivedByRestriction && baseContentSpecHandle > -1 ) {
if (left == -2) {
left = baseContentSpecHandle;
}
else
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
baseContentSpecHandle,
left,
false);
}
// REVISIT: this is when sees a topelevel <complexType name="abc">attrs*</complexType>
if (content.length() == 0 && base.length() == 0 && left == -2) {
contentSpecType = XMLElementDecl.TYPE_ANY;
}
if (content.length() == 0 && simpleTypeValidator == null && left == -2 ) {
if (base.length() > 0 && baseTypeInfo != null
&& baseTypeInfo.contentType == XMLElementDecl.TYPE_EMPTY) {
contentSpecType = XMLElementDecl.TYPE_EMPTY;
}
}
if ( DEBUGGING )
System.out.println("!!!!!>>>>>" + typeName+", "+ baseTypeInfo + ", "
+ baseContentSpecHandle +", " + left +", "+scopeDefined);
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
typeInfo.baseComplexTypeInfo = baseTypeInfo;
typeInfo.baseDataTypeValidator = baseTypeValidator;
int derivedByInt = -1;
if (derivedBy.length() > 0) {
derivedByInt = parseComplexDerivedBy(derivedBy);
}
typeInfo.derivedBy = derivedByInt;
typeInfo.scopeDefined = scopeDefined;
typeInfo.contentSpecHandle = left;
typeInfo.contentType = contentSpecType;
typeInfo.datatypeValidator = simpleTypeValidator;
typeInfo.blockSet = parseBlockSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_BLOCK));
typeInfo.finalSet = parseFinalSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_FINAL));
typeInfo.isAbstract = isAbstract.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false ;
//add a template element to the grammar element decl pool.
int typeNameIndex = fStringPool.addSymbol(typeName);
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex =
fSchemaGrammar.addElementDecl(new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==-1) ? -1 : fCurrentScope, scopeDefined,
contentSpecType, left,
-1, simpleTypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex);
// (attribute | attrGroupRef)*
XMLAttributeDecl attWildcard = null;
Vector anyAttDecls = new Vector();
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) {
if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+
", base type has simpleType "+
"content and derivation method is"+
" 'restriction', can't have any "+
"attribute children at all");
break;
}
traverseAttributeDecl(child, typeInfo);
}
else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+", base "+
"type has simpleType content and "+
"derivation method is 'restriction',"+
" can't have any attribute children at all");
break;
}
traverseAttributeGroupDecl(child,typeInfo,anyAttDecls);
}
else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
attWildcard = traverseAnyAttribute(child);
}
}
if (attWildcard != null) {
XMLAttributeDecl fromGroup = null;
final int count = anyAttDecls.size();
if ( count > 0) {
fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0);
for (int i=1; i<count; i++) {
fromGroup = mergeTwoAnyAttribute(fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i));
}
}
if (fromGroup != null) {
int saveProcessContents = attWildcard.defaultType;
attWildcard = mergeTwoAnyAttribute(attWildcard, fromGroup);
attWildcard.defaultType = saveProcessContents;
}
}
else {
//REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case
}
// merge in base type's attribute decls
XMLAttributeDecl baseAttWildcard = null;
if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) {
int attDefIndex = baseTypeInfo.attlistHead;
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
fSchemaGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) {
if (attWildcard == null) {
baseAttWildcard = fTempAttributeDecl;
}
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
// if found a duplicate, if it is derived by restriction. then skip the one from the base type
/**/
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name);
if ( temp > -1) {
if (derivedByRestriction) {
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
}
/**/
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
fTempAttributeDecl.name, fTempAttributeDecl.type,
fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType,
fTempAttributeDecl.defaultValue,
fTempAttributeDecl.datatypeValidator,
fTempAttributeDecl.list);
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
// att wildcard will inserted after all attributes were processed
if (attWildcard != null) {
if (attWildcard.type != -1) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attWildcard.name, attWildcard.type,
attWildcard.enumeration, attWildcard.defaultType,
attWildcard.defaultValue,
attWildcard.datatypeValidator,
attWildcard.list);
}
else {
//REVISIT: unclear in Schema spec if should report error here.
}
}
else if (baseAttWildcard != null) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
baseAttWildcard.name, baseAttWildcard.type,
baseAttWildcard.enumeration, baseAttWildcard.defaultType,
baseAttWildcard.defaultValue,
baseAttWildcard.datatypeValidator,
baseAttWildcard.list);
}
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex);
if (!typeName.startsWith("#")) {
typeName = fTargetNSURIString + "," + typeName;
}
typeInfo.typeName = new String(typeName);
if ( DEBUGGING )
System.out.println("add complex Type to Registry: " + typeName +","+content+".");
fComplexTypeRegistry.put(typeName,typeInfo);
// before exit the complex type definition, restore the scope, mainly for nested Anonymous Types
fCurrentScope = previousScope;
if (isNamedType) {
fCurrentTypeNameStack.pop();
checkRecursingComplexType();
}
//set template element's typeInfo
fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo);
typeNameIndex = fStringPool.addSymbol(typeName);
return typeNameIndex;
} // end of method: traverseComplexTypeDecl
private void checkRecursingComplexType() throws Exception {
if ( fCurrentTypeNameStack.empty() ) {
if (! fElementRecurseComplex.isEmpty() ) {
Enumeration e = fElementRecurseComplex.keys();
while( e.hasMoreElements() ) {
QName nameThenScope = (QName) e.nextElement();
String typeName = (String) fElementRecurseComplex.get(nameThenScope);
int eltUriIndex = nameThenScope.uri;
int eltNameIndex = nameThenScope.localpart;
int enclosingScope = nameThenScope.prefix;
ComplexTypeInfo typeInfo =
(ComplexTypeInfo) fComplexTypeRegistry.get(fTargetNSURIString+","+typeName);
if (typeInfo==null) {
throw new Exception ( "Internal Error in void checkRecursingComplexType(). " );
}
else {
int elementIndex = fSchemaGrammar.addElementDecl(new QName(-1, eltNameIndex, eltNameIndex, eltUriIndex),
enclosingScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle,
typeInfo.attlistHead,
typeInfo.datatypeValidator);
fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo);
}
}
fElementRecurseComplex.clear();
}
}
}
private void checkParticleDerivationOK(Element derivedTypeNode, Element baseTypeNode) {
//TO DO: !!!
}
private int expandContentModel ( int index, Element particle) throws Exception {
String minOccurs = particle.getAttribute(SchemaSymbols.ATT_MINOCCURS);
String maxOccurs = particle.getAttribute(SchemaSymbols.ATT_MAXOCCURS);
int min=1, max=1;
if (minOccurs.equals("")) {
minOccurs = "1";
}
if (maxOccurs.equals("") ){
if ( minOccurs.equals("0")) {
maxOccurs = "1";
}
else {
maxOccurs = minOccurs;
}
}
int leafIndex = index;
//REVISIT: !!! minoccurs, maxoccurs.
if (minOccurs.equals("1")&& maxOccurs.equals("1")) {
}
else if (minOccurs.equals("0")&& maxOccurs.equals("1")) {
//zero or one
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE,
index,
-1,
false);
}
else if (minOccurs.equals("0")&& maxOccurs.equals("unbounded")) {
//zero or more
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE,
index,
-1,
false);
}
else if (minOccurs.equals("1")&& maxOccurs.equals("unbounded")) {
//one or more
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE,
index,
-1,
false);
}
else if (maxOccurs.equals("unbounded") ) {
// >=2 or more
try {
min = Integer.parseInt(minOccurs);
}
catch (Exception e) {
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "illegal value for minOccurs : '" +e.getMessage()+ "' " });
}
if (min<2) {
//REVISIT: report Error here
}
// => a,a,..,a+
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE,
index,
-1,
false);
for (int i=0; i < (min-1); i++) {
index = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
leafIndex,
index,
false);
}
}
else {
// {n,m} => a,a,a,...(a),(a),...
try {
min = Integer.parseInt(minOccurs);
max = Integer.parseInt(maxOccurs);
}
catch (Exception e){
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "});
}
if (min==0) {
int optional = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE,
leafIndex,
-1,
false);
index = optional;
for (int i=0; i < (max-min-1); i++) {
index = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
index,
optional,
false);
}
}
else {
for (int i=0; i<(min-1); i++) {
index = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
index,
leafIndex,
false);
}
int optional = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE,
leafIndex,
-1,
false);
for (int i=0; i < (max-min); i++) {
index = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
index,
optional,
false);
}
}
}
return index;
}
/**
* Traverses Schema attribute declaration.
*
* <attribute
* form = qualified | unqualified
* id = ID
* name = NCName
* ref = QName
* type = QName
* use = default | fixed | optional | prohibited | required
* value = string>
* Content: (annotation? , simpleType?)
* <attribute/>
*
* @param attributeDecl
* @return
* @exception Exception
*/
private int traverseAttributeDecl( Element attrDecl, ComplexTypeInfo typeInfo ) throws Exception {
String attNameStr = attrDecl.getAttribute(SchemaSymbols.ATT_NAME);
int attName = fStringPool.addSymbol(attNameStr);// attribute name
String isQName = attrDecl.getAttribute(SchemaSymbols.ATT_FORM);//form attribute
DatatypeValidator dv = null;
// attribute type
int attType = -1;
boolean attIsList = false;
int dataTypeSymbol = -1;
String ref = attrDecl.getAttribute(SchemaSymbols.ATT_REF);
String datatype = attrDecl.getAttribute(SchemaSymbols.ATT_TYPE);
String localpart = null;
if (!ref.equals("")) {
if (XUtil.getFirstChildElement(attrDecl) != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
String prefix = "";
localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo);
return -1;
// TO DO
// REVISIT: different NS, not supported yet.
// REVISIT: Localize
//reportGenericSchemaError("Feature not supported: see an attribute from different NS");
}
Element referredAttribute = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTE,localpart);
if (referredAttribute != null) {
traverseAttributeDecl(referredAttribute, typeInfo);
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Couldn't find top level attribute " + ref);
}
return -1;
}
if (datatype.equals("")) {
Element child = XUtil.getFirstChildElement(attrDecl);
while (child != null &&
!child.getNodeName().equals(SchemaSymbols.ELT_SIMPLETYPE))
child = XUtil.getNextSiblingElement(child);
if (child != null && child.getNodeName().equals(SchemaSymbols.ELT_SIMPLETYPE)) {
attType = XMLAttributeDecl.TYPE_SIMPLE;
dataTypeSymbol = traverseSimpleTypeDecl(child);
localpart = fStringPool.toString(dataTypeSymbol);
}
else {
attType = XMLAttributeDecl.TYPE_SIMPLE;
localpart = "string";
dataTypeSymbol = fStringPool.addSymbol(localpart);
}
localpart = fStringPool.toString(dataTypeSymbol);
dv = fDatatypeRegistry.getDatatypeValidator(localpart);
} else {
String prefix = "";
localpart = datatype;
dataTypeSymbol = fStringPool.addSymbol(localpart);
int colonptr = datatype.indexOf(":");
if ( colonptr > 0) {
prefix = datatype.substring(0,colonptr);
localpart = datatype.substring(colonptr+1);
}
String typeURI = resolvePrefixToURI(prefix);
if ( typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
|| typeURI.length()==0) {
dv = getDatatypeValidator("", localpart);
if (localpart.equals("ID")) {
attType = XMLAttributeDecl.TYPE_ID;
} else if (localpart.equals("IDREF")) {
attType = XMLAttributeDecl.TYPE_IDREF;
} else if (localpart.equals("IDREFS")) {
attType = XMLAttributeDecl.TYPE_IDREF;
attIsList = true;
} else if (localpart.equals("ENTITY")) {
attType = XMLAttributeDecl.TYPE_ENTITY;
} else if (localpart.equals("ENTITIES")) {
attType = XMLAttributeDecl.TYPE_ENTITY;
attIsList = true;
} else if (localpart.equals("NMTOKEN")) {
attType = XMLAttributeDecl.TYPE_NMTOKEN;
} else if (localpart.equals("NMTOKENS")) {
attType = XMLAttributeDecl.TYPE_NMTOKEN;
attIsList = true;
} else if (localpart.equals(SchemaSymbols.ELT_NOTATION)) {
attType = XMLAttributeDecl.TYPE_NOTATION;
}
else {
attType = XMLAttributeDecl.TYPE_SIMPLE;
if (dv == null && typeURI.length() == 0) {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}else {
// REVISIT: Localize
reportGenericSchemaError("simpleType not found : " + localpart);
}
}
}
} else {
// check if the type is from the same Schema
dv = getDatatypeValidator(typeURI, localpart);
if (dv == null && typeURI.equals(fTargetNSURIString) ) {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}else {
// REVISIT: Localize
reportGenericSchemaError("simpleType not found : " + localpart);
}
}
attType = XMLAttributeDecl.TYPE_SIMPLE;
}
}
// attribute default type
int attDefaultType = -1;
int attDefaultValue = -1;
String use = attrDecl.getAttribute(SchemaSymbols.ATT_USE);
boolean required = use.equals(SchemaSymbols.ATTVAL_REQUIRED);
if (dv == null) {
// REVISIT: Localize
reportGenericSchemaError("could not resolve the type or get a null validator for datatype : "
+ fStringPool.toString(dataTypeSymbol));
}
if (required) {
attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
} else {
if (use.equals(SchemaSymbols.ATTVAL_FIXED)) {
String fixed = attrDecl.getAttribute(SchemaSymbols.ATT_VALUE);
if (!fixed.equals("")) {
attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_FIXED;
attDefaultValue = fStringPool.addString(fixed);
}
}
else if (use.equals(SchemaSymbols.ATTVAL_DEFAULT)) {
// attribute default value
String defaultValue = attrDecl.getAttribute(SchemaSymbols.ATT_VALUE);
if (!defaultValue.equals("")) {
attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_DEFAULT;
attDefaultValue = fStringPool.addString(defaultValue);
}
}
else if (use.equals(SchemaSymbols.ATTVAL_PROHIBITED)) {
//REVISIT, TO DO. !!!
attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_IMPLIED;
//attDefaultValue = fStringPool.addString("");
}
else {
attDefaultType = XMLAttributeDecl.DEFAULT_TYPE_IMPLIED;
} // check default value is valid for the datatype.
if (attType == XMLAttributeDecl.TYPE_SIMPLE && attDefaultValue != -1) {
try {
if (dv != null)
//REVISIT
dv.validate(fStringPool.toString(attDefaultValue), null);
else
reportSchemaError(SchemaMessageProvider.NoValidatorFor,
new Object [] { datatype });
} catch (InvalidDatatypeValueException idve) {
reportSchemaError(SchemaMessageProvider.IncorrectDefaultType,
new Object [] { attrDecl.getAttribute(SchemaSymbols.ATT_NAME), idve.getMessage() });
} catch (Exception e) {
e.printStackTrace();
System.out.println("Internal error in attribute datatype validation");
}
}
}
int uriIndex = -1;
if ( isQName.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fAttributeDefaultQualified || isTopLevel(attrDecl) ) {
uriIndex = fTargetNSURI;
}
QName attQName = new QName(-1,attName,attName,uriIndex);
if ( DEBUGGING )
System.out.println(" the dataType Validator for " + fStringPool.toString(attName) + " is " + dv);
//put the top-levels in the attribute decl registry.
if (isTopLevel(attrDecl)) {
fTempAttributeDecl.datatypeValidator = dv;
fTempAttributeDecl.name.setValues(attQName);
fTempAttributeDecl.type = attType;
fTempAttributeDecl.defaultType = attDefaultType;
fTempAttributeDecl.list = attIsList;
if (attDefaultValue != -1 ) {
fTempAttributeDecl.defaultValue = new String(fStringPool.toString(attDefaultValue));
}
fAttributeDeclRegistry.put(attNameStr, new XMLAttributeDecl(fTempAttributeDecl));
}
// add attribute to attr decl pool in fSchemaGrammar,
if (typeInfo != null) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attQName, attType,
dataTypeSymbol, attDefaultType,
fStringPool.toString( attDefaultValue), dv, attIsList);
}
return -1;
} // end of method traverseAttribute
private int addAttributeDeclFromAnotherSchema( String name, String uriStr, ComplexTypeInfo typeInfo) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #addAttributeDeclFromAnotherSchema, schema uri : " + uriStr);
return -1;
}
Hashtable attrRegistry = aGrammar.getAttirubteDeclRegistry();
if (attrRegistry == null) {
// REVISIT: Localize
reportGenericSchemaError("no attribute was defined in schema : " + uriStr);
return -1;
}
XMLAttributeDecl tempAttrDecl = (XMLAttributeDecl) attrRegistry.get(name);
if (tempAttrDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
if (typeInfo!= null) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
tempAttrDecl.name, tempAttrDecl.type,
-1, tempAttrDecl.defaultType,
tempAttrDecl.defaultValue,
tempAttrDecl.datatypeValidator,
tempAttrDecl.list);
}
return 0;
}
/*
*
* <attributeGroup
* id = ID
* name = NCName
* ref = QName>
* Content: (annotation?, (attribute|attributeGroup), anyAttribute?)
* </>
*
*/
private int traverseAttributeGroupDecl( Element attrGrpDecl, ComplexTypeInfo typeInfo, Vector anyAttDecls ) throws Exception {
// attribute name
int attGrpName = fStringPool.addSymbol(attrGrpDecl.getAttribute(SchemaSymbols.ATT_NAME));
String ref = attrGrpDecl.getAttribute(SchemaSymbols.ATT_REF);
// attribute type
int attType = -1;
int enumeration = -1;
if (!ref.equals("")) {
if (XUtil.getFirstChildElement(attrGrpDecl) != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
traverseAttributeGroupDeclFromAnotherSchema(localpart, uriStr, typeInfo, anyAttDecls);
return -1;
// TO DO
// REVISIST: different NS, not supported yet.
// REVISIT: Localize
//reportGenericSchemaError("Feature not supported: see an attribute from different NS");
}
Element referredAttrGrp = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTEGROUP,localpart);
if (referredAttrGrp != null) {
traverseAttributeGroupDecl(referredAttrGrp, typeInfo, anyAttDecls);
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Couldn't find top level attributegroup " + ref);
}
return -1;
}
for ( Element child = XUtil.getFirstChildElement(attrGrpDecl);
child != null ; child = XUtil.getNextSiblingElement(child)) {
if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){
traverseAttributeDecl(child, typeInfo);
}
else if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
traverseAttributeGroupDecl(child, typeInfo,anyAttDecls);
}
else if ( child.getNodeName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
anyAttDecls.addElement(traverseAnyAttribute(child));
break;
}
else if (child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION) ) {
// REVISIT: what about appInfo
}
}
return -1;
} // end of method traverseAttributeGroup
private int traverseAttributeGroupDeclFromAnotherSchema( String attGrpName , String uriStr,
ComplexTypeInfo typeInfo,
Vector anyAttDecls ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar == null || ! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseAttributeGroupDeclFromAnotherSchema, schema uri : " + uriStr);
return -1;
}
// attribute name
Element attGrpDecl = (Element) aGrammar.topLevelAttrGrpDecls.get((Object)attGrpName);
if (attGrpDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute group named \"" + attGrpName
+ "\" was defined in schema : " + uriStr);
return -1;
}
NamespacesScope saveNSMapping = fNamespacesScope;
int saveTargetNSUri = fTargetNSURI;
fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI());
fNamespacesScope = aGrammar.getNamespacesScope();
// attribute type
int attType = -1;
int enumeration = -1;
for ( Element child = XUtil.getFirstChildElement(attGrpDecl);
child != null ; child = XUtil.getNextSiblingElement(child)) {
//child attribute couldn't be a top-level attribute DEFINITION,
if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){
String childAttName = child.getAttribute(SchemaSymbols.ATT_NAME);
if ( childAttName.length() > 0 ) {
Hashtable attDeclRegistry = aGrammar.getAttirubteDeclRegistry();
if (attDeclRegistry != null) {
if (attDeclRegistry.get((Object)childAttName) != null ){
addAttributeDeclFromAnotherSchema(childAttName, uriStr, typeInfo);
return -1;
}
}
}
else
traverseAttributeDecl(child, typeInfo);
}
else if ( child.getNodeName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
traverseAttributeGroupDecl(child, typeInfo, anyAttDecls);
}
else if ( child.getNodeName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
anyAttDecls.addElement(traverseAnyAttribute(child));
break;
}
else if (child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION) ) {
// REVISIT: what about appInfo
}
}
fNamespacesScope = saveNSMapping;
fTargetNSURI = saveTargetNSUri;
return -1;
} // end of method traverseAttributeGroupFromAnotherSchema
/**
* Traverse element declaration:
* <element
* abstract = boolean
* block = #all or (possibly empty) subset of {equivClass, extension, restriction}
* default = string
* equivClass = QName
* final = #all or (possibly empty) subset of {extension, restriction}
* fixed = string
* form = qualified | unqualified
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* nullable = boolean
* ref = QName
* type = QName>
* Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*)
* </element>
*
*
* The following are identity-constraint definitions
* <unique
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </unique>
*
* <key
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </key>
*
* <keyref
* id = ID
* name = NCName
* refer = QName>
* Content: (annotation? , (selector , field+))
* </keyref>
*
* <selector>
* Content: XPathExprApprox : An XPath expression
* </selector>
*
* <field>
* Content: XPathExprApprox : An XPath expression
* </field>
*
*
* @param elementDecl
* @return
* @exception Exception
*/
private QName traverseElementDecl(Element elementDecl) throws Exception {
int contentSpecType = -1;
int contentSpecNodeIndex = -1;
int typeNameIndex = -1;
int scopeDefined = -2; //signal a error if -2 gets gets through
//cause scope can never be -2.
DatatypeValidator dv = null;
String name = elementDecl.getAttribute(SchemaSymbols.ATT_NAME);
if ( DEBUGGING )
System.out.println("traversing element decl : " + name );
String ref = elementDecl.getAttribute(SchemaSymbols.ATT_REF);
String type = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE);
String minOccurs = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS);
String maxOccurs = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS);
String dflt = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT);
String fixed = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED);
String equivClass = elementDecl.getAttribute(SchemaSymbols.ATT_EQUIVCLASS);
// form attribute
String isQName = elementDecl.getAttribute(SchemaSymbols.ATT_FORM);
String fromAnotherSchema = null;
if (isTopLevel(elementDecl)) {
int nameIndex = fStringPool.addSymbol(name);
int eltKey = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, nameIndex,TOP_LEVEL_SCOPE);
if (eltKey > -1 ) {
return new QName(-1,nameIndex,nameIndex,fTargetNSURI);
}
}
// parse out 'block', 'final', 'nullable', 'abstract'
int blockSet = parseBlockSet(elementDecl.getAttribute(SchemaSymbols.ATT_BLOCK));
int finalSet = parseFinalSet(elementDecl.getAttribute(SchemaSymbols.ATT_FINAL));
boolean isNullable = elementDecl.getAttribute
(SchemaSymbols.ATT_NULLABLE).equals(SchemaSymbols.ATTVAL_TRUE)? true:false;
boolean isAbstract = elementDecl.getAttribute
(SchemaSymbols.ATT_ABSTRACT).equals(SchemaSymbols.ATTVAL_TRUE)? true:false;
int elementMiscFlags = 0;
if (isNullable) {
elementMiscFlags += SchemaSymbols.NULLABLE;
}
if (isAbstract) {
elementMiscFlags += SchemaSymbols.ABSTRACT;
}
//if this is a reference to a global element
int attrCount = 0;
if (!ref.equals("")) attrCount++;
if (!type.equals("")) attrCount++;
//REVISIT top level check for ref & archref
if (attrCount > 1)
reportSchemaError(SchemaMessageProvider.OneOfTypeRefArchRef, null);
if (!ref.equals("")) {
if (XUtil.getFirstChildElement(elementDecl) != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String uriString = resolvePrefixToURI(prefix);
QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1,
localpartIndex,
fStringPool.addSymbol(ref),
uriString != null ? fStringPool.addSymbol(uriString) : -1);
//if from another schema, just return the element QName
if (! uriString.equals(fTargetNSURIString) ) {
return eltName;
}
int elementIndex = fSchemaGrammar.getElementDeclIndex(eltName, TOP_LEVEL_SCOPE);
//if not found, traverse the top level element that if referenced
if (elementIndex == -1 ) {
Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart);
if (targetElement == null ) {
// REVISIT: Localize
reportGenericSchemaError("Element " + localpart + " not found in the Schema");
//REVISIT, for now, the QName anyway
return eltName;
//return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString));
}
else {
// do nothing here, other wise would cause infinite loop for
// <element name="recur"><complexType><element ref="recur"> ...
//eltName= traverseElementDecl(targetElement);
}
}
return eltName;
}
// Handle the equivClass
Element equivClassElementDecl = null;
int equivClassElementDeclIndex = -1;
boolean noErrorSoFar = true;
String equivClassUri = null;
String equivClassLocalpart = null;
String equivClassFullName = null;
ComplexTypeInfo equivClassEltTypeInfo = null;
DatatypeValidator equivClassEltDV = null;
if ( equivClass.length() > 0 ) {
equivClassUri = resolvePrefixToURI(getPrefix(equivClass));
equivClassLocalpart = getLocalPart(equivClass);
equivClassFullName = equivClassUri+","+equivClassLocalpart;
if ( !equivClassUri.equals(fTargetNSURIString) ) {
equivClassEltTypeInfo = getElementDeclTypeInfoFromNS(equivClassUri, equivClassLocalpart);
if (equivClassEltTypeInfo == null) {
equivClassEltDV = getElementDeclTypeValidatorFromNS(equivClassUri, equivClassLocalpart);
if (equivClassEltDV == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type for element '" +equivClassLocalpart
+ "' in schema '" + equivClassUri+"'");
}
}
}
else {
equivClassElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, equivClassLocalpart);
if (equivClassElementDecl == null) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("Equivclass affiliation element "
+equivClass
+" in element declaration "
+name);
}
else {
equivClassElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(equivClass),TOP_LEVEL_SCOPE);
if ( equivClassElementDeclIndex == -1) {
traverseElementDecl(equivClassElementDecl);
equivClassElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(equivClass),TOP_LEVEL_SCOPE);
}
}
if (equivClassElementDeclIndex != -1) {
equivClassEltTypeInfo = fSchemaGrammar.getElementComplexTypeInfo( equivClassElementDeclIndex );
if (equivClassEltTypeInfo == null) {
fSchemaGrammar.getElementDecl(equivClassElementDeclIndex, fTempElementDecl);
equivClassEltDV = fTempElementDecl.datatypeValidator;
if (equivClassEltDV == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type for element '" +equivClassLocalpart
+ "' in schema '" + equivClassUri+"'");
}
}
}
}
}
//
// resolving the type for this element right here
//
ComplexTypeInfo typeInfo = null;
// element has a single child element, either a datatype or a type, null if primitive
Element child = XUtil.getFirstChildElement(elementDecl);
while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION))
child = XUtil.getNextSiblingElement(child);
boolean haveAnonType = false;
// Handle Anonymous type if there is one
if (child != null) {
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("anonymous complexType in element '" + name +"' has a name attribute");
}
else
typeNameIndex = traverseComplexTypeDecl(child);
if (typeNameIndex != -1 ) {
typeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex));
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("traverse complexType error in element '" + name +"'");
}
haveAnonType = true;
}
else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
// TO DO: the Default and fixed attribute handling should be here.
if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("anonymous simpleType in element '" + name +"' has a name attribute");
}
else
typeNameIndex = traverseSimpleTypeDecl(child);
if (typeNameIndex != -1) {
dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("traverse simpleType error in element '" + name +"'");
}
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
haveAnonType = true;
} else if (type.equals("")) { // "ur-typed" leaf
contentSpecType = XMLElementDecl.TYPE_ANY;
//REVISIT: is this right?
//contentSpecType = fStringPool.addSymbol("UR_TYPE");
// set occurrence count
contentSpecNodeIndex = -1;
} else {
System.out.println("unhandled case in TraverseElementDecl");
}
}
// handle type="" here
if (haveAnonType && (type.length()>0)) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError( "Element '"+ name +
"' have both a type attribute and a annoymous type child" );
}
// type specified as an attribute and no child is type decl.
else if (!type.equals("")) {
if (equivClassElementDecl != null) {
checkEquivClassOK(elementDecl, equivClassElementDecl);
}
String prefix = "";
String localpart = type;
int colonptr = type.indexOf(":");
if ( colonptr > 0) {
prefix = type.substring(0,colonptr);
localpart = type.substring(colonptr+1);
}
String typeURI = resolvePrefixToURI(prefix);
// check if the type is from the same Schema
if ( !typeURI.equals(fTargetNSURIString)
&& !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0) { // REVISIT, only needed because of resolvePrifixToURI.
fromAnotherSchema = typeURI;
typeInfo = getTypeInfoFromNS(typeURI, localpart);
if (typeInfo == null) {
dv = getTypeValidatorFromNS(typeURI, localpart);
if (dv == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type " +localpart
+ " in schema " + typeURI);
}
}
}
else {
typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart);
if (typeInfo == null) {
dv = getDatatypeValidator(typeURI, localpart);
if (dv == null )
if (typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& !fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA))
{
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("type not found : " + typeURI+":"+localpart);
}
else {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (topleveltype != null) {
if (fCurrentTypeNameStack.search((Object)localpart) > - 1) {
//then we found a recursive element using complexType.
// REVISIT: this will be broken when recursing happens between 2 schemas
int uriInd = -1;
if ( isQName.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified) {
uriInd = fTargetNSURI;
}
int nameIndex = fStringPool.addSymbol(name);
QName tempQName = new QName(fCurrentScope, nameIndex, nameIndex, uriInd);
fElementRecurseComplex.put(tempQName, localpart);
return new QName(-1, nameIndex, nameIndex, uriInd);
}
else {
typeNameIndex = traverseComplexTypeDecl( topleveltype );
typeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex));
}
}
else {
topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
typeNameIndex = traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
// TO DO: the Default and fixed attribute handling should be here.
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("type not found : " + typeURI+":"+localpart);
}
}
}
}
}
}
else if (haveAnonType){
if (equivClassElementDecl != null ) {
checkEquivClassOK(elementDecl, equivClassElementDecl);
}
}
// this element is ur-type, check its equivClass afficliation.
else {
// if there is equivClass affiliation and not type defintion found for this element,
// then grab equivClass affiliation's type and give it to this element
if ( typeInfo == null && dv == null ) typeInfo = equivClassEltTypeInfo;
if ( typeInfo == null && dv == null ) dv = equivClassEltDV;
}
if (typeInfo == null && dv==null) {
if (noErrorSoFar) {
// Actually this Element's type definition is ur-type;
contentSpecType = XMLElementDecl.TYPE_ANY;
// REVISIT, need to wait till we have wildcards implementation.
// ADD attribute wildcards here
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError ("untyped element : " + name );
}
}
// if element belongs to a compelx type
if (typeInfo!=null) {
contentSpecNodeIndex = typeInfo.contentSpecHandle;
contentSpecType = typeInfo.contentType;
scopeDefined = typeInfo.scopeDefined;
dv = typeInfo.datatypeValidator;
}
// if element belongs to a simple type
if (dv!=null) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
}
//
// key/keyref/unique processing\
//
child = XUtil.getFirstChildElement(elementDecl);
Vector idConstraints = null;
while (child != null){
String childName = child.getNodeName();
/****
if ( childName.equals(SchemaSymbols.ELT_KEY) ) {
traverseKey(child, idCnstrt);
}
else if ( childName.equals(SchemaSymbols.ELT_KEYREF) ) {
traverseKeyRef(child, idCnstrt);
}
else if ( childName.equals(SchemaSymbols.ELT_UNIQUE) ) {
traverseUnique(child, idCnstrt);
}
if (idCnstrt!= null) {
if (idConstraints != null) {
idConstraints = new Vector();
}
idConstraints.addElement(idCnstrt);
}
/****/
child = XUtil.getNextSiblingElement(child);
}
//
// Create element decl
//
int elementNameIndex = fStringPool.addSymbol(name);
int localpartIndex = elementNameIndex;
int uriIndex = -1;
int enclosingScope = fCurrentScope;
if ( isQName.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified ) {
uriIndex = fTargetNSURI;
}
if ( isTopLevel(elementDecl)) {
uriIndex = fTargetNSURI;
enclosingScope = TOP_LEVEL_SCOPE;
}
//There can never be two elements with the same name and different type in the same scope.
int existSuchElementIndex = fSchemaGrammar.getElementDeclIndex(uriIndex, localpartIndex, enclosingScope);
if ( existSuchElementIndex > -1) {
fSchemaGrammar.getElementDecl(existSuchElementIndex, fTempElementDecl);
DatatypeValidator edv = fTempElementDecl.datatypeValidator;
ComplexTypeInfo eTypeInfo = fSchemaGrammar.getElementComplexTypeInfo(existSuchElementIndex);
if ( ((eTypeInfo != null)&&(eTypeInfo!=typeInfo))
|| ((edv != null)&&(edv != dv)) ) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("duplicate element decl in the same scope : " +
fStringPool.toString(localpartIndex));
}
}
QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex);
// add element decl to pool
int attrListHead = -1 ;
// copy up attribute decls from type object
if (typeInfo != null) {
attrListHead = typeInfo.attlistHead;
}
int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined,
contentSpecType, contentSpecNodeIndex,
attrListHead, dv);
if ( DEBUGGING ) {
/***/
System.out.println("########elementIndex:"+elementIndex+" ("+fStringPool.toString(eltQName.uri)+","
+ fStringPool.toString(eltQName.localpart) + ")"+
" eltType:"+type+" contentSpecType:"+contentSpecType+
" SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope +
" scopeDefined: " +scopeDefined+"\n");
/***/
}
if (typeInfo != null) {
fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo);
}
else {
fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo);
// REVISIT: should we report error from here?
}
// mark element if its type belongs to different Schema.
fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema);
// set BlockSet, FinalSet, Nullable and Abstract for this element decl
fSchemaGrammar.setElementDeclBlockSet(elementIndex, blockSet);
fSchemaGrammar.setElementDeclFinalSet(elementIndex, finalSet);
fSchemaGrammar.setElementDeclMiscFlags(elementIndex, elementMiscFlags);
// setEquivClassElementFullName
fSchemaGrammar.setElementDeclEquivClassElementFullName(elementIndex, equivClassFullName);
return eltQName;
}// end of method traverseElementDecl(Element)
int getLocalPartIndex(String fullName){
int colonAt = fullName.indexOf(":");
String localpart = fullName;
if ( colonAt > -1 ) {
localpart = fullName.substring(colonAt+1);
}
return fStringPool.addSymbol(localpart);
}
String getLocalPart(String fullName){
int colonAt = fullName.indexOf(":");
String localpart = fullName;
if ( colonAt > -1 ) {
localpart = fullName.substring(colonAt+1);
}
return localpart;
}
int getPrefixIndex(String fullName){
int colonAt = fullName.indexOf(":");
String prefix = "";
if ( colonAt > -1 ) {
prefix = fullName.substring(0,colonAt);
}
return fStringPool.addSymbol(prefix);
}
String getPrefix(String fullName){
int colonAt = fullName.indexOf(":");
String prefix = "";
if ( colonAt > -1 ) {
prefix = fullName.substring(0,colonAt);
}
return prefix;
}
private void checkEquivClassOK(Element elementDecl, Element equivClassElementDecl){
//TO DO!!
}
private Element getTopLevelComponentByName(String componentCategory, String name) throws Exception {
Element child = XUtil.getFirstChildElement(fSchemaRootElement);
if (child == null) {
return null;
}
while (child != null ){
if ( child.getNodeName().equals(componentCategory)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) {
return child;
}
}
child = XUtil.getNextSiblingElement(child);
}
return null;
}
private boolean isTopLevel(Element component) {
//REVISIT, is this the right way to check ?
/****
if (component.getParentNode() == fSchemaRootElement ) {
return true;
}
/****/
if (component.getParentNode().getNodeName().endsWith(SchemaSymbols.ELT_SCHEMA) ) {
return true;
}
return false;
}
DatatypeValidator getTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception {
// The following impl is for the case where every Schema Grammar has its own instance of DatatypeRegistry.
// Now that we have only one DataTypeRegistry used by all schemas. this is not needed.
/*****
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
DatatypeValidator dv = (DatatypeValidator) fSchemaGrammar.getDatatypeRegistry().getDatatypeValidator(localpart);
return dv;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeValidatorFromNS");
}
return null;
/*****/
return getDatatypeValidator(newSchemaURI, localpart);
}
ComplexTypeInfo getTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
ComplexTypeInfo typeInfo = (ComplexTypeInfo) sGrammar.getComplexTypeRegistry().get(newSchemaURI+","+localpart);
return typeInfo;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeInfoFromNS");
}
return null;
}
DatatypeValidator getElementDeclTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI),
fStringPool.addSymbol(localpart),
TOP_LEVEL_SCOPE);
DatatypeValidator dv = null;
if (eltIndex>-1) {
sGrammar.getElementDecl(eltIndex, fTempElementDecl);
dv = fTempElementDecl.datatypeValidator;
}
else {
reportGenericSchemaError("could not find global element : '" + localpart
+ " in the SchemaGrammar "+newSchemaURI);
}
return dv;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI
+ " to a SchemaGrammar in getELementDeclTypeValidatorFromNS");
}
return null;
}
ComplexTypeInfo getElementDeclTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI),
fStringPool.addSymbol(localpart),
TOP_LEVEL_SCOPE);
ComplexTypeInfo typeInfo = null;
if (eltIndex>-1) {
typeInfo = sGrammar.getElementComplexTypeInfo(eltIndex);
}
else {
reportGenericSchemaError("could not find global element : '" + localpart
+ " in the SchemaGrammar "+newSchemaURI);
}
return typeInfo;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI
+ " to a SchemaGrammar in getElementDeclTypeInfoFromNS");
}
return null;
}
/**
* Traverse attributeGroup Declaration
*
* <attributeGroup
* id = ID
* ref = QName>
* Content: (annotation?)
* </>
*
* @param elementDecl
* @exception Exception
*/
/*private int traverseAttributeGroupDecl( Element attributeGroupDecl ) throws Exception {
int attributeGroupID = fStringPool.addSymbol(
attributeGroupDecl.getAttribute( SchemaSymbols.ATTVAL_ID ));
int attributeGroupName = fStringPool.addSymbol(
attributeGroupDecl.getAttribute( SchemaSymbols.ATT_NAME ));
return -1;
}*/
/**
* Traverse Group Declaration.
*
* <group
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* ref = QName>
* Content: (annotation? , (element | group | all | choice | sequence | any)*)
* <group/>
*
* @param elementDecl
* @return
* @exception Exception
*/
private int traverseGroupDecl( Element groupDecl ) throws Exception {
String groupName = groupDecl.getAttribute(SchemaSymbols.ATT_NAME);
String ref = groupDecl.getAttribute(SchemaSymbols.ATT_REF);
if (!ref.equals("")) {
if (XUtil.getFirstChildElement(groupDecl) != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
return traverseGroupDeclFromAnotherSchema(localpart, uriStr);
}
int contentSpecIndex = -1;
Element referredGroup = getTopLevelComponentByName(SchemaSymbols.ELT_GROUP,localpart);
if (referredGroup == null) {
// REVISIT: Localize
reportGenericSchemaError("Group " + localpart + " not found in the Schema");
//REVISIT, this should be some custom Exception
throw new Exception("Group " + localpart + " not found in the Schema");
}
else {
contentSpecIndex = traverseGroupDecl(referredGroup);
}
return contentSpecIndex;
}
boolean traverseElt = true;
if (fCurrentScope == TOP_LEVEL_SCOPE) {
traverseElt = false;
}
Element child = XUtil.getFirstChildElement(groupDecl);
while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION))
child = XUtil.getNextSiblingElement(child);
int contentSpecType = 0;
int csnType = 0;
int allChildren[] = null;
int allChildCount = 0;
csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
int left = -2;
int right = -2;
boolean hadContent = false;
boolean seeAll = false;
boolean seeParticle = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
hadContent = true;
boolean illegalChild = false;
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
//seeParticle = true;
seeAll = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if ( ! illegalChild ) {
index = expandContentModel( index, child);
}
if (seeParticle && seeAll) {
reportSchemaError( SchemaMessageProvider.GroupContentRestricted,
new Object [] { "'all' needs to be 'the' only Child", childName});
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent && right != -2)
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
return left;
}
private int traverseGroupDeclFromAnotherSchema( String groupName , String uriStr ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseGroupDeclFromAnotherSchema, "+
"schema uri: " + uriStr
+", groupName: " + groupName);
return -1;
}
Element groupDecl = (Element) aGrammar.topLevelGroupDecls.get((Object)groupName);
if (groupDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no group named \"" + groupName
+ "\" was defined in schema : " + uriStr);
return -1;
}
NamespacesScope saveNSMapping = fNamespacesScope;
int saveTargetNSUri = fTargetNSURI;
fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI());
fNamespacesScope = aGrammar.getNamespacesScope();
boolean traverseElt = true;
if (fCurrentScope == TOP_LEVEL_SCOPE) {
traverseElt = false;
}
Element child = XUtil.getFirstChildElement(groupDecl);
while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION))
child = XUtil.getNextSiblingElement(child);
int contentSpecType = 0;
int csnType = 0;
int allChildren[] = null;
int allChildCount = 0;
csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
hadContent = true;
boolean seeParticle = false;
String childName = child.getNodeName();
int childNameIndex = fStringPool.addSymbol(childName);
String formAttrVal = child.getAttribute(SchemaSymbols.ATT_FORM);
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if (seeParticle) {
index = expandContentModel( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent && right != -2)
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
fNamespacesScope = saveNSMapping;
fTargetNSURI = saveTargetNSUri;
return left;
} // end of method traverseGroupDeclFromAnotherSchema
/**
*
* Traverse the Sequence declaration
*
* <sequence
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </sequence>
*
**/
int traverseSequence (Element sequenceDecl) throws Exception {
Element child = XUtil.getFirstChildElement(sequenceDecl);
while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION))
child = XUtil.getNextSiblingElement(child);
int contentSpecType = 0;
int csnType = 0;
csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
hadContent = true;
boolean seeParticle = false;
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if (seeParticle) {
index = expandContentModel( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent && right != -2)
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
return left;
}
/**
*
* Traverse the Sequence declaration
*
* <choice
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </choice>
*
**/
int traverseChoice (Element choiceDecl) throws Exception {
// REVISIT: traverseChoice, traverseSequence can be combined
Element child = XUtil.getFirstChildElement(choiceDecl);
while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION))
child = XUtil.getNextSiblingElement(child);
int contentSpecType = 0;
int csnType = 0;
csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
hadContent = true;
boolean seeParticle = false;
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if (seeParticle) {
index = expandContentModel( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent && right != -2)
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
return left;
}
/**
*
* Traverse the "All" declaration
*
* <all
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </all>
*
**/
int traverseAll( Element allDecl) throws Exception {
Element child = XUtil.getFirstChildElement(allDecl);
while (child != null && child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION))
child = XUtil.getNextSiblingElement(child);
int allChildren[] = null;
int allChildCount = 0;
int left = -2;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
boolean seeParticle = false;
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if (seeParticle) {
index = expandContentModel( index, child);
}
try {
allChildren[allChildCount] = index;
}
catch (NullPointerException ne) {
allChildren = new int[32];
allChildren[allChildCount] = index;
}
catch (ArrayIndexOutOfBoundsException ae) {
int[] newArray = new int[allChildren.length*2];
System.arraycopy(allChildren, 0, newArray, 0, allChildren.length);
allChildren[allChildCount] = index;
}
allChildCount++;
}
left = buildAllModel(allChildren,allChildCount);
return left;
}
/** builds the all content model */
private int buildAllModel(int children[], int count) throws Exception {
// build all model
if (count > 1) {
// create and initialize singletons
XMLContentSpec choice = new XMLContentSpec();
choice.type = XMLContentSpec.CONTENTSPECNODE_CHOICE;
choice.value = -1;
choice.otherValue = -1;
int[] exactChildren = new int[count];
System.arraycopy(children,0,exactChildren,0,count);
// build all model
sort(exactChildren, 0, count);
int index = buildAllModel(exactChildren, 0, choice);
return index;
}
if (count > 0) {
return children[0];
}
return -1;
}
/** Builds the all model. */
private int buildAllModel(int src[], int offset,
XMLContentSpec choice) throws Exception {
// swap last two places
if (src.length - offset == 2) {
int seqIndex = createSeq(src);
if (choice.value == -1) {
choice.value = seqIndex;
}
else {
if (choice.otherValue != -1) {
choice.value = fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false);
}
choice.otherValue = seqIndex;
}
swap(src, offset, offset + 1);
seqIndex = createSeq(src);
if (choice.value == -1) {
choice.value = seqIndex;
}
else {
if (choice.otherValue != -1) {
choice.value = fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false);
}
choice.otherValue = seqIndex;
}
return fSchemaGrammar.addContentSpecNode(choice.type, choice.value, choice.otherValue, false);
}
// recurse
for (int i = offset; i < src.length - 1; i++) {
choice.value = buildAllModel(src, offset + 1, choice);
choice.otherValue = -1;
sort(src, offset, src.length - offset);
shift(src, offset, i + 1);
}
int choiceIndex = buildAllModel(src, offset + 1, choice);
sort(src, offset, src.length - offset);
return choiceIndex;
} // buildAllModel(int[],int,ContentSpecNode,ContentSpecNode):int
/** Creates a sequence. */
private int createSeq(int src[]) throws Exception {
int left = src[0];
int right = src[1];
for (int i = 2; i < src.length; i++) {
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
left, right, false);
right = src[i];
}
return fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
left, right, false);
} // createSeq(int[]):int
/** Shifts a value into position. */
private void shift(int src[], int pos, int offset) {
int temp = src[offset];
for (int i = offset; i > pos; i--) {
src[i] = src[i - 1];
}
src[pos] = temp;
} // shift(int[],int,int)
/** Simple sort. */
private void sort(int src[], final int offset, final int length) {
for (int i = offset; i < offset + length - 1; i++) {
int lowest = i;
for (int j = i + 1; j < offset + length; j++) {
if (src[j] < src[lowest]) {
lowest = j;
}
}
if (lowest != i) {
int temp = src[i];
src[i] = src[lowest];
src[lowest] = temp;
}
}
} // sort(int[],int,int)
/** Swaps two values. */
private void swap(int src[], int i, int j) {
int temp = src[i];
src[i] = src[j];
src[j] = temp;
} // swap(int[],int,int)
/**
* Traverse Wildcard declaration
*
* <any
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}
* processContents = lax | skip | strict>
* Content: (annotation?)
* </any>
* @param elementDecl
* @return
* @exception Exception
*/
private int traverseWildcardDecl( Element wildcardDecl ) throws Exception {
int wildcardID = fStringPool.addSymbol(
wildcardDecl.getAttribute( SchemaSymbols.ATTVAL_ID ));
int wildcardMaxOccurs = fStringPool.addSymbol(
wildcardDecl.getAttribute( SchemaSymbols.ATT_MAXOCCURS ));
int wildcardMinOccurs = fStringPool.addSymbol(
wildcardDecl.getAttribute( SchemaSymbols.ATT_MINOCCURS ));
int wildcardNamespace = fStringPool.addSymbol(
wildcardDecl.getAttribute( SchemaSymbols.ATT_NAMESPACE ));
int wildcardProcessContents = fStringPool.addSymbol(
wildcardDecl.getAttribute( SchemaSymbols.ATT_PROCESSCONTENTS ));
int wildcardContent = fStringPool.addSymbol(
wildcardDecl.getAttribute( SchemaSymbols.ATT_CONTENT ));
return -1;
}
// utilities from Tom Watson's SchemaParser class
// TO DO: Need to make this more conformant with Schema int type parsing
private int parseInt (String intString) throws Exception
{
if ( intString.equals("*") ) {
return SchemaSymbols.INFINITY;
} else {
return Integer.parseInt (intString);
}
}
private int parseSimpleDerivedBy (String derivedByString) throws Exception
{
if ( derivedByString.equals (SchemaSymbols.ATTVAL_LIST) ) {
return SchemaSymbols.LIST;
}
else if ( derivedByString.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
return SchemaSymbols.RESTRICTION;
}
else {
// REVISIT: Localize
reportGenericSchemaError ("SimpleType: Invalid value for 'derivedBy'");
return -1;
}
}
private int parseComplexDerivedBy (String derivedByString) throws Exception
{
if ( derivedByString.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
return SchemaSymbols.EXTENSION;
}
else if ( derivedByString.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
return SchemaSymbols.RESTRICTION;
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "ComplexType: Invalid value for 'derivedBy'" );
return -1;
}
}
private int parseSimpleFinal (String finalString) throws Exception
{
if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.ENUMERATION+SchemaSymbols.RESTRICTION+SchemaSymbols.LIST+SchemaSymbols.REPRODUCTION;
} else {
int enumerate = 0;
int restrict = 0;
int list = 0;
int reproduce = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ("restriction in set twice");
}
} else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) {
if ( list == 0 ) {
list = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ("list in set twice");
}
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid value (" +
finalString +
")" );
}
}
return enumerate+restrict+list+reproduce;
}
}
private int parseComplexContent (String contentString) throws Exception
{
if ( contentString.equals (SchemaSymbols.ATTVAL_EMPTY) ) {
return XMLElementDecl.TYPE_EMPTY;
} else if ( contentString.equals (SchemaSymbols.ATTVAL_ELEMENTONLY) ) {
return XMLElementDecl.TYPE_CHILDREN;
} else if ( contentString.equals (SchemaSymbols.ATTVAL_TEXTONLY) ) {
return XMLElementDecl.TYPE_SIMPLE;
} else if ( contentString.equals (SchemaSymbols.ATTVAL_MIXED) ) {
return XMLElementDecl.TYPE_MIXED;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid value for content" );
return -1;
}
}
private int parseDerivationSet (String finalString) throws Exception
{
if ( finalString.equals ("#all") ) {
return SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION;
} else {
int extend = 0;
int restrict = 0;
int reproduce = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "extension already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "restriction already in set" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
return extend+restrict+reproduce;
}
}
private int parseBlockSet (String finalString) throws Exception
{
if ( finalString.equals ("#all") ) {
return SchemaSymbols.EQUIVCLASS+SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION;
} else {
int extend = 0;
int restrict = 0;
int reproduce = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_EQUIVCLASS) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EQUIVCLASS;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "'equivClass' already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "extension already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "'list' already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "restriction already in set" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
return extend+restrict+reproduce;
}
}
private int parseFinalSet (String finalString) throws Exception
{
if ( finalString.equals ("#all") ) {
return SchemaSymbols.EQUIVCLASS+SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.REPRODUCTION;
} else {
int extend = 0;
int restrict = 0;
int reproduce = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_EQUIVCLASS) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EQUIVCLASS;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "'equivClass' already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "extension already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_LIST) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "'list' already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "restriction already in set" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
return extend+restrict+reproduce;
}
}
private void reportGenericSchemaError (String error) throws Exception {
if (fErrorReporter == null) {
System.err.println("__TraverseSchemaError__ : " + error);
}
else {
reportSchemaError (SchemaMessageProvider.GenericError, new Object[] { error });
}
}
private void reportSchemaError(int major, Object args[]) throws Exception {
if (fErrorReporter == null) {
System.out.println("__TraverseSchemaError__ : " + SchemaMessageProvider.fgMessageKeys[major]);
for (int i=0; i< args.length ; i++) {
System.out.println((String)args[i]);
}
}
else {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
major,
SchemaMessageProvider.MSG_NONE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
//Unit Test here
public static void main(String args[] ) {
if( args.length != 1 ) {
System.out.println( "Error: Usage java TraverseSchema yourFile.xsd" );
System.exit(0);
}
DOMParser parser = new DOMParser() {
public void ignorableWhitespace(char ch[], int start, int length) {}
public void ignorableWhitespace(int dataIdx) {}
};
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( args[0]);
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
OutputFormat format = new OutputFormat( document );
java.io.StringWriter outWriter = new java.io.StringWriter();
XMLSerializer serial = new XMLSerializer( outWriter,format);
TraverseSchema tst = null;
try {
Element root = document.getDocumentElement();// This is what we pass to TraverserSchema
//serial.serialize( root );
//System.out.println(outWriter.toString());
tst = new TraverseSchema( root, new StringPool(), new SchemaGrammar(), (GrammarResolver) new GrammarResolverImpl() );
}
catch (Exception e) {
e.printStackTrace(System.err);
}
parser.getDocument();
}
static class Resolver implements EntityResolver {
private static final String SYSTEM[] = {
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/structures.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/datatypes.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/versionInfo.ent",
};
private static final String PATH[] = {
"structures.dtd",
"datatypes.dtd",
"versionInfo.ent",
};
public InputSource resolveEntity(String publicId, String systemId)
throws IOException {
// looking for the schema DTDs?
for (int i = 0; i < SYSTEM.length; i++) {
if (systemId.equals(SYSTEM[i])) {
InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i]));
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
}
}
// use default resolution
return null;
} // resolveEntity(String,String):InputSource
} // class Resolver
static class ErrorHandler implements org.xml.sax.ErrorHandler {
/** Warning. */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Error. */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Fatal error. */
public void fatalError(SAXParseException ex) throws SAXException {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
throw ex;
}
//
// Private methods
//
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
} // getLocationString(SAXParseException):String
}
}
| true | true | private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception {
String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT );
String base = complexTypeDecl.getAttribute(SchemaSymbols.ATT_BASE);
String blockSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_BLOCK );
String content = complexTypeDecl.getAttribute(SchemaSymbols.ATT_CONTENT);
String derivedBy = complexTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY );
String finalSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_FINAL );
String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID );
String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME);
boolean isNamedType = false;
if ( DEBUGGING )
System.out.println("traversing complex Type : " + typeName +","+base+","+content+".");
if (typeName.equals("")) { // gensym a unique name
//typeName = "http://www.apache.org/xml/xerces/internalType"+fTypeCount++;
typeName = "#"+fAnonTypeCount++;
}
else {
fCurrentTypeNameStack.push(typeName);
isNamedType = true;
}
if (isTopLevel(complexTypeDecl)) {
String fullName = fTargetNSURIString+","+typeName;
ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName);
if (temp != null ) {
return fStringPool.addSymbol(fullName);
}
}
int scopeDefined = fScopeCount++;
int previousScope = fCurrentScope;
fCurrentScope = scopeDefined;
Element child = null;
int contentSpecType = -1;
int csnType = 0;
int left = -2;
int right = -2;
ComplexTypeInfo baseTypeInfo = null; //if base is a complexType;
DatatypeValidator baseTypeValidator = null; //if base is a simple type or a complex type derived from a simpleType
DatatypeValidator simpleTypeValidator = null;
int baseTypeSymbol = -1;
String fullBaseName = "";
boolean baseIsSimpleSimple = false;
boolean baseIsComplexSimple = false;
boolean derivedByRestriction = true;
boolean derivedByExtension = false;
int baseContentSpecHandle = -1;
Element baseTypeNode = null;
//int parsedderivedBy = parseComplexDerivedBy(derivedBy);
//handle the inhreitance here.
if (base.length()>0) {
//first check if derivedBy is present
if (derivedBy.length() == 0) {
// REVISIT: Localize
reportGenericSchemaError("derivedBy must be present when base is present in "
+SchemaSymbols.ELT_COMPLEXTYPE
+" "+ typeName);
}
else {
if (derivedBy.equals(SchemaSymbols.ATTVAL_EXTENSION)) {
derivedByRestriction = false;
}
String prefix = "";
String localpart = base;
int colonptr = base.indexOf(":");
if ( colonptr > 0) {
prefix = base.substring(0,colonptr);
localpart = base.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String typeURI = resolvePrefixToURI(prefix);
// check if the base type is from the same Schema;
if ( ! typeURI.equals(fTargetNSURIString)
&& ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0 ) /*REVISIT, !!!! a hack: for schema that has no target namespace, e.g. personal-schema.xml*/{
baseTypeInfo = getTypeInfoFromNS(typeURI, localpart);
if (baseTypeInfo == null) {
baseTypeValidator = getTypeValidatorFromNS(typeURI, localpart);
if (baseTypeValidator == null) {
//TO DO: report error here;
System.out.println("Could not find base type " +localpart
+ " in schema " + typeURI);
}
else{
baseIsSimpleSimple = true;
}
}
}
else {
fullBaseName = typeURI+","+localpart;
// assume the base is a complexType and try to locate the base type first
baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName);
// if not found, 2 possibilities: 1: ComplexType in question has not been compiled yet;
// 2: base is SimpleTYpe;
if (baseTypeInfo == null) {
baseTypeValidator = getDatatypeValidator(typeURI, localpart);
if (baseTypeValidator == null) {
baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode );
baseTypeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol)); //REVISIT: should it be fullBaseName;
}
else {
baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode );
simpleTypeValidator = baseTypeValidator = getDatatypeValidator(typeURI, localpart);
if (simpleTypeValidator == null) {
//TO DO: signal error here.
}
baseIsSimpleSimple = true;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Base type could not be found : " + base);
}
}
}
else {
simpleTypeValidator = baseTypeValidator;
baseIsSimpleSimple = true;
}
}
}
//Schema Spec : 5.11: Complex Type Definition Properties Correct : 2
if (baseIsSimpleSimple && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("base is a simpledType, can't derive by restriction in " + typeName);
}
//if the base is a complexType
if (baseTypeInfo != null ) {
//Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1
// 5.11: Derivation Valid ( Restriction, Complex ) 1.2.1
if (derivedByRestriction) {
//REVISIT: check base Type's finalset does not include "restriction"
}
else {
//REVISIT: check base Type's finalset doest not include "extension"
}
if ( baseTypeInfo.contentSpecHandle > -1) {
if (derivedByRestriction) {
//REVISIT: !!! really hairy staff to check the particle derivation OK in 5.10
checkParticleDerivationOK(complexTypeDecl, baseTypeNode);
}
baseContentSpecHandle = baseTypeInfo.contentSpecHandle;
}
else if ( baseTypeInfo.datatypeValidator != null ) {
baseTypeValidator = baseTypeInfo.datatypeValidator;
baseIsComplexSimple = true;
}
}
//Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1
if (baseIsComplexSimple && !derivedByRestriction ) {
// REVISIT: Localize
reportGenericSchemaError("base is ComplexSimple, can't derive by extension in " + typeName);
}
} // END of if (derivedBy.length() == 0) {} else {}
} // END of if (base.length() > 0) {}
// skip refinement and annotations
child = null;
if (baseIsComplexSimple) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
int numEnumerationLiterals = 0;
int numFacets = 0;
Hashtable facetData = new Hashtable();
Vector enumData = new Vector();
//REVISIT: there is a better way to do this,
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null && (child.getNodeName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MININCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_PRECISION) ||
child.getNodeName().equals(SchemaSymbols.ELT_SCALE) ||
child.getNodeName().equals(SchemaSymbols.ELT_LENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_MINLENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXLENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_ENCODING) ||
child.getNodeName().equals(SchemaSymbols.ELT_PERIOD) ||
child.getNodeName().equals(SchemaSymbols.ELT_DURATION) ||
child.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION) ||
child.getNodeName().equals(SchemaSymbols.ELT_PATTERN) ||
child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION));
child = XUtil.getNextSiblingElement(child))
{
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element facetElt = (Element) child;
numFacets++;
if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE));
//Enumerations can have annotations ? ( 0 | 1 )
Element enumContent = XUtil.getFirstChildElement( facetElt );
if( enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){
traverseAnnotationDecl( child );
}
// TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over
} else {
facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE ));
}
}
}
if (numEnumerationLiterals > 0) {
facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
//if (numFacets > 0)
// baseTypeValidator.setFacets(facetData, derivedBy );
if (numFacets > 0) {
simpleTypeValidator = fDatatypeRegistry.createDatatypeValidator( typeName, baseTypeValidator,
facetData, false );
}
else
simpleTypeValidator = baseTypeValidator;
if (child != null) {
// REVISIT: Localize
reportGenericSchemaError("Invalid child '"+child.getNodeName()+"' in complexType : '" + typeName
+ "', because it restricts another complexSimpleType");
}
}
// if content = textonly, base is a datatype
if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) {
//TO DO
if (base.length() == 0) {
simpleTypeValidator = baseTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING);
}
else if ( baseTypeValidator == null
&& baseTypeInfo != null && baseTypeInfo.datatypeValidator==null ) // must be datatype
reportSchemaError(SchemaMessageProvider.NotADatatype,
new Object [] { base }); //REVISIT check forward refs
//handle datatypes
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
/****
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF,
fStringPool.addSymbol(base),
-1, false);
/****/
}
else {
if (!baseIsComplexSimple) {
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
}
csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
boolean mixedContent = false;
//REVISIT: is the default content " elementOnly"
boolean elementContent = true;
boolean textContent = false;
boolean emptyContent = false;
left = -2;
right = -2;
boolean hadContent = false;
if (content.equals(SchemaSymbols.ATTVAL_EMPTY)) {
contentSpecType = XMLElementDecl.TYPE_EMPTY;
emptyContent = true;
elementContent = false;
left = -1; // no contentSpecNode needed
} else if (content.equals(SchemaSymbols.ATTVAL_MIXED) ) {
contentSpecType = XMLElementDecl.TYPE_MIXED;
mixedContent = true;
elementContent = false;
csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
} else if (content.equals(SchemaSymbols.ATTVAL_ELEMENTONLY) || content.equals("")) {
elementContent = true;
} else if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) {
textContent = true;
elementContent = false;
}
if (mixedContent) {
// add #PCDATA leaf
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF,
-1, // -1 means "#PCDATA" is name
-1, false);
csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
}
boolean seeParticle = false;
boolean seeOtherParticle = false;
boolean seeAll = false;
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2; // to save the particle's contentSpec handle
hadContent = true;
seeParticle = false;
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
if (mixedContent || elementContent) {
if ( DEBUGGING )
System.out.println(" child element name " + child.getAttribute(SchemaSymbols.ATT_NAME));
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
seeOtherParticle = true;
}
else {
reportSchemaError(SchemaMessageProvider.EltRefOnlyInMixedElemOnly, null);
}
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
seeParticle = true;
seeAll = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE) ||
childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
break; // attr processing is done later on in this method
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANNOTATION)) {
//REVISIT, do nothing for annotation for now.
}
else if (childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE)) {
break;
//REVISIT, do nothing for attribute wildcard for now.
}
else { // datatype qual
if (!baseIsComplexSimple )
if (base.equals(""))
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "unrecogized child '"+childName+"' in compelx type "+typeName });
else
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "unrecogized child '"+childName+"' in compelx type '"+typeName+"' with base "+base });
}
// if base is complextype with simpleType content, can't have any particle children at all.
if (baseIsComplexSimple && seeParticle) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+", base type is complextype with simpleType content, can't have any particle children at all");
hadContent = false;
left = index = -2;
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
break;
}
// check the minOccurs and maxOccurs of the particle, and fix the
// contentspec accordingly
if (seeParticle) {
index = expandContentModel(index, child);
} //end of if (seeParticle)
if (seeAll && seeOtherParticle) {
// REVISIT: Localize
reportGenericSchemaError ( " 'All' group needs to be the only child in Complextype : " + typeName);
}
if (seeAll) {
//TO DO: REVISIT
//check the minOccurs = 1 and maxOccurs = 1
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
} //end looping through the children
if ( ! ( seeOtherParticle || seeAll ) && (elementContent || mixedContent)
&& (base.length() == 0 || ( base.length() > 0 && derivedByRestriction)) ) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
simpleTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING);
// REVISIT: Localize
reportGenericSchemaError ( " complexType '"+typeName+"' with a elementOnly or mixed content "
+"need to have at least one particle child");
}
if (hadContent && right != -2)
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
if (mixedContent && hadContent) {
// set occurrence count
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE,
left, -1, false);
}
}
// if derived by extension and base complextype has a content model,
// compose the final content model by concatenating the base and the
// current in sequence.
if (!derivedByRestriction && baseContentSpecHandle > -1 ) {
if (left == -2) {
left = baseContentSpecHandle;
}
else
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
baseContentSpecHandle,
left,
false);
}
// REVISIT: this is when sees a topelevel <complexType name="abc">attrs*</complexType>
if (content.length() == 0 && base.length() == 0 && left == -2) {
contentSpecType = XMLElementDecl.TYPE_ANY;
}
if (content.length() == 0 && simpleTypeValidator == null && left == -2 ) {
if (base.length() > 0 && baseTypeInfo != null
&& baseTypeInfo.contentType == XMLElementDecl.TYPE_EMPTY) {
contentSpecType = XMLElementDecl.TYPE_EMPTY;
}
}
if ( DEBUGGING )
System.out.println("!!!!!>>>>>" + typeName+", "+ baseTypeInfo + ", "
+ baseContentSpecHandle +", " + left +", "+scopeDefined);
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
typeInfo.baseComplexTypeInfo = baseTypeInfo;
typeInfo.baseDataTypeValidator = baseTypeValidator;
int derivedByInt = -1;
if (derivedBy.length() > 0) {
derivedByInt = parseComplexDerivedBy(derivedBy);
}
typeInfo.derivedBy = derivedByInt;
typeInfo.scopeDefined = scopeDefined;
typeInfo.contentSpecHandle = left;
typeInfo.contentType = contentSpecType;
typeInfo.datatypeValidator = simpleTypeValidator;
typeInfo.blockSet = parseBlockSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_BLOCK));
typeInfo.finalSet = parseFinalSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_FINAL));
typeInfo.isAbstract = isAbstract.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false ;
//add a template element to the grammar element decl pool.
int typeNameIndex = fStringPool.addSymbol(typeName);
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex =
fSchemaGrammar.addElementDecl(new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==-1) ? -1 : fCurrentScope, scopeDefined,
contentSpecType, left,
-1, simpleTypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex);
// (attribute | attrGroupRef)*
XMLAttributeDecl attWildcard = null;
Vector anyAttDecls = new Vector();
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) {
if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+
", base type has simpleType "+
"content and derivation method is"+
" 'restriction', can't have any "+
"attribute children at all");
break;
}
traverseAttributeDecl(child, typeInfo);
}
else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+", base "+
"type has simpleType content and "+
"derivation method is 'restriction',"+
" can't have any attribute children at all");
break;
}
traverseAttributeGroupDecl(child,typeInfo,anyAttDecls);
}
else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
attWildcard = traverseAnyAttribute(child);
}
}
if (attWildcard != null) {
XMLAttributeDecl fromGroup = null;
final int count = anyAttDecls.size();
if ( count > 0) {
fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0);
for (int i=1; i<count; i++) {
fromGroup = mergeTwoAnyAttribute(fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i));
}
}
if (fromGroup != null) {
int saveProcessContents = attWildcard.defaultType;
attWildcard = mergeTwoAnyAttribute(attWildcard, fromGroup);
attWildcard.defaultType = saveProcessContents;
}
}
else {
//REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case
}
// merge in base type's attribute decls
XMLAttributeDecl baseAttWildcard = null;
if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) {
int attDefIndex = baseTypeInfo.attlistHead;
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
fSchemaGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) {
if (attWildcard == null) {
baseAttWildcard = fTempAttributeDecl;
}
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
// if found a duplicate, if it is derived by restriction. then skip the one from the base type
/**/
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name);
if ( temp > -1) {
if (derivedByRestriction) {
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
}
/**/
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
fTempAttributeDecl.name, fTempAttributeDecl.type,
fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType,
fTempAttributeDecl.defaultValue,
fTempAttributeDecl.datatypeValidator,
fTempAttributeDecl.list);
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
// att wildcard will inserted after all attributes were processed
if (attWildcard != null) {
if (attWildcard.type != -1) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attWildcard.name, attWildcard.type,
attWildcard.enumeration, attWildcard.defaultType,
attWildcard.defaultValue,
attWildcard.datatypeValidator,
attWildcard.list);
}
else {
//REVISIT: unclear in Schema spec if should report error here.
}
}
else if (baseAttWildcard != null) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
baseAttWildcard.name, baseAttWildcard.type,
baseAttWildcard.enumeration, baseAttWildcard.defaultType,
baseAttWildcard.defaultValue,
baseAttWildcard.datatypeValidator,
baseAttWildcard.list);
}
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex);
if (!typeName.startsWith("#")) {
typeName = fTargetNSURIString + "," + typeName;
}
typeInfo.typeName = new String(typeName);
if ( DEBUGGING )
System.out.println("add complex Type to Registry: " + typeName +","+content+".");
fComplexTypeRegistry.put(typeName,typeInfo);
// before exit the complex type definition, restore the scope, mainly for nested Anonymous Types
fCurrentScope = previousScope;
if (isNamedType) {
fCurrentTypeNameStack.pop();
checkRecursingComplexType();
}
//set template element's typeInfo
fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo);
typeNameIndex = fStringPool.addSymbol(typeName);
return typeNameIndex;
} // end of method: traverseComplexTypeDecl
| private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception {
String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT );
String base = complexTypeDecl.getAttribute(SchemaSymbols.ATT_BASE);
String blockSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_BLOCK );
String content = complexTypeDecl.getAttribute(SchemaSymbols.ATT_CONTENT);
String derivedBy = complexTypeDecl.getAttribute( SchemaSymbols.ATT_DERIVEDBY );
String finalSet = complexTypeDecl.getAttribute( SchemaSymbols.ATT_FINAL );
String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID );
String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME);
boolean isNamedType = false;
if ( DEBUGGING )
System.out.println("traversing complex Type : " + typeName +","+base+","+content+".");
if (typeName.equals("")) { // gensym a unique name
//typeName = "http://www.apache.org/xml/xerces/internalType"+fTypeCount++;
typeName = "#"+fAnonTypeCount++;
}
else {
fCurrentTypeNameStack.push(typeName);
isNamedType = true;
}
if (isTopLevel(complexTypeDecl)) {
String fullName = fTargetNSURIString+","+typeName;
ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName);
if (temp != null ) {
return fStringPool.addSymbol(fullName);
}
}
int scopeDefined = fScopeCount++;
int previousScope = fCurrentScope;
fCurrentScope = scopeDefined;
Element child = null;
int contentSpecType = -1;
int csnType = 0;
int left = -2;
int right = -2;
ComplexTypeInfo baseTypeInfo = null; //if base is a complexType;
DatatypeValidator baseTypeValidator = null; //if base is a simple type or a complex type derived from a simpleType
DatatypeValidator simpleTypeValidator = null;
int baseTypeSymbol = -1;
String fullBaseName = "";
boolean baseIsSimpleSimple = false;
boolean baseIsComplexSimple = false;
boolean derivedByRestriction = true;
boolean derivedByExtension = false;
int baseContentSpecHandle = -1;
Element baseTypeNode = null;
//int parsedderivedBy = parseComplexDerivedBy(derivedBy);
//handle the inhreitance here.
if (base.length()>0) {
//first check if derivedBy is present
if (derivedBy.length() == 0) {
// REVISIT: Localize
reportGenericSchemaError("derivedBy must be present when base is present in "
+SchemaSymbols.ELT_COMPLEXTYPE
+" "+ typeName);
}
else {
if (derivedBy.equals(SchemaSymbols.ATTVAL_EXTENSION)) {
derivedByRestriction = false;
}
String prefix = "";
String localpart = base;
int colonptr = base.indexOf(":");
if ( colonptr > 0) {
prefix = base.substring(0,colonptr);
localpart = base.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String typeURI = resolvePrefixToURI(prefix);
// check if the base type is from the same Schema;
if ( ! typeURI.equals(fTargetNSURIString)
&& ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0 ) /*REVISIT, !!!! a hack: for schema that has no target namespace, e.g. personal-schema.xml*/{
baseTypeInfo = getTypeInfoFromNS(typeURI, localpart);
if (baseTypeInfo == null) {
baseTypeValidator = getTypeValidatorFromNS(typeURI, localpart);
if (baseTypeValidator == null) {
//TO DO: report error here;
System.out.println("Could not find base type " +localpart
+ " in schema " + typeURI);
}
else{
baseIsSimpleSimple = true;
}
}
}
else {
fullBaseName = typeURI+","+localpart;
// assume the base is a complexType and try to locate the base type first
baseTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName);
// if not found, 2 possibilities: 1: ComplexType in question has not been compiled yet;
// 2: base is SimpleTYpe;
if (baseTypeInfo == null) {
baseTypeValidator = getDatatypeValidator(typeURI, localpart);
if (baseTypeValidator == null) {
baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode );
baseTypeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol)); //REVISIT: should it be fullBaseName;
}
else {
baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode );
simpleTypeValidator = baseTypeValidator = getDatatypeValidator(typeURI, localpart);
if (simpleTypeValidator == null) {
//TO DO: signal error here.
}
baseIsSimpleSimple = true;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Base type could not be found : " + base);
}
}
}
else {
simpleTypeValidator = baseTypeValidator;
baseIsSimpleSimple = true;
}
}
}
//Schema Spec : 5.11: Complex Type Definition Properties Correct : 2
if (baseIsSimpleSimple && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("base is a simpledType, can't derive by restriction in " + typeName);
}
//if the base is a complexType
if (baseTypeInfo != null ) {
//Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1
// 5.11: Derivation Valid ( Restriction, Complex ) 1.2.1
if (derivedByRestriction) {
//REVISIT: check base Type's finalset does not include "restriction"
}
else {
//REVISIT: check base Type's finalset doest not include "extension"
}
if ( baseTypeInfo.contentSpecHandle > -1) {
if (derivedByRestriction) {
//REVISIT: !!! really hairy staff to check the particle derivation OK in 5.10
checkParticleDerivationOK(complexTypeDecl, baseTypeNode);
}
baseContentSpecHandle = baseTypeInfo.contentSpecHandle;
}
else if ( baseTypeInfo.datatypeValidator != null ) {
baseTypeValidator = baseTypeInfo.datatypeValidator;
baseIsComplexSimple = true;
}
}
//Schema Spec : 5.11: Derivation Valid ( Extension ) 1.1.1
if (baseIsComplexSimple && !derivedByRestriction ) {
// REVISIT: Localize
reportGenericSchemaError("base is ComplexSimple, can't derive by extension in " + typeName);
}
} // END of if (derivedBy.length() == 0) {} else {}
} // END of if (base.length() > 0) {}
// skip refinement and annotations
child = null;
if (baseIsComplexSimple) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
int numEnumerationLiterals = 0;
int numFacets = 0;
Hashtable facetData = new Hashtable();
Vector enumData = new Vector();
//REVISIT: there is a better way to do this,
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null && (child.getNodeName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MININCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) ||
child.getNodeName().equals(SchemaSymbols.ELT_PRECISION) ||
child.getNodeName().equals(SchemaSymbols.ELT_SCALE) ||
child.getNodeName().equals(SchemaSymbols.ELT_LENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_MINLENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_MAXLENGTH) ||
child.getNodeName().equals(SchemaSymbols.ELT_ENCODING) ||
child.getNodeName().equals(SchemaSymbols.ELT_PERIOD) ||
child.getNodeName().equals(SchemaSymbols.ELT_DURATION) ||
child.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION) ||
child.getNodeName().equals(SchemaSymbols.ELT_PATTERN) ||
child.getNodeName().equals(SchemaSymbols.ELT_ANNOTATION));
child = XUtil.getNextSiblingElement(child))
{
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element facetElt = (Element) child;
numFacets++;
if (facetElt.getNodeName().equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE));
//Enumerations can have annotations ? ( 0 | 1 )
Element enumContent = XUtil.getFirstChildElement( facetElt );
if( enumContent != null && enumContent.getNodeName().equals( SchemaSymbols.ELT_ANNOTATION ) ){
traverseAnnotationDecl( child );
}
// TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over
} else {
facetData.put(facetElt.getNodeName(),facetElt.getAttribute( SchemaSymbols.ATT_VALUE ));
}
}
}
if (numEnumerationLiterals > 0) {
facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
//if (numFacets > 0)
// baseTypeValidator.setFacets(facetData, derivedBy );
if (numFacets > 0) {
simpleTypeValidator = fDatatypeRegistry.createDatatypeValidator( typeName, baseTypeValidator,
facetData, false );
}
else
simpleTypeValidator = baseTypeValidator;
if (child != null) {
// REVISIT: Localize
reportGenericSchemaError("Invalid child '"+child.getNodeName()+"' in complexType : '" + typeName
+ "', because it restricts another complexSimpleType");
}
}
// if content = textonly, base is a datatype
if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) {
//TO DO
if (base.length() == 0) {
simpleTypeValidator = baseTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING);
}
else if ( baseTypeValidator == null
&& baseTypeInfo != null && baseTypeInfo.datatypeValidator==null ) // must be datatype
reportSchemaError(SchemaMessageProvider.NotADatatype,
new Object [] { base }); //REVISIT check forward refs
//handle datatypes
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
/****
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF,
fStringPool.addSymbol(base),
-1, false);
/****/
}
else {
if (!baseIsComplexSimple) {
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
}
csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
boolean mixedContent = false;
//REVISIT: is the default content " elementOnly"
boolean elementContent = true;
boolean textContent = false;
boolean emptyContent = false;
left = -2;
right = -2;
boolean hadContent = false;
if (content.equals(SchemaSymbols.ATTVAL_EMPTY)) {
contentSpecType = XMLElementDecl.TYPE_EMPTY;
emptyContent = true;
elementContent = false;
left = -1; // no contentSpecNode needed
} else if (content.equals(SchemaSymbols.ATTVAL_MIXED) ) {
contentSpecType = XMLElementDecl.TYPE_MIXED;
mixedContent = true;
elementContent = false;
csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
} else if (content.equals(SchemaSymbols.ATTVAL_ELEMENTONLY) || content.equals("")) {
elementContent = true;
} else if (content.equals(SchemaSymbols.ATTVAL_TEXTONLY)) {
textContent = true;
elementContent = false;
}
if (mixedContent) {
// add #PCDATA leaf
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF,
-1, // -1 means "#PCDATA" is name
-1, false);
csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
}
boolean seeParticle = false;
boolean seeOtherParticle = false;
boolean seeAll = false;
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2; // to save the particle's contentSpec handle
hadContent = true;
seeParticle = false;
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
if (mixedContent || elementContent) {
if ( DEBUGGING )
System.out.println(" child element name " + child.getAttribute(SchemaSymbols.ATT_NAME));
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
seeOtherParticle = true;
}
else {
reportSchemaError(SchemaMessageProvider.EltRefOnlyInMixedElemOnly, null);
}
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
seeParticle = true;
seeAll = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE) ||
childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
break; // attr processing is done later on in this method
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
seeOtherParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANNOTATION)) {
//REVISIT, do nothing for annotation for now.
}
else if (childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE)) {
break;
//REVISIT, do nothing for attribute wildcard for now.
}
else { // datatype qual
if (!baseIsComplexSimple )
if (base.equals(""))
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "unrecogized child '"+childName+"' in compelx type "+typeName });
else
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "unrecogized child '"+childName+"' in compelx type '"+typeName+"' with base "+base });
}
// if base is complextype with simpleType content, can't have any particle children at all.
if (baseIsComplexSimple && seeParticle) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+", base type is complextype with simpleType content, can't have any particle children at all");
hadContent = false;
left = index = -2;
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
break;
}
// check the minOccurs and maxOccurs of the particle, and fix the
// contentspec accordingly
if (seeParticle) {
index = expandContentModel(index, child);
} //end of if (seeParticle)
if (seeAll && seeOtherParticle) {
// REVISIT: Localize
reportGenericSchemaError ( " 'All' group needs to be the only child in Complextype : " + typeName);
}
if (seeAll) {
//TO DO: REVISIT
//check the minOccurs = 1 and maxOccurs = 1
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
} //end looping through the children
if ( ! ( seeOtherParticle || seeAll ) && (elementContent || mixedContent)
&& (base.length() == 0 || ( base.length() > 0 && derivedByRestriction && !baseIsComplexSimple)) ) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
simpleTypeValidator = getDatatypeValidator("", SchemaSymbols.ATTVAL_STRING);
// REVISIT: Localize
reportGenericSchemaError ( " complexType '"+typeName+"' with a elementOnly or mixed content "
+"need to have at least one particle child");
}
if (hadContent && right != -2)
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
if (mixedContent && hadContent) {
// set occurrence count
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE,
left, -1, false);
}
}
// if derived by extension and base complextype has a content model,
// compose the final content model by concatenating the base and the
// current in sequence.
if (!derivedByRestriction && baseContentSpecHandle > -1 ) {
if (left == -2) {
left = baseContentSpecHandle;
}
else
left = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
baseContentSpecHandle,
left,
false);
}
// REVISIT: this is when sees a topelevel <complexType name="abc">attrs*</complexType>
if (content.length() == 0 && base.length() == 0 && left == -2) {
contentSpecType = XMLElementDecl.TYPE_ANY;
}
if (content.length() == 0 && simpleTypeValidator == null && left == -2 ) {
if (base.length() > 0 && baseTypeInfo != null
&& baseTypeInfo.contentType == XMLElementDecl.TYPE_EMPTY) {
contentSpecType = XMLElementDecl.TYPE_EMPTY;
}
}
if ( DEBUGGING )
System.out.println("!!!!!>>>>>" + typeName+", "+ baseTypeInfo + ", "
+ baseContentSpecHandle +", " + left +", "+scopeDefined);
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
typeInfo.baseComplexTypeInfo = baseTypeInfo;
typeInfo.baseDataTypeValidator = baseTypeValidator;
int derivedByInt = -1;
if (derivedBy.length() > 0) {
derivedByInt = parseComplexDerivedBy(derivedBy);
}
typeInfo.derivedBy = derivedByInt;
typeInfo.scopeDefined = scopeDefined;
typeInfo.contentSpecHandle = left;
typeInfo.contentType = contentSpecType;
typeInfo.datatypeValidator = simpleTypeValidator;
typeInfo.blockSet = parseBlockSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_BLOCK));
typeInfo.finalSet = parseFinalSet(complexTypeDecl.getAttribute(SchemaSymbols.ATT_FINAL));
typeInfo.isAbstract = isAbstract.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false ;
//add a template element to the grammar element decl pool.
int typeNameIndex = fStringPool.addSymbol(typeName);
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex =
fSchemaGrammar.addElementDecl(new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==-1) ? -1 : fCurrentScope, scopeDefined,
contentSpecType, left,
-1, simpleTypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex);
// (attribute | attrGroupRef)*
XMLAttributeDecl attWildcard = null;
Vector anyAttDecls = new Vector();
for (child = XUtil.getFirstChildElement(complexTypeDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getNodeName();
if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) {
if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+
", base type has simpleType "+
"content and derivation method is"+
" 'restriction', can't have any "+
"attribute children at all");
break;
}
traverseAttributeDecl(child, typeInfo);
}
else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
if ((baseIsComplexSimple||baseIsSimpleSimple) && derivedByRestriction) {
// REVISIT: Localize
reportGenericSchemaError("In complexType "+typeName+", base "+
"type has simpleType content and "+
"derivation method is 'restriction',"+
" can't have any attribute children at all");
break;
}
traverseAttributeGroupDecl(child,typeInfo,anyAttDecls);
}
else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
attWildcard = traverseAnyAttribute(child);
}
}
if (attWildcard != null) {
XMLAttributeDecl fromGroup = null;
final int count = anyAttDecls.size();
if ( count > 0) {
fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0);
for (int i=1; i<count; i++) {
fromGroup = mergeTwoAnyAttribute(fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i));
}
}
if (fromGroup != null) {
int saveProcessContents = attWildcard.defaultType;
attWildcard = mergeTwoAnyAttribute(attWildcard, fromGroup);
attWildcard.defaultType = saveProcessContents;
}
}
else {
//REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case
}
// merge in base type's attribute decls
XMLAttributeDecl baseAttWildcard = null;
if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) {
int attDefIndex = baseTypeInfo.attlistHead;
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
fSchemaGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) {
if (attWildcard == null) {
baseAttWildcard = fTempAttributeDecl;
}
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
// if found a duplicate, if it is derived by restriction. then skip the one from the base type
/**/
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name);
if ( temp > -1) {
if (derivedByRestriction) {
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
}
/**/
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
fTempAttributeDecl.name, fTempAttributeDecl.type,
fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType,
fTempAttributeDecl.defaultValue,
fTempAttributeDecl.datatypeValidator,
fTempAttributeDecl.list);
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
// att wildcard will inserted after all attributes were processed
if (attWildcard != null) {
if (attWildcard.type != -1) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attWildcard.name, attWildcard.type,
attWildcard.enumeration, attWildcard.defaultType,
attWildcard.defaultValue,
attWildcard.datatypeValidator,
attWildcard.list);
}
else {
//REVISIT: unclear in Schema spec if should report error here.
}
}
else if (baseAttWildcard != null) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
baseAttWildcard.name, baseAttWildcard.type,
baseAttWildcard.enumeration, baseAttWildcard.defaultType,
baseAttWildcard.defaultValue,
baseAttWildcard.datatypeValidator,
baseAttWildcard.list);
}
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(typeInfo.templateElementIndex);
if (!typeName.startsWith("#")) {
typeName = fTargetNSURIString + "," + typeName;
}
typeInfo.typeName = new String(typeName);
if ( DEBUGGING )
System.out.println("add complex Type to Registry: " + typeName +","+content+".");
fComplexTypeRegistry.put(typeName,typeInfo);
// before exit the complex type definition, restore the scope, mainly for nested Anonymous Types
fCurrentScope = previousScope;
if (isNamedType) {
fCurrentTypeNameStack.pop();
checkRecursingComplexType();
}
//set template element's typeInfo
fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo);
typeNameIndex = fStringPool.addSymbol(typeName);
return typeNameIndex;
} // end of method: traverseComplexTypeDecl
|
diff --git a/test/src/framework/FXCompilerTestCase.java b/test/src/framework/FXCompilerTestCase.java
index 405d7a797..cd2a4dd5d 100644
--- a/test/src/framework/FXCompilerTestCase.java
+++ b/test/src/framework/FXCompilerTestCase.java
@@ -1,225 +1,228 @@
/*
* Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package framework;
import com.sun.javafx.api.JavafxCompiler;
import junit.framework.TestCase;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.filters.StringInputStream;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.PumpStreamHandler;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Path;
import java.io.*;
import java.lang.reflect.Method;
import java.util.*;
/**
* Compiles a single JavaFX script source file and executes the resulting class.
*
* @author tball
*/
public class FXCompilerTestCase extends TestCase {
private final File test;
private final File buildDir;
private final boolean shouldRun;
private String className;
private final List<String> auxFiles;
private static final JavafxCompiler compiler = compilerLocator();
public static final String TEST_ROOT = "test";
public static final String BUILD_ROOT = "build/test";
public static final String TEST_PREFIX = TEST_ROOT + File.separator;
public FXCompilerTestCase(File test, String name, boolean shouldRun, Collection<String> auxFiles) {
super(name);
this.test = test;
this.shouldRun = shouldRun;
assertTrue("path not a relative pathname", test.getPath().startsWith(TEST_PREFIX));
this.buildDir = new File(BUILD_ROOT + File.separator + test.getParent().substring(TEST_PREFIX.length()));
this.auxFiles = new LinkedList<String>(auxFiles);
}
@Override
protected void runTest() throws Throwable {
className = test.getName();
assertTrue(className.endsWith(".fx"));
String outputFileName = buildDir + File.separator + className + ".OUTPUT";
String errorFileName = buildDir + File.separator + className + ".ERROR";
String expectedFileName = test.getPath() + ".EXPECTED";
compile();
if (shouldRun) {
execute(outputFileName, errorFileName);
compare(outputFileName, expectedFileName);
}
}
private void compile() throws IOException {
File buildRoot = new File(BUILD_ROOT);
if (!buildRoot.exists())
fail("no " + BUILD_ROOT + " directory in " + new File(".").getAbsolutePath());
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
buildDir.mkdirs();
List<String> args = new ArrayList<String>();
args.add("-target");
args.add("1.5");
args.add("-d");
args.add(buildDir.getPath());
args.add(test.getPath());
for (String f : auxFiles)
args.add(new File(test.getParent(), f).getPath());
System.out.println("Compiling " + test);
int errors = compiler.run(null, out, err, args.toArray(new String[0]));
if (errors != 0) {
dumpFile(new StringInputStream(new String(err.toByteArray())), "Compiler Output");
System.out.println("--");
StringBuilder sb = new StringBuilder();
sb.append(errors).append(" error");
if (errors > 1)
sb.append('s');
sb.append(" compiling ").append(test);
fail(sb.toString());
}
}
private void execute(String outputFileName, String errorFileName) throws IOException {
System.out.println("Running " + test);
CommandlineJava commandLine = new CommandlineJava();
String mainClass = className.substring(0, className.length() - ".fx".length());
commandLine.setClassname(mainClass);
Project project = new Project();
Path p = commandLine.createClasspath(project);
p.createPathElement().setPath(System.getProperty("java.class.path"));
p.createPathElement().setPath(buildDir.getPath());
PumpStreamHandler sh = new PumpStreamHandler(new FileOutputStream(outputFileName), new FileOutputStream(errorFileName));
Execute exe = new Execute(sh);
String[] strings = commandLine.getCommandline();
exe.setCommandline(strings);
try {
exe.execute();
File errorFileHandle = new File(errorFileName);
if (errorFileHandle.length() > 0) {
dumpFile(new FileInputStream(outputFileName), "Test Output");
dumpFile(new FileInputStream(errorFileName), "Test Error");
System.out.println("--");
fail("Output written to standard error");
}
} catch (IOException e) {
fail("Failure running test " + test + ": " + e.getMessage());
}
}
private void compare(String outputFileName, String expectedFileName) throws IOException {
File expectedFile = new File(expectedFileName);
if (expectedFile.exists()) {
System.out.println("Comparing " + test);
BufferedReader expected = new BufferedReader(new InputStreamReader(new FileInputStream(expectedFileName)));
BufferedReader actual = new BufferedReader(new InputStreamReader(new FileInputStream(outputFileName)));
int lineCount = 0;
while (true) {
String es = expected.readLine();
String as = actual.readLine();
while (as != null && as.startsWith("Cobertura:"))
as = actual.readLine();
++lineCount;
if (es == null && as == null)
break;
else if (es == null)
fail("Expected output for " + test + " ends prematurely at line " + lineCount);
else if (as == null)
fail("Program output for " + test + " ends prematurely at line " + lineCount);
else if (!es.equals(as))
fail("Program output for " + test + " differs from expected at line " + lineCount);
}
}
}
private void dumpFile(InputStream file, String header) throws IOException {
System.out.println("--" + header + " for " + test + "--");
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
try {
while (true) {
String line = reader.readLine();
if (line == null)
break;
System.out.println(line);
}
} finally {
reader.close();
}
}
private static JavafxCompiler compilerLocator() {
Iterator<?> iterator;
Class<?> loaderClass;
String loadMethodName;
boolean usingServiceLoader;
try {
loaderClass = Class.forName("java.util.ServiceLoader");
loadMethodName = "load";
usingServiceLoader = true;
} catch (ClassNotFoundException cnfe) {
try {
loaderClass = Class.forName("sun.misc.Service");
loadMethodName = "providers";
usingServiceLoader = false;
} catch (ClassNotFoundException cnfe2) {
throw new AssertionError("Failed discovering ServiceLoader");
}
}
try {
// java.util.ServiceLoader.load or sun.misc.Service.providers
Method loadMethod = loaderClass.getMethod(loadMethodName,
Class.class,
ClassLoader.class);
ClassLoader cl = FXCompilerTestCase.class.getClassLoader();
Object result = loadMethod.invoke(null, JavafxCompiler.class, cl);
// For java.util.ServiceLoader, we have to call another
// method to get the iterator.
if (usingServiceLoader) {
Method m = loaderClass.getMethod("iterator");
result = m.invoke(result); // serviceLoader.iterator();
}
iterator = (Iterator<?>) result;
} catch (Throwable t) {
t.printStackTrace();
- throw new AssertionError("Failed accessing ServiceLoader: " + t);
+ fail("Failed accessing ServiceLoader: " + t);
+ throw new AssertionError(); // not executed
}
- if (!iterator.hasNext())
- throw new AssertionError("No JavaFX Script compiler found");
+ if (!iterator.hasNext()) {
+ fail("No JavaFX Script compiler found");
+ throw new AssertionError(); // not executed
+ }
return (JavafxCompiler)iterator.next();
}
}
| false | true | private static JavafxCompiler compilerLocator() {
Iterator<?> iterator;
Class<?> loaderClass;
String loadMethodName;
boolean usingServiceLoader;
try {
loaderClass = Class.forName("java.util.ServiceLoader");
loadMethodName = "load";
usingServiceLoader = true;
} catch (ClassNotFoundException cnfe) {
try {
loaderClass = Class.forName("sun.misc.Service");
loadMethodName = "providers";
usingServiceLoader = false;
} catch (ClassNotFoundException cnfe2) {
throw new AssertionError("Failed discovering ServiceLoader");
}
}
try {
// java.util.ServiceLoader.load or sun.misc.Service.providers
Method loadMethod = loaderClass.getMethod(loadMethodName,
Class.class,
ClassLoader.class);
ClassLoader cl = FXCompilerTestCase.class.getClassLoader();
Object result = loadMethod.invoke(null, JavafxCompiler.class, cl);
// For java.util.ServiceLoader, we have to call another
// method to get the iterator.
if (usingServiceLoader) {
Method m = loaderClass.getMethod("iterator");
result = m.invoke(result); // serviceLoader.iterator();
}
iterator = (Iterator<?>) result;
} catch (Throwable t) {
t.printStackTrace();
throw new AssertionError("Failed accessing ServiceLoader: " + t);
}
if (!iterator.hasNext())
throw new AssertionError("No JavaFX Script compiler found");
return (JavafxCompiler)iterator.next();
}
| private static JavafxCompiler compilerLocator() {
Iterator<?> iterator;
Class<?> loaderClass;
String loadMethodName;
boolean usingServiceLoader;
try {
loaderClass = Class.forName("java.util.ServiceLoader");
loadMethodName = "load";
usingServiceLoader = true;
} catch (ClassNotFoundException cnfe) {
try {
loaderClass = Class.forName("sun.misc.Service");
loadMethodName = "providers";
usingServiceLoader = false;
} catch (ClassNotFoundException cnfe2) {
throw new AssertionError("Failed discovering ServiceLoader");
}
}
try {
// java.util.ServiceLoader.load or sun.misc.Service.providers
Method loadMethod = loaderClass.getMethod(loadMethodName,
Class.class,
ClassLoader.class);
ClassLoader cl = FXCompilerTestCase.class.getClassLoader();
Object result = loadMethod.invoke(null, JavafxCompiler.class, cl);
// For java.util.ServiceLoader, we have to call another
// method to get the iterator.
if (usingServiceLoader) {
Method m = loaderClass.getMethod("iterator");
result = m.invoke(result); // serviceLoader.iterator();
}
iterator = (Iterator<?>) result;
} catch (Throwable t) {
t.printStackTrace();
fail("Failed accessing ServiceLoader: " + t);
throw new AssertionError(); // not executed
}
if (!iterator.hasNext()) {
fail("No JavaFX Script compiler found");
throw new AssertionError(); // not executed
}
return (JavafxCompiler)iterator.next();
}
|
diff --git a/src/org/treblefrei/kedr/database/musicdns/DigestMaker.java b/src/org/treblefrei/kedr/database/musicdns/DigestMaker.java
index 6299e4e..6f9ca9e 100644
--- a/src/org/treblefrei/kedr/database/musicdns/DigestMaker.java
+++ b/src/org/treblefrei/kedr/database/musicdns/DigestMaker.java
@@ -1,83 +1,84 @@
package org.treblefrei.kedr.database.musicdns;
import org.treblefrei.kedr.audio.AudioDecoder;
import org.treblefrei.kedr.audio.AudioDecoderException;
import org.treblefrei.kedr.audio.DecodedAudioData;
import org.treblefrei.kedr.database.musicdns.ofa.Ofa;
import org.treblefrei.kedr.model.Album;
import org.treblefrei.kedr.model.Track;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class DigestMakerRunnable implements Runnable {
private Track track;
private Map<Track, Digest> store;
public DigestMakerRunnable(Track track, Map<Track, Digest> store) {
this.track = track;
this.store = store;
}
public void run() {
DecodedAudioData audioData = null;
try {
audioData = AudioDecoder.getSamples(track.getFilepath(), 135);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
track.setDuration(audioData.getDuration());
track.setFormat(audioData.getFormat());
- String digestString = Ofa.createPrint(audioData);
- synchronized (store) {
- try {
- store.put(track, new Digest(digestString));
- } catch (AudioDecoderException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- } catch (FileNotFoundException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
+ try {
+ String digestString = Ofa.createPrint(audioData);
+ } catch (AudioDecoderException e) {
+ e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
+ } catch (FileNotFoundException e) {
+ e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
+ } finally {
+ synchronized (store) {
+ store.put(track, new Digest(digestString));
+ }
+ }
}
}
public class DigestMaker {
public static Map<Track, Digest> getAlbumDigest(Album album) throws AudioDecoderException, FileNotFoundException {
List<Track> tracks = album.getTracks();
Map<Track, Digest> digests = new HashMap<Track, Digest>();
for (Track track : tracks) {
DecodedAudioData audioData = AudioDecoder.getSamples(track.getFilepath(), 135);
track.setDuration(audioData.getDuration());
track.setFormat(audioData.getFormat());
digests.put(track, new Digest(Ofa.createPrint(audioData)));
}
return digests;
}
public static Map<Track, Digest> getAlbumDigestThreaded(Album album) {
List<Track> tracks = album.getTracks();
Map<Track, Digest> digests = new HashMap<Track, Digest>();
ExecutorService executor = Executors.newCachedThreadPool();
for (Track track : tracks) {
executor.execute(new DigestMakerRunnable(track, digests));
}
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return digests;
}
}
| true | true | public void run() {
DecodedAudioData audioData = null;
try {
audioData = AudioDecoder.getSamples(track.getFilepath(), 135);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
track.setDuration(audioData.getDuration());
track.setFormat(audioData.getFormat());
String digestString = Ofa.createPrint(audioData);
synchronized (store) {
try {
store.put(track, new Digest(digestString));
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
| public void run() {
DecodedAudioData audioData = null;
try {
audioData = AudioDecoder.getSamples(track.getFilepath(), 135);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
track.setDuration(audioData.getDuration());
track.setFormat(audioData.getFormat());
try {
String digestString = Ofa.createPrint(audioData);
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
synchronized (store) {
store.put(track, new Digest(digestString));
}
}
}
|
diff --git a/src/org/openstreetmap/josm/gui/MapView.java b/src/org/openstreetmap/josm/gui/MapView.java
index 82215edf..5297cfa8 100644
--- a/src/org/openstreetmap/josm/gui/MapView.java
+++ b/src/org/openstreetmap/josm/gui/MapView.java
@@ -1,550 +1,550 @@
// License: GPL. See LICENSE file for details.
package org.openstreetmap.josm.gui;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.GeneralPath;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.actions.AutoScaleAction;
import org.openstreetmap.josm.actions.JosmAction;
import org.openstreetmap.josm.actions.MoveAction;
import org.openstreetmap.josm.actions.mapmode.MapMode;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.SelectionChangedListener;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.osm.DataSet;
import org.openstreetmap.josm.data.osm.DataSource;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
import org.openstreetmap.josm.gui.layer.Layer;
import org.openstreetmap.josm.gui.layer.MapViewPaintable;
import org.openstreetmap.josm.gui.layer.OsmDataLayer;
import org.openstreetmap.josm.gui.layer.OsmDataLayer.ModifiedChangedListener;
import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer;
import org.openstreetmap.josm.gui.layer.markerlayer.PlayHeadMarker;
import org.openstreetmap.josm.tools.AudioPlayer;
/**
* This is a component used in the MapFrame for browsing the map. It use is to
* provide the MapMode's enough capabilities to operate.
*
* MapView hold meta-data about the data set currently displayed, as scale level,
* center point viewed, what scrolling mode or editing mode is selected or with
* what projection the map is viewed etc..
*
* MapView is able to administrate several layers.
*
* @author imi
*/
public class MapView extends NavigatableComponent implements PropertyChangeListener {
/**
* A list of all layers currently loaded.
*/
private ArrayList<Layer> layers = new ArrayList<Layer>();
/**
* The play head marker: there is only one of these so it isn't in any specific layer
*/
public PlayHeadMarker playHeadMarker = null;
/**
* The layer from the layers list that is currently active.
*/
private Layer activeLayer;
/**
* The last event performed by mouse.
*/
public MouseEvent lastMEvent;
private LinkedList<MapViewPaintable> temporaryLayers = new LinkedList<MapViewPaintable>();
private BufferedImage offscreenBuffer;
public MapView() {
addComponentListener(new ComponentAdapter(){
@Override public void componentResized(ComponentEvent e) {
removeComponentListener(this);
MapSlider zoomSlider = new MapSlider(MapView.this);
add(zoomSlider);
zoomSlider.setBounds(3, 0, 114, 30);
MapScaler scaler = new MapScaler(MapView.this);
add(scaler);
scaler.setLocation(10,30);
if (!zoomToEditLayerBoundingBox()) {
new AutoScaleAction("data").actionPerformed(null);
}
new MapMover(MapView.this, Main.contentPane);
JosmAction mv;
mv = new MoveAction(MoveAction.Direction.UP);
if (mv.getShortcut() != null) {
Main.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(mv.getShortcut().getKeyStroke(), "UP");
Main.contentPane.getActionMap().put("UP", mv);
}
mv = new MoveAction(MoveAction.Direction.DOWN);
if (mv.getShortcut() != null) {
Main.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(mv.getShortcut().getKeyStroke(), "DOWN");
Main.contentPane.getActionMap().put("DOWN", mv);
}
mv = new MoveAction(MoveAction.Direction.LEFT);
if (mv.getShortcut() != null) {
Main.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(mv.getShortcut().getKeyStroke(), "LEFT");
Main.contentPane.getActionMap().put("LEFT", mv);
}
mv = new MoveAction(MoveAction.Direction.RIGHT);
if (mv.getShortcut() != null) {
Main.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(mv.getShortcut().getKeyStroke(), "RIGHT");
Main.contentPane.getActionMap().put("RIGHT", mv);
}
}
});
// listend to selection changes to redraw the map
DataSet.selListeners.add(new SelectionChangedListener(){
public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
repaint();
}
});
//store the last mouse action
this.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
mouseMoved(e);
}
public void mouseMoved(MouseEvent e) {
lastMEvent = e;
}
});
}
/**
* Add a layer to the current MapView. The layer will be added at topmost
* position.
*/
public void addLayer(Layer layer) {
if (layer instanceof OsmDataLayer) {
OsmDataLayer editLayer = (OsmDataLayer)layer;
editLayer.listenerModified.add(new ModifiedChangedListener(){
public void modifiedChanged(boolean value, OsmDataLayer source) {
JOptionPane.getFrameForComponent(Main.parent).setTitle((value?"*":"")
+tr("Java OpenStreetMap Editor"));
}
});
}
if (layer instanceof MarkerLayer && playHeadMarker == null) {
playHeadMarker = PlayHeadMarker.create();
}
int pos = layers.size();
while(pos > 0 && layers.get(pos-1).background) {
--pos;
}
layers.add(pos, layer);
for (Layer.LayerChangeListener l : Layer.listeners) {
l.layerAdded(layer);
}
if (layer instanceof OsmDataLayer || activeLayer == null) {
// autoselect the new layer
Layer old = activeLayer;
setActiveLayer(layer);
for (Layer.LayerChangeListener l : Layer.listeners) {
l.activeLayerChange(old, layer);
}
}
layer.addPropertyChangeListener(this);
AudioPlayer.reset();
repaint();
}
@Override
protected DataSet getCurrentDataSet() {
if(activeLayer != null && activeLayer instanceof OsmDataLayer)
return ((OsmDataLayer)activeLayer).data;
return null;
}
/**
* Replies true if the active layer is drawable.
*
* @return true if the active layer is drawable, false otherwise
*/
public boolean isActiveLayerDrawable() {
return activeLayer != null && activeLayer instanceof OsmDataLayer;
}
/**
* Replies true if the active layer is visible.
*
* @return true if the active layer is visible, false otherwise
*/
public boolean isActiveLayerVisible() {
return isActiveLayerDrawable() && activeLayer.isVisible();
}
protected void fireActiveLayerChanged(Layer oldLayer, Layer newLayer) {
for (Layer.LayerChangeListener l : Layer.listeners) {
l.activeLayerChange(oldLayer, newLayer);
}
}
/**
* Remove the layer from the mapview. If the layer was in the list before,
* an LayerChange event is fired.
*/
public void removeLayer(Layer layer) {
boolean deletedLayerWasActiveLayer = false;
if (layer == activeLayer) {
activeLayer = null;
deletedLayerWasActiveLayer = true;
fireActiveLayerChanged(layer, null);
}
if (layers.remove(layer)) {
for (Layer.LayerChangeListener l : Layer.listeners) {
l.layerRemoved(layer);
}
}
layer.removePropertyChangeListener(this);
layer.destroy();
AudioPlayer.reset();
if (layer instanceof OsmDataLayer && deletedLayerWasActiveLayer) {
for (Layer l : layers) {
if (l instanceof OsmDataLayer) {
activeLayer = l;
fireActiveLayerChanged(null, activeLayer);
}
}
}
repaint();
}
private boolean virtualNodesEnabled = false;
public void setVirtualNodesEnabled(boolean enabled) {
if(virtualNodesEnabled != enabled) {
virtualNodesEnabled = enabled;
repaint();
}
}
public boolean isVirtualNodesEnabled() {
return virtualNodesEnabled;
}
/**
* Moves the layer to the given new position. No event is fired.
* @param layer The layer to move
* @param pos The new position of the layer
*/
public void moveLayer(Layer layer, int pos) {
int curLayerPos = layers.indexOf(layer);
if (curLayerPos == -1)
throw new IllegalArgumentException(tr("layer not in list."));
if (pos == curLayerPos)
return; // already in place.
layers.remove(curLayerPos);
if (pos >= layers.size()) {
layers.add(layer);
} else {
layers.add(pos, layer);
}
AudioPlayer.reset();
}
public int getLayerPos(Layer layer) {
int curLayerPos = layers.indexOf(layer);
if (curLayerPos == -1)
throw new IllegalArgumentException(tr("layer not in list."));
return curLayerPos;
}
/**
* Draw the component.
*/
@Override public void paint(Graphics g) {
if (center == null)
return; // no data loaded yet.
// re-create offscreen-buffer if we've been resized, otherwise
// just re-use it.
if (null == offscreenBuffer || offscreenBuffer.getWidth() != getWidth()
|| offscreenBuffer.getHeight() != getHeight()) {
offscreenBuffer = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
Graphics2D tempG = offscreenBuffer.createGraphics();
tempG.setColor(Main.pref.getColor("background", Color.BLACK));
tempG.fillRect(0, 0, getWidth(), getHeight());
Layer activeLayer = getActiveLayer();
for (int i = layers.size()-1; i >= 0; --i) {
Layer l = layers.get(i);
if (l.isVisible() && l != getActiveLayer()) {
l.paint(tempG, this);
}
}
- if (activeLayer != null) {
+ if (activeLayer != null && activeLayer.isVisible()) {
activeLayer.paint(tempG, this);
}
for (MapViewPaintable mvp : temporaryLayers) {
mvp.paint(tempG, this);
}
// draw world borders
tempG.setColor(Color.WHITE);
GeneralPath path = new GeneralPath();
Bounds b = getProjection().getWorldBoundsLatLon();
double lat = b.min.lat();
double lon = b.min.lon();
Point p = getPoint(b.min);
path.moveTo(p.x, p.y);
double max = b.max.lat();
for(; lat <= max; lat += 1.0)
{
p = getPoint(new LatLon(lat >= max ? max : lat, lon));
path.lineTo(p.x, p.y);
}
lat = max; max = b.max.lon();
for(; lon <= max; lon += 1.0)
{
p = getPoint(new LatLon(lat, lon >= max ? max : lon));
path.lineTo(p.x, p.y);
}
lon = max; max = b.min.lat();
for(; lat >= max; lat -= 1.0)
{
p = getPoint(new LatLon(lat <= max ? max : lat, lon));
path.lineTo(p.x, p.y);
}
lat = max; max = b.min.lon();
for(; lon >= max; lon -= 1.0)
{
p = getPoint(new LatLon(lat, lon <= max ? max : lon));
path.lineTo(p.x, p.y);
}
if (playHeadMarker != null) {
playHeadMarker.paint(tempG, this);
}
tempG.draw(path);
g.drawImage(offscreenBuffer, 0, 0, null);
super.paint(g);
}
/**
* Set the new dimension to the view.
*/
public void recalculateCenterScale(BoundingXYVisitor box) {
if (box == null) {
box = new BoundingXYVisitor();
}
if (box.getBounds() == null) {
box.visit(getProjection().getWorldBoundsLatLon());
}
if (!box.hasExtend()) {
box.enlargeBoundingBox();
}
zoomTo(box.getBounds());
}
/**
* @return An unmodifiable collection of all layers
*/
public Collection<Layer> getAllLayers() {
return Collections.unmodifiableCollection(layers);
}
/**
* @return An unmodifiable ordered list of all layers
*/
public List<Layer> getAllLayersAsList() {
return Collections.unmodifiableList(layers);
}
/**
* Replies an unmodifiable list of layers of a certain type.
*
* Example:
* <pre>
* List<WMSLayer> wmsLayers = getLayersOfType(WMSLayer.class);
* </pre>
*
* @return an unmodifiable list of layers of a certain type.
*/
public <T> List<T> getLayersOfType(Class<T> ofType) {
ArrayList<T> ret = new ArrayList<T>();
for (Layer layer : getAllLayersAsList()) {
if (ofType.isInstance(layer)) {
ret.add(ofType.cast(layer));
}
}
return ret;
}
/**
* Replies the number of layers managed by this mav view
*
* @return the number of layers managed by this mav view
*/
public int getNumLayers() {
return layers.size();
}
/**
* Replies true if there is at least one layer in this map view
*
* @return true if there is at least one layer in this map view
*/
public boolean hasLayers() {
return getNumLayers() > 0;
}
/**
* Sets the active layer to <code>layer</code>. If <code>layer</code> is an instance
* of {@see OsmDataLayer} also sets {@see #editLayer} to <code>layer</code>.
*
* @param layer the layer to be activate; must be one of the layers in the list of layers
* @exception IllegalArgumentException thrown if layer is not in the lis of layers
*/
public void setActiveLayer(Layer layer) {
if (!layers.contains(layer))
throw new IllegalArgumentException(tr("Layer ''{0}'' must be in list of layers", layer.toString()));
if (! (layer instanceof OsmDataLayer)) {
if (getCurrentDataSet() != null) {
getCurrentDataSet().setSelected();
DataSet.fireSelectionChanged(getCurrentDataSet().getSelected());
}
}
Layer old = activeLayer;
activeLayer = layer;
if (old != layer) {
for (Layer.LayerChangeListener l : Layer.listeners) {
l.activeLayerChange(old, layer);
}
}
/* This only makes the buttons look disabled. Disabling the actions as well requires
* the user to re-select the tool after i.e. moving a layer. While testing I found
* that I switch layers and actions at the same time and it was annoying to mind the
* order. This way it works as visual clue for new users */
for (Enumeration<AbstractButton> e = Main.map.toolGroup.getElements() ; e.hasMoreElements() ;) {
AbstractButton x=e.nextElement();
x.setEnabled(((MapMode)x.getAction()).layerIsSupported(layer));
}
AudioPlayer.reset();
repaint();
}
/**
* Replies the currently active layer
*
* @return the currently active layer (may be null)
*/
public Layer getActiveLayer() {
return activeLayer;
}
/**
* Replies the current edit layer, if any
*
* @return the current edit layer. May be null.
*/
public OsmDataLayer getEditLayer() {
if (activeLayer instanceof OsmDataLayer)
return (OsmDataLayer)activeLayer;
// the first OsmDataLayer is the edit layer
//
for (Layer layer : layers) {
if (layer instanceof OsmDataLayer)
return (OsmDataLayer)layer;
}
return null;
}
/**
* replies true if the list of layers managed by this map view contain layer
*
* @param layer the layer
* @return true if the list of layers managed by this map view contain layer
*/
public boolean hasLayer(Layer layer) {
return layers.contains(layer);
}
/**
* Tries to zoom to the download boundingbox[es] of the current edit layer
* (aka {@link OsmDataLayer}). If the edit layer has multiple download bounding
* boxes it zooms to a large virtual bounding box containing all smaller ones.
* This implementation can be used for resolving ticket #1461.
*
* @return <code>true</code> if a zoom operation has been performed
*/
public boolean zoomToEditLayerBoundingBox() {
// workaround for #1461 (zoom to download bounding box instead of all data)
// In case we already have an existing data layer ...
OsmDataLayer layer= getEditLayer();
if (layer == null)
return false;
Collection<DataSource> dataSources = layer.data.dataSources;
// ... with bounding box[es] of data loaded from OSM or a file...
BoundingXYVisitor bbox = new BoundingXYVisitor();
for (DataSource ds : dataSources) {
bbox.visit(ds.bounds);
if (bbox.hasExtend()) {
// ... we zoom to it's bounding box
recalculateCenterScale(bbox);
return true;
}
}
return false;
}
public boolean addTemporaryLayer(MapViewPaintable mvp) {
if (temporaryLayers.contains(mvp)) return false;
return temporaryLayers.add(mvp);
}
public boolean removeTemporaryLayer(MapViewPaintable mvp) {
return temporaryLayers.remove(mvp);
}
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(Layer.VISIBLE_PROP)) {
repaint();
}
}
}
| true | true | @Override public void paint(Graphics g) {
if (center == null)
return; // no data loaded yet.
// re-create offscreen-buffer if we've been resized, otherwise
// just re-use it.
if (null == offscreenBuffer || offscreenBuffer.getWidth() != getWidth()
|| offscreenBuffer.getHeight() != getHeight()) {
offscreenBuffer = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
Graphics2D tempG = offscreenBuffer.createGraphics();
tempG.setColor(Main.pref.getColor("background", Color.BLACK));
tempG.fillRect(0, 0, getWidth(), getHeight());
Layer activeLayer = getActiveLayer();
for (int i = layers.size()-1; i >= 0; --i) {
Layer l = layers.get(i);
if (l.isVisible() && l != getActiveLayer()) {
l.paint(tempG, this);
}
}
if (activeLayer != null) {
activeLayer.paint(tempG, this);
}
for (MapViewPaintable mvp : temporaryLayers) {
mvp.paint(tempG, this);
}
// draw world borders
tempG.setColor(Color.WHITE);
GeneralPath path = new GeneralPath();
Bounds b = getProjection().getWorldBoundsLatLon();
double lat = b.min.lat();
double lon = b.min.lon();
Point p = getPoint(b.min);
path.moveTo(p.x, p.y);
double max = b.max.lat();
for(; lat <= max; lat += 1.0)
{
p = getPoint(new LatLon(lat >= max ? max : lat, lon));
path.lineTo(p.x, p.y);
}
lat = max; max = b.max.lon();
for(; lon <= max; lon += 1.0)
{
p = getPoint(new LatLon(lat, lon >= max ? max : lon));
path.lineTo(p.x, p.y);
}
lon = max; max = b.min.lat();
for(; lat >= max; lat -= 1.0)
{
p = getPoint(new LatLon(lat <= max ? max : lat, lon));
path.lineTo(p.x, p.y);
}
lat = max; max = b.min.lon();
for(; lon >= max; lon -= 1.0)
{
p = getPoint(new LatLon(lat, lon <= max ? max : lon));
path.lineTo(p.x, p.y);
}
if (playHeadMarker != null) {
playHeadMarker.paint(tempG, this);
}
tempG.draw(path);
g.drawImage(offscreenBuffer, 0, 0, null);
super.paint(g);
}
| @Override public void paint(Graphics g) {
if (center == null)
return; // no data loaded yet.
// re-create offscreen-buffer if we've been resized, otherwise
// just re-use it.
if (null == offscreenBuffer || offscreenBuffer.getWidth() != getWidth()
|| offscreenBuffer.getHeight() != getHeight()) {
offscreenBuffer = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
Graphics2D tempG = offscreenBuffer.createGraphics();
tempG.setColor(Main.pref.getColor("background", Color.BLACK));
tempG.fillRect(0, 0, getWidth(), getHeight());
Layer activeLayer = getActiveLayer();
for (int i = layers.size()-1; i >= 0; --i) {
Layer l = layers.get(i);
if (l.isVisible() && l != getActiveLayer()) {
l.paint(tempG, this);
}
}
if (activeLayer != null && activeLayer.isVisible()) {
activeLayer.paint(tempG, this);
}
for (MapViewPaintable mvp : temporaryLayers) {
mvp.paint(tempG, this);
}
// draw world borders
tempG.setColor(Color.WHITE);
GeneralPath path = new GeneralPath();
Bounds b = getProjection().getWorldBoundsLatLon();
double lat = b.min.lat();
double lon = b.min.lon();
Point p = getPoint(b.min);
path.moveTo(p.x, p.y);
double max = b.max.lat();
for(; lat <= max; lat += 1.0)
{
p = getPoint(new LatLon(lat >= max ? max : lat, lon));
path.lineTo(p.x, p.y);
}
lat = max; max = b.max.lon();
for(; lon <= max; lon += 1.0)
{
p = getPoint(new LatLon(lat, lon >= max ? max : lon));
path.lineTo(p.x, p.y);
}
lon = max; max = b.min.lat();
for(; lat >= max; lat -= 1.0)
{
p = getPoint(new LatLon(lat <= max ? max : lat, lon));
path.lineTo(p.x, p.y);
}
lat = max; max = b.min.lon();
for(; lon >= max; lon -= 1.0)
{
p = getPoint(new LatLon(lat, lon <= max ? max : lon));
path.lineTo(p.x, p.y);
}
if (playHeadMarker != null) {
playHeadMarker.paint(tempG, this);
}
tempG.draw(path);
g.drawImage(offscreenBuffer, 0, 0, null);
super.paint(g);
}
|
diff --git a/src/test/java/edu/mines/acmX/exhibit/module_management/ModuleManagerWithKinectPluggedInTest.java b/src/test/java/edu/mines/acmX/exhibit/module_management/ModuleManagerWithKinectPluggedInTest.java
index 1b81306..4edc48b 100644
--- a/src/test/java/edu/mines/acmX/exhibit/module_management/ModuleManagerWithKinectPluggedInTest.java
+++ b/src/test/java/edu/mines/acmX/exhibit/module_management/ModuleManagerWithKinectPluggedInTest.java
@@ -1,117 +1,117 @@
package edu.mines.acmX.exhibit.module_management;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.print.DocFlavor.URL;
import org.junit.Before;
import org.junit.Test;
import edu.mines.acmX.exhibit.input_services.hardware.BadDeviceFunctionalityRequestException;
import edu.mines.acmX.exhibit.input_services.hardware.HardwareManager;
import edu.mines.acmX.exhibit.input_services.hardware.HardwareManagerManifestException;
import edu.mines.acmX.exhibit.input_services.hardware.drivers.InvalidConfigurationFileException;
import edu.mines.acmX.exhibit.module_management.loaders.ManifestLoadException;
import edu.mines.acmX.exhibit.module_management.loaders.ModuleLoadException;
import edu.mines.acmX.exhibit.module_management.metas.DependencyType;
import edu.mines.acmX.exhibit.module_management.metas.ModuleManagerMetaData;
import edu.mines.acmX.exhibit.module_management.metas.ModuleMetaData;
import edu.mines.acmX.exhibit.module_management.metas.ModuleMetaDataBuilder;
import edu.mines.acmX.exhibit.module_management.modules.CommandlineModule;
import edu.mines.acmX.exhibit.module_management.modules.ModuleInterface;
/**
* Unit test for ModuleManager
*/
public class ModuleManagerWithKinectPluggedInTest {
@Before
public void resetModuleManager() {
ModuleManager.removeInstance();
ModuleManager.createEmptyInstance();
}
/**
* Test that module manager loads when hardware is there and setup correctly
* @throws ManifestLoadException
* @throws BadDeviceFunctionalityRequestException
* @throws HardwareManagerManifestException
* @throws ModuleLoadException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
@Test
public void testNoRevertAndOkayOnGoodDriverRequest() throws ManifestLoadException, ModuleLoadException, HardwareManagerManifestException, BadDeviceFunctionalityRequestException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ModuleManager.removeInstance();
ModuleManager.configure("src/test/resources/module_manager/BadHardwareRequestModuleManagerManifest.xml");
ModuleManager m = ModuleManager.getInstance();
// The next three lines are to give the hardware manager support
Map<String, String> configStore = new HashMap<String, String>();
- configStore.put("kinectopenni", "openni_config.xml");
+ configStore.put("kinectopenni", "src/test/resources/openni_config.xml");
HardwareManager.getInstance().setConfigurationFileStore(configStore);
// pretend the next module was set (to skip that logic)
// default = false
Field loadDefault = ModuleManager.class.getDeclaredField("loadDefault");
loadDefault.setAccessible(true);
loadDefault.set(m, false);
// set the nextModuleMetaData
// TODO change this to instead use a generated ModuleMetaData so we can skip some of the logic for ModuleManager
ModuleMetaData badMetaData = m.getModuleMetaDataMap().get("edu.mines.ademaria.goodmodules.goodrequireddriver");
Field nextModuleMeta = ModuleManager.class.getDeclaredField("nextModuleMetaData");
nextModuleMeta.setAccessible(true);
nextModuleMeta.set(m, badMetaData);
// call the setup function
Method setupDefaultRuntime = ModuleManager.class.getDeclaredMethod("setupPreRuntime");
setupDefaultRuntime.setAccessible(true);
setupDefaultRuntime.invoke(m);
// check that the module was reverted to default
Field currentMeta = ModuleManager.class.getDeclaredField("currentModuleMetaData");
currentMeta.setAccessible(true);
ModuleMetaData actual = (ModuleMetaData) currentMeta.get(m);
assertEquals("edu.mines.ademaria.goodmodules.goodrequireddriver", actual.getPackageName());
}
@Test
public void testDefaultCheckPermissionsPassForRuntime()
throws ManifestLoadException, ModuleLoadException,
HardwareManagerManifestException,
BadDeviceFunctionalityRequestException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
ModuleManager.removeInstance();
ModuleManager.configure("src/test/resources/module_manager/ExampleModuleManagerManifest.xml");
ModuleManager m = ModuleManager.getInstance();
m.setDefault(true);
ModuleMetaDataBuilder builder = new ModuleMetaDataBuilder();
builder.addInputType("rgbimage", DependencyType.REQUIRED);
builder.setPackageName("com.austindiviness.cltest");
builder.setClassName("Launch");
ModuleMetaData mmd = builder.build();
mmd.setJarFileName("cltest.jar");
m.setDefaultModuleMetaData(mmd);
Method preDefaultRT = ModuleManager.class.getDeclaredMethod("setupPreRuntime");
preDefaultRT.setAccessible(true);
preDefaultRT.invoke(m);
}
}
| true | true | public void testNoRevertAndOkayOnGoodDriverRequest() throws ManifestLoadException, ModuleLoadException, HardwareManagerManifestException, BadDeviceFunctionalityRequestException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ModuleManager.removeInstance();
ModuleManager.configure("src/test/resources/module_manager/BadHardwareRequestModuleManagerManifest.xml");
ModuleManager m = ModuleManager.getInstance();
// The next three lines are to give the hardware manager support
Map<String, String> configStore = new HashMap<String, String>();
configStore.put("kinectopenni", "openni_config.xml");
HardwareManager.getInstance().setConfigurationFileStore(configStore);
// pretend the next module was set (to skip that logic)
// default = false
Field loadDefault = ModuleManager.class.getDeclaredField("loadDefault");
loadDefault.setAccessible(true);
loadDefault.set(m, false);
// set the nextModuleMetaData
// TODO change this to instead use a generated ModuleMetaData so we can skip some of the logic for ModuleManager
ModuleMetaData badMetaData = m.getModuleMetaDataMap().get("edu.mines.ademaria.goodmodules.goodrequireddriver");
Field nextModuleMeta = ModuleManager.class.getDeclaredField("nextModuleMetaData");
nextModuleMeta.setAccessible(true);
nextModuleMeta.set(m, badMetaData);
// call the setup function
Method setupDefaultRuntime = ModuleManager.class.getDeclaredMethod("setupPreRuntime");
setupDefaultRuntime.setAccessible(true);
setupDefaultRuntime.invoke(m);
// check that the module was reverted to default
Field currentMeta = ModuleManager.class.getDeclaredField("currentModuleMetaData");
currentMeta.setAccessible(true);
ModuleMetaData actual = (ModuleMetaData) currentMeta.get(m);
assertEquals("edu.mines.ademaria.goodmodules.goodrequireddriver", actual.getPackageName());
}
| public void testNoRevertAndOkayOnGoodDriverRequest() throws ManifestLoadException, ModuleLoadException, HardwareManagerManifestException, BadDeviceFunctionalityRequestException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ModuleManager.removeInstance();
ModuleManager.configure("src/test/resources/module_manager/BadHardwareRequestModuleManagerManifest.xml");
ModuleManager m = ModuleManager.getInstance();
// The next three lines are to give the hardware manager support
Map<String, String> configStore = new HashMap<String, String>();
configStore.put("kinectopenni", "src/test/resources/openni_config.xml");
HardwareManager.getInstance().setConfigurationFileStore(configStore);
// pretend the next module was set (to skip that logic)
// default = false
Field loadDefault = ModuleManager.class.getDeclaredField("loadDefault");
loadDefault.setAccessible(true);
loadDefault.set(m, false);
// set the nextModuleMetaData
// TODO change this to instead use a generated ModuleMetaData so we can skip some of the logic for ModuleManager
ModuleMetaData badMetaData = m.getModuleMetaDataMap().get("edu.mines.ademaria.goodmodules.goodrequireddriver");
Field nextModuleMeta = ModuleManager.class.getDeclaredField("nextModuleMetaData");
nextModuleMeta.setAccessible(true);
nextModuleMeta.set(m, badMetaData);
// call the setup function
Method setupDefaultRuntime = ModuleManager.class.getDeclaredMethod("setupPreRuntime");
setupDefaultRuntime.setAccessible(true);
setupDefaultRuntime.invoke(m);
// check that the module was reverted to default
Field currentMeta = ModuleManager.class.getDeclaredField("currentModuleMetaData");
currentMeta.setAccessible(true);
ModuleMetaData actual = (ModuleMetaData) currentMeta.get(m);
assertEquals("edu.mines.ademaria.goodmodules.goodrequireddriver", actual.getPackageName());
}
|
diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java
index af72ac6528..f7d8759ad3 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java
@@ -1,114 +1,114 @@
package org.drools.compiler.kie.builder.impl;
import org.drools.compiler.kproject.models.KieBaseModelImpl;
import org.drools.compiler.kproject.models.KieSessionModelImpl;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.drools.compiler.kie.builder.impl.AbstractKieModule.buildKnowledgePackages;
public abstract class AbstractKieProject implements KieProject {
private static final Logger log = LoggerFactory.getLogger(KieProject.class);
protected final Map<String, KieBaseModel> kBaseModels = new HashMap<String, KieBaseModel>();
private KieBaseModel defaultKieBase = null;
private KieSessionModel defaultKieSession = null;
private KieSessionModel defaultStatelessKieSession = null;
protected final Map<String, KieSessionModel> kSessionModels = new HashMap<String, KieSessionModel>();
public ResultsImpl verify() {
ResultsImpl messages = new ResultsImpl();
verify(messages);
return messages;
}
public void verify(ResultsImpl messages) {
for ( KieBaseModel model : kBaseModels.values() ) {
buildKnowledgePackages((KieBaseModelImpl) model, this, messages);
}
}
public KieBaseModel getDefaultKieBaseModel() {
return defaultKieBase;
}
public KieSessionModel getDefaultKieSession() {
return defaultKieSession;
}
public KieSessionModel getDefaultStatelessKieSession() {
return defaultStatelessKieSession;
}
public KieBaseModel getKieBaseModel(String kBaseName) {
return kBaseModels.get( kBaseName );
}
public KieSessionModel getKieSessionModel(String kSessionName) {
return kSessionModels.get( kSessionName );
}
protected void indexParts(Collection<InternalKieModule> kieModules,
Map<String, InternalKieModule> kJarFromKBaseName) {
for ( InternalKieModule kJar : kieModules ) {
KieModuleModel kieProject = kJar.getKieModuleModel();
for ( KieBaseModel kieBaseModel : kieProject.getKieBaseModels().values() ) {
if (kieBaseModel.isDefault()) {
if (defaultKieBase == null) {
defaultKieBase = kieBaseModel;
} else {
defaultKieBase = null;
- log.warn("Found more than one defualt KieBase: disabling all. KieBases will be accessible only by name");
+ log.warn("Found more than one default KieBase: disabling all. KieBases will be accessible only by name");
}
}
kBaseModels.put( kieBaseModel.getName(), kieBaseModel );
((KieBaseModelImpl) kieBaseModel).setKModule( kieProject ); // should already be set, but just in case
kJarFromKBaseName.put( kieBaseModel.getName(), kJar );
for ( KieSessionModel kieSessionModel : kieBaseModel.getKieSessionModels().values() ) {
if (kieSessionModel.isDefault()) {
if (kieSessionModel.getType() == KieSessionModel.KieSessionType.STATEFUL) {
if (defaultKieSession == null) {
defaultKieSession = kieSessionModel;
} else {
defaultKieSession = null;
log.warn("Found more than one defualt KieSession: disabling all. KieSessions will be accessible only by name");
}
} else {
if (defaultStatelessKieSession == null) {
defaultStatelessKieSession = kieSessionModel;
} else {
defaultStatelessKieSession = null;
log.warn("Found more than one defualt StatelessKieSession: disabling all. StatelessKieSessions will be accessible only by name");
}
}
}
((KieSessionModelImpl) kieSessionModel).setKBase( kieBaseModel ); // should already be set, but just in case
kSessionModels.put( kieSessionModel.getName(), kieSessionModel );
}
}
}
}
protected void cleanIndex() {
kBaseModels.clear();
kSessionModels.clear();
defaultKieBase = null;
defaultKieSession = null;
defaultStatelessKieSession = null;
}
}
| true | true | protected void indexParts(Collection<InternalKieModule> kieModules,
Map<String, InternalKieModule> kJarFromKBaseName) {
for ( InternalKieModule kJar : kieModules ) {
KieModuleModel kieProject = kJar.getKieModuleModel();
for ( KieBaseModel kieBaseModel : kieProject.getKieBaseModels().values() ) {
if (kieBaseModel.isDefault()) {
if (defaultKieBase == null) {
defaultKieBase = kieBaseModel;
} else {
defaultKieBase = null;
log.warn("Found more than one defualt KieBase: disabling all. KieBases will be accessible only by name");
}
}
kBaseModels.put( kieBaseModel.getName(), kieBaseModel );
((KieBaseModelImpl) kieBaseModel).setKModule( kieProject ); // should already be set, but just in case
kJarFromKBaseName.put( kieBaseModel.getName(), kJar );
for ( KieSessionModel kieSessionModel : kieBaseModel.getKieSessionModels().values() ) {
if (kieSessionModel.isDefault()) {
if (kieSessionModel.getType() == KieSessionModel.KieSessionType.STATEFUL) {
if (defaultKieSession == null) {
defaultKieSession = kieSessionModel;
} else {
defaultKieSession = null;
log.warn("Found more than one defualt KieSession: disabling all. KieSessions will be accessible only by name");
}
} else {
if (defaultStatelessKieSession == null) {
defaultStatelessKieSession = kieSessionModel;
} else {
defaultStatelessKieSession = null;
log.warn("Found more than one defualt StatelessKieSession: disabling all. StatelessKieSessions will be accessible only by name");
}
}
}
((KieSessionModelImpl) kieSessionModel).setKBase( kieBaseModel ); // should already be set, but just in case
kSessionModels.put( kieSessionModel.getName(), kieSessionModel );
}
}
}
}
| protected void indexParts(Collection<InternalKieModule> kieModules,
Map<String, InternalKieModule> kJarFromKBaseName) {
for ( InternalKieModule kJar : kieModules ) {
KieModuleModel kieProject = kJar.getKieModuleModel();
for ( KieBaseModel kieBaseModel : kieProject.getKieBaseModels().values() ) {
if (kieBaseModel.isDefault()) {
if (defaultKieBase == null) {
defaultKieBase = kieBaseModel;
} else {
defaultKieBase = null;
log.warn("Found more than one default KieBase: disabling all. KieBases will be accessible only by name");
}
}
kBaseModels.put( kieBaseModel.getName(), kieBaseModel );
((KieBaseModelImpl) kieBaseModel).setKModule( kieProject ); // should already be set, but just in case
kJarFromKBaseName.put( kieBaseModel.getName(), kJar );
for ( KieSessionModel kieSessionModel : kieBaseModel.getKieSessionModels().values() ) {
if (kieSessionModel.isDefault()) {
if (kieSessionModel.getType() == KieSessionModel.KieSessionType.STATEFUL) {
if (defaultKieSession == null) {
defaultKieSession = kieSessionModel;
} else {
defaultKieSession = null;
log.warn("Found more than one defualt KieSession: disabling all. KieSessions will be accessible only by name");
}
} else {
if (defaultStatelessKieSession == null) {
defaultStatelessKieSession = kieSessionModel;
} else {
defaultStatelessKieSession = null;
log.warn("Found more than one defualt StatelessKieSession: disabling all. StatelessKieSessions will be accessible only by name");
}
}
}
((KieSessionModelImpl) kieSessionModel).setKBase( kieBaseModel ); // should already be set, but just in case
kSessionModels.put( kieSessionModel.getName(), kieSessionModel );
}
}
}
}
|
diff --git a/src/org/apache/sandesha2/msgprocessors/SequenceProcessor.java b/src/org/apache/sandesha2/msgprocessors/SequenceProcessor.java
index 00e0dc09..f2219194 100644
--- a/src/org/apache/sandesha2/msgprocessors/SequenceProcessor.java
+++ b/src/org/apache/sandesha2/msgprocessors/SequenceProcessor.java
@@ -1,379 +1,379 @@
/*
* Copyright 2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.apache.sandesha2.msgprocessors;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.addressing.RelatesTo;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.engine.Handler.InvocationResponse;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.RMMsgContext;
import org.apache.sandesha2.Sandesha2Constants;
import org.apache.sandesha2.SandeshaException;
import org.apache.sandesha2.i18n.SandeshaMessageHelper;
import org.apache.sandesha2.i18n.SandeshaMessageKeys;
import org.apache.sandesha2.policy.SandeshaPolicyBean;
import org.apache.sandesha2.security.SecurityManager;
import org.apache.sandesha2.security.SecurityToken;
import org.apache.sandesha2.storage.StorageManager;
import org.apache.sandesha2.storage.beanmanagers.InvokerBeanMgr;
import org.apache.sandesha2.storage.beanmanagers.RMDBeanMgr;
import org.apache.sandesha2.storage.beanmanagers.RMSBeanMgr;
import org.apache.sandesha2.storage.beanmanagers.SenderBeanMgr;
import org.apache.sandesha2.storage.beans.InvokerBean;
import org.apache.sandesha2.storage.beans.RMDBean;
import org.apache.sandesha2.storage.beans.RMSBean;
import org.apache.sandesha2.storage.beans.SenderBean;
import org.apache.sandesha2.util.AcknowledgementManager;
import org.apache.sandesha2.util.FaultManager;
import org.apache.sandesha2.util.SandeshaUtil;
import org.apache.sandesha2.util.TerminateManager;
import org.apache.sandesha2.workers.SandeshaThread;
import org.apache.sandesha2.wsrm.Sequence;
/**
* Responsible for processing the Sequence header (if present) on an incoming
* message.
*/
public class SequenceProcessor {
private static final Log log = LogFactory.getLog(SequenceProcessor.class);
public InvocationResponse processSequenceHeader(RMMsgContext rmMsgCtx) throws AxisFault {
if (log.isDebugEnabled())
log.debug("Enter: SequenceProcessor::processSequenceHeader");
InvocationResponse result = InvocationResponse.CONTINUE;
Sequence sequence = (Sequence) rmMsgCtx.getMessagePart(Sandesha2Constants.MessageParts.SEQUENCE);
if(sequence != null) {
// This is a reliable message, so hand it on to the main routine
result = processReliableMessage(rmMsgCtx);
} else {
if (log.isDebugEnabled())
log.debug("Message does not contain a sequence header");
}
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processSequenceHeader " + result);
return result;
}
public InvocationResponse processReliableMessage(RMMsgContext rmMsgCtx) throws AxisFault {
if (log.isDebugEnabled())
log.debug("Enter: SequenceProcessor::processReliableMessage");
InvocationResponse result = InvocationResponse.CONTINUE;
if (rmMsgCtx.getProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE) != null
&& rmMsgCtx.getProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE).equals("true")) {
return result;
}
MessageContext msgCtx = rmMsgCtx.getMessageContext();
StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(msgCtx.getConfigurationContext(),msgCtx.getConfigurationContext().getAxisConfiguration());
Sequence sequence = (Sequence) rmMsgCtx.getMessagePart(Sandesha2Constants.MessageParts.SEQUENCE);
String sequenceId = sequence.getIdentifier().getIdentifier();
long msgNo = sequence.getMessageNumber().getMessageNumber();
boolean lastMessage = sequence.getLastMessage() != null;
// Check that both the Sequence header and message body have been secured properly
RMDBeanMgr mgr = storageManager.getRMDBeanMgr();
RMDBean bean = mgr.retrieve(sequenceId);
if(bean != null && bean.getSecurityTokenData() != null) {
SecurityManager secManager = SandeshaUtil.getSecurityManager(msgCtx.getConfigurationContext());
QName seqName = new QName(rmMsgCtx.getRMNamespaceValue(), Sandesha2Constants.WSRM_COMMON.SEQUENCE);
SOAPEnvelope envelope = msgCtx.getEnvelope();
OMElement body = envelope.getBody();
OMElement seqHeader = envelope.getHeader().getFirstChildWithName(seqName);
SecurityToken token = secManager.recoverSecurityToken(bean.getSecurityTokenData());
secManager.checkProofOfPossession(token, seqHeader, msgCtx);
secManager.checkProofOfPossession(token, body, msgCtx);
}
// Store the inbound sequence id, number and lastMessage onto the operation context
OperationContext opCtx = msgCtx.getOperationContext();
if(opCtx != null) {
opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_SEQUENCE_ID, sequenceId);
opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_MESSAGE_NUMBER, new Long(msgNo));
if(lastMessage) opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_LAST_MESSAGE, Boolean.TRUE);
}
// setting acked msg no range
ConfigurationContext configCtx = rmMsgCtx.getMessageContext().getConfigurationContext();
if (configCtx == null) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.configContextNotSet);
log.debug(message);
throw new SandeshaException(message);
}
if (FaultManager.checkForUnknownSequence(rmMsgCtx, sequenceId, storageManager)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Unknown sequence");
return InvocationResponse.ABORT;
}
// throwing a fault if the sequence is terminated
if (FaultManager.checkForSequenceTerminated(rmMsgCtx, sequenceId, bean)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Sequence terminated");
return InvocationResponse.ABORT;
}
// throwing a fault if the sequence is closed.
if (FaultManager.checkForSequenceClosed(rmMsgCtx, sequenceId, bean)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Sequence closed");
return InvocationResponse.ABORT;
}
FaultManager.checkForLastMsgNumberExceeded(rmMsgCtx, storageManager);
if (FaultManager.checkForMessageRolledOver(rmMsgCtx, sequenceId, msgNo)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Message rolled over " + msgNo);
return InvocationResponse.ABORT;
}
// Pause the messages bean if not the right message to invoke.
// updating the last activated time of the sequence.
bean.setLastActivatedTime(System.currentTimeMillis());
if (lastMessage) {
//setting this as the LastMessage number
bean.setLastInMessageId(msgCtx.getMessageID());
}
EndpointReference replyTo = rmMsgCtx.getReplyTo();
String key = SandeshaUtil.getUUID(); // key to store the message.
// updating the Highest_In_Msg_No property which gives the highest
// message number retrieved from this sequence.
long highestInMsgNo = bean.getHighestInMessageNumber();
if (msgNo > highestInMsgNo) {
// If WS-Addressing is turned off there may not be a message id written into the SOAP
// headers, but we can still fake one up to help us match up requests and replies within
// this end of the connection.
String messageId = msgCtx.getMessageID();
if(messageId == null) {
messageId = SandeshaUtil.getUUID();
msgCtx.setMessageID(messageId);
}
bean.setHighestInMessageId(messageId);
bean.setHighestInMessageNumber(msgNo);
}
String specVersion = rmMsgCtx.getRMSpecVersion();
- if (rmMsgCtx.getMessageContext().getAxisOperation().getName().getLocalPart().equals("RMInOutDuplicateMessageOperation")
+ if (rmMsgCtx.getMessageContext().getAxisOperation().getName().getLocalPart().equals(Sandesha2Constants.RM_DUPLICATE_OPERATION.getLocalPart())
&& (Sandesha2Constants.QOS.InvocationType.DEFAULT_INVOCATION_TYPE == Sandesha2Constants.QOS.InvocationType.EXACTLY_ONCE)) {
// this is a duplicate message and the invocation type is EXACTLY_ONCE. We try to return
// ack messages at this point, as if someone is sending duplicates then they may have
// missed earlier acks. We also have special processing for sync 2-way with RM 1.0
if((replyTo==null || replyTo.hasAnonymousAddress()) &&
(specVersion!=null && specVersion.equals(Sandesha2Constants.SPEC_VERSIONS.v1_0))) {
SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr();
SenderBean findSenderBean = new SenderBean ();
findSenderBean.setMessageType(Sandesha2Constants.MessageTypes.APPLICATION);
findSenderBean.setInboundSequenceId(sequence.getIdentifier().getIdentifier());
findSenderBean.setInboundMessageNumber(sequence.getMessageNumber().getMessageNumber());
findSenderBean.setSend(true);
SenderBean replyMessageBean = senderBeanMgr.findUnique(findSenderBean);
// this is effectively a poll for the replyMessage, wo re-use the logic in the MakeConnection
// processor. This will use this thread to re-send the reply, writing it into the transport.
// As the reply is now written we do not want to continue processing, or suspend, so we abort.
if(replyMessageBean != null) {
if(log.isDebugEnabled()) log.debug("Found matching reply for replayed message");
MakeConnectionProcessor.replyToPoll(rmMsgCtx, replyMessageBean, storageManager, false, null);
result = InvocationResponse.ABORT;
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, replayed message: " + result);
return result;
}
}
EndpointReference acksTo = new EndpointReference (bean.getAcksToEPR());
// Send an Ack if needed.
//We are not sending acks for duplicate messages in the RM 1.0 anon InOut case.
//If a standalone ack get sent before the actualy message (I.e. before the original msg get
//replied), the client may take this as a InOnly message and may avoid looking for the application
//response.
if (!(Sandesha2Constants.SPEC_VERSIONS.v1_0.equals(rmMsgCtx.getRMSpecVersion()) &&
rmMsgCtx.getReplyTo().hasAnonymousAddress())) {
sendAckIfNeeded(bean, sequenceId, rmMsgCtx, storageManager, true, acksTo.hasAnonymousAddress());
}
result = InvocationResponse.ABORT;
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, dropping duplicate: " + result);
return result;
}
// If the message is a reply to an outbound message then we can update the RMSBean that
// matches.
String outboundSequence = bean.getOutboundInternalSequence();
if(outboundSequence != null) {
RMSBean outBean = SandeshaUtil.getRMSBeanFromInternalSequenceId(storageManager, outboundSequence);
if(outBean != null && outBean.getExpectedReplies() > 0 ) {
outBean.setExpectedReplies(outBean.getExpectedReplies() - 1);
RMSBeanMgr outMgr = storageManager.getRMSBeanMgr();
outMgr.update(outBean);
}
}
// Set the last activated time
bean.setLastActivatedTime(System.currentTimeMillis());
// Update the RMD bean
mgr.update(bean);
// If we are doing sync 2-way over WSRM 1.0, then we may just have received one of
// the reply messages that we were looking for. If so we can remove the matching sender bean.
int mep = msgCtx.getAxisOperation().getAxisSpecifMEPConstant();
if(specVersion!=null && specVersion.equals(Sandesha2Constants.SPEC_VERSIONS.v1_0) &&
mep == WSDLConstants.MEP_CONSTANT_OUT_IN) {
RelatesTo relatesTo = msgCtx.getRelatesTo();
if(relatesTo != null) {
String messageId = relatesTo.getValue();
SenderBean matcher = new SenderBean();
matcher.setMessageID(messageId);
SenderBean sender = storageManager.getSenderBeanMgr().findUnique(matcher);
if(sender != null) {
if(log.isDebugEnabled()) log.debug("Deleting sender for sync-2-way message");
storageManager.removeMessageContext(sender.getMessageContextRefKey());
storageManager.getSenderBeanMgr().delete(messageId);
// Try and terminate the corresponding outbound sequence
RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sender.getSequenceID());
TerminateManager.checkAndTerminate(rmMsgCtx.getConfigurationContext(), storageManager, rmsBean);
}
}
}
//setting properties for the messageContext
rmMsgCtx.setProperty(Sandesha2Constants.MessageContextProperties.SEQUENCE_ID,sequenceId);
rmMsgCtx.setProperty(Sandesha2Constants.MessageContextProperties.MESSAGE_NUMBER,new Long (msgNo));
// We only create an ack message if:
// - We have anonymous acks, and the backchannel is free
// - We have async acks
boolean backchannelFree = (replyTo != null && !replyTo.hasAnonymousAddress()) ||
WSDLConstants.MEP_CONSTANT_IN_ONLY == mep;
EndpointReference acksTo = new EndpointReference (bean.getAcksToEPR());
if (acksTo.hasAnonymousAddress() && backchannelFree) {
Object responseWritten = msgCtx.getOperationContext().getProperty(Constants.RESPONSE_WRITTEN);
if (responseWritten==null || !Constants.VALUE_TRUE.equals(responseWritten)) {
RMMsgContext ackRMMsgContext = AcknowledgementManager.generateAckMessage(rmMsgCtx, bean, sequenceId, storageManager,true);
msgCtx.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE);
AcknowledgementManager.sendAckNow(ackRMMsgContext);
}
} else if (!acksTo.hasAnonymousAddress()) {
SandeshaPolicyBean policyBean = SandeshaUtil.getPropertyBean (msgCtx.getAxisOperation());
long ackInterval = policyBean.getAcknowledgementInterval();
long timeToSend = System.currentTimeMillis() + ackInterval;
RMMsgContext ackRMMsgContext = AcknowledgementManager.generateAckMessage(rmMsgCtx, bean, sequenceId, storageManager,true);
AcknowledgementManager.addAckBeanEntry(ackRMMsgContext, sequenceId, timeToSend, storageManager);
}
// If this message matches the WSRM 1.0 pattern for an empty last message (e.g.
// the sender wanted to signal the last message, but didn't have an application
// message to send) then we do not need to send the message on to the application.
if(Sandesha2Constants.SPEC_2005_02.Actions.ACTION_LAST_MESSAGE.equals(msgCtx.getWSAAction()) ||
Sandesha2Constants.SPEC_2005_02.Actions.SOAP_ACTION_LAST_MESSAGE.equals(msgCtx.getSoapAction())) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, got WSRM 1.0 lastmessage, aborting");
return InvocationResponse.ABORT;
}
// If the storage manager has an invoker, then they may be implementing inOrder, or
// transactional delivery. Either way, if they have one we should use it.
SandeshaThread invoker = storageManager.getInvoker();
if (invoker != null) {
// Whatever the MEP, we stop processing here and the invoker will do the real work. We only
// SUSPEND if we need to keep the backchannel open for the response... we may as well ABORT
// to let other cases end more quickly.
if(backchannelFree) {
result = InvocationResponse.ABORT;
} else {
result = InvocationResponse.SUSPEND;
}
InvokerBeanMgr storageMapMgr = storageManager.getInvokerBeanMgr();
storageManager.storeMessageContext(key, rmMsgCtx.getMessageContext());
storageMapMgr.insert(new InvokerBean(key, msgNo, sequenceId));
// This will avoid performing application processing more than once.
rmMsgCtx.setProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE, "true");
}
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage " + result);
return result;
}
private void sendAckIfNeeded(RMDBean rmdBean, String sequenceId, RMMsgContext rmMsgCtx,
StorageManager storageManager, boolean serverSide, boolean anonymousAcksTo)
throws AxisFault {
if (log.isDebugEnabled())
log.debug("Enter: SequenceProcessor::sendAckIfNeeded " + sequenceId);
RMMsgContext ackRMMsgCtx = AcknowledgementManager.generateAckMessage(
rmMsgCtx, rmdBean, sequenceId, storageManager, serverSide);
if (anonymousAcksTo) {
rmMsgCtx.getMessageContext().getOperationContext().
setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE);
AcknowledgementManager.sendAckNow(ackRMMsgCtx);
} else {
long ackInterval = SandeshaUtil.getPropertyBean(
rmMsgCtx.getMessageContext().getAxisService())
.getAcknowledgementInterval();
long timeToSend = System.currentTimeMillis() + ackInterval;
AcknowledgementManager.addAckBeanEntry(ackRMMsgCtx, sequenceId, timeToSend, storageManager);
}
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::sendAckIfNeeded");
}
}
| true | true | public InvocationResponse processReliableMessage(RMMsgContext rmMsgCtx) throws AxisFault {
if (log.isDebugEnabled())
log.debug("Enter: SequenceProcessor::processReliableMessage");
InvocationResponse result = InvocationResponse.CONTINUE;
if (rmMsgCtx.getProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE) != null
&& rmMsgCtx.getProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE).equals("true")) {
return result;
}
MessageContext msgCtx = rmMsgCtx.getMessageContext();
StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(msgCtx.getConfigurationContext(),msgCtx.getConfigurationContext().getAxisConfiguration());
Sequence sequence = (Sequence) rmMsgCtx.getMessagePart(Sandesha2Constants.MessageParts.SEQUENCE);
String sequenceId = sequence.getIdentifier().getIdentifier();
long msgNo = sequence.getMessageNumber().getMessageNumber();
boolean lastMessage = sequence.getLastMessage() != null;
// Check that both the Sequence header and message body have been secured properly
RMDBeanMgr mgr = storageManager.getRMDBeanMgr();
RMDBean bean = mgr.retrieve(sequenceId);
if(bean != null && bean.getSecurityTokenData() != null) {
SecurityManager secManager = SandeshaUtil.getSecurityManager(msgCtx.getConfigurationContext());
QName seqName = new QName(rmMsgCtx.getRMNamespaceValue(), Sandesha2Constants.WSRM_COMMON.SEQUENCE);
SOAPEnvelope envelope = msgCtx.getEnvelope();
OMElement body = envelope.getBody();
OMElement seqHeader = envelope.getHeader().getFirstChildWithName(seqName);
SecurityToken token = secManager.recoverSecurityToken(bean.getSecurityTokenData());
secManager.checkProofOfPossession(token, seqHeader, msgCtx);
secManager.checkProofOfPossession(token, body, msgCtx);
}
// Store the inbound sequence id, number and lastMessage onto the operation context
OperationContext opCtx = msgCtx.getOperationContext();
if(opCtx != null) {
opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_SEQUENCE_ID, sequenceId);
opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_MESSAGE_NUMBER, new Long(msgNo));
if(lastMessage) opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_LAST_MESSAGE, Boolean.TRUE);
}
// setting acked msg no range
ConfigurationContext configCtx = rmMsgCtx.getMessageContext().getConfigurationContext();
if (configCtx == null) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.configContextNotSet);
log.debug(message);
throw new SandeshaException(message);
}
if (FaultManager.checkForUnknownSequence(rmMsgCtx, sequenceId, storageManager)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Unknown sequence");
return InvocationResponse.ABORT;
}
// throwing a fault if the sequence is terminated
if (FaultManager.checkForSequenceTerminated(rmMsgCtx, sequenceId, bean)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Sequence terminated");
return InvocationResponse.ABORT;
}
// throwing a fault if the sequence is closed.
if (FaultManager.checkForSequenceClosed(rmMsgCtx, sequenceId, bean)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Sequence closed");
return InvocationResponse.ABORT;
}
FaultManager.checkForLastMsgNumberExceeded(rmMsgCtx, storageManager);
if (FaultManager.checkForMessageRolledOver(rmMsgCtx, sequenceId, msgNo)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Message rolled over " + msgNo);
return InvocationResponse.ABORT;
}
// Pause the messages bean if not the right message to invoke.
// updating the last activated time of the sequence.
bean.setLastActivatedTime(System.currentTimeMillis());
if (lastMessage) {
//setting this as the LastMessage number
bean.setLastInMessageId(msgCtx.getMessageID());
}
EndpointReference replyTo = rmMsgCtx.getReplyTo();
String key = SandeshaUtil.getUUID(); // key to store the message.
// updating the Highest_In_Msg_No property which gives the highest
// message number retrieved from this sequence.
long highestInMsgNo = bean.getHighestInMessageNumber();
if (msgNo > highestInMsgNo) {
// If WS-Addressing is turned off there may not be a message id written into the SOAP
// headers, but we can still fake one up to help us match up requests and replies within
// this end of the connection.
String messageId = msgCtx.getMessageID();
if(messageId == null) {
messageId = SandeshaUtil.getUUID();
msgCtx.setMessageID(messageId);
}
bean.setHighestInMessageId(messageId);
bean.setHighestInMessageNumber(msgNo);
}
String specVersion = rmMsgCtx.getRMSpecVersion();
if (rmMsgCtx.getMessageContext().getAxisOperation().getName().getLocalPart().equals("RMInOutDuplicateMessageOperation")
&& (Sandesha2Constants.QOS.InvocationType.DEFAULT_INVOCATION_TYPE == Sandesha2Constants.QOS.InvocationType.EXACTLY_ONCE)) {
// this is a duplicate message and the invocation type is EXACTLY_ONCE. We try to return
// ack messages at this point, as if someone is sending duplicates then they may have
// missed earlier acks. We also have special processing for sync 2-way with RM 1.0
if((replyTo==null || replyTo.hasAnonymousAddress()) &&
(specVersion!=null && specVersion.equals(Sandesha2Constants.SPEC_VERSIONS.v1_0))) {
SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr();
SenderBean findSenderBean = new SenderBean ();
findSenderBean.setMessageType(Sandesha2Constants.MessageTypes.APPLICATION);
findSenderBean.setInboundSequenceId(sequence.getIdentifier().getIdentifier());
findSenderBean.setInboundMessageNumber(sequence.getMessageNumber().getMessageNumber());
findSenderBean.setSend(true);
SenderBean replyMessageBean = senderBeanMgr.findUnique(findSenderBean);
// this is effectively a poll for the replyMessage, wo re-use the logic in the MakeConnection
// processor. This will use this thread to re-send the reply, writing it into the transport.
// As the reply is now written we do not want to continue processing, or suspend, so we abort.
if(replyMessageBean != null) {
if(log.isDebugEnabled()) log.debug("Found matching reply for replayed message");
MakeConnectionProcessor.replyToPoll(rmMsgCtx, replyMessageBean, storageManager, false, null);
result = InvocationResponse.ABORT;
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, replayed message: " + result);
return result;
}
}
EndpointReference acksTo = new EndpointReference (bean.getAcksToEPR());
// Send an Ack if needed.
//We are not sending acks for duplicate messages in the RM 1.0 anon InOut case.
//If a standalone ack get sent before the actualy message (I.e. before the original msg get
//replied), the client may take this as a InOnly message and may avoid looking for the application
//response.
if (!(Sandesha2Constants.SPEC_VERSIONS.v1_0.equals(rmMsgCtx.getRMSpecVersion()) &&
rmMsgCtx.getReplyTo().hasAnonymousAddress())) {
sendAckIfNeeded(bean, sequenceId, rmMsgCtx, storageManager, true, acksTo.hasAnonymousAddress());
}
result = InvocationResponse.ABORT;
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, dropping duplicate: " + result);
return result;
}
// If the message is a reply to an outbound message then we can update the RMSBean that
// matches.
String outboundSequence = bean.getOutboundInternalSequence();
if(outboundSequence != null) {
RMSBean outBean = SandeshaUtil.getRMSBeanFromInternalSequenceId(storageManager, outboundSequence);
if(outBean != null && outBean.getExpectedReplies() > 0 ) {
outBean.setExpectedReplies(outBean.getExpectedReplies() - 1);
RMSBeanMgr outMgr = storageManager.getRMSBeanMgr();
outMgr.update(outBean);
}
}
// Set the last activated time
bean.setLastActivatedTime(System.currentTimeMillis());
// Update the RMD bean
mgr.update(bean);
// If we are doing sync 2-way over WSRM 1.0, then we may just have received one of
// the reply messages that we were looking for. If so we can remove the matching sender bean.
int mep = msgCtx.getAxisOperation().getAxisSpecifMEPConstant();
if(specVersion!=null && specVersion.equals(Sandesha2Constants.SPEC_VERSIONS.v1_0) &&
mep == WSDLConstants.MEP_CONSTANT_OUT_IN) {
RelatesTo relatesTo = msgCtx.getRelatesTo();
if(relatesTo != null) {
String messageId = relatesTo.getValue();
SenderBean matcher = new SenderBean();
matcher.setMessageID(messageId);
SenderBean sender = storageManager.getSenderBeanMgr().findUnique(matcher);
if(sender != null) {
if(log.isDebugEnabled()) log.debug("Deleting sender for sync-2-way message");
storageManager.removeMessageContext(sender.getMessageContextRefKey());
storageManager.getSenderBeanMgr().delete(messageId);
// Try and terminate the corresponding outbound sequence
RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sender.getSequenceID());
TerminateManager.checkAndTerminate(rmMsgCtx.getConfigurationContext(), storageManager, rmsBean);
}
}
}
//setting properties for the messageContext
rmMsgCtx.setProperty(Sandesha2Constants.MessageContextProperties.SEQUENCE_ID,sequenceId);
rmMsgCtx.setProperty(Sandesha2Constants.MessageContextProperties.MESSAGE_NUMBER,new Long (msgNo));
// We only create an ack message if:
// - We have anonymous acks, and the backchannel is free
// - We have async acks
boolean backchannelFree = (replyTo != null && !replyTo.hasAnonymousAddress()) ||
WSDLConstants.MEP_CONSTANT_IN_ONLY == mep;
EndpointReference acksTo = new EndpointReference (bean.getAcksToEPR());
if (acksTo.hasAnonymousAddress() && backchannelFree) {
Object responseWritten = msgCtx.getOperationContext().getProperty(Constants.RESPONSE_WRITTEN);
if (responseWritten==null || !Constants.VALUE_TRUE.equals(responseWritten)) {
RMMsgContext ackRMMsgContext = AcknowledgementManager.generateAckMessage(rmMsgCtx, bean, sequenceId, storageManager,true);
msgCtx.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE);
AcknowledgementManager.sendAckNow(ackRMMsgContext);
}
} else if (!acksTo.hasAnonymousAddress()) {
SandeshaPolicyBean policyBean = SandeshaUtil.getPropertyBean (msgCtx.getAxisOperation());
long ackInterval = policyBean.getAcknowledgementInterval();
long timeToSend = System.currentTimeMillis() + ackInterval;
RMMsgContext ackRMMsgContext = AcknowledgementManager.generateAckMessage(rmMsgCtx, bean, sequenceId, storageManager,true);
AcknowledgementManager.addAckBeanEntry(ackRMMsgContext, sequenceId, timeToSend, storageManager);
}
// If this message matches the WSRM 1.0 pattern for an empty last message (e.g.
// the sender wanted to signal the last message, but didn't have an application
// message to send) then we do not need to send the message on to the application.
if(Sandesha2Constants.SPEC_2005_02.Actions.ACTION_LAST_MESSAGE.equals(msgCtx.getWSAAction()) ||
Sandesha2Constants.SPEC_2005_02.Actions.SOAP_ACTION_LAST_MESSAGE.equals(msgCtx.getSoapAction())) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, got WSRM 1.0 lastmessage, aborting");
return InvocationResponse.ABORT;
}
// If the storage manager has an invoker, then they may be implementing inOrder, or
// transactional delivery. Either way, if they have one we should use it.
SandeshaThread invoker = storageManager.getInvoker();
if (invoker != null) {
// Whatever the MEP, we stop processing here and the invoker will do the real work. We only
// SUSPEND if we need to keep the backchannel open for the response... we may as well ABORT
// to let other cases end more quickly.
if(backchannelFree) {
result = InvocationResponse.ABORT;
} else {
result = InvocationResponse.SUSPEND;
}
InvokerBeanMgr storageMapMgr = storageManager.getInvokerBeanMgr();
storageManager.storeMessageContext(key, rmMsgCtx.getMessageContext());
storageMapMgr.insert(new InvokerBean(key, msgNo, sequenceId));
// This will avoid performing application processing more than once.
rmMsgCtx.setProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE, "true");
}
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage " + result);
return result;
}
| public InvocationResponse processReliableMessage(RMMsgContext rmMsgCtx) throws AxisFault {
if (log.isDebugEnabled())
log.debug("Enter: SequenceProcessor::processReliableMessage");
InvocationResponse result = InvocationResponse.CONTINUE;
if (rmMsgCtx.getProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE) != null
&& rmMsgCtx.getProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE).equals("true")) {
return result;
}
MessageContext msgCtx = rmMsgCtx.getMessageContext();
StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(msgCtx.getConfigurationContext(),msgCtx.getConfigurationContext().getAxisConfiguration());
Sequence sequence = (Sequence) rmMsgCtx.getMessagePart(Sandesha2Constants.MessageParts.SEQUENCE);
String sequenceId = sequence.getIdentifier().getIdentifier();
long msgNo = sequence.getMessageNumber().getMessageNumber();
boolean lastMessage = sequence.getLastMessage() != null;
// Check that both the Sequence header and message body have been secured properly
RMDBeanMgr mgr = storageManager.getRMDBeanMgr();
RMDBean bean = mgr.retrieve(sequenceId);
if(bean != null && bean.getSecurityTokenData() != null) {
SecurityManager secManager = SandeshaUtil.getSecurityManager(msgCtx.getConfigurationContext());
QName seqName = new QName(rmMsgCtx.getRMNamespaceValue(), Sandesha2Constants.WSRM_COMMON.SEQUENCE);
SOAPEnvelope envelope = msgCtx.getEnvelope();
OMElement body = envelope.getBody();
OMElement seqHeader = envelope.getHeader().getFirstChildWithName(seqName);
SecurityToken token = secManager.recoverSecurityToken(bean.getSecurityTokenData());
secManager.checkProofOfPossession(token, seqHeader, msgCtx);
secManager.checkProofOfPossession(token, body, msgCtx);
}
// Store the inbound sequence id, number and lastMessage onto the operation context
OperationContext opCtx = msgCtx.getOperationContext();
if(opCtx != null) {
opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_SEQUENCE_ID, sequenceId);
opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_MESSAGE_NUMBER, new Long(msgNo));
if(lastMessage) opCtx.setProperty(Sandesha2Constants.MessageContextProperties.INBOUND_LAST_MESSAGE, Boolean.TRUE);
}
// setting acked msg no range
ConfigurationContext configCtx = rmMsgCtx.getMessageContext().getConfigurationContext();
if (configCtx == null) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.configContextNotSet);
log.debug(message);
throw new SandeshaException(message);
}
if (FaultManager.checkForUnknownSequence(rmMsgCtx, sequenceId, storageManager)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Unknown sequence");
return InvocationResponse.ABORT;
}
// throwing a fault if the sequence is terminated
if (FaultManager.checkForSequenceTerminated(rmMsgCtx, sequenceId, bean)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Sequence terminated");
return InvocationResponse.ABORT;
}
// throwing a fault if the sequence is closed.
if (FaultManager.checkForSequenceClosed(rmMsgCtx, sequenceId, bean)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Sequence closed");
return InvocationResponse.ABORT;
}
FaultManager.checkForLastMsgNumberExceeded(rmMsgCtx, storageManager);
if (FaultManager.checkForMessageRolledOver(rmMsgCtx, sequenceId, msgNo)) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, Message rolled over " + msgNo);
return InvocationResponse.ABORT;
}
// Pause the messages bean if not the right message to invoke.
// updating the last activated time of the sequence.
bean.setLastActivatedTime(System.currentTimeMillis());
if (lastMessage) {
//setting this as the LastMessage number
bean.setLastInMessageId(msgCtx.getMessageID());
}
EndpointReference replyTo = rmMsgCtx.getReplyTo();
String key = SandeshaUtil.getUUID(); // key to store the message.
// updating the Highest_In_Msg_No property which gives the highest
// message number retrieved from this sequence.
long highestInMsgNo = bean.getHighestInMessageNumber();
if (msgNo > highestInMsgNo) {
// If WS-Addressing is turned off there may not be a message id written into the SOAP
// headers, but we can still fake one up to help us match up requests and replies within
// this end of the connection.
String messageId = msgCtx.getMessageID();
if(messageId == null) {
messageId = SandeshaUtil.getUUID();
msgCtx.setMessageID(messageId);
}
bean.setHighestInMessageId(messageId);
bean.setHighestInMessageNumber(msgNo);
}
String specVersion = rmMsgCtx.getRMSpecVersion();
if (rmMsgCtx.getMessageContext().getAxisOperation().getName().getLocalPart().equals(Sandesha2Constants.RM_DUPLICATE_OPERATION.getLocalPart())
&& (Sandesha2Constants.QOS.InvocationType.DEFAULT_INVOCATION_TYPE == Sandesha2Constants.QOS.InvocationType.EXACTLY_ONCE)) {
// this is a duplicate message and the invocation type is EXACTLY_ONCE. We try to return
// ack messages at this point, as if someone is sending duplicates then they may have
// missed earlier acks. We also have special processing for sync 2-way with RM 1.0
if((replyTo==null || replyTo.hasAnonymousAddress()) &&
(specVersion!=null && specVersion.equals(Sandesha2Constants.SPEC_VERSIONS.v1_0))) {
SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr();
SenderBean findSenderBean = new SenderBean ();
findSenderBean.setMessageType(Sandesha2Constants.MessageTypes.APPLICATION);
findSenderBean.setInboundSequenceId(sequence.getIdentifier().getIdentifier());
findSenderBean.setInboundMessageNumber(sequence.getMessageNumber().getMessageNumber());
findSenderBean.setSend(true);
SenderBean replyMessageBean = senderBeanMgr.findUnique(findSenderBean);
// this is effectively a poll for the replyMessage, wo re-use the logic in the MakeConnection
// processor. This will use this thread to re-send the reply, writing it into the transport.
// As the reply is now written we do not want to continue processing, or suspend, so we abort.
if(replyMessageBean != null) {
if(log.isDebugEnabled()) log.debug("Found matching reply for replayed message");
MakeConnectionProcessor.replyToPoll(rmMsgCtx, replyMessageBean, storageManager, false, null);
result = InvocationResponse.ABORT;
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, replayed message: " + result);
return result;
}
}
EndpointReference acksTo = new EndpointReference (bean.getAcksToEPR());
// Send an Ack if needed.
//We are not sending acks for duplicate messages in the RM 1.0 anon InOut case.
//If a standalone ack get sent before the actualy message (I.e. before the original msg get
//replied), the client may take this as a InOnly message and may avoid looking for the application
//response.
if (!(Sandesha2Constants.SPEC_VERSIONS.v1_0.equals(rmMsgCtx.getRMSpecVersion()) &&
rmMsgCtx.getReplyTo().hasAnonymousAddress())) {
sendAckIfNeeded(bean, sequenceId, rmMsgCtx, storageManager, true, acksTo.hasAnonymousAddress());
}
result = InvocationResponse.ABORT;
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, dropping duplicate: " + result);
return result;
}
// If the message is a reply to an outbound message then we can update the RMSBean that
// matches.
String outboundSequence = bean.getOutboundInternalSequence();
if(outboundSequence != null) {
RMSBean outBean = SandeshaUtil.getRMSBeanFromInternalSequenceId(storageManager, outboundSequence);
if(outBean != null && outBean.getExpectedReplies() > 0 ) {
outBean.setExpectedReplies(outBean.getExpectedReplies() - 1);
RMSBeanMgr outMgr = storageManager.getRMSBeanMgr();
outMgr.update(outBean);
}
}
// Set the last activated time
bean.setLastActivatedTime(System.currentTimeMillis());
// Update the RMD bean
mgr.update(bean);
// If we are doing sync 2-way over WSRM 1.0, then we may just have received one of
// the reply messages that we were looking for. If so we can remove the matching sender bean.
int mep = msgCtx.getAxisOperation().getAxisSpecifMEPConstant();
if(specVersion!=null && specVersion.equals(Sandesha2Constants.SPEC_VERSIONS.v1_0) &&
mep == WSDLConstants.MEP_CONSTANT_OUT_IN) {
RelatesTo relatesTo = msgCtx.getRelatesTo();
if(relatesTo != null) {
String messageId = relatesTo.getValue();
SenderBean matcher = new SenderBean();
matcher.setMessageID(messageId);
SenderBean sender = storageManager.getSenderBeanMgr().findUnique(matcher);
if(sender != null) {
if(log.isDebugEnabled()) log.debug("Deleting sender for sync-2-way message");
storageManager.removeMessageContext(sender.getMessageContextRefKey());
storageManager.getSenderBeanMgr().delete(messageId);
// Try and terminate the corresponding outbound sequence
RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sender.getSequenceID());
TerminateManager.checkAndTerminate(rmMsgCtx.getConfigurationContext(), storageManager, rmsBean);
}
}
}
//setting properties for the messageContext
rmMsgCtx.setProperty(Sandesha2Constants.MessageContextProperties.SEQUENCE_ID,sequenceId);
rmMsgCtx.setProperty(Sandesha2Constants.MessageContextProperties.MESSAGE_NUMBER,new Long (msgNo));
// We only create an ack message if:
// - We have anonymous acks, and the backchannel is free
// - We have async acks
boolean backchannelFree = (replyTo != null && !replyTo.hasAnonymousAddress()) ||
WSDLConstants.MEP_CONSTANT_IN_ONLY == mep;
EndpointReference acksTo = new EndpointReference (bean.getAcksToEPR());
if (acksTo.hasAnonymousAddress() && backchannelFree) {
Object responseWritten = msgCtx.getOperationContext().getProperty(Constants.RESPONSE_WRITTEN);
if (responseWritten==null || !Constants.VALUE_TRUE.equals(responseWritten)) {
RMMsgContext ackRMMsgContext = AcknowledgementManager.generateAckMessage(rmMsgCtx, bean, sequenceId, storageManager,true);
msgCtx.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE);
AcknowledgementManager.sendAckNow(ackRMMsgContext);
}
} else if (!acksTo.hasAnonymousAddress()) {
SandeshaPolicyBean policyBean = SandeshaUtil.getPropertyBean (msgCtx.getAxisOperation());
long ackInterval = policyBean.getAcknowledgementInterval();
long timeToSend = System.currentTimeMillis() + ackInterval;
RMMsgContext ackRMMsgContext = AcknowledgementManager.generateAckMessage(rmMsgCtx, bean, sequenceId, storageManager,true);
AcknowledgementManager.addAckBeanEntry(ackRMMsgContext, sequenceId, timeToSend, storageManager);
}
// If this message matches the WSRM 1.0 pattern for an empty last message (e.g.
// the sender wanted to signal the last message, but didn't have an application
// message to send) then we do not need to send the message on to the application.
if(Sandesha2Constants.SPEC_2005_02.Actions.ACTION_LAST_MESSAGE.equals(msgCtx.getWSAAction()) ||
Sandesha2Constants.SPEC_2005_02.Actions.SOAP_ACTION_LAST_MESSAGE.equals(msgCtx.getSoapAction())) {
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage, got WSRM 1.0 lastmessage, aborting");
return InvocationResponse.ABORT;
}
// If the storage manager has an invoker, then they may be implementing inOrder, or
// transactional delivery. Either way, if they have one we should use it.
SandeshaThread invoker = storageManager.getInvoker();
if (invoker != null) {
// Whatever the MEP, we stop processing here and the invoker will do the real work. We only
// SUSPEND if we need to keep the backchannel open for the response... we may as well ABORT
// to let other cases end more quickly.
if(backchannelFree) {
result = InvocationResponse.ABORT;
} else {
result = InvocationResponse.SUSPEND;
}
InvokerBeanMgr storageMapMgr = storageManager.getInvokerBeanMgr();
storageManager.storeMessageContext(key, rmMsgCtx.getMessageContext());
storageMapMgr.insert(new InvokerBean(key, msgNo, sequenceId));
// This will avoid performing application processing more than once.
rmMsgCtx.setProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE, "true");
}
if (log.isDebugEnabled())
log.debug("Exit: SequenceProcessor::processReliableMessage " + result);
return result;
}
|
diff --git a/src/main/java/net/vhati/modmanager/core/XMLPatcher.java b/src/main/java/net/vhati/modmanager/core/XMLPatcher.java
index 14673e7..22a6422 100644
--- a/src/main/java/net/vhati/modmanager/core/XMLPatcher.java
+++ b/src/main/java/net/vhati/modmanager/core/XMLPatcher.java
@@ -1,571 +1,571 @@
package net.vhati.modmanager.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.vhati.modmanager.core.SloppyXMLParser;
import org.jdom2.Attribute;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.filter.AbstractFilter;
import org.jdom2.filter.ElementFilter;
import org.jdom2.filter.Filter;
import org.jdom2.input.JDOMParseException;
import org.jdom2.input.SAXBuilder;
/**
* Programmatically edits existing XML with instructions from another XML doc.
* Other tags are simply appended as-is.
*/
public class XMLPatcher {
protected Namespace modNS;
protected Namespace modAppendNS;
protected Namespace modOverwriteNS;
public XMLPatcher() {
modNS = Namespace.getNamespace( "mod", "mod" );
modAppendNS = Namespace.getNamespace( "mod-append", "mod-append" );
modOverwriteNS = Namespace.getNamespace( "mod-overwrite", "mod-overwrite" );
}
public Document patch( Document mainDoc, Document appendDoc ) {
Document resultDoc = mainDoc.clone();
Element resultRoot = resultDoc.getRootElement();
Element appendRoot = appendDoc.getRootElement();
ElementFilter modFilter = new ElementFilter( modNS );
for ( Content content : appendRoot.getContent() ) {
if ( modFilter.matches( content ) ) {
Element node = (Element)content;
boolean handled = false;
List<Element> matchedNodes = handleModFind( resultRoot, node );
if ( matchedNodes != null ) {
handled = true;
for ( Element matchedNode : matchedNodes ) {
handleModCommands( matchedNode, node );
}
}
if ( !handled ) {
throw new IllegalArgumentException( String.format( "Unrecognized mod tag <%s> (%s).", node.getName(), getPathToRoot(node) ) );
}
}
else {
resultRoot.addContent( content.clone() );
}
}
return resultDoc;
}
/**
* Returns find results if node is a find tag, or null if it's not.
*
* An empty list will be returned if there were no matches.
*
* TODO: Throw an exception in callers if results are required.
*/
protected List<Element> handleModFind( Element contextNode, Element node ) {
List<Element> result = null;
if ( node.getNamespace().equals( modNS ) ) {
if ( node.getName().equals( "findName" ) ) {
String searchName = node.getAttributeValue( "name" );
String searchType = node.getAttributeValue( "type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", true );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", 1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchName == null || searchName.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> requires a name attribute (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
attrMap.put( "name", searchName );
LikeFilter searchFilter = new LikeFilter( searchType, attrMap, null );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findLike" ) ) {
String searchType = node.getAttributeValue( "type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
String searchValue = null;
Element selectorNode = node.getChild( "selector", modNS );
if ( selectorNode != null ) {
for ( Attribute attr : selectorNode.getAttributes() ) {
if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) {
// Blank element values can't be detected as different from absent values (never null).
// Forbid "" attributes for consistency. :/
if ( attr.getValue().length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> attributes, when present, can't be empty (%s).", selectorNode.getName(), getPathToRoot(selectorNode) ) );
attrMap.put( attr.getName(), attr.getValue() );
}
}
searchValue = selectorNode.getTextTrim(); // Never null, but often "".
- if ( searchValue.length() > 0 ) searchValue = null;
+ if ( searchValue.length() == 0 ) searchValue = null;
}
LikeFilter searchFilter = new LikeFilter( searchType, attrMap, searchValue );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findWithChildLike" ) ) {
String searchType = node.getAttributeValue( "type" );
String searchChildType = node.getAttributeValue( "child-type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchChildType != null && searchChildType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> child-type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
String searchValue = null;
Element selectorNode = node.getChild( "selector", modNS );
if ( selectorNode != null ) {
for ( Attribute attr : selectorNode.getAttributes() ) {
if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) {
// TODO: Forbid "" attributes, because blank value doesn't work?
attrMap.put( attr.getName(), attr.getValue() );
}
}
searchValue = selectorNode.getTextTrim(); // Never null, but often "".
- if ( searchValue.length() > 0 ) searchValue = null;
+ if ( searchValue.length() == 0 ) searchValue = null;
}
LikeFilter searchChildFilter = new LikeFilter( searchChildType, attrMap, searchValue );
WithChildFilter searchFilter = new WithChildFilter( searchType, searchChildFilter );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findComposite" ) ) {
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Element parNode = node.getChild( "par", modNS );
if ( parNode == null )
throw new IllegalArgumentException( String.format( "<%s> requires a <par> tag (%s).", node.getName(), getPathToRoot(node) ) );
List<Element> matchedNodes = handleModPar( contextNode, parNode );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
}
return result;
}
/**
* Returns collated find results (and par results, handled recursively), or null if node wasn't a par.
*
* Unique results from all finds will be combined and sorted in the order they appear under contextNode.
*/
protected List<Element> handleModPar( Element contextNode, Element node ) {
List<Element> result = null;
if ( node.getNamespace().equals( modNS ) ) {
if ( node.getName().equals( "par" ) ) {
String parOp = node.getAttributeValue( "op" );
if ( parOp == null || (!parOp.equals("AND") && !parOp.equals("OR")) )
throw new IllegalArgumentException( String.format( "Invalid \"op\" attribute (%s). Must be 'AND' or 'OR'.", getPathToRoot(node) ) );
boolean isAnd = parOp.equals("AND");
boolean isOr = parOp.equals("OR");
Set<Element> candidateSet = new HashSet<Element>();
for ( Element criteriaNode : node.getChildren() ) {
List<Element> candidates;
if ( criteriaNode.getName().equals( "par" ) && criteriaNode.getNamespace().equals( modNS ) ) {
candidates = handleModPar( contextNode, criteriaNode );
} else {
candidates = handleModFind( contextNode, criteriaNode );
if ( candidates == null )
throw new IllegalArgumentException( String.format( "Invalid <par> search criteria <%s> (%s). Must be a <find...> or <par>.", criteriaNode.getName(), getPathToRoot(criteriaNode) ) );
}
if ( isOr || candidateSet.isEmpty() ) {
candidateSet.addAll( candidates );
}
else if ( isAnd ) {
candidateSet.retainAll( candidates );
}
}
Map<Integer,Element> orderedCandidateMap = new TreeMap<Integer,Element>();
for ( Element candidate : candidateSet ) {
int index = contextNode.indexOf( candidate );
orderedCandidateMap.put( new Integer(index), candidate );
}
List<Element> matchedNodes = new ArrayList<Element>( orderedCandidateMap.values() );
result = matchedNodes;
}
}
return result;
}
/**
* Performs child mod-commands under node, against contextNode.
*
* TODO: Maybe have handleModCommand() returning null when unrecognized,
* or an object with flags to continue or stop looping commands at
* contextNode (e.g., halting after removeTag).
*/
protected void handleModCommands( Element contextNode, Element node ) {
for ( Element cmdNode : node.getChildren() ) {
boolean handled = false;
if ( cmdNode.getNamespace().equals( modNS ) ) {
// Handle nested finds.
List<Element> matchedNodes = handleModFind( contextNode, cmdNode );
if ( matchedNodes != null ) {
handled = true;
for ( Element matchedNode : matchedNodes ) {
handleModCommands( matchedNode, cmdNode );
}
}
else if ( cmdNode.getName().equals( "selector" ) ) {
handled = true;
// No-op.
}
else if ( cmdNode.getName().equals( "par" ) ) {
handled = true;
// No-op.
}
else if ( cmdNode.getName().equals( "setAttributes" ) ) {
handled = true;
for ( Attribute attrib : cmdNode.getAttributes() ) {
contextNode.setAttribute( attrib.clone() );
}
}
else if ( cmdNode.getName().equals( "setValue" ) ) {
handled = true;
contextNode.setText( cmdNode.getTextTrim() );
}
else if ( cmdNode.getName().equals( "removeTag" ) ) {
handled = true;
contextNode.detach();
break;
}
}
else if ( cmdNode.getNamespace().equals( modAppendNS ) ) {
// Append cmdNode (sans namespace) to the contextNode.
handled = true;
Element newNode = cmdNode.clone();
newNode.setNamespace( null );
contextNode.addContent( newNode );
}
else if ( cmdNode.getNamespace().equals( modOverwriteNS ) ) {
// Remove the first child with the same type and insert cmdNode at its position.
// Or just append if nothing was replaced.
handled = true;
Element newNode = cmdNode.clone();
newNode.setNamespace( null );
Element doomedNode = contextNode.getChild( cmdNode.getName(), null );
if ( doomedNode != null ) {
int doomedIndex = contextNode.indexOf( doomedNode );
doomedNode.detach();
contextNode.addContent( doomedIndex, newNode );
}
else {
contextNode.addContent( newNode );
}
}
if ( !handled ) {
throw new IllegalArgumentException( String.format( "Unrecognized mod tag <%s> (%s).", cmdNode.getName(), getPathToRoot(cmdNode) ) );
}
}
}
/**
* Returns a string describing this element's location.
*
* Example: /root/event(SOME_NAME)/choice/text
*/
protected String getPathToRoot( Element node ) {
StringBuilder buf = new StringBuilder();
String chunk;
String tmp;
while ( node != null ) {
chunk = "/"+ node.getName();
tmp = node.getAttributeValue( "name" );
if ( tmp != null && tmp.length() > 0 )
chunk += "("+ tmp +")";
buf.insert( 0, chunk );
node = node.getParentElement();
}
return buf.toString();
}
/**
* Returns the boolean value of an attribute, or a default when the attribute is null.
* Only 'true' and 'false' are accepted.
*/
protected boolean getAttributeBooleanValue( Element node, String attrName, boolean defaultValue ) {
String tmp = node.getAttributeValue( attrName );
if ( tmp == null ) return defaultValue;
if ( tmp.equals( "true" ) ) {
return true;
} else if ( tmp.equals( "false" ) ) {
return false;
} else {
throw new IllegalArgumentException( String.format( "Invalid boolean attribute \"%s\" (%s). Must be 'true' or 'false'.", attrName, getPathToRoot(node) ) );
}
}
/**
* Returns the int value of an attribute, or a default when the attribute is null.
*/
protected int getAttributeIntValue( Element node, String attrName, int defaultValue ) {
String tmp = node.getAttributeValue( attrName );
if ( tmp == null ) return defaultValue;
try {
return Integer.parseInt( tmp );
}
catch ( NumberFormatException e ) {
throw new IllegalArgumentException( String.format( "Invalid int attribute \"%s\" (%s).", attrName, getPathToRoot(node) ) );
}
}
/**
* Matches elements with equal type/attributes/value.
* Null args are ignored. A blank type or value arg is ignored.
* All given attributes must be present on a candidate to match.
* Attribute values in the map must not be null.
*/
protected static class LikeFilter extends AbstractFilter<Element> {
private String type = null;;
private Map<String,String> attrMap = null;
private String value = null;
public LikeFilter( String type, Element selectorNode ) {
this.type = type;
if ( selectorNode.hasAttributes() ) {
this.attrMap = new HashMap<String,String>();
for ( Attribute attr : selectorNode.getAttributes() ) {
attrMap.put( attr.getName(), attr.getValue() );
}
}
this.value = selectorNode.getTextTrim();
if ( this.value.length() == 0 ) this.value = null;
}
public LikeFilter( String type, Map<String,String> attrMap, String value ) {
super();
if ( type != null && type.length() == 0 ) type = null;
if ( value != null && value.length() == 0 ) value = null;
this.type = type;
this.attrMap = attrMap;
this.value = value;
}
@Override
public Element filter( Object content ) {
if ( content instanceof Element == false ) return null;
Element node = (Element)content;
String tmp;
if ( type != null ) {
if ( type.equals( node.getName() ) == false ) {
return null;
}
}
if ( attrMap != null ) {
for ( Map.Entry<String,String> entry : attrMap.entrySet() ) {
String attrName = entry.getKey();
String attrValue = entry.getValue();
tmp = node.getAttributeValue( attrName );
if ( attrValue.equals( tmp ) == false ) {
return null;
}
}
}
if ( value != null ) {
if ( value.equals( node.getTextTrim() ) == false ) {
return null;
}
}
return node;
}
}
/**
* Matches elements with child elements that match a filter.
* If the filter is null, matches all elements with children.
*/
protected static class WithChildFilter extends AbstractFilter<Element> {
private String type;
private Filter<Element> childFilter;
public WithChildFilter( Filter<Element> childFilter ) {
this( null, childFilter );
}
public WithChildFilter( String type, Filter<Element> childFilter ) {
this.type = type;
this.childFilter = childFilter;
}
@Override
public Element filter( Object content ) {
if ( content instanceof Element == false ) return null;
Element node = (Element)content;
if ( type != null ) {
if ( type.equals( node.getName() ) == false ) {
return null;
}
}
if ( childFilter != null ) {
if ( node.getContent( childFilter ).isEmpty() )
return null;
}
else if ( node.getChildren().isEmpty() ) {
return null;
}
return node;
}
}
}
| false | true | protected List<Element> handleModFind( Element contextNode, Element node ) {
List<Element> result = null;
if ( node.getNamespace().equals( modNS ) ) {
if ( node.getName().equals( "findName" ) ) {
String searchName = node.getAttributeValue( "name" );
String searchType = node.getAttributeValue( "type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", true );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", 1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchName == null || searchName.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> requires a name attribute (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
attrMap.put( "name", searchName );
LikeFilter searchFilter = new LikeFilter( searchType, attrMap, null );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findLike" ) ) {
String searchType = node.getAttributeValue( "type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
String searchValue = null;
Element selectorNode = node.getChild( "selector", modNS );
if ( selectorNode != null ) {
for ( Attribute attr : selectorNode.getAttributes() ) {
if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) {
// Blank element values can't be detected as different from absent values (never null).
// Forbid "" attributes for consistency. :/
if ( attr.getValue().length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> attributes, when present, can't be empty (%s).", selectorNode.getName(), getPathToRoot(selectorNode) ) );
attrMap.put( attr.getName(), attr.getValue() );
}
}
searchValue = selectorNode.getTextTrim(); // Never null, but often "".
if ( searchValue.length() > 0 ) searchValue = null;
}
LikeFilter searchFilter = new LikeFilter( searchType, attrMap, searchValue );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findWithChildLike" ) ) {
String searchType = node.getAttributeValue( "type" );
String searchChildType = node.getAttributeValue( "child-type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchChildType != null && searchChildType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> child-type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
String searchValue = null;
Element selectorNode = node.getChild( "selector", modNS );
if ( selectorNode != null ) {
for ( Attribute attr : selectorNode.getAttributes() ) {
if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) {
// TODO: Forbid "" attributes, because blank value doesn't work?
attrMap.put( attr.getName(), attr.getValue() );
}
}
searchValue = selectorNode.getTextTrim(); // Never null, but often "".
if ( searchValue.length() > 0 ) searchValue = null;
}
LikeFilter searchChildFilter = new LikeFilter( searchChildType, attrMap, searchValue );
WithChildFilter searchFilter = new WithChildFilter( searchType, searchChildFilter );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findComposite" ) ) {
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Element parNode = node.getChild( "par", modNS );
if ( parNode == null )
throw new IllegalArgumentException( String.format( "<%s> requires a <par> tag (%s).", node.getName(), getPathToRoot(node) ) );
List<Element> matchedNodes = handleModPar( contextNode, parNode );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
}
return result;
}
| protected List<Element> handleModFind( Element contextNode, Element node ) {
List<Element> result = null;
if ( node.getNamespace().equals( modNS ) ) {
if ( node.getName().equals( "findName" ) ) {
String searchName = node.getAttributeValue( "name" );
String searchType = node.getAttributeValue( "type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", true );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", 1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchName == null || searchName.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> requires a name attribute (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
attrMap.put( "name", searchName );
LikeFilter searchFilter = new LikeFilter( searchType, attrMap, null );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findLike" ) ) {
String searchType = node.getAttributeValue( "type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
String searchValue = null;
Element selectorNode = node.getChild( "selector", modNS );
if ( selectorNode != null ) {
for ( Attribute attr : selectorNode.getAttributes() ) {
if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) {
// Blank element values can't be detected as different from absent values (never null).
// Forbid "" attributes for consistency. :/
if ( attr.getValue().length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> attributes, when present, can't be empty (%s).", selectorNode.getName(), getPathToRoot(selectorNode) ) );
attrMap.put( attr.getName(), attr.getValue() );
}
}
searchValue = selectorNode.getTextTrim(); // Never null, but often "".
if ( searchValue.length() == 0 ) searchValue = null;
}
LikeFilter searchFilter = new LikeFilter( searchType, attrMap, searchValue );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findWithChildLike" ) ) {
String searchType = node.getAttributeValue( "type" );
String searchChildType = node.getAttributeValue( "child-type" );
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchType != null && searchType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchChildType != null && searchChildType.length() == 0 )
throw new IllegalArgumentException( String.format( "<%s> child-type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Map<String,String> attrMap = new HashMap<String,String>();
String searchValue = null;
Element selectorNode = node.getChild( "selector", modNS );
if ( selectorNode != null ) {
for ( Attribute attr : selectorNode.getAttributes() ) {
if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) {
// TODO: Forbid "" attributes, because blank value doesn't work?
attrMap.put( attr.getName(), attr.getValue() );
}
}
searchValue = selectorNode.getTextTrim(); // Never null, but often "".
if ( searchValue.length() == 0 ) searchValue = null;
}
LikeFilter searchChildFilter = new LikeFilter( searchChildType, attrMap, searchValue );
WithChildFilter searchFilter = new WithChildFilter( searchType, searchChildFilter );
List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
else if ( node.getName().equals( "findComposite" ) ) {
boolean searchReverse = getAttributeBooleanValue( node, "reverse", false );
int searchStart = getAttributeIntValue( node, "start", 0 );
int searchLimit = getAttributeIntValue( node, "limit", -1 );
boolean panic = getAttributeBooleanValue( node, "panic", false );
if ( searchStart < 0 )
throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) );
if ( searchLimit < -1 )
throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) );
Element parNode = node.getChild( "par", modNS );
if ( parNode == null )
throw new IllegalArgumentException( String.format( "<%s> requires a <par> tag (%s).", node.getName(), getPathToRoot(node) ) );
List<Element> matchedNodes = handleModPar( contextNode, parNode );
if ( searchReverse ) Collections.reverse( matchedNodes );
if ( searchStart < matchedNodes.size() ) {
if ( searchLimit > -1 ) {
matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) );
} else if ( searchStart > 0 ) {
matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() );
}
}
if ( panic && matchedNodes.isEmpty() )
throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) );
result = matchedNodes;
}
}
return result;
}
|
diff --git a/src/net/derkholm/nmica/extra/app/seq/FeatureToFeatureDistance.java b/src/net/derkholm/nmica/extra/app/seq/FeatureToFeatureDistance.java
index 64c0d76..97f54d5 100644
--- a/src/net/derkholm/nmica/extra/app/seq/FeatureToFeatureDistance.java
+++ b/src/net/derkholm/nmica/extra/app/seq/FeatureToFeatureDistance.java
@@ -1,159 +1,159 @@
package net.derkholm.nmica.extra.app.seq;
import gfftools.GFFUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import net.derkholm.nmica.build.NMExtraApp;
import net.derkholm.nmica.build.VirtualMachine;
import net.derkholm.nmica.extra.seq.DistanceFromStartOfStrandedFeatureToPointLocationComparator;
import org.biojava.bio.SmallAnnotation;
import org.biojava.bio.program.gff.GFFRecord;
import org.biojava.bio.program.gff.GFFWriter;
import org.biojava.bio.seq.DNATools;
import org.biojava.bio.seq.FeatureFilter;
import org.biojava.bio.seq.FeatureHolder;
import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.SequenceTools;
import org.biojava.bio.seq.StrandedFeature;
import org.biojava.bio.symbol.PointLocation;
import org.biojava.bio.symbol.RangeLocation;
import org.bjv2.util.cli.App;
import org.bjv2.util.cli.Option;
@App(overview = "Calculate the distance of features in one feature set to the closest features of another feature set", generateStub = true)
@NMExtraApp(launchName = "nmfeatdist", vm = VirtualMachine.SERVER)
public class FeatureToFeatureDistance {
private int distanceThreshold = 2000;
private File comparisonFeatures;
private File features;
private File outFile;
private GFFWriter gffWriter;
@Option(help="Feature set to find the closest features for")
public void setFeatures(File f) {
this.features = f;
}
@Option(help="Distance threshold",optional=true)
public void setDistThreshold(int i) {
this.distanceThreshold = i;
}
@Option(help="Comparison feature set")
public void setToFeatures(File f) {
this.comparisonFeatures = f;
}
@Option(help="Output file (output goes to stdout if no file given)", optional=true)
public void setOut(File f) {
this.outFile = f;
}
public void main(String[] args) throws Exception {
final OutputStream os;
if (this.outFile == null) {
os = System.out;
} else {
os = new FileOutputStream(this.outFile);
}
this.gffWriter = new GFFWriter(new PrintWriter(os));
Map<String, List<GFFRecord>> featureMap = GFFUtils.gffToRecordMap(this.features);
Map<String, Sequence> sequenceMap = gffToAnnotationMap(this.comparisonFeatures);
for (String str : featureMap.keySet()) {
List<GFFRecord> locs = featureMap.get(str);
for (GFFRecord r : locs) {
RangeLocation l = (RangeLocation) new RangeLocation(r.getStart(), r.getEnd());;
int point = l.getMin() + (l.getMax() - l.getMin()) / 2;
Comparator<StrandedFeature> comp =
new DistanceFromStartOfStrandedFeatureToPointLocationComparator(new PointLocation(point));
- SortedSet<StrandedFeature> feats = new TreeSet<StrandedFeature>();
+ SortedSet<StrandedFeature> feats = new TreeSet<StrandedFeature>(comp);
Sequence seq = sequenceMap.get(str);
FeatureFilter locationFilter =
new FeatureFilter.OverlapsLocation(
new RangeLocation(point - this.distanceThreshold, point + this.distanceThreshold));
FeatureHolder filteredFeatures = seq.filter(locationFilter);
Iterator<?> fs = filteredFeatures.features();
while (fs.hasNext()) {feats.add((StrandedFeature) fs.next());}
if (feats.size() > 0) {
StrandedFeature closestFeature = feats.first();
int distance =
DistanceFromStartOfStrandedFeatureToPointLocationComparator
.distance(closestFeature, point);
r.getGroupAttributes().put("distance", distance);
gffWriter.recordLine(r);
gffWriter.endDocument();// forces buffer flush
} else {
System.err.printf("WARNING: No feature found within +/- %d from %s:%d%n",this.distanceThreshold, str, point);
}
}
}
}
public static Map<String, Sequence> gffToAnnotationMap(File f) throws Exception {
Map<String, List<GFFRecord>> recs = GFFUtils.gffToRecordMap(f);
Map<String, Sequence> map = new TreeMap<String, Sequence>();
for (String str : recs.keySet()) {
List<GFFRecord> seqRecs = recs.get(str);
Sequence s =
SequenceTools.createDummy(
DNATools.getDNA(),
Integer.MAX_VALUE,
DNATools.n(),
null,
str);
map.put(str, s);
for (GFFRecord r : seqRecs) {
StrandedFeature.Template templ = new StrandedFeature.Template();
templ.source = r.getSource();
templ.type = r.getFeature();
templ.annotation = new SmallAnnotation();
templ.location = new RangeLocation(r.getStart(), r.getEnd());
templ.strand = r.getStrand();
templ.annotation.setProperty("score", r.getScore());
if (r.getComment() != null) {
templ.annotation.setProperty("comment", r.getComment());
}
for (Object o : r.getGroupAttributes().keySet())
{templ.annotation.setProperty(o, r.getGroupAttributes().get(o));}
s.createFeature(templ);
}
}
return map;
}
}
| true | true | public void main(String[] args) throws Exception {
final OutputStream os;
if (this.outFile == null) {
os = System.out;
} else {
os = new FileOutputStream(this.outFile);
}
this.gffWriter = new GFFWriter(new PrintWriter(os));
Map<String, List<GFFRecord>> featureMap = GFFUtils.gffToRecordMap(this.features);
Map<String, Sequence> sequenceMap = gffToAnnotationMap(this.comparisonFeatures);
for (String str : featureMap.keySet()) {
List<GFFRecord> locs = featureMap.get(str);
for (GFFRecord r : locs) {
RangeLocation l = (RangeLocation) new RangeLocation(r.getStart(), r.getEnd());;
int point = l.getMin() + (l.getMax() - l.getMin()) / 2;
Comparator<StrandedFeature> comp =
new DistanceFromStartOfStrandedFeatureToPointLocationComparator(new PointLocation(point));
SortedSet<StrandedFeature> feats = new TreeSet<StrandedFeature>();
Sequence seq = sequenceMap.get(str);
FeatureFilter locationFilter =
new FeatureFilter.OverlapsLocation(
new RangeLocation(point - this.distanceThreshold, point + this.distanceThreshold));
FeatureHolder filteredFeatures = seq.filter(locationFilter);
Iterator<?> fs = filteredFeatures.features();
while (fs.hasNext()) {feats.add((StrandedFeature) fs.next());}
if (feats.size() > 0) {
StrandedFeature closestFeature = feats.first();
int distance =
DistanceFromStartOfStrandedFeatureToPointLocationComparator
.distance(closestFeature, point);
r.getGroupAttributes().put("distance", distance);
gffWriter.recordLine(r);
gffWriter.endDocument();// forces buffer flush
} else {
System.err.printf("WARNING: No feature found within +/- %d from %s:%d%n",this.distanceThreshold, str, point);
}
}
}
}
| public void main(String[] args) throws Exception {
final OutputStream os;
if (this.outFile == null) {
os = System.out;
} else {
os = new FileOutputStream(this.outFile);
}
this.gffWriter = new GFFWriter(new PrintWriter(os));
Map<String, List<GFFRecord>> featureMap = GFFUtils.gffToRecordMap(this.features);
Map<String, Sequence> sequenceMap = gffToAnnotationMap(this.comparisonFeatures);
for (String str : featureMap.keySet()) {
List<GFFRecord> locs = featureMap.get(str);
for (GFFRecord r : locs) {
RangeLocation l = (RangeLocation) new RangeLocation(r.getStart(), r.getEnd());;
int point = l.getMin() + (l.getMax() - l.getMin()) / 2;
Comparator<StrandedFeature> comp =
new DistanceFromStartOfStrandedFeatureToPointLocationComparator(new PointLocation(point));
SortedSet<StrandedFeature> feats = new TreeSet<StrandedFeature>(comp);
Sequence seq = sequenceMap.get(str);
FeatureFilter locationFilter =
new FeatureFilter.OverlapsLocation(
new RangeLocation(point - this.distanceThreshold, point + this.distanceThreshold));
FeatureHolder filteredFeatures = seq.filter(locationFilter);
Iterator<?> fs = filteredFeatures.features();
while (fs.hasNext()) {feats.add((StrandedFeature) fs.next());}
if (feats.size() > 0) {
StrandedFeature closestFeature = feats.first();
int distance =
DistanceFromStartOfStrandedFeatureToPointLocationComparator
.distance(closestFeature, point);
r.getGroupAttributes().put("distance", distance);
gffWriter.recordLine(r);
gffWriter.endDocument();// forces buffer flush
} else {
System.err.printf("WARNING: No feature found within +/- %d from %s:%d%n",this.distanceThreshold, str, point);
}
}
}
}
|
diff --git a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel1.java b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel1.java
index 5fb36b2c5..39d111e9c 100644
--- a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel1.java
+++ b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel1.java
@@ -1,207 +1,207 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* KeywordSearchConfigurationPanel1.java
*
* Created on Feb 28, 2012, 4:12:47 PM
*/
package org.sleuthkit.autopsy.keywordsearch;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JOptionPane;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.corecomponents.OptionsPanel;
import org.sleuthkit.autopsy.ingest.IngestManager;
/**
* Panel containing all other Keyword search Options panels.
*/
public class KeywordSearchConfigurationPanel1 extends javax.swing.JPanel implements OptionsPanel {
KeywordSearchListsManagementPanel listsManagementPanel;
KeywordSearchEditListPanel editListPanel;
private static final Logger logger = Logger.getLogger(KeywordSearchConfigurationPanel1.class.getName());
private static final String KEYWORD_CONFIG_NAME = org.openide.util.NbBundle.getMessage(KeywordSearchPanel.class, "ListBundleConfig");
/** Creates new form KeywordSearchConfigurationPanel1 */
KeywordSearchConfigurationPanel1() {
initComponents();
customizeComponents();
setName(KEYWORD_CONFIG_NAME);
}
private void customizeComponents() {
listsManagementPanel = new KeywordSearchListsManagementPanel();
editListPanel = new KeywordSearchEditListPanel();
listsManagementPanel.addListSelectionListener(editListPanel);
editListPanel.addDeleteButtonActionPerformed(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (KeywordSearchUtil.displayConfirmDialog("Delete a keyword list"
, "This will delete the keyword list globally (for all Cases). "
+ "Do you want to proceed with the deletion? "
, KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN) ) {
KeywordSearchListsXML deleter = KeywordSearchListsXML.getCurrent();
String toDelete = editListPanel.getCurrentKeywordList().getName();
editListPanel.setCurrentKeywordList(null);
editListPanel.initButtons();
deleter.deleteList(toDelete);
listsManagementPanel.resync();
}
}
});
editListPanel.addSaveButtonActionPerformed(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final String FEATURE_NAME = "Save Keyword List";
KeywordSearchListsXML writer = KeywordSearchListsXML.getCurrent();
KeywordSearchList currentKeywordList = editListPanel.getCurrentKeywordList();
List<Keyword> keywords = currentKeywordList.getKeywords();
if (keywords.isEmpty()) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Keyword List is empty and cannot be saved", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
return;
}
String listName = (String) JOptionPane.showInputDialog(
null,
"New keyword list name:",
FEATURE_NAME,
JOptionPane.PLAIN_MESSAGE,
null,
null,
- currentKeywordList != null ? currentKeywordList : "");
+ currentKeywordList != null ? currentKeywordList.getName() : "");
if (listName == null || listName.trim().equals("")) {
return;
}
if (writer.listExists(listName) && writer.getList(listName).isLocked()) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Cannot overwrite default list", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN);
return;
}
boolean shouldAdd = false;
if (writer.listExists(listName)) {
boolean replace = KeywordSearchUtil.displayConfirmDialog(FEATURE_NAME, "Keyword List <" + listName + "> already exists, do you want to replace it?",
KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN);
if (replace) {
shouldAdd = true;
}
} else {
shouldAdd = true;
}
if (shouldAdd) {
writer.addList(listName, keywords);
}
currentKeywordList = writer.getList(listName);
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Keyword List <" + listName + "> saved", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
listsManagementPanel.resync();
}
});
mainSplitPane.setLeftComponent(listsManagementPanel);
mainSplitPane.setRightComponent(editListPanel);
mainSplitPane.revalidate();
mainSplitPane.repaint();
}
@Override
public void store() {
KeywordSearchListsXML.getCurrent().save();
//refresh the list viewer/searcher panel
KeywordSearchListsViewerPanel.getDefault().resync();
}
@Override
public void load() {
listsManagementPanel.load();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
mainSplitPane = new javax.swing.JSplitPane();
leftPanel = new javax.swing.JPanel();
rightPanel = new javax.swing.JPanel();
mainSplitPane.setBorder(null);
mainSplitPane.setDividerLocation(275);
javax.swing.GroupLayout leftPanelLayout = new javax.swing.GroupLayout(leftPanel);
leftPanel.setLayout(leftPanelLayout);
leftPanelLayout.setHorizontalGroup(
leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 275, Short.MAX_VALUE)
);
leftPanelLayout.setVerticalGroup(
leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 327, Short.MAX_VALUE)
);
mainSplitPane.setLeftComponent(leftPanel);
javax.swing.GroupLayout rightPanelLayout = new javax.swing.GroupLayout(rightPanel);
rightPanel.setLayout(rightPanelLayout);
rightPanelLayout.setHorizontalGroup(
rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 318, Short.MAX_VALUE)
);
rightPanelLayout.setVerticalGroup(
rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 327, Short.MAX_VALUE)
);
mainSplitPane.setRightComponent(rightPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainSplitPane)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainSplitPane)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel leftPanel;
private javax.swing.JSplitPane mainSplitPane;
private javax.swing.JPanel rightPanel;
// End of variables declaration//GEN-END:variables
}
| true | true | private void customizeComponents() {
listsManagementPanel = new KeywordSearchListsManagementPanel();
editListPanel = new KeywordSearchEditListPanel();
listsManagementPanel.addListSelectionListener(editListPanel);
editListPanel.addDeleteButtonActionPerformed(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (KeywordSearchUtil.displayConfirmDialog("Delete a keyword list"
, "This will delete the keyword list globally (for all Cases). "
+ "Do you want to proceed with the deletion? "
, KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN) ) {
KeywordSearchListsXML deleter = KeywordSearchListsXML.getCurrent();
String toDelete = editListPanel.getCurrentKeywordList().getName();
editListPanel.setCurrentKeywordList(null);
editListPanel.initButtons();
deleter.deleteList(toDelete);
listsManagementPanel.resync();
}
}
});
editListPanel.addSaveButtonActionPerformed(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final String FEATURE_NAME = "Save Keyword List";
KeywordSearchListsXML writer = KeywordSearchListsXML.getCurrent();
KeywordSearchList currentKeywordList = editListPanel.getCurrentKeywordList();
List<Keyword> keywords = currentKeywordList.getKeywords();
if (keywords.isEmpty()) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Keyword List is empty and cannot be saved", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
return;
}
String listName = (String) JOptionPane.showInputDialog(
null,
"New keyword list name:",
FEATURE_NAME,
JOptionPane.PLAIN_MESSAGE,
null,
null,
currentKeywordList != null ? currentKeywordList : "");
if (listName == null || listName.trim().equals("")) {
return;
}
if (writer.listExists(listName) && writer.getList(listName).isLocked()) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Cannot overwrite default list", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN);
return;
}
boolean shouldAdd = false;
if (writer.listExists(listName)) {
boolean replace = KeywordSearchUtil.displayConfirmDialog(FEATURE_NAME, "Keyword List <" + listName + "> already exists, do you want to replace it?",
KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN);
if (replace) {
shouldAdd = true;
}
} else {
shouldAdd = true;
}
if (shouldAdd) {
writer.addList(listName, keywords);
}
currentKeywordList = writer.getList(listName);
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Keyword List <" + listName + "> saved", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
listsManagementPanel.resync();
}
});
mainSplitPane.setLeftComponent(listsManagementPanel);
mainSplitPane.setRightComponent(editListPanel);
mainSplitPane.revalidate();
mainSplitPane.repaint();
}
| private void customizeComponents() {
listsManagementPanel = new KeywordSearchListsManagementPanel();
editListPanel = new KeywordSearchEditListPanel();
listsManagementPanel.addListSelectionListener(editListPanel);
editListPanel.addDeleteButtonActionPerformed(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (KeywordSearchUtil.displayConfirmDialog("Delete a keyword list"
, "This will delete the keyword list globally (for all Cases). "
+ "Do you want to proceed with the deletion? "
, KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN) ) {
KeywordSearchListsXML deleter = KeywordSearchListsXML.getCurrent();
String toDelete = editListPanel.getCurrentKeywordList().getName();
editListPanel.setCurrentKeywordList(null);
editListPanel.initButtons();
deleter.deleteList(toDelete);
listsManagementPanel.resync();
}
}
});
editListPanel.addSaveButtonActionPerformed(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final String FEATURE_NAME = "Save Keyword List";
KeywordSearchListsXML writer = KeywordSearchListsXML.getCurrent();
KeywordSearchList currentKeywordList = editListPanel.getCurrentKeywordList();
List<Keyword> keywords = currentKeywordList.getKeywords();
if (keywords.isEmpty()) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Keyword List is empty and cannot be saved", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
return;
}
String listName = (String) JOptionPane.showInputDialog(
null,
"New keyword list name:",
FEATURE_NAME,
JOptionPane.PLAIN_MESSAGE,
null,
null,
currentKeywordList != null ? currentKeywordList.getName() : "");
if (listName == null || listName.trim().equals("")) {
return;
}
if (writer.listExists(listName) && writer.getList(listName).isLocked()) {
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Cannot overwrite default list", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN);
return;
}
boolean shouldAdd = false;
if (writer.listExists(listName)) {
boolean replace = KeywordSearchUtil.displayConfirmDialog(FEATURE_NAME, "Keyword List <" + listName + "> already exists, do you want to replace it?",
KeywordSearchUtil.DIALOG_MESSAGE_TYPE.WARN);
if (replace) {
shouldAdd = true;
}
} else {
shouldAdd = true;
}
if (shouldAdd) {
writer.addList(listName, keywords);
}
currentKeywordList = writer.getList(listName);
KeywordSearchUtil.displayDialog(FEATURE_NAME, "Keyword List <" + listName + "> saved", KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
listsManagementPanel.resync();
}
});
mainSplitPane.setLeftComponent(listsManagementPanel);
mainSplitPane.setRightComponent(editListPanel);
mainSplitPane.revalidate();
mainSplitPane.repaint();
}
|
diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java
index 4d131ca8e..2c394b3a3 100644
--- a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java
+++ b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java
@@ -1,412 +1,415 @@
/**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
* http://www.collectionspace.org
* http://wiki.collectionspace.org
* Copyright 2009 University of California at Berkeley
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.collectionspace.services.relation.nuxeo;
import java.util.HashMap;
import java.util.Iterator;
import org.collectionspace.services.client.PoxPayloadIn;
import org.collectionspace.services.client.PoxPayloadOut;
import org.collectionspace.services.common.ResourceBase;
import org.collectionspace.services.common.ResourceMap;
import org.collectionspace.services.common.ServiceMain;
import org.collectionspace.services.common.api.RefName;
import org.collectionspace.services.common.api.Tools;
import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
import org.collectionspace.services.common.context.ServiceBindingUtils;
import org.collectionspace.services.common.document.DocumentNotFoundException;
import org.collectionspace.services.common.document.InvalidDocumentException;
import org.collectionspace.services.common.relation.RelationJAXBSchema;
import org.collectionspace.services.common.relation.nuxeo.RelationConstants;
import org.collectionspace.services.common.context.ServiceContext;
import org.collectionspace.services.common.repository.RepositoryClient;
import org.collectionspace.services.common.repository.RepositoryClientFactory;
import org.collectionspace.services.common.service.ServiceBindingType;
import org.collectionspace.services.nuxeo.util.NuxeoUtils;
import org.collectionspace.services.relation.RelationsCommon;
import org.collectionspace.services.relation.RelationsCommonList;
import org.collectionspace.services.relation.RelationsCommonList.RelationListItem;
// HACK HACK HACK
import org.collectionspace.services.client.PersonAuthorityClient;
import org.collectionspace.services.client.OrgAuthorityClient;
import org.collectionspace.services.client.LocationAuthorityClient;
import org.collectionspace.services.client.TaxonomyAuthorityClient;
import org.collectionspace.services.common.document.DocumentWrapper;
import org.collectionspace.services.jaxb.AbstractCommonList;
import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl;
import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
import org.collectionspace.services.relation.RelationsDocListItem;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.model.PropertyException;
import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* RelationDocumentModelHandler
*
* $LastChangedRevision: $
* $LastChangedDate: $
*/
public class RelationDocumentModelHandler
extends RemoteDocumentModelHandlerImpl<RelationsCommon, RelationsCommonList> {
private final Logger logger = LoggerFactory.getLogger(RelationDocumentModelHandler.class);
/**
* relation is used to stash JAXB object to use when handle is called
* for Action.CREATE, Action.UPDATE or Action.GET
*/
private RelationsCommon relation;
/**
* relationList is stashed when handle is called
* for ACTION.GET_ALL
*/
private RelationsCommonList relationList;
@Override
public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
// Merge in the data from the payload
super.handleCreate(wrapDoc);
// And take care of ensuring all the values for the relation info are correct
populateSubjectAndObjectValues(wrapDoc);
}
@Override
public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
// Merge in the data from the payload
super.handleUpdate(wrapDoc);
// And take care of ensuring all the values for the relation info are correct
populateSubjectAndObjectValues(wrapDoc);
}
private void populateSubjectAndObjectValues(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
// Obtain document models for the subject and object of the relation, so that
// we ensure we have value docType, URI info. If the docModels support refNames,
// we will also set those.
// Note that this introduces another caching problem...
DocumentModel relationDocModel = wrapDoc.getWrappedObject();
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
RepositoryInstance repoSession = this.getRepositorySession();
DocumentModel subjectDocModel = getSubjectOrObjectDocModel(repoSession, relationDocModel, SUBJ_DOC_MODEL);
DocumentModel objectDocModel = getSubjectOrObjectDocModel(repoSession, relationDocModel, OBJ_DOC_MODEL);
// Use values from the subject and object document models to populate the
// relevant fields of the relation's own document model.
if (subjectDocModel != null) {
populateSubjectOrObjectValues(relationDocModel, subjectDocModel, SUBJ_DOC_MODEL);
}
if (objectDocModel != null) {
populateSubjectOrObjectValues(relationDocModel, objectDocModel, OBJ_DOC_MODEL);
}
}
@Override
public RelationsCommon getCommonPart() {
return relation;
}
@Override
public void setCommonPart(RelationsCommon theRelation) {
this.relation = theRelation;
}
/**get associated Relation (for index/GET_ALL)
*/
@Override
public RelationsCommonList getCommonPartList() {
return relationList;
}
@Override
public void setCommonPartList(RelationsCommonList theRelationList) {
this.relationList = theRelationList;
}
@Override
public RelationsCommon extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc)
throws Exception {
throw new UnsupportedOperationException();
}
@Override
public void fillCommonPart(RelationsCommon theRelation, DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public RelationsCommonList extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
RelationsCommonList relList = this.extractPagingInfo(new RelationsCommonList(), wrapDoc);
relList.setFieldsReturned("subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object");
ServiceContext ctx = getServiceContext();
String serviceContextPath = getServiceContextPath();
TenantBindingConfigReaderImpl tReader = ServiceMain.getInstance().getTenantBindingConfigReader();
String serviceName = getServiceContext().getServiceName().toLowerCase();
ServiceBindingType sbt = tReader.getServiceBinding(ctx.getTenantId(), serviceName);
Iterator<DocumentModel> iter = wrapDoc.getWrappedObject().iterator();
while (iter.hasNext()) {
DocumentModel docModel = iter.next();
RelationListItem relListItem = getRelationListItem(ctx, sbt, tReader, docModel, serviceContextPath);
relList.getRelationListItem().add(relListItem);
}
return relList;
}
/** Gets the relation list item, looking up the subject and object documents, and getting summary
* info via the objectName and objectNumber properties in tenant-bindings.
* @param ctx the ctx
* @param sbt the ServiceBindingType of Relations service
* @param tReader the tenant-bindings reader, for looking up docnumber and docname
* @param docModel the doc model
* @param serviceContextPath the service context path
* @return the relation list item, with nested subject and object summary info.
* @throws Exception the exception
*/
private RelationListItem getRelationListItem(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
ServiceBindingType sbt,
TenantBindingConfigReaderImpl tReader,
DocumentModel docModel,
String serviceContextPath) throws Exception {
RelationListItem relationListItem = new RelationListItem();
String id = getCsid(docModel);
relationListItem.setCsid(id);
relationListItem.setSubjectCsid((String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.SUBJECT_CSID));
String predicate = (String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.RELATIONSHIP_TYPE);
relationListItem.setRelationshipType(predicate);
relationListItem.setPredicate(predicate); //predicate is new name for relationshipType.
relationListItem.setPredicateDisplayName((String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.RELATIONSHIP_TYPE_DISPLAYNAME));
relationListItem.setObjectCsid((String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.OBJECT_CSID));
relationListItem.setUri(serviceContextPath + id);
//Now fill in summary info for the related docs: subject and object.
String subjectCsid = relationListItem.getSubjectCsid();
String subjectDocumentType = (String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.SUBJECT_DOCTYPE);
RelationsDocListItem subject = createRelationsDocListItem(ctx, sbt, subjectCsid, tReader, subjectDocumentType);
String subjectUri = (String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.SUBJECT_URI);
subject.setUri(subjectUri);
String subjectRefName = (String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.SUBJECT_REFNAME);
subject.setRefName(subjectRefName);
relationListItem.setSubject(subject);
String objectCsid = relationListItem.getObjectCsid();
String objectDocumentType = (String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.OBJECT_DOCTYPE);
RelationsDocListItem object = createRelationsDocListItem(ctx, sbt, objectCsid, tReader, objectDocumentType);
String objectUri = (String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.OBJECT_URI);
object.setUri(objectUri);
String objectRefName = (String) docModel.getProperty(ctx.getCommonPartLabel(),
RelationJAXBSchema.OBJECT_REFNAME);
object.setRefName(objectRefName);
relationListItem.setObject(object);
return relationListItem;
}
// DocumentModel itemDocModel = docModelFromCSID(ctx, itemCsid);
protected RelationsDocListItem createRelationsDocListItem(
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
ServiceBindingType sbt,
String itemCsid,
TenantBindingConfigReaderImpl tReader,
String documentType) throws Exception {
RelationsDocListItem item = new RelationsDocListItem();
item.setDocumentType(documentType);//this one comes from the record, as subjectDocumentType, objectDocumentType.
item.setCsid(itemCsid);
DocumentModel itemDocModel = NuxeoUtils.getDocFromCsid(ctx, this.getRepositorySession(), itemCsid); //null if not found.
if (itemDocModel != null) {
String itemDocType = itemDocModel.getDocumentType().getName();
if (Tools.isBlank(documentType)) {
item.setDocumentType(itemDocType);
}
//TODO: ensure that itemDocType is really the entry point, i.e. servicename==doctype
//ServiceBindingType itemSbt2 = tReader.getServiceBinding(ctx.getTenantId(), itemDocType);
String propName = "ERROR-FINDING-PROP-VALUE";
ServiceBindingType itemSbt = tReader.getServiceBindingForDocType(ctx.getTenantId(), itemDocType);
try {
propName = ServiceBindingUtils.getPropertyValue(itemSbt, ServiceBindingUtils.OBJ_NAME_PROP);
String itemDocname = ServiceBindingUtils.getMappedFieldInDoc(itemSbt, ServiceBindingUtils.OBJ_NAME_PROP, itemDocModel);
if (propName == null || itemDocname == null) {
} else {
item.setName(itemDocname);
}
} catch (Throwable t) {
logger.error("====Error finding objectNameProperty: " + itemDocModel + " field " + ServiceBindingUtils.OBJ_NAME_PROP + "=" + propName
+ " not found in itemDocType: " + itemDocType + " inner: " + t.getMessage());
}
propName = "ERROR-FINDING-PROP-VALUE";
try {
propName = ServiceBindingUtils.getPropertyValue(itemSbt, ServiceBindingUtils.OBJ_NUMBER_PROP);
String itemDocnumber = ServiceBindingUtils.getMappedFieldInDoc(itemSbt, ServiceBindingUtils.OBJ_NUMBER_PROP, itemDocModel);
if (propName == null || itemDocnumber == null) {
} else {
item.setNumber(itemDocnumber);
}
} catch (Throwable t) {
logger.error("====Error finding objectNumberProperty: " + ServiceBindingUtils.OBJ_NUMBER_PROP + "=" + propName
+ " not found in itemDocType: " + itemDocType + " inner: " + t.getMessage());
}
} else {
item.setError("INVALID: related object is absent");
// Laramie20110510 CSPACE-3739 throw the exception for 3739, otherwise, don't throw it.
//throw new Exception("INVALID: related object is absent "+itemCsid);
}
return item;
}
@Override
public String getQProperty(String prop) {
return "/" + RelationConstants.NUXEO_SCHEMA_ROOT_ELEMENT + "/" + prop;
}
private final boolean SUBJ_DOC_MODEL = true;
private final boolean OBJ_DOC_MODEL = false;
private DocumentModel getSubjectOrObjectDocModel(
RepositoryInstance repoSession,
DocumentModel relationDocModel,
boolean fSubject) throws Exception {
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
// Get the document model for the object of the relation.
String commonPartLabel = ctx.getCommonPartLabel();
String csid = "";
String refName = "";
DocumentModel docModel = null;
// FIXME: Currently assumes that the object CSID is valid if present
// in the incoming payload.
try {
csid = (String) relationDocModel.getProperty(commonPartLabel,
(fSubject?RelationJAXBSchema.SUBJECT_CSID:RelationJAXBSchema.OBJECT_CSID));
} catch (PropertyException pe) {
// Per CSPACE-4468, ignore any property exception here.
// The objectCsid and/or subjectCsid field in a relation record
// can now be null (missing), because a refName value can be
// provided as an alternate identifier.
}
if (Tools.notBlank(csid)) {
RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
DocumentWrapper<DocumentModel> docWrapper = nuxeoRepoClient.getDocFromCsid(ctx, repoSession, csid);
docModel = docWrapper.getWrappedObject();
} else { // if (Tools.isBlank(objectCsid)) {
try {
refName = (String) relationDocModel.getProperty(commonPartLabel,
(fSubject?RelationJAXBSchema.SUBJECT_REFNAME:RelationJAXBSchema.OBJECT_REFNAME));
docModel = ResourceBase.getDocModelForRefName(repoSession, refName, ctx.getResourceMap());
} catch (Exception e) {
throw new InvalidDocumentException(
"Relation record must have a CSID or refName to identify the object of the relation.", e);
}
}
if(docModel==null) {
throw new DocumentNotFoundException("Relation.getSubjectOrObjectDocModel could not find doc with CSID: "
+csid+" and/or refName: "+refName );
}
return docModel;
}
private void populateSubjectOrObjectValues(
DocumentModel relationDocModel,
DocumentModel subjectOrObjectDocModel,
boolean fSubject ) {
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
HashMap<String,Object> properties = new HashMap<String,Object>();
try {
String doctype = (String) subjectOrObjectDocModel.getType();
properties.put((fSubject?RelationJAXBSchema.SUBJECT_DOCTYPE:RelationJAXBSchema.OBJECT_DOCTYPE),
doctype);
String csid = (String) subjectOrObjectDocModel.getName();
properties.put((fSubject?RelationJAXBSchema.SUBJECT_CSID:RelationJAXBSchema.OBJECT_CSID),
csid);
String uri = (String) subjectOrObjectDocModel.getProperty(COLLECTIONSPACE_CORE_SCHEMA,
COLLECTIONSPACE_CORE_URI);
properties.put((fSubject?RelationJAXBSchema.SUBJECT_URI:RelationJAXBSchema.OBJECT_URI),
uri);
String common_schema = getCommonSchemaNameForDocType(doctype);
if(common_schema!=null) {
String refname = (String)subjectOrObjectDocModel.getProperty(common_schema,
RefName.REFNAME );
properties.put((fSubject?RelationJAXBSchema.SUBJECT_REFNAME:RelationJAXBSchema.OBJECT_REFNAME),
refname);
}
} catch (ClientException ce) {
throw new RuntimeException(
"populateSubjectOrObjectValues: Problem fetching field " + ce.getLocalizedMessage());
}
// FIXME: Call below is based solely on Nuxeo API docs; have not yet verified that it correctly updates existing
// property values in the target document model.
try {
relationDocModel.setProperties(ctx.getCommonPartLabel(), properties);
} catch (ClientException ce) {
throw new RuntimeException(
"populateSubjectValues: Problem setting fields " + ce.getLocalizedMessage());
}
}
private String getCommonSchemaNameForDocType(String docType) {
String common_schema = null;
- if("Person".equals(docType))
- common_schema = PersonAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
- else if("Organization".equals(docType))
- common_schema = OrgAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
- else if("Locationitem".equals(docType))
- common_schema = LocationAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
- else if("Taxon".equals(docType))
- common_schema = TaxonomyAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
- //else leave it null.
+ if(docType!=null) {
+ // HACK - Use startsWith to allow for extension of schemas.
+ if(docType.startsWith("Person"))
+ common_schema = PersonAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
+ else if(docType.startsWith("Organization"))
+ common_schema = OrgAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
+ else if(docType.startsWith("Locationitem"))
+ common_schema = LocationAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
+ else if(docType.startsWith("Taxon"))
+ common_schema = TaxonomyAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
+ //else leave it null.
+ }
return common_schema;
}
}
| true | true | private DocumentModel getSubjectOrObjectDocModel(
RepositoryInstance repoSession,
DocumentModel relationDocModel,
boolean fSubject) throws Exception {
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
// Get the document model for the object of the relation.
String commonPartLabel = ctx.getCommonPartLabel();
String csid = "";
String refName = "";
DocumentModel docModel = null;
// FIXME: Currently assumes that the object CSID is valid if present
// in the incoming payload.
try {
csid = (String) relationDocModel.getProperty(commonPartLabel,
(fSubject?RelationJAXBSchema.SUBJECT_CSID:RelationJAXBSchema.OBJECT_CSID));
} catch (PropertyException pe) {
// Per CSPACE-4468, ignore any property exception here.
// The objectCsid and/or subjectCsid field in a relation record
// can now be null (missing), because a refName value can be
// provided as an alternate identifier.
}
if (Tools.notBlank(csid)) {
RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
DocumentWrapper<DocumentModel> docWrapper = nuxeoRepoClient.getDocFromCsid(ctx, repoSession, csid);
docModel = docWrapper.getWrappedObject();
} else { // if (Tools.isBlank(objectCsid)) {
try {
refName = (String) relationDocModel.getProperty(commonPartLabel,
(fSubject?RelationJAXBSchema.SUBJECT_REFNAME:RelationJAXBSchema.OBJECT_REFNAME));
docModel = ResourceBase.getDocModelForRefName(repoSession, refName, ctx.getResourceMap());
} catch (Exception e) {
throw new InvalidDocumentException(
"Relation record must have a CSID or refName to identify the object of the relation.", e);
}
}
if(docModel==null) {
throw new DocumentNotFoundException("Relation.getSubjectOrObjectDocModel could not find doc with CSID: "
+csid+" and/or refName: "+refName );
}
return docModel;
}
private void populateSubjectOrObjectValues(
DocumentModel relationDocModel,
DocumentModel subjectOrObjectDocModel,
boolean fSubject ) {
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
HashMap<String,Object> properties = new HashMap<String,Object>();
try {
String doctype = (String) subjectOrObjectDocModel.getType();
properties.put((fSubject?RelationJAXBSchema.SUBJECT_DOCTYPE:RelationJAXBSchema.OBJECT_DOCTYPE),
doctype);
String csid = (String) subjectOrObjectDocModel.getName();
properties.put((fSubject?RelationJAXBSchema.SUBJECT_CSID:RelationJAXBSchema.OBJECT_CSID),
csid);
String uri = (String) subjectOrObjectDocModel.getProperty(COLLECTIONSPACE_CORE_SCHEMA,
COLLECTIONSPACE_CORE_URI);
properties.put((fSubject?RelationJAXBSchema.SUBJECT_URI:RelationJAXBSchema.OBJECT_URI),
uri);
String common_schema = getCommonSchemaNameForDocType(doctype);
if(common_schema!=null) {
String refname = (String)subjectOrObjectDocModel.getProperty(common_schema,
RefName.REFNAME );
properties.put((fSubject?RelationJAXBSchema.SUBJECT_REFNAME:RelationJAXBSchema.OBJECT_REFNAME),
refname);
}
} catch (ClientException ce) {
throw new RuntimeException(
"populateSubjectOrObjectValues: Problem fetching field " + ce.getLocalizedMessage());
}
// FIXME: Call below is based solely on Nuxeo API docs; have not yet verified that it correctly updates existing
// property values in the target document model.
try {
relationDocModel.setProperties(ctx.getCommonPartLabel(), properties);
} catch (ClientException ce) {
throw new RuntimeException(
"populateSubjectValues: Problem setting fields " + ce.getLocalizedMessage());
}
}
private String getCommonSchemaNameForDocType(String docType) {
String common_schema = null;
if("Person".equals(docType))
common_schema = PersonAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
else if("Organization".equals(docType))
common_schema = OrgAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
else if("Locationitem".equals(docType))
common_schema = LocationAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
else if("Taxon".equals(docType))
common_schema = TaxonomyAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
//else leave it null.
return common_schema;
}
}
| private DocumentModel getSubjectOrObjectDocModel(
RepositoryInstance repoSession,
DocumentModel relationDocModel,
boolean fSubject) throws Exception {
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
// Get the document model for the object of the relation.
String commonPartLabel = ctx.getCommonPartLabel();
String csid = "";
String refName = "";
DocumentModel docModel = null;
// FIXME: Currently assumes that the object CSID is valid if present
// in the incoming payload.
try {
csid = (String) relationDocModel.getProperty(commonPartLabel,
(fSubject?RelationJAXBSchema.SUBJECT_CSID:RelationJAXBSchema.OBJECT_CSID));
} catch (PropertyException pe) {
// Per CSPACE-4468, ignore any property exception here.
// The objectCsid and/or subjectCsid field in a relation record
// can now be null (missing), because a refName value can be
// provided as an alternate identifier.
}
if (Tools.notBlank(csid)) {
RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
DocumentWrapper<DocumentModel> docWrapper = nuxeoRepoClient.getDocFromCsid(ctx, repoSession, csid);
docModel = docWrapper.getWrappedObject();
} else { // if (Tools.isBlank(objectCsid)) {
try {
refName = (String) relationDocModel.getProperty(commonPartLabel,
(fSubject?RelationJAXBSchema.SUBJECT_REFNAME:RelationJAXBSchema.OBJECT_REFNAME));
docModel = ResourceBase.getDocModelForRefName(repoSession, refName, ctx.getResourceMap());
} catch (Exception e) {
throw new InvalidDocumentException(
"Relation record must have a CSID or refName to identify the object of the relation.", e);
}
}
if(docModel==null) {
throw new DocumentNotFoundException("Relation.getSubjectOrObjectDocModel could not find doc with CSID: "
+csid+" and/or refName: "+refName );
}
return docModel;
}
private void populateSubjectOrObjectValues(
DocumentModel relationDocModel,
DocumentModel subjectOrObjectDocModel,
boolean fSubject ) {
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
HashMap<String,Object> properties = new HashMap<String,Object>();
try {
String doctype = (String) subjectOrObjectDocModel.getType();
properties.put((fSubject?RelationJAXBSchema.SUBJECT_DOCTYPE:RelationJAXBSchema.OBJECT_DOCTYPE),
doctype);
String csid = (String) subjectOrObjectDocModel.getName();
properties.put((fSubject?RelationJAXBSchema.SUBJECT_CSID:RelationJAXBSchema.OBJECT_CSID),
csid);
String uri = (String) subjectOrObjectDocModel.getProperty(COLLECTIONSPACE_CORE_SCHEMA,
COLLECTIONSPACE_CORE_URI);
properties.put((fSubject?RelationJAXBSchema.SUBJECT_URI:RelationJAXBSchema.OBJECT_URI),
uri);
String common_schema = getCommonSchemaNameForDocType(doctype);
if(common_schema!=null) {
String refname = (String)subjectOrObjectDocModel.getProperty(common_schema,
RefName.REFNAME );
properties.put((fSubject?RelationJAXBSchema.SUBJECT_REFNAME:RelationJAXBSchema.OBJECT_REFNAME),
refname);
}
} catch (ClientException ce) {
throw new RuntimeException(
"populateSubjectOrObjectValues: Problem fetching field " + ce.getLocalizedMessage());
}
// FIXME: Call below is based solely on Nuxeo API docs; have not yet verified that it correctly updates existing
// property values in the target document model.
try {
relationDocModel.setProperties(ctx.getCommonPartLabel(), properties);
} catch (ClientException ce) {
throw new RuntimeException(
"populateSubjectValues: Problem setting fields " + ce.getLocalizedMessage());
}
}
private String getCommonSchemaNameForDocType(String docType) {
String common_schema = null;
if(docType!=null) {
// HACK - Use startsWith to allow for extension of schemas.
if(docType.startsWith("Person"))
common_schema = PersonAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
else if(docType.startsWith("Organization"))
common_schema = OrgAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
else if(docType.startsWith("Locationitem"))
common_schema = LocationAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
else if(docType.startsWith("Taxon"))
common_schema = TaxonomyAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME;
//else leave it null.
}
return common_schema;
}
}
|
diff --git a/src/main/java/com/silverpeas/migration/questionreply/ReplyContent.java b/src/main/java/com/silverpeas/migration/questionreply/ReplyContent.java
index ac7ca95..b030d6f 100644
--- a/src/main/java/com/silverpeas/migration/questionreply/ReplyContent.java
+++ b/src/main/java/com/silverpeas/migration/questionreply/ReplyContent.java
@@ -1,73 +1,73 @@
/*
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.com/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.silverpeas.migration.questionreply;
/**
*
* @author ehugonnet
*/
public class ReplyContent {
private String content;
private String instanceId;
private int id;
public ReplyContent(int id, String instanceId, String content) {
if (content != null) {
- this.content = content;
+ this.content = content.replace("\r\n", "<br/>").replace("\n", "<br/>");
} else {
this.content = "";
}
this.instanceId = instanceId;
this.id = id;
}
/**
* Get the value of id
*
* @return the value of id
*/
public int getId() {
return id;
}
/**
* Get the value of instanceId
*
* @return the value of instanceId
*/
public String getInstanceId() {
return instanceId;
}
/**
* Get the value of content
*
* @return the value of content
*/
public String getContent() {
return content;
}
}
| true | true | public ReplyContent(int id, String instanceId, String content) {
if (content != null) {
this.content = content;
} else {
this.content = "";
}
this.instanceId = instanceId;
this.id = id;
}
| public ReplyContent(int id, String instanceId, String content) {
if (content != null) {
this.content = content.replace("\r\n", "<br/>").replace("\n", "<br/>");
} else {
this.content = "";
}
this.instanceId = instanceId;
this.id = id;
}
|
diff --git a/src/org/subsurface/ws/json/DiveParser.java b/src/org/subsurface/ws/json/DiveParser.java
index be717f8..5788192 100644
--- a/src/org/subsurface/ws/json/DiveParser.java
+++ b/src/org/subsurface/ws/json/DiveParser.java
@@ -1,52 +1,54 @@
package org.subsurface.ws.json;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.subsurface.model.DiveLocationLog;
public class DiveParser {
public static List<DiveLocationLog> parseDives(InputStream in) throws JSONException, IOException {
ArrayList<DiveLocationLog> dives = new ArrayList<DiveLocationLog>();
// Get stream content
ByteArrayOutputStream streamContent = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int readBytes;
while ((readBytes = in.read(buff)) != -1) {
streamContent.write(buff, 0, readBytes);
}
// Parse dives
JSONObject jsonRoot = new JSONObject(new String(streamContent.toByteArray()));
JSONArray jsonDives = jsonRoot.getJSONArray("dives");
- int diveLength = jsonDives.length();
- for (int i = 0; i < diveLength; ++i) {
- JSONObject jsonDive = jsonDives.getJSONObject(i);
- DiveLocationLog dive = new DiveLocationLog();
- dive.setName(jsonDive.optString("name", ""));
- dive.setLongitude(jsonDive.getLong("longitude"));
- dive.setLatitude(jsonDive.getLong("latitude"));
- try {
- long timestamp = new SimpleDateFormat("yyyy-MM-dd").parse(jsonDive.getString("date")).getTime();
- timestamp += new SimpleDateFormat("HH:mm").parse(jsonDive.getString("time")).getTime();
- dive.setTimestamp(timestamp);
- } catch (ParseException pe) {
- throw new JSONException("Could not parse date");
+ if (jsonDives != null) {
+ int diveLength = jsonDives.length();
+ for (int i = 0; i < diveLength; ++i) {
+ JSONObject jsonDive = jsonDives.getJSONObject(i);
+ DiveLocationLog dive = new DiveLocationLog();
+ dive.setSent(true);
+ dive.setName(jsonDive.optString("name", ""));
+ dive.setLongitude(jsonDive.getLong("longitude"));
+ dive.setLatitude(jsonDive.getLong("latitude"));
+ try {
+ long timestamp = new SimpleDateFormat("yyyy-MM-dd").parse(jsonDive.getString("date")).getTime();
+ timestamp += new SimpleDateFormat("HH:mm").parse(jsonDive.getString("time")).getTime();
+ dive.setTimestamp(timestamp);
+ dives.add(dive);
+ } catch (ParseException pe) {
+ throw new JSONException("Could not parse date");
+ }
}
- dive.setSent(true);
- dives.add(dive);
}
return dives;
}
}
| false | true | public static List<DiveLocationLog> parseDives(InputStream in) throws JSONException, IOException {
ArrayList<DiveLocationLog> dives = new ArrayList<DiveLocationLog>();
// Get stream content
ByteArrayOutputStream streamContent = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int readBytes;
while ((readBytes = in.read(buff)) != -1) {
streamContent.write(buff, 0, readBytes);
}
// Parse dives
JSONObject jsonRoot = new JSONObject(new String(streamContent.toByteArray()));
JSONArray jsonDives = jsonRoot.getJSONArray("dives");
int diveLength = jsonDives.length();
for (int i = 0; i < diveLength; ++i) {
JSONObject jsonDive = jsonDives.getJSONObject(i);
DiveLocationLog dive = new DiveLocationLog();
dive.setName(jsonDive.optString("name", ""));
dive.setLongitude(jsonDive.getLong("longitude"));
dive.setLatitude(jsonDive.getLong("latitude"));
try {
long timestamp = new SimpleDateFormat("yyyy-MM-dd").parse(jsonDive.getString("date")).getTime();
timestamp += new SimpleDateFormat("HH:mm").parse(jsonDive.getString("time")).getTime();
dive.setTimestamp(timestamp);
} catch (ParseException pe) {
throw new JSONException("Could not parse date");
}
dive.setSent(true);
dives.add(dive);
}
return dives;
}
| public static List<DiveLocationLog> parseDives(InputStream in) throws JSONException, IOException {
ArrayList<DiveLocationLog> dives = new ArrayList<DiveLocationLog>();
// Get stream content
ByteArrayOutputStream streamContent = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int readBytes;
while ((readBytes = in.read(buff)) != -1) {
streamContent.write(buff, 0, readBytes);
}
// Parse dives
JSONObject jsonRoot = new JSONObject(new String(streamContent.toByteArray()));
JSONArray jsonDives = jsonRoot.getJSONArray("dives");
if (jsonDives != null) {
int diveLength = jsonDives.length();
for (int i = 0; i < diveLength; ++i) {
JSONObject jsonDive = jsonDives.getJSONObject(i);
DiveLocationLog dive = new DiveLocationLog();
dive.setSent(true);
dive.setName(jsonDive.optString("name", ""));
dive.setLongitude(jsonDive.getLong("longitude"));
dive.setLatitude(jsonDive.getLong("latitude"));
try {
long timestamp = new SimpleDateFormat("yyyy-MM-dd").parse(jsonDive.getString("date")).getTime();
timestamp += new SimpleDateFormat("HH:mm").parse(jsonDive.getString("time")).getTime();
dive.setTimestamp(timestamp);
dives.add(dive);
} catch (ParseException pe) {
throw new JSONException("Could not parse date");
}
}
}
return dives;
}
|
diff --git a/src/main/ed/js/E4X.java b/src/main/ed/js/E4X.java
index f5b877bba..3de96f578 100644
--- a/src/main/ed/js/E4X.java
+++ b/src/main/ed/js/E4X.java
@@ -1,1756 +1,1766 @@
// E4X.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.js;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import ed.js.func.*;
import ed.js.engine.*;
import ed.util.*;
public class E4X {
public static JSFunction _cons = new XML();
public static JSFunction _ns = new NamespaceCons();
public static class NamespaceCons extends JSFunctionCalls1 {
public JSObject newOne(){
return new Namespace();
}
public Object call( Scope scope , Object str , Object [] args){
Object blah = scope.getThis();
Namespace n;
if ( blah instanceof Namespace)
n = (Namespace)blah;
else {
n = new Namespace( str.toString() );
}
n.init( str.toString() );
return n;
}
}
public static class XML extends JSFunctionCalls1 {
public JSObject newOne(){
return new ENode();
}
public Object call( Scope scope , Object str , Object [] args){
Object blah = scope.getThis();
ENode e;
if ( blah instanceof ENode)
e = (ENode)blah;
else
e = new ENode();
e.init( str.toString() );
return e;
}
public Object get( Object o ) {
if( o.toString().equals( "ignoreComments" ) )
return E4X.ignoreComments;
if( o.toString().equals( "ignoreWhitespace" ) )
return E4X.ignoreWhitespace;
if( o.toString().equals( "ignoreProcessingInstructions" ) )
return E4X.ignoreProcessingInstructions;
if( o.toString().equals( "prettyPrinting" ) )
return E4X.prettyPrinting;
if( o.toString().equals( "prettyIndent" ) )
return E4X.prettyIndent;
return null;
}
public Object set( Object o, Object v ) {
if( o.toString().equals( "ignoreComments" ) )
E4X.ignoreComments = Boolean.parseBoolean( v.toString() );
if( o.toString().equals( "ignoreWhitespace" ) )
E4X.ignoreWhitespace = Boolean.parseBoolean( v.toString() );
if( o.toString().equals( "ignoreProcessingInstructions" ) )
E4X.ignoreProcessingInstructions = Boolean.parseBoolean( v.toString() );
if( o.toString().equals( "prettyPrinting" ) )
E4X.prettyPrinting = Boolean.parseBoolean( v.toString() );
if( o.toString().equals( "prettyIndent" ) )
E4X.prettyIndent = Integer.parseInt( v.toString() );
return v;
}
public static JSObject settings() {
return E4X.settings();
}
public static void setSettings( JSObject obj ) {
E4X.setSettings( obj );
}
public static JSObject defaultSettings() {
return E4X.defaultSettings();
}
}
public static JSObject settings() {
JSObjectBase sets = new JSObjectBase();
sets.set("ignoreComments", ignoreComments);
sets.set("ignoreProcessingInstructions", ignoreProcessingInstructions);
sets.set("ignoreWhitespace", ignoreWhitespace);
sets.set("prettyPrinting", prettyPrinting);
sets.set("prettyIndent", prettyIndent);
return sets;
}
public static void setSettings() {
setSettings(null);
}
public static void setSettings( JSObject settings ) {
if( settings == null ) {
ignoreComments = true;
ignoreProcessingInstructions = true;
ignoreWhitespace = true;
prettyPrinting = true;
prettyIndent = 2;
return;
}
Object setting = settings.get("ignoreComments");
if(setting != null && setting instanceof Boolean)
ignoreComments = ((Boolean)setting).booleanValue();
setting = settings.get("ignoreProcessingInstructions");
if(setting != null && setting instanceof Boolean)
ignoreProcessingInstructions = ((Boolean)setting).booleanValue();
setting = settings.get("ignoreWhitespace");
if(setting != null && setting instanceof Boolean)
ignoreWhitespace = ((Boolean)setting).booleanValue();
setting = settings.get("prettyPrinting");
if(setting != null && setting instanceof Boolean)
prettyPrinting = ((Boolean)setting).booleanValue();
setting = settings.get("prettyIndent");
if(setting != null && setting instanceof Integer)
prettyIndent = ((Integer)setting).intValue();
}
public static JSObject defaultSettings() {
JSObjectBase sets = new JSObjectBase();
sets.set("ignoreComments", true);
sets.set("ignoreProcessingInstructions", true);
sets.set("ignoreWhitespace", true);
sets.set("prettyPrinting", true);
sets.set("prettyIndent", 2);
return sets;
}
public static boolean ignoreComments = true;
public static boolean ignoreProcessingInstructions = true;
public static boolean ignoreWhitespace = true;
public static boolean prettyPrinting = true;
public static int prettyIndent = 2;
static class ENode extends JSObjectBase {
private ENode(){
this( new LinkedList<ENode>() );
}
private ENode( Node n ) {
this( n, null );
}
private ENode( List<ENode> n ) {
this( null, null, n );
}
private ENode( Node n, ENode parent ) {
this( n, parent, null );
}
private ENode( Node n, ENode parent, List<ENode> children ) {
if( n != null &&
children == null &&
n.getNodeType() != Node.TEXT_NODE &&
n.getNodeType() != Node.ATTRIBUTE_NODE )
this.children = new LinkedList<ENode>();
else if( children != null ) {
this.children = children;
}
this.node = n;
this.parent = parent;
this.inScopeNamespaces = new ArrayList<Namespace>();
addNativeFunctions();
}
// creates an empty node with a given parent and tag name
private ENode( ENode parent, Object o ) {
if(parent != null && parent.node != null)
node = parent.node.getOwnerDocument().createElement(o.toString());
this.children = new LinkedList<ENode>();
this.parent = parent;
this._dummy = true;
this.inScopeNamespaces = new ArrayList<Namespace>();
addNativeFunctions();
}
void addNativeFunctions() {
nativeFuncs.put("addNamespace", new addNamespace());
nativeFuncs.put("appendChild", new appendChild());
nativeFuncs.put("attribute", new attribute());
nativeFuncs.put("attributes", new attributes());
nativeFuncs.put("child", new child());
nativeFuncs.put("childIndex", new childIndex());
nativeFuncs.put("children", new children());
nativeFuncs.put("comments", new comments());
nativeFuncs.put("contains", new contains());
nativeFuncs.put("copy", new copy());
nativeFuncs.put("descendants", new descendants());
nativeFuncs.put("elements", new elements());
nativeFuncs.put("hasOwnProperty", new hasOwnProperty());
nativeFuncs.put("hasComplexContent", new hasComplexContent());
nativeFuncs.put("hasSimpleContent", new hasSimpleContent());
nativeFuncs.put("inScopeNamespaces", new inScopeNamespaces());
nativeFuncs.put("insertChildAfter", new insertChildAfter());
nativeFuncs.put("insertChildBefore", new insertChildBefore());
nativeFuncs.put("length", new length());
nativeFuncs.put("localName", new localName());
nativeFuncs.put("name", new name());
nativeFuncs.put("namespace", new namespace());
nativeFuncs.put("namespaceDeclarations", new namespaceDeclarations());
nativeFuncs.put("nodeKind", new nodeKind());
nativeFuncs.put("normalize", new normalize());
nativeFuncs.put("parent", new parent());
nativeFuncs.put("processingInstructions", new processingInstructions());
nativeFuncs.put("prependChild", new prependChild());
nativeFuncs.put("propertyIsEnumerable", new propertyIsEnumerable());
nativeFuncs.put("removeNamespace", new removeNamespace());
nativeFuncs.put("replace", new replace());
nativeFuncs.put("setChildren", new setChildren());
nativeFuncs.put("setLocalName", new setLocalName());
nativeFuncs.put("setName", new setName());
nativeFuncs.put("setNamespace", new setNamespace());
nativeFuncs.put("text", new text());
nativeFuncs.put("toString", new toString());
nativeFuncs.put("toXMLString", new toXMLString());
nativeFuncs.put("valueOf", new valueOf());
}
void buildENodeDom(ENode parent) {
NamedNodeMap attr = parent.node.getAttributes();
for( int i=0; attr != null && i< attr.getLength(); i++) {
parent.children.add( new ENode(attr.item(i)) );
}
if( parent.node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE ) {
Properties piProp = new Properties();
try {
piProp.load(new ByteArrayInputStream(((ProcessingInstruction)parent.node).getData().replaceAll("\" ", "\"\n").getBytes("UTF-8")));
for (Enumeration e = piProp.propertyNames(); e.hasMoreElements();) {
String propName = e.nextElement().toString();
String propValue = piProp.getProperty( propName );
Attr pi = parent.node.getOwnerDocument().createAttribute(propName.toString());
pi.setValue( propValue.substring(1, propValue.length()-1) );
parent.children.add( new ENode( pi ) );
}
}
catch (Exception e) {
System.out.println("no processing instructions for you.");
e.printStackTrace();
}
}
NodeList kids = parent.node.getChildNodes();
for( int i=0; i<kids.getLength(); i++) {
if( ( kids.item(i).getNodeType() == Node.COMMENT_NODE && E4X.ignoreComments ) ||
( kids.item(i).getNodeType() == Node.PROCESSING_INSTRUCTION_NODE && E4X.ignoreProcessingInstructions ) )
continue;
ENode n = new ENode(kids.item(i), parent);
buildENodeDom(n);
parent.children.add(n);
}
}
void init( String s ){
try {
// get rid of newlines and spaces if ignoreWhitespace is set (default)
if( E4X.ignoreWhitespace ) {
Pattern p = Pattern.compile("\\>\\s+\\<");
Matcher m = p.matcher(s);
s = m.replaceAll("><");
}
_document = XMLUtil.parse( s );
children = new LinkedList<ENode>();
node = _document.getDocumentElement();
buildENodeDom(this);
}
catch ( Exception e ){
throw new RuntimeException( "can't parse : " + e );
}
}
Hashtable<String, ENodeFunction> nativeFuncs = new Hashtable<String, ENodeFunction>();
public Object get( Object n ){
if ( n == null )
return null;
if ( n instanceof Number )
return child( ((Number)n).intValue() );
if ( n instanceof String || n instanceof JSString ){
String s = n.toString();
if( nativeFuncs.containsKey(s) )
return nativeFuncs.get( s );
if(s.equals("tojson")) return null;
Object o = _nodeGet( this, s );
return (o == null && E4X.isXMLName(s)) ? new ENode( this, s ) : o;
}
if ( n instanceof Query ) {
Query q = (Query)n;
List<ENode> matching = new ArrayList<ENode>();
for ( ENode theNode : children ){
if ( q.match( theNode ) ) {
matching.add( theNode );
}
}
return _handleListReturn( matching );
}
throw new RuntimeException( "can't handle : " + n.getClass() );
}
public Object set( Object k, Object v ) {
if( v == null )
v = "null";
if(this.children == null ) this.children = new LinkedList<ENode>();
if( k.toString().startsWith("@") )
return setAttribute(k.toString(), v.toString());
// attach any dummy ancestors to the tree
if( this._dummy ) {
ENode topParent = this;
this._dummy = false;
while( topParent.parent._dummy ) {
topParent = topParent.parent;
topParent._dummy = false;
}
topParent.parent.children.add(topParent);
}
// if v is already XML and it's not an XML attribute, just add v to this enode's children
if( v instanceof ENode ) {
if( k.toString().equals("*") ) {
this.children = new LinkedList<ENode>();
this.children.add((ENode)v);
}
else {
this.children.add((ENode)v);
}
return v;
}
// find out if this k/v pair exists
ENode n;
Object obj = get(k);
if( obj instanceof ENode )
n = ( ENode )obj;
else {
n = (( ENodeFunction )obj).cnode;
if( n == null ) {
n = new ENode();
}
}
Pattern num = Pattern.compile("-?\\d+");
Matcher m = num.matcher(k.toString());
// k is a number
if( m.matches() ) {
int index;
// the index must be greater than 0
if( ( index = Integer.parseInt(k.toString()) ) < 0)
return v;
// this index is greater than the number of elements existing
if( index >= n.children.size() ) {
Node content;
if(this.node != null)
content = this.node.getOwnerDocument().createTextNode(v.toString());
else if(this.children != null && this.children.size() > 0)
content = this.children.get(0).node.getOwnerDocument().createTextNode(v.toString());
else
return null;
// if k/v doesn't really exist, "get" returns a dummy node, an emtpy node with nodeName = key
if( n._dummy ) {
// if there is a list of future siblings, get the last one
ENode rep = this.parent == null ? this.children.get(this.children.size()-1) : this;
ENode attachee = rep.parent;
n.node = rep.node.getOwnerDocument().createElement(rep.node.getNodeName());
n.children.add( new ENode( content, n ) );
n.parent = attachee;
attachee.children.add( rep.childIndex()+1, n );
n._dummy = false;
}
else {
Node newNode;
ENode refNode = ( this.node == null ) ? this.children.get( this.children.size() - 1 ) : this.parent;
newNode = refNode.node.getOwnerDocument().createElement(refNode.node.getNodeName());
newNode.appendChild(content);
ENode newEn = new ENode(newNode, this);
buildENodeDom(newEn);
// get the last sibling's position & insert this new one there
int childIdx = refNode.childIndex();
refNode.parent.children.add( childIdx+1, newEn );
}
}
// replace an existing element
else {
// reset the child list
n.children = new LinkedList<ENode>();
NodeList kids = n.node.getChildNodes();
for( int i=0; kids != null && i<kids.getLength(); i++) {
n.node.removeChild(kids.item(i));
}
Node content = n.node.getOwnerDocument().createTextNode(v.toString());
appendChild(content, n);
}
}
// k must be a string
else {
// XMLList
if(this.node == null ) {
return v;
}
int index = this.children.size();
- if( n.node == null ) {
- // if there is more than one matching child, delete them all and replace with the new k/v
- while( n != null && n.children != null && n.children.size() > 0 ) {
- index = this.children.indexOf( n.children.get(0) );
- this.children.remove( n.children.get(0) );
- n.children.remove( 0 );
+ if( n.node != null && n.node.getNodeType() != Node.ATTRIBUTE_NODE) {
+ index = this.children.indexOf( n );
+ this.children.remove( n );
+ }
+ else {
+ // there are a list of children, so delete them all and replace with the new k/v
+ for( int i=0; n != null && n.children != null && i<n.children.size(); i++) {
+ if( n.children.get(i).node.getNodeType() == Node.ATTRIBUTE_NODE )
+ continue;
+ // find the index of this node in the tree
+ index = this.children.indexOf( n.children.get(i) );
+ // remove it from the tree
+ this.children.remove( n.children.get(i) ) ;
}
- n.node = node.getOwnerDocument().createElement(k.toString());
}
- Node content = node.getOwnerDocument().createTextNode(v.toString());
+ n = new ENode(this.node.getOwnerDocument().createElement(k.toString()), this);
+ Node content = this.node.getOwnerDocument().createTextNode(v.toString());
n.children.add( new ENode( content, n ) );
if( !this.children.contains( n ) )
- this.children.add( index, n );
+ if( index >= 0 )
+ this.children.add( index, n );
+ else
+ this.children.add( n );
}
return v;
}
private Object setAttribute( String k, String v ) {
if( !k.startsWith("@") )
return v;
Object obj = get(k);
k = k.substring(1);
// create a new attribute
if( obj == null ) {
Attr newNode = node.getOwnerDocument().createAttribute(k);
newNode.setValue( v );
this.children.add( new ENode(newNode, this) );
}
// change an existing attribute
else {
List<ENode> list = this.getAttributes();
for( ENode n : list ) {
if( ((Attr)n.node).getName().equals( k ) )
((Attr)n.node).setValue( v );
}
}
return v;
}
/**
* Called for delete xml.prop
*/
public Object removeField(Object o) {
ENode n = (ENode)get(o);
if(n.node != null)
return n.parent.children.remove(n);
for(ENode e : n.children)
children.remove(e);
return true;
}
public class addNamespace extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
throw new RuntimeException("not yet implemented");
}
}
private ENode appendChild(Node child, ENode parent) {
if(parent.children == null)
parent.children = new LinkedList<ENode>();
ENode echild = new ENode(child, parent);
buildENodeDom(echild);
parent.children.add(echild);
return this;
}
private ENode appendChild(ENode child) {
return appendChild(child.node, this);
}
public class appendChild extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode parent = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
if( foo.length == 0 )
return parent;
ENode child = toXML( foo[0] );
return child == null ? parent : parent.appendChild(child);
}
}
private String attribute( String prop ) {
Object o = this.get("@"+prop);
return (o == null) ? "" : o.toString();
}
public class attribute extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
if(foo.length == 0)
return null;
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.attribute(foo[0].toString());
}
}
public class attributes extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
Object obj = s.getThis();
if(obj instanceof ENode)
return ((ENode)obj).get("@*");
else
return ((ENodeFunction)obj).cnode.get("@*");
}
}
private ENode child(Object propertyName) {
Pattern num = Pattern.compile("-?\\d+(\\.\\d+)?");
Matcher m = num.matcher(propertyName.toString());
if( m.matches() ) {
int i = Integer.parseInt(propertyName.toString());
if(i < 0 )
return null;
if( i < this.children.size() )
return (ENode)this.children.get(i);
else {
return new ENode( this, this.node == null ? null : this.node.getNodeName() );
}
}
else {
return (ENode)this.get(propertyName);
}
}
public class child extends ENodeFunction {
public Object call( Scope s, Object foo[]) {
if( foo.length == 0 )
return null;
Object obj = s.getThis();
if( obj instanceof ENode )
return ((ENode)obj).child( foo[0].toString() );
else
return ((ENodeFunction)obj).cnode.child( foo[0].toString() );
}
}
private int childIndex() {
if( parent == null || parent.node.getNodeType() == Node.ATTRIBUTE_NODE )
return -1;
List<ENode> sibs = parent.children;
for( int i=0; i<sibs.size(); i++ ) {
if(sibs.get(i).equals(this))
return i;
}
return -1;
}
public class childIndex extends ENodeFunction {
public Object call (Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.childIndex();
}
}
private ENode children() {
ENode childrenNode = this.copy();
childrenNode.node = null;
return childrenNode;
}
public class children extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.children();
}
}
public ENode clone() {
ENode newNode = new ENode(this.node, this.parent);
newNode.children.addAll(this.children);
return newNode;
}
public ENode comments() {
ENode comments = new ENode();
for( ENode child : this.children ) {
if( child.node.getNodeType() == Node.COMMENT_NODE )
comments.children.add( child );
}
return comments;
}
public class comments extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode t = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return t.comments();
}
}
// this is to spec, but doesn't seem right... it's "equals", not "contains"
public class contains extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
if( foo.length == 0 || !(foo[0] instanceof ENode) )
return false;
ENode o = (ENode)foo[0];
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.node.isEqualNode(o.node);
}
}
private ENode copy() {
return (ENode)this.clone();
}
public class copy extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.copy();
}
};
private ENode descendants( String name ) {
List kids = new LinkedList<ENode>();
ENode childs = (ENode)this.get(name);
for( int i=0; i<childs.children.size(); i++) {
kids.add(childs.children.get(i));
ENode el = ((ENode)childs.children.get(i)).descendants(name);
for( int j=0; j<el.children.size(); j++) {
kids.add(el.children.get(j));
}
}
return new ENode(kids);
}
public class descendants extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
String name = ( foo.length == 0) ? "*" : foo[0].toString();
return enode.descendants(name);
}
}
public class elements extends ENodeFunction {
public Object call( Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
String name = (foo.length == 0) ? "*" : foo[0].toString();
if( enode.children == null || enode.children.size() == 0)
return null;
if(name == null || name == "") {
name = "*";
}
ENode list = new ENode();
for( ENode n : enode.children ) {
if( n.node != null && n.node.getNodeType() == Node.ELEMENT_NODE && (name.equals( "*" ) || n.node.getNodeName().equals(name)) )
list.children.add( n );
}
return list;
}
}
public class hasOwnProperty extends ENodeFunction {
public Object call(Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode en = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
if(foo.length == 0 || en.children == null || en.children.size() == 0)
return false;
String prop = foo[0].toString();
for( ENode n : en.children ) {
if( n.node != null && n.node.getNodeName().equals(prop) )
return true;
}
return false;
}
}
private boolean isSimpleTypeNode( short type ) {
if( type == Node.ATTRIBUTE_NODE ||
type == Node.PROCESSING_INSTRUCTION_NODE ||
type == Node.COMMENT_NODE ||
type == Node.TEXT_NODE )
return true;
return false;
}
/**
* Returns if this node contains complex content. That is, if this node has child nodes that are element-type nodes.
*/
public class hasComplexContent extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode en = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
if( isSimpleTypeNode(en.node.getNodeType()) )
return false;
for( ENode n : en.children ) {
if( n.node.getNodeType() == Node.ELEMENT_NODE )
return false;
}
return true;
}
}
/**
* Returns if this node contains simple content. An XML node is considered to have simple content if it represents a text or attribute node or an XML element with no child elements.
*/
public class hasSimpleContent extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode en = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
short type = en.node.getNodeType();
if( type == Node.PROCESSING_INSTRUCTION_NODE ||
type == Node.COMMENT_NODE )
return false;
for( ENode n : en.children ) {
if( n.node.getNodeType() == Node.ELEMENT_NODE )
return false;
}
return true;
}
}
private JSObject _getUniqueNamespaces() {
JSObject inScopeNS = new JSObjectBase();
ENode y = this.copy();
while( y != null ) {
for( Namespace ns : y.inScopeNamespaces ) {
if( inScopeNS.get( ns.prefix ) != null )
inScopeNS.set( ns.prefix.toString(), ns );
}
y = y.parent;
}
return inScopeNS;
}
private JSArray inScopeNamespaces() {
JSObject inScopeNS = _getUniqueNamespaces();
JSArray a = new JSArray();
Iterator k = (inScopeNS.keySet()).iterator();
while(k.hasNext()) {
a.add( inScopeNS.get(k).toString() );
}
return a;
}
public class inScopeNamespaces extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.inScopeNamespaces();
}
}
private ENode insertChildAfter(Object child1, ENode child2) {
return _insertChild(child1, child2, 1);
}
private ENode insertChildBefore(Object child1, ENode child2) {
return _insertChild(child1, child2, 0);
}
public class insertChildAfter extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
if(foo.length == 0 )
return enode.insertChildAfter((Object)null, (ENode)null);
if(foo.length == 1 )
return enode.insertChildAfter((Object)foo[0], (ENode)null);
return enode.insertChildAfter((Object)foo[0], (ENode)foo[1]);
}
}
public class insertChildBefore extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
if(foo.length == 0 )
return enode.insertChildBefore((Object)null, (ENode)null);
if(foo.length == 1 )
return enode.insertChildBefore((Object)foo[0], (ENode)null);
return enode.insertChildBefore((Object)foo[0], (ENode)foo[1]);
}
}
private ENode _insertChild( Object child1, ENode child2, int j ) {
if( isSimpleTypeNode(this.node.getNodeType() ) ) return null;
if( child1 == null ) {
this.children.add( 0, child2 );
return this;
}
else if ( child1 instanceof ENode ) {
for( int i=0; i<children.size(); i++) {
if( children.get(i) == child1 ) {
children.add(i+j, child2);
return this;
}
}
}
return null;
}
public class length extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return ( enode.node != null ) ? 1 : enode.children.size();
}
}
private String localName() {
return this.name == null ? null : this.name.localName;
}
public class localName extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.localName();
}
}
private QName name() {
return this.name;
}
public class name extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.name();
}
}
private Namespace namespace( String prefix ) {
JSObject obj = _getUniqueNamespaces();
if( prefix == null ) {
if( isSimpleTypeNode( this.node.getNodeType() ) )
return null;
return this.name.getNamespace( obj );
}
else {
return (Namespace)obj.get( prefix );
}
}
public class namespace extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
String prefix = (foo.length > 0) ? foo[0].toString() : null;
return enode.namespace( prefix );
}
}
private JSArray namespaceDeclarations() {
JSArray a = new JSArray();
if( isSimpleTypeNode( this.node.getNodeType() ) )
return a;
ArrayList<Namespace> declaredNS = (ArrayList<Namespace>)this.parent.inScopeNamespaces.clone();
for( int i=0; i < this.inScopeNamespaces.size(); i++) {
declaredNS.remove( this.inScopeNamespaces.get(i) );
}
for( int i=0; i < declaredNS.size(); i++) {
a.add( declaredNS.get(i) );
}
return a;
}
public class namespaceDeclarations extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return enode.namespaceDeclarations();
}
}
public class nodeKind extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode n = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
switch ( n.node.getNodeType() ) {
case Node.ELEMENT_NODE :
return "element";
case Node.COMMENT_NODE :
return "comment";
case Node.ATTRIBUTE_NODE :
return "attribute";
case Node.TEXT_NODE :
return "text";
case Node.PROCESSING_INSTRUCTION_NODE :
return "processing-instruction";
default :
return "unknown";
}
}
}
private ENode normalize() {
int i=0;
while( i< this.children.size()) {
if( this.children.get(i).node.getNodeType() == Node.ELEMENT_NODE ) {
this.children.get(i).normalize();
i++;
}
else if( this.children.get(i).node.getNodeType() == Node.TEXT_NODE ) {
while( i+1 < this.children.size() && this.children.get(i+1).node.getNodeType() == Node.TEXT_NODE ) {
this.children.get(i).node.setNodeValue( this.children.get(i).node.getNodeValue() + this.children.get(i+1).node.getNodeValue());
this.children.remove(i+1);
}
if( this.children.get(i).node.getNodeValue().length() == 0 ) {
this.children.remove(i);
}
else {
i++;
}
}
else {
i++;
}
}
return this;
}
/** Merges adjacent text nodes and eliminates empty text nodes */
public class normalize extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode n = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return n.normalize();
}
}
public class parent extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode n = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return n.parent;
}
}
public ENode processingInstructions( String name ) {
boolean all = name.equals( "*" );
ENode list = new ENode();
for( ENode n : this.children ) {
if ( n.node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE && ( all || name.equals(n.node.getLocalName()) ) ) {
list.children.add( n );
}
}
return list;
}
public class processingInstructions extends ENodeFunction {
public Object call(Scope s, Object foo[] ) {
Object obj = s.getThis();
ENode en = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
String name = (foo.length == 0 ) ? "*" : foo[0].toString();
return en.processingInstructions(name);
}
}
/** Inserts the given child into this object prior to the existing XML properties.
*/
public class prependChild extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode en = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return en._insertChild( (Object)null, (ENode)foo[0], 0 );
}
}
/**
* So, the spec says that this should only return toString(prop) == "0". However, the Rhino implementation returns true
* whenever prop is a valid index, so I'm going with that.
*/
private boolean propertyIsEnumerable( String prop ) {
Pattern num = Pattern.compile("\\d+");
Matcher m = num.matcher(prop);
if( m.matches() ) {
ENode n = this.child(prop);
return !n._dummy;
}
return false;
}
public class propertyIsEnumerable extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
String prop = foo[0].toString();
return enode.propertyIsEnumerable( prop );
}
}
public class removeNamespace extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
throw new RuntimeException("not yet implemented");
}
}
public class replace extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
String name = foo[0].toString();
Object value = foo[1];
ENode exists = (ENode)enode.get(name);
if( exists == null )
return this;
return enode.set(name, value);
}
}
private Object setChildren( Object value ) {
this.set("*", value);
return this;
}
/** not right */
public class setChildren extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode enode = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
Object value = foo[0];
return enode.setChildren(value);
}
}
private void setLocalName( Object name ) {
if( this.node == null ||
this.node.getNodeType() == Node.TEXT_NODE ||
this.node.getNodeType() == Node.COMMENT_NODE )
return;
this.name.localName = ( name instanceof QName ) ? ((QName)name).localName : name.toString();
}
public class setLocalName extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode n = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
Object name = (foo.length > 0) ? foo[0] : null;
if(name == null)
return null;
n.setLocalName( name );
return null;
}
}
private void setName( Object name ) {
if( this.node == null ||
this.node.getNodeType() == Node.TEXT_NODE ||
this.node.getNodeType() == Node.COMMENT_NODE )
return;
if ( name instanceof QName && ((QName)name).uri.equals("") )
name = ((QName)name).localName;
QName n = new QName( name );
if( this.node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE )
n.uri = "";
this.name = n;
Namespace ns = new Namespace( n.prefix, n.uri );
if( this.node.getNodeType() == Node.ATTRIBUTE_NODE ) {
if( this.parent == null )
return;
this.parent.addInScopeNamespace( ns );
}
if( this.node.getNodeType() == Node.ELEMENT_NODE )
this.addInScopeNamespace( ns );
}
public class setName extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode n = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
if (foo.length > 0 )
n.setName(foo[0].toString());
return null;
}
}
private void setNamespace( Object ns) {
if( this.node == null ||
this.node.getNodeType() == Node.TEXT_NODE ||
this.node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE ||
this.node.getNodeType() == Node.COMMENT_NODE )
return;
Namespace ns2 = new Namespace( ns );
this.name = new QName( ns2, this.name );
if( this.node.getNodeType() == Node.ATTRIBUTE_NODE ) {
if (this.parent == null )
return;
this.parent.addInScopeNamespace(ns2 );
}
if( this.node.getNodeType() == Node.ELEMENT_NODE ) {
this.addInScopeNamespace(ns2 );
}
}
public class setNamespace extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
if( foo.length == 0 )
return null;
Object obj = s.getThis();
ENode n = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
n.setNamespace( foo[0] );
return null;
}
}
public class text extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode en = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
ENode list = new ENode();
if( en.node != null && en.node.getNodeType() == Node.TEXT_NODE ) {
list.children.add( en );
return list;
}
for ( ENode n : en.children ) {
if( n.node.getNodeType() == Node.TEXT_NODE ) {
list.children.add( n );
}
}
return list;
}
}
public String toString() {
if ( this.node == null && this.children == null )
return null;
StringBuilder xml = new StringBuilder();
// XML
if( this.node != null || this.children.size() == 1 ) {
ENode singleNode = ( this.node != null ) ? this : this.children.get(0);
List<ENode> kids = singleNode.printableChildren();
// if this is an empty top level element, return nothing
if( singleNode.node.getNodeType() == Node.ELEMENT_NODE && ( kids == null || kids.size() == 0 ) )
return "";
if( singleNode.node.getNodeType() == Node.ATTRIBUTE_NODE || singleNode.node.getNodeType() == Node.TEXT_NODE )
return singleNode.node.getNodeValue();
if ( singleNode.node.getNodeType() == Node.ELEMENT_NODE &&
singleNode.children != null &&
singleNode.childrenAreTextNodes() ) {
for( ENode n : singleNode.children )
xml.append( n.node.getNodeValue() );
return xml.toString();
}
append( singleNode, xml, 0);
}
// XMLList
else {
for( int i=0; i<this.children.size(); i++ ) {
append( this.children.get( i ), xml, 0);
}
}
// XMLUtil's toString always appends a "\n" to the end
if( xml.length() > 0 && xml.charAt(xml.length() - 1) == '\n' ) {
xml.deleteCharAt(xml.length()-1);
}
return xml.toString();
}
public StringBuilder append( ENode n , StringBuilder buf , int level ){
switch (n.node.getNodeType() ) {
case Node.ATTRIBUTE_NODE:
return _level(buf, level).append( E4X.prettyPrinting ? n.node.getNodeValue().trim() : n.node.getNodeValue() );
case Node.TEXT_NODE:
return _level(buf, level).append( E4X.prettyPrinting ? n.node.getNodeValue().trim() : n.node.getNodeValue() ).append("\n");
case Node.COMMENT_NODE:
return _level(buf, level).append( "<!--"+n.node.getNodeValue()+"-->" ).append("\n");
case Node.PROCESSING_INSTRUCTION_NODE:
return _level(buf, level).append( "<?"+n.node.getNodeName() + attributesToString( n )+"?>").append("\n");
}
_level( buf , level ).append( "<" ).append( n.node.getNodeName() );
buf.append(attributesToString( n ));
List<ENode> kids = n.printableChildren();
if ( kids == null || kids.size() == 0 ) {
return buf.append( "/>\n" );
}
buf.append(">");
if( (kids.size() == 1 && kids.get(0).node.getNodeType() == Node.ELEMENT_NODE) ||
kids.size() > 1 ) {
buf.append( "\n" );
}
else {
return buf.append( E4X.prettyPrinting ? kids.get(0).node.getNodeValue().trim() : kids.get(0).node.getNodeValue() ).append( "</" ).append( n.node.getNodeName() ).append( ">\n" );
}
for ( int i=0; i<kids.size(); i++ ){
ENode c = kids.get(i);
if( ( E4X.ignoreComments && c.node.getNodeType() == Node.ATTRIBUTE_NODE ) ||
( E4X.ignoreComments && c.node.getNodeType() == Node.COMMENT_NODE ) ||
( E4X.ignoreProcessingInstructions && c.node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE ) )
continue;
else {
append( c , buf , level + 1 );
}
}
return _level( buf , level ).append( "</" ).append( n.node.getNodeName() ).append( ">\n" );
}
private StringBuilder _level( StringBuilder buf , int level ){
for ( int i=0; i<level; i++ ) {
for( int j=0; j<E4X.prettyIndent; j++) {
buf.append( " " );
}
}
return buf;
}
private String attributesToString( ENode n ) {
StringBuilder buf = new StringBuilder();
ArrayList<ENode> attr = n.getAttributes();
String[] attrArr = new String[attr.size()];
for( int i = 0; i< attr.size(); i++ ) {
attrArr[i] = " " + attr.get(i).node.getNodeName() + "=\"" + attr.get(i).node.getNodeValue() + "\"";
}
Arrays.sort(attrArr);
for( String a : attrArr ) {
buf.append( a );
}
return buf.toString();
}
private List<ENode> printableChildren() {
List list = new LinkedList<ENode>();
for ( int i=0; this.children != null && i<this.children.size(); i++ ){
ENode c = this.children.get(i);
if( c.node.getNodeType() == Node.ATTRIBUTE_NODE ||
( c.node.getNodeType() == Node.COMMENT_NODE && E4X.ignoreComments ) ||
( c.node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE && E4X.ignoreProcessingInstructions ) )
continue;
list.add(c);
}
return list;
}
private boolean childrenAreTextNodes() {
for( ENode n : this.children ) {
if( n.node.getNodeType() != Node.TEXT_NODE )
return false;
}
return true;
}
public class toString extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode n = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
return n.toString();
}
}
/** too painful to do right now */
public class toXMLString extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
ENode n = ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
throw new RuntimeException("not yet implemented");
}
}
public class valueOf extends ENodeFunction {
public Object call(Scope s, Object foo[]) {
Object obj = s.getThis();
return ( obj instanceof ENode ) ? (ENode)obj : ((ENodeFunction)obj).cnode;
}
}
public NodeList getChildNodes() {
return node.getChildNodes();
}
private void addInScopeNamespace( Namespace n ) {
if (this.node == null)
return;
short type = this.node.getNodeType();
if( type == Node.COMMENT_NODE ||
type == Node.PROCESSING_INSTRUCTION_NODE ||
type == Node.TEXT_NODE ||
type == Node.ATTRIBUTE_NODE )
return;
if( n.prefix == null )
return;
if( n.prefix.equals("") && (this.name == null || this.name.uri.equals("") ))
return;
Namespace match = null;
for( Namespace ns : this.inScopeNamespaces ) {
if( n.prefix.equals( ns.prefix ) ) {
match = ns;
}
}
if( match != null && !match.uri.equals(n.uri) )
this.inScopeNamespaces.remove(match);
this.inScopeNamespaces.add( n );
if( this.name.prefix.equals( n.prefix ) )
this.name.prefix = null;
}
public ArrayList getAttributes() {
if(node == null && ( children == null || children.size() == 0)) return null;
ArrayList<ENode> list = new ArrayList<ENode>();
if(this.node != null && this.children != null) {
for( ENode child : this.children ) {
if( child.node.getNodeType() == Node.ATTRIBUTE_NODE ) {
list.add(child);
}
}
}
else if (this.children != null ) {
for( ENode child : this.children ) {
if( child.node.getNodeType() == Node.ELEMENT_NODE ) {
list.addAll(child.getAttributes());
}
}
}
return list;
}
public ENode toXML( Object input ) {
if( input == null )
return null;
if( input instanceof Boolean ||
input instanceof Number ||
input instanceof JSString )
return toXML(input.toString());
else if( input instanceof String )
return new ENode(this.node.getOwnerDocument().createTextNode((String)input));
else if( input instanceof Node )
return new ENode((Node)input);
else if( input instanceof ENode )
return (ENode)input;
else
return null;
}
public abstract class ENodeFunction extends JSFunctionCalls0 {
public String toString() {
if( cnode == null ) {
cnode = (ENode)E4X._nodeGet(ENode.this, this.getClass().getSimpleName());
}
return cnode == null ? "" : cnode.toString();
}
public Object get( Object n ) {
if ( cnode == null ) {
cnode = (ENode)E4X._nodeGet(ENode.this, this.getClass().getSimpleName());
}
return cnode.get( n );
}
public Object set( Object n, Object v ) {
// there's this stupid thing where set is called for every xml node created
if( n.equals("prototype") && v instanceof JSObjectBase)
return null;
if( cnode == null ) {
cnode = (ENode)E4X._nodeGet(ENode.this, this.getClass().getSimpleName());
if( cnode == null )
return null;
}
return cnode.set( n, v );
}
ENode cnode;
}
private Document _document;
private List<ENode> children;
private ENode parent;
private Node node;
private boolean _dummy;
private ArrayList<Namespace> inScopeNamespaces;
private QName name;
}
/* static class XMLList implements List {
private List<ENode> nodes;
}
*/
static Object _nodeGet( ENode start , String s ){
List<ENode> ln = new LinkedList<ENode>();
if( start.node == null )
for(int i=0; i<start.children.size(); i++) {
ln.add(start.children.get(i));
}
else
ln.add(start);
return _nodeGet( ln, s );
}
static Object _nodeGet( List<ENode> start , String s ){
final boolean search = s.startsWith( ".." );
if ( search )
s = s.substring(2);
final boolean attr = s.startsWith( "@" );
if ( attr )
s = s.substring(1);
final boolean all = s.endsWith("*");
if( all ) {
if( s.length() > 1) return null;
s = "";
}
List<ENode> traverse = new LinkedList<ENode>();
List<ENode> res = new ArrayList<ENode>();
for(int k=0; k< start.size(); k++) {
traverse.add( start.get(k) );
while ( ! traverse.isEmpty() ){
ENode n = traverse.remove(0);
if ( attr ){
ArrayList<ENode> nnm = n.getAttributes();
for(int i=0; i < nnm.size(); i++) {
if( all || nnm.get(i).node.getNodeName().equals( s ) ) {
res.add( nnm.get(i) );
}
}
}
List<ENode> kids = n.children;
if ( kids == null || kids.size() == 0 )
continue;
for ( int i=0; i<kids.size(); i++ ){
ENode c = kids.get(i);
if ( ! attr && c.node.getNodeType() != Node.ATTRIBUTE_NODE && ( all || c.node.getNodeName().equals( s ) ) ) {
res.add( c );
}
if ( search )
traverse.add( c );
}
}
}
return _handleListReturn( res );
}
static Object _handleListReturn( List<ENode> lst ){
if ( lst.size() == 0 )
return null;
if ( lst.size() == 1 ){
return lst.get(0);
}
return new ENode(lst);
}
public static abstract class Query {
public Query( String what , JSString match ){
_what = what;
_match = match;
}
abstract boolean match( ENode n );
final String _what;
final JSString _match;
}
public static class Query_EQ extends Query {
public Query_EQ( String what , JSString match ){
super( what , match );
}
boolean match( ENode n ){
ENode result = (ENode)n.get( _what );
if( result._dummy )
return false;
if( result.node.getNodeType() == Node.ATTRIBUTE_NODE )
return result.node.getNodeValue().equals( _match.toString() );
else
return JSInternalFunctions.JS_eq( _nodeGet( n , _what ) , _match );
}
public String toString(){
return " [[ " + _what + " == " + _match + " ]] ";
}
}
public static boolean isXMLName( String name ) {
Pattern invalidChars = Pattern.compile("[@\\s\\{\\/\\']|(\\.\\.)|(\\:\\:)");
Matcher m = invalidChars.matcher( name );
if( m.find() ) {
return false;
}
return true;
}
static class QName {
public String localName;
public String uri;
public String prefix;
public QName() {
this( null, null );
}
public QName( Object name ) {
this( null, name );
}
public QName( Namespace namespace, Object name ) {
if( name instanceof QName ) {
if ( namespace == null ) {
this.localName = ((QName)name).localName;
this.uri = ((QName)name).uri;
return;
}
else {
this.localName = ((QName)name).localName;
}
}
if( name == null ) {
this.localName = "";
}
else {
this.localName = name.toString();
}
if( namespace == null ) {
if( this.localName.equals("*") ) {
namespace = null;
}
else {
namespace = E4X.getDefaultNamespace();
}
}
if( namespace == null ) {
this.uri = null;
}
else {
namespace = new Namespace(namespace);
this.uri = namespace.uri;
}
}
public String toString() {
String s = "";
if( !this.uri.equals("") ) {
if( this.uri == null ) {
s = "*::";
}
else {
s = this.uri + "*::";
}
}
return s + this.localName;
}
public Namespace getNamespace( JSObject inScopeNS ) {
if( this.uri == null )
return null;
if( inScopeNS == null )
inScopeNS = new JSObjectBase();
Namespace ns = (Namespace)inScopeNS.get( this.uri );
if( ns == null )
return new Namespace( this.uri );
return ns;
}
}
static class Namespace extends JSObjectBase {
void init( String s ) {
this.uri = s;
defaultNamespace = new Namespace( s );
}
public String prefix;
public String uri;
public Namespace() {
this(null, null);
}
public Namespace( Object uri) {
this(null, uri);
}
public Namespace( String prefix, Object uri) {
if(prefix == null && uri == null) {
this.prefix = "";
this.uri = "";
}
else if (prefix == null) {
if ( uri instanceof Namespace ) {
this.prefix = ((Namespace)uri).prefix;
this.uri = ((Namespace)uri).uri;
}
else if( uri instanceof QName ) {
this.uri = ((QName)uri).uri;
}
else {
this.uri = uri.toString();
if( this.uri.equals("") )
this.prefix = "";
else
this.prefix = null;
}
}
else {
if( uri instanceof QName && ((QName)uri).uri != null) {
this.uri = ((QName)uri).uri;
}
else {
this.uri = uri.toString();
}
if( this.uri.equals("") ) {
if( prefix == null || prefix.equals("") ) {
this.prefix = "";
}
else {
return;
}
}
else if( prefix == null || !E4X.isXMLName( prefix ) ) {
this.prefix = null;
}
else {
this.prefix = prefix;
}
}
}
public String toString() {
return this.uri;
}
}
private static Namespace defaultNamespace;
public static Namespace getDefaultNamespace() {
if(defaultNamespace == null)
defaultNamespace = new Namespace();
return defaultNamespace;
}
public static Namespace setAndGetDefaultNamespace(Object o) {
if( o instanceof Namespace )
defaultNamespace = (Namespace)o;
return defaultNamespace;
}
}
| false | true | public Object set( Object k, Object v ) {
if( v == null )
v = "null";
if(this.children == null ) this.children = new LinkedList<ENode>();
if( k.toString().startsWith("@") )
return setAttribute(k.toString(), v.toString());
// attach any dummy ancestors to the tree
if( this._dummy ) {
ENode topParent = this;
this._dummy = false;
while( topParent.parent._dummy ) {
topParent = topParent.parent;
topParent._dummy = false;
}
topParent.parent.children.add(topParent);
}
// if v is already XML and it's not an XML attribute, just add v to this enode's children
if( v instanceof ENode ) {
if( k.toString().equals("*") ) {
this.children = new LinkedList<ENode>();
this.children.add((ENode)v);
}
else {
this.children.add((ENode)v);
}
return v;
}
// find out if this k/v pair exists
ENode n;
Object obj = get(k);
if( obj instanceof ENode )
n = ( ENode )obj;
else {
n = (( ENodeFunction )obj).cnode;
if( n == null ) {
n = new ENode();
}
}
Pattern num = Pattern.compile("-?\\d+");
Matcher m = num.matcher(k.toString());
// k is a number
if( m.matches() ) {
int index;
// the index must be greater than 0
if( ( index = Integer.parseInt(k.toString()) ) < 0)
return v;
// this index is greater than the number of elements existing
if( index >= n.children.size() ) {
Node content;
if(this.node != null)
content = this.node.getOwnerDocument().createTextNode(v.toString());
else if(this.children != null && this.children.size() > 0)
content = this.children.get(0).node.getOwnerDocument().createTextNode(v.toString());
else
return null;
// if k/v doesn't really exist, "get" returns a dummy node, an emtpy node with nodeName = key
if( n._dummy ) {
// if there is a list of future siblings, get the last one
ENode rep = this.parent == null ? this.children.get(this.children.size()-1) : this;
ENode attachee = rep.parent;
n.node = rep.node.getOwnerDocument().createElement(rep.node.getNodeName());
n.children.add( new ENode( content, n ) );
n.parent = attachee;
attachee.children.add( rep.childIndex()+1, n );
n._dummy = false;
}
else {
Node newNode;
ENode refNode = ( this.node == null ) ? this.children.get( this.children.size() - 1 ) : this.parent;
newNode = refNode.node.getOwnerDocument().createElement(refNode.node.getNodeName());
newNode.appendChild(content);
ENode newEn = new ENode(newNode, this);
buildENodeDom(newEn);
// get the last sibling's position & insert this new one there
int childIdx = refNode.childIndex();
refNode.parent.children.add( childIdx+1, newEn );
}
}
// replace an existing element
else {
// reset the child list
n.children = new LinkedList<ENode>();
NodeList kids = n.node.getChildNodes();
for( int i=0; kids != null && i<kids.getLength(); i++) {
n.node.removeChild(kids.item(i));
}
Node content = n.node.getOwnerDocument().createTextNode(v.toString());
appendChild(content, n);
}
}
// k must be a string
else {
// XMLList
if(this.node == null ) {
return v;
}
int index = this.children.size();
if( n.node == null ) {
// if there is more than one matching child, delete them all and replace with the new k/v
while( n != null && n.children != null && n.children.size() > 0 ) {
index = this.children.indexOf( n.children.get(0) );
this.children.remove( n.children.get(0) );
n.children.remove( 0 );
}
n.node = node.getOwnerDocument().createElement(k.toString());
}
Node content = node.getOwnerDocument().createTextNode(v.toString());
n.children.add( new ENode( content, n ) );
if( !this.children.contains( n ) )
this.children.add( index, n );
}
return v;
}
| public Object set( Object k, Object v ) {
if( v == null )
v = "null";
if(this.children == null ) this.children = new LinkedList<ENode>();
if( k.toString().startsWith("@") )
return setAttribute(k.toString(), v.toString());
// attach any dummy ancestors to the tree
if( this._dummy ) {
ENode topParent = this;
this._dummy = false;
while( topParent.parent._dummy ) {
topParent = topParent.parent;
topParent._dummy = false;
}
topParent.parent.children.add(topParent);
}
// if v is already XML and it's not an XML attribute, just add v to this enode's children
if( v instanceof ENode ) {
if( k.toString().equals("*") ) {
this.children = new LinkedList<ENode>();
this.children.add((ENode)v);
}
else {
this.children.add((ENode)v);
}
return v;
}
// find out if this k/v pair exists
ENode n;
Object obj = get(k);
if( obj instanceof ENode )
n = ( ENode )obj;
else {
n = (( ENodeFunction )obj).cnode;
if( n == null ) {
n = new ENode();
}
}
Pattern num = Pattern.compile("-?\\d+");
Matcher m = num.matcher(k.toString());
// k is a number
if( m.matches() ) {
int index;
// the index must be greater than 0
if( ( index = Integer.parseInt(k.toString()) ) < 0)
return v;
// this index is greater than the number of elements existing
if( index >= n.children.size() ) {
Node content;
if(this.node != null)
content = this.node.getOwnerDocument().createTextNode(v.toString());
else if(this.children != null && this.children.size() > 0)
content = this.children.get(0).node.getOwnerDocument().createTextNode(v.toString());
else
return null;
// if k/v doesn't really exist, "get" returns a dummy node, an emtpy node with nodeName = key
if( n._dummy ) {
// if there is a list of future siblings, get the last one
ENode rep = this.parent == null ? this.children.get(this.children.size()-1) : this;
ENode attachee = rep.parent;
n.node = rep.node.getOwnerDocument().createElement(rep.node.getNodeName());
n.children.add( new ENode( content, n ) );
n.parent = attachee;
attachee.children.add( rep.childIndex()+1, n );
n._dummy = false;
}
else {
Node newNode;
ENode refNode = ( this.node == null ) ? this.children.get( this.children.size() - 1 ) : this.parent;
newNode = refNode.node.getOwnerDocument().createElement(refNode.node.getNodeName());
newNode.appendChild(content);
ENode newEn = new ENode(newNode, this);
buildENodeDom(newEn);
// get the last sibling's position & insert this new one there
int childIdx = refNode.childIndex();
refNode.parent.children.add( childIdx+1, newEn );
}
}
// replace an existing element
else {
// reset the child list
n.children = new LinkedList<ENode>();
NodeList kids = n.node.getChildNodes();
for( int i=0; kids != null && i<kids.getLength(); i++) {
n.node.removeChild(kids.item(i));
}
Node content = n.node.getOwnerDocument().createTextNode(v.toString());
appendChild(content, n);
}
}
// k must be a string
else {
// XMLList
if(this.node == null ) {
return v;
}
int index = this.children.size();
if( n.node != null && n.node.getNodeType() != Node.ATTRIBUTE_NODE) {
index = this.children.indexOf( n );
this.children.remove( n );
}
else {
// there are a list of children, so delete them all and replace with the new k/v
for( int i=0; n != null && n.children != null && i<n.children.size(); i++) {
if( n.children.get(i).node.getNodeType() == Node.ATTRIBUTE_NODE )
continue;
// find the index of this node in the tree
index = this.children.indexOf( n.children.get(i) );
// remove it from the tree
this.children.remove( n.children.get(i) ) ;
}
}
n = new ENode(this.node.getOwnerDocument().createElement(k.toString()), this);
Node content = this.node.getOwnerDocument().createTextNode(v.toString());
n.children.add( new ENode( content, n ) );
if( !this.children.contains( n ) )
if( index >= 0 )
this.children.add( index, n );
else
this.children.add( n );
}
return v;
}
|
diff --git a/org.eclipse.scout.rt.ui.swing/src/org/eclipse/scout/rt/ui/swing/form/fields/tablefield/SwingScoutTableField.java b/org.eclipse.scout.rt.ui.swing/src/org/eclipse/scout/rt/ui/swing/form/fields/tablefield/SwingScoutTableField.java
index d3b2030b0d..ed67ca9243 100644
--- a/org.eclipse.scout.rt.ui.swing/src/org/eclipse/scout/rt/ui/swing/form/fields/tablefield/SwingScoutTableField.java
+++ b/org.eclipse.scout.rt.ui.swing/src/org/eclipse/scout/rt/ui/swing/form/fields/tablefield/SwingScoutTableField.java
@@ -1,156 +1,158 @@
/*******************************************************************************
* Copyright (c) 2010 BSI Business Systems Integration AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BSI Business Systems Integration AG - initial API and implementation
******************************************************************************/
package org.eclipse.scout.rt.ui.swing.form.fields.tablefield;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import org.eclipse.scout.commons.exception.IProcessingStatus;
import org.eclipse.scout.rt.client.ui.basic.table.ITable;
import org.eclipse.scout.rt.client.ui.form.IForm;
import org.eclipse.scout.rt.client.ui.form.fields.groupbox.IGroupBox;
import org.eclipse.scout.rt.client.ui.form.fields.tablefield.ITableField;
import org.eclipse.scout.rt.ui.swing.LogicalGridData;
import org.eclipse.scout.rt.ui.swing.LogicalGridLayout;
import org.eclipse.scout.rt.ui.swing.basic.table.ISwingScoutTable;
import org.eclipse.scout.rt.ui.swing.basic.table.SwingScoutTable;
import org.eclipse.scout.rt.ui.swing.ext.JPanelEx;
import org.eclipse.scout.rt.ui.swing.ext.JStatusLabelEx;
import org.eclipse.scout.rt.ui.swing.ext.JTableEx;
import org.eclipse.scout.rt.ui.swing.ext.JTableHeaderEx;
import org.eclipse.scout.rt.ui.swing.form.fields.LogicalGridDataBuilder;
import org.eclipse.scout.rt.ui.swing.form.fields.SwingScoutFieldComposite;
public class SwingScoutTableField extends SwingScoutFieldComposite<ITableField<?>> implements ISwingScoutTableField {
private ISwingScoutTable m_tableComposite;
private ISwingTableStatus m_swingTableStatus;
@Override
protected void initializeSwing() {
JPanelEx container = new JPanelEx();
container.setName(getScoutObject().getClass().getName() + ".container");
container.setOpaque(false);
JStatusLabelEx label = getSwingEnvironment().createStatusLabel();
container.add(label);
m_swingTableStatus = createSwingTableStatus(container);
//
setSwingContainer(container);
setSwingLabel(label);
// layout
container.setLayout(new LogicalGridLayout(getSwingEnvironment(), 1, 0));
}
protected ISwingTableStatus createSwingTableStatus(JComponent container) {
if (getScoutObject().isTableStatusVisible()) {
//
return new SwingTableStatus(getSwingEnvironment(), container, getScoutObject());
}
return null;
}
@Override
public JScrollPane getSwingScrollPane() {
return m_tableComposite != null ? m_tableComposite.getSwingScrollPane() : null;
}
@Override
public JTableEx getSwingTable() {
return m_tableComposite != null ? m_tableComposite.getSwingTable() : null;
}
@Override
public ISwingTableStatus getSwingTableStatus() {
return m_swingTableStatus;
}
@Override
protected void attachScout() {
super.attachScout();
setTableFromScout();
setTableStatusFromScout();
}
@Override
protected void setEnabledFromScout(boolean b) {
// no super call, don't disable table to further support selection and menus
getSwingLabel().setEnabled(b);
if (getSwingScrollPane() != null) {
getSwingScrollPane().getViewport().setOpaque(b);
}
}
protected void setTableStatusFromScout() {
if (m_swingTableStatus != null) {
IProcessingStatus dataStatus = getScoutObject().getTablePopulateStatus();
IProcessingStatus selectionStatus = getScoutObject().getTableSelectionStatus();
m_swingTableStatus.setStatus(dataStatus, selectionStatus);
}
}
protected void setTableFromScout() {
ITable oldTable = m_tableComposite != null ? m_tableComposite.getScoutObject() : null;
ITable newTable = getScoutObject().getTable();
if (oldTable != newTable) {
JComponent container = getSwingContainer();
if (m_tableComposite != null) {
container.remove(m_tableComposite.getSwingScrollPane());
setSwingField(null);
m_tableComposite.disconnectFromScout();
m_tableComposite = null;
}
if (newTable != null) {
ISwingScoutTable newTableComposite = new SwingScoutTable();
newTableComposite.createField(newTable, getSwingEnvironment());
// TODO replace with AbstractSwingEnvironment.createFormField.
IForm form = (getScoutObject() != null) ? getScoutObject().getForm() : null;
JTableEx newSwingTable = newTableComposite.getSwingTable();
if (newSwingTable != null && form != null && IForm.VIEW_ID_PAGE_TABLE.equals(form.getDisplayViewId())) {
newSwingTable.setName("Synth.WideTable");
if (newSwingTable.getTableHeader() instanceof JTableHeaderEx) {
((JTableHeaderEx) newSwingTable.getTableHeader()).updatePreferredHeight();
}
}
newTableComposite.getSwingScrollPane().putClientProperty(LogicalGridData.CLIENT_PROPERTY_NAME, LogicalGridDataBuilder.createField(getSwingEnvironment(), getScoutObject().getGridData()));
- // top level table in form has no border
- JScrollPane scrollPane = newTableComposite.getSwingScrollPane();
- if (getScoutObject().getParentField() instanceof IGroupBox) {
- IGroupBox g = (IGroupBox) getScoutObject().getParentField();
- if (g.isMainBox() && !g.isBorderVisible()) {
- scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
+ // top level table in top-level form has no border
+ if (getScoutObject().getForm().getOuterForm() == null) {
+ if (getScoutObject().getParentField() instanceof IGroupBox) {
+ IGroupBox g = (IGroupBox) getScoutObject().getParentField();
+ if (g.isMainBox() && !g.isBorderVisible()) {
+ JScrollPane scrollPane = newTableComposite.getSwingScrollPane();
+ scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
+ }
}
}
m_tableComposite = newTableComposite;
container.add(newTableComposite.getSwingScrollPane());
setSwingField(newTableComposite.getSwingTable());
container.revalidate();
container.repaint();
}
}
}
@Override
protected void handleScoutPropertyChange(String name, Object newValue) {
super.handleScoutPropertyChange(name, newValue);
if (name.equals(ITableField.PROP_TABLE)) {
setTableFromScout();
}
else if (name.equals(ITableField.PROP_TABLE_SELECTION_STATUS)) {
setTableStatusFromScout();
}
else if (name.equals(ITableField.PROP_TABLE_POPULATE_STATUS)) {
setTableStatusFromScout();
}
}
}
| true | true | protected void setTableFromScout() {
ITable oldTable = m_tableComposite != null ? m_tableComposite.getScoutObject() : null;
ITable newTable = getScoutObject().getTable();
if (oldTable != newTable) {
JComponent container = getSwingContainer();
if (m_tableComposite != null) {
container.remove(m_tableComposite.getSwingScrollPane());
setSwingField(null);
m_tableComposite.disconnectFromScout();
m_tableComposite = null;
}
if (newTable != null) {
ISwingScoutTable newTableComposite = new SwingScoutTable();
newTableComposite.createField(newTable, getSwingEnvironment());
// TODO replace with AbstractSwingEnvironment.createFormField.
IForm form = (getScoutObject() != null) ? getScoutObject().getForm() : null;
JTableEx newSwingTable = newTableComposite.getSwingTable();
if (newSwingTable != null && form != null && IForm.VIEW_ID_PAGE_TABLE.equals(form.getDisplayViewId())) {
newSwingTable.setName("Synth.WideTable");
if (newSwingTable.getTableHeader() instanceof JTableHeaderEx) {
((JTableHeaderEx) newSwingTable.getTableHeader()).updatePreferredHeight();
}
}
newTableComposite.getSwingScrollPane().putClientProperty(LogicalGridData.CLIENT_PROPERTY_NAME, LogicalGridDataBuilder.createField(getSwingEnvironment(), getScoutObject().getGridData()));
// top level table in form has no border
JScrollPane scrollPane = newTableComposite.getSwingScrollPane();
if (getScoutObject().getParentField() instanceof IGroupBox) {
IGroupBox g = (IGroupBox) getScoutObject().getParentField();
if (g.isMainBox() && !g.isBorderVisible()) {
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
}
}
m_tableComposite = newTableComposite;
container.add(newTableComposite.getSwingScrollPane());
setSwingField(newTableComposite.getSwingTable());
container.revalidate();
container.repaint();
}
}
}
| protected void setTableFromScout() {
ITable oldTable = m_tableComposite != null ? m_tableComposite.getScoutObject() : null;
ITable newTable = getScoutObject().getTable();
if (oldTable != newTable) {
JComponent container = getSwingContainer();
if (m_tableComposite != null) {
container.remove(m_tableComposite.getSwingScrollPane());
setSwingField(null);
m_tableComposite.disconnectFromScout();
m_tableComposite = null;
}
if (newTable != null) {
ISwingScoutTable newTableComposite = new SwingScoutTable();
newTableComposite.createField(newTable, getSwingEnvironment());
// TODO replace with AbstractSwingEnvironment.createFormField.
IForm form = (getScoutObject() != null) ? getScoutObject().getForm() : null;
JTableEx newSwingTable = newTableComposite.getSwingTable();
if (newSwingTable != null && form != null && IForm.VIEW_ID_PAGE_TABLE.equals(form.getDisplayViewId())) {
newSwingTable.setName("Synth.WideTable");
if (newSwingTable.getTableHeader() instanceof JTableHeaderEx) {
((JTableHeaderEx) newSwingTable.getTableHeader()).updatePreferredHeight();
}
}
newTableComposite.getSwingScrollPane().putClientProperty(LogicalGridData.CLIENT_PROPERTY_NAME, LogicalGridDataBuilder.createField(getSwingEnvironment(), getScoutObject().getGridData()));
// top level table in top-level form has no border
if (getScoutObject().getForm().getOuterForm() == null) {
if (getScoutObject().getParentField() instanceof IGroupBox) {
IGroupBox g = (IGroupBox) getScoutObject().getParentField();
if (g.isMainBox() && !g.isBorderVisible()) {
JScrollPane scrollPane = newTableComposite.getSwingScrollPane();
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
}
}
}
m_tableComposite = newTableComposite;
container.add(newTableComposite.getSwingScrollPane());
setSwingField(newTableComposite.getSwingTable());
container.revalidate();
container.repaint();
}
}
}
|
diff --git a/src-pos/com/openbravo/pos/inventory/TaxEditor.java b/src-pos/com/openbravo/pos/inventory/TaxEditor.java
index e0e5632..63f71cb 100644
--- a/src-pos/com/openbravo/pos/inventory/TaxEditor.java
+++ b/src-pos/com/openbravo/pos/inventory/TaxEditor.java
@@ -1,272 +1,272 @@
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2008 Openbravo, S.L.
// http://sourceforge.net/projects/openbravopos
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.openbravo.pos.inventory;
import java.awt.Component;
import java.util.UUID;
import javax.swing.*;
import com.openbravo.pos.forms.AppLocal;
import com.openbravo.format.Formats;
import com.openbravo.basic.BasicException;
import com.openbravo.data.gui.ComboBoxValModel;
import com.openbravo.data.loader.SentenceList;
import com.openbravo.data.user.EditorRecord;
import com.openbravo.data.user.DirtyManager;
import com.openbravo.pos.forms.AppView;
import com.openbravo.pos.forms.DataLogicSales;
import java.util.List;
public class TaxEditor extends JPanel implements EditorRecord {
private Object m_oId;
private SentenceList taxcatsent;
private ComboBoxValModel taxcatmodel;
private SentenceList taxcustcatsent;
private ComboBoxValModel taxcustcatmodel;
private SentenceList taxparentsent;
private ComboBoxValModel taxparentmodel;
/** Creates new form taxEditor */
public TaxEditor(AppView app, DirtyManager dirty) {
DataLogicSales dlSales = (DataLogicSales) app.getBean("com.openbravo.pos.forms.DataLogicSalesCreate");
initComponents();
taxcatsent = dlSales.getTaxCategoriesList();
taxcatmodel = new ComboBoxValModel();
taxcustcatsent = dlSales.getTaxCustCategoriesList();
taxcustcatmodel = new ComboBoxValModel();
taxparentsent = dlSales.getTaxList();
taxparentmodel = new ComboBoxValModel();
m_jName.getDocument().addDocumentListener(dirty);
m_jTaxCategory.addActionListener(dirty);
m_jCustTaxCategory.addActionListener(dirty);
m_jTaxParent.addActionListener(dirty);
m_jRate.getDocument().addDocumentListener(dirty);
jCascade.addActionListener(dirty);
jOrder.getDocument().addDocumentListener(dirty);
writeValueEOF();
}
public void activate() throws BasicException {
List a = taxcatsent.list();
taxcatmodel = new ComboBoxValModel(a);
m_jTaxCategory.setModel(taxcatmodel);
a = taxcustcatsent.list();
a.add(0, null); // The null item
taxcustcatmodel = new ComboBoxValModel(a);
m_jCustTaxCategory.setModel(taxcustcatmodel);
a = taxparentsent.list();
a.add(0, null); // The null item
taxparentmodel = new ComboBoxValModel(a);
m_jTaxParent.setModel(taxparentmodel);
}
public void writeValueEOF() {
m_oId = null;
m_jName.setText(null);
taxcatmodel.setSelectedKey(null);
taxcustcatmodel.setSelectedKey(null);
taxparentmodel.setSelectedKey(null);
m_jRate.setText(null);
jCascade.setSelected(false);
jOrder.setText(null);
m_jName.setEnabled(false);
m_jTaxCategory.setEnabled(false);
m_jCustTaxCategory.setEnabled(false);
m_jTaxParent.setEnabled(false);
m_jRate.setEnabled(false);
jCascade.setEnabled(false);
jOrder.setEnabled(false);
}
public void writeValueInsert() {
m_oId = null;
m_jName.setText(null);
taxcatmodel.setSelectedKey(null);
taxcustcatmodel.setSelectedKey(null);
taxparentmodel.setSelectedKey(null);
m_jRate.setText(null);
jCascade.setSelected(false);
jOrder.setText(null);
m_jName.setEnabled(true);
m_jTaxCategory.setEnabled(true);
m_jCustTaxCategory.setEnabled(true);
m_jTaxParent.setEnabled(true);
m_jRate.setEnabled(true);
jCascade.setEnabled(true);
jOrder.setEnabled(true);
}
public void writeValueDelete(Object value) {
Object[] tax = (Object[]) value;
m_oId = tax[0];
m_jName.setText(Formats.STRING.formatValue(tax[1]));
taxcatmodel.setSelectedKey(tax[2]);
taxcustcatmodel.setSelectedKey(tax[3]);
taxparentmodel.setSelectedKey(tax[4]);
m_jRate.setText(Formats.PERCENT.formatValue(tax[5]));
jCascade.setSelected((Boolean) tax[6]);
jOrder.setText(Formats.INT.formatValue(tax[7]));
m_jName.setEnabled(false);
m_jTaxCategory.setEnabled(false);
m_jCustTaxCategory.setEnabled(false);
m_jTaxParent.setEnabled(false);
m_jRate.setEnabled(false);
jCascade.setEnabled(false);
jOrder.setEnabled(false);
}
public void writeValueEdit(Object value) {
Object[] tax = (Object[]) value;
m_oId = tax[0];
m_jName.setText(Formats.STRING.formatValue(tax[1]));
taxcatmodel.setSelectedKey(tax[2]);
taxcustcatmodel.setSelectedKey(tax[3]);
taxparentmodel.setSelectedKey(tax[4]);
m_jRate.setText(Formats.PERCENT.formatValue(tax[5]));
jCascade.setSelected((Boolean) tax[6]);
jOrder.setText(Formats.INT.formatValue(tax[7]));
m_jName.setEnabled(true);
m_jTaxCategory.setEnabled(true);
m_jCustTaxCategory.setEnabled(true);
m_jTaxParent.setEnabled(true);
m_jRate.setEnabled(true);
jCascade.setEnabled(true);
jOrder.setEnabled(true);
}
public Object createValue() throws BasicException {
Object[] tax = new Object[8];
tax[0] = m_oId == null ? UUID.randomUUID().toString() : m_oId;
tax[1] = m_jName.getText();
tax[2] = taxcatmodel.getSelectedKey();
tax[3] = taxcustcatmodel.getSelectedKey();
tax[4] = taxparentmodel.getSelectedKey();
tax[5] = Formats.PERCENT.parseValue(m_jRate.getText());
tax[6] = Boolean.valueOf(jCascade.isSelected());
tax[7] = Formats.INT.parseValue(jOrder.getText());
return tax;
}
public Component getComponent() {
return this;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
m_jName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
m_jRate = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jCascade = new javax.swing.JCheckBox();
m_jTaxCategory = new javax.swing.JComboBox();
m_jTaxParent = new javax.swing.JComboBox();
m_jCustTaxCategory = new javax.swing.JComboBox();
jLabel6 = new javax.swing.JLabel();
jOrder = new javax.swing.JTextField();
setLayout(null);
add(m_jName);
m_jName.setBounds(240, 20, 200, 19);
jLabel2.setText(AppLocal.getIntString("Label.Name")); // NOI18N
add(jLabel2);
jLabel2.setBounds(20, 20, 220, 15);
jLabel3.setText(AppLocal.getIntString("label.dutyrate")); // NOI18N
add(jLabel3);
jLabel3.setBounds(20, 140, 220, 15);
add(m_jRate);
m_jRate.setBounds(240, 140, 60, 19);
jLabel1.setText(AppLocal.getIntString("label.taxcategory")); // NOI18N
add(jLabel1);
jLabel1.setBounds(20, 50, 220, 15);
jLabel4.setText(AppLocal.getIntString("label.custtaxcategory")); // NOI18N
add(jLabel4);
jLabel4.setBounds(20, 80, 220, 15);
jLabel5.setText(AppLocal.getIntString("label.taxparent")); // NOI18N
add(jLabel5);
jLabel5.setBounds(20, 110, 220, 15);
jCascade.setText(AppLocal.getIntString("label.cascade")); // NOI18N
add(jCascade);
jCascade.setBounds(320, 140, 110, 23);
add(m_jTaxCategory);
m_jTaxCategory.setBounds(240, 50, 200, 24);
add(m_jTaxParent);
m_jTaxParent.setBounds(240, 110, 200, 24);
add(m_jCustTaxCategory);
m_jCustTaxCategory.setBounds(240, 80, 200, 24);
jLabel6.setText(AppLocal.getIntString("label.order")); // NOI18N
add(jLabel6);
- jLabel6.setBounds(20, 170, 35, 15);
+ jLabel6.setBounds(20, 170, 220, 15);
add(jOrder);
jOrder.setBounds(240, 170, 60, 19);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox jCascade;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JTextField jOrder;
private javax.swing.JComboBox m_jCustTaxCategory;
private javax.swing.JTextField m_jName;
private javax.swing.JTextField m_jRate;
private javax.swing.JComboBox m_jTaxCategory;
private javax.swing.JComboBox m_jTaxParent;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
m_jName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
m_jRate = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jCascade = new javax.swing.JCheckBox();
m_jTaxCategory = new javax.swing.JComboBox();
m_jTaxParent = new javax.swing.JComboBox();
m_jCustTaxCategory = new javax.swing.JComboBox();
jLabel6 = new javax.swing.JLabel();
jOrder = new javax.swing.JTextField();
setLayout(null);
add(m_jName);
m_jName.setBounds(240, 20, 200, 19);
jLabel2.setText(AppLocal.getIntString("Label.Name")); // NOI18N
add(jLabel2);
jLabel2.setBounds(20, 20, 220, 15);
jLabel3.setText(AppLocal.getIntString("label.dutyrate")); // NOI18N
add(jLabel3);
jLabel3.setBounds(20, 140, 220, 15);
add(m_jRate);
m_jRate.setBounds(240, 140, 60, 19);
jLabel1.setText(AppLocal.getIntString("label.taxcategory")); // NOI18N
add(jLabel1);
jLabel1.setBounds(20, 50, 220, 15);
jLabel4.setText(AppLocal.getIntString("label.custtaxcategory")); // NOI18N
add(jLabel4);
jLabel4.setBounds(20, 80, 220, 15);
jLabel5.setText(AppLocal.getIntString("label.taxparent")); // NOI18N
add(jLabel5);
jLabel5.setBounds(20, 110, 220, 15);
jCascade.setText(AppLocal.getIntString("label.cascade")); // NOI18N
add(jCascade);
jCascade.setBounds(320, 140, 110, 23);
add(m_jTaxCategory);
m_jTaxCategory.setBounds(240, 50, 200, 24);
add(m_jTaxParent);
m_jTaxParent.setBounds(240, 110, 200, 24);
add(m_jCustTaxCategory);
m_jCustTaxCategory.setBounds(240, 80, 200, 24);
jLabel6.setText(AppLocal.getIntString("label.order")); // NOI18N
add(jLabel6);
jLabel6.setBounds(20, 170, 35, 15);
add(jOrder);
jOrder.setBounds(240, 170, 60, 19);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
m_jName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
m_jRate = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jCascade = new javax.swing.JCheckBox();
m_jTaxCategory = new javax.swing.JComboBox();
m_jTaxParent = new javax.swing.JComboBox();
m_jCustTaxCategory = new javax.swing.JComboBox();
jLabel6 = new javax.swing.JLabel();
jOrder = new javax.swing.JTextField();
setLayout(null);
add(m_jName);
m_jName.setBounds(240, 20, 200, 19);
jLabel2.setText(AppLocal.getIntString("Label.Name")); // NOI18N
add(jLabel2);
jLabel2.setBounds(20, 20, 220, 15);
jLabel3.setText(AppLocal.getIntString("label.dutyrate")); // NOI18N
add(jLabel3);
jLabel3.setBounds(20, 140, 220, 15);
add(m_jRate);
m_jRate.setBounds(240, 140, 60, 19);
jLabel1.setText(AppLocal.getIntString("label.taxcategory")); // NOI18N
add(jLabel1);
jLabel1.setBounds(20, 50, 220, 15);
jLabel4.setText(AppLocal.getIntString("label.custtaxcategory")); // NOI18N
add(jLabel4);
jLabel4.setBounds(20, 80, 220, 15);
jLabel5.setText(AppLocal.getIntString("label.taxparent")); // NOI18N
add(jLabel5);
jLabel5.setBounds(20, 110, 220, 15);
jCascade.setText(AppLocal.getIntString("label.cascade")); // NOI18N
add(jCascade);
jCascade.setBounds(320, 140, 110, 23);
add(m_jTaxCategory);
m_jTaxCategory.setBounds(240, 50, 200, 24);
add(m_jTaxParent);
m_jTaxParent.setBounds(240, 110, 200, 24);
add(m_jCustTaxCategory);
m_jCustTaxCategory.setBounds(240, 80, 200, 24);
jLabel6.setText(AppLocal.getIntString("label.order")); // NOI18N
add(jLabel6);
jLabel6.setBounds(20, 170, 220, 15);
add(jOrder);
jOrder.setBounds(240, 170, 60, 19);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/SpaceFarmer/src/App/factory/UniverseFactory.java b/SpaceFarmer/src/App/factory/UniverseFactory.java
index b4f379b..db9ba50 100644
--- a/SpaceFarmer/src/App/factory/UniverseFactory.java
+++ b/SpaceFarmer/src/App/factory/UniverseFactory.java
@@ -1,118 +1,119 @@
package App.factory;
import App.model.*;
import App.service.Randomizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UniverseFactory {
private static Map<String, Planet> planets;
private static Map<String, PlanetarySystem> systems;
public static PlanetarySystem getSystem(String name)
{
return systems.get(name);
}
public static Planet getPlanet(String name)
{
return planets.get(name);
}
public static Map<String, Planet> getPlanets(){
return planets;
}
public static Map<String, PlanetarySystem> getPlanetarySystems(){
return systems;
}
/**
* Fills the factory with planets.
*
* @param names List of the Planet's possible names
* @param maxXDim Length of the game's x-axis
* @param maxYDim Length of the game's y-axis
* @param numPlanets how many planets for this game
*/
public static void createUniverse(List<String> planetNames,List<String> planetarySystemNames, int numPlanets,int numSystems,int systemRows, int systemCols, int uniRows, int uniCols,int quadrantXDimension,int quadrantYDimension,int minDistance){
planets = new HashMap<String, Planet>();
systems= new HashMap<String,PlanetarySystem>();
- Map<String,Planet> systemPlanets=new HashMap<String,Planet>();
+ Map<String,Planet> systemPlanets;
Planet planet;
PlanetarySystem system;
int planetNameIndex,systemNameIndex;
String planetName,systemName;
List<String> planetNamesHolder = new ArrayList<String>(planetNames);
List<String> systemNamesHolder = new ArrayList<String>(planetarySystemNames);
int systemDistribution[]=Randomizer.distributeNumber(uniRows*uniCols,numSystems);
int planetDistribution[]=Randomizer.distributeNumber(numSystems, numPlanets);
List<Integer[]> planetPositions;
Map<Integer,List<Integer[]>> systemDimensions=new HashMap<Integer,List<Integer[]>>(numSystems);
for (int i=0;i<uniRows*uniCols;i++)
{
systemDimensions.put(i,Randomizer.generateDimensionsRange(systemDistribution[i],quadrantXDimension,quadrantYDimension, minDistance));
}
int quadrantIndex=0;
int systemIndex=0;
int planetIndex=0;
int systemCount=0;
while (quadrantIndex < uniRows*uniCols && !systemNamesHolder.isEmpty() && !planetNamesHolder.isEmpty()){
systemIndex=0;
while (systemIndex < systemDistribution[quadrantIndex] && !systemNamesHolder.isEmpty() && !planetNamesHolder.isEmpty()){
planetIndex=0;
system=new PlanetarySystem();
+ systemPlanets=new HashMap<String,Planet>();
planetPositions=Randomizer.generateDimensions(planetDistribution[systemCount], systemRows, systemCols);
systemNameIndex=Randomizer.nextInt(systemNamesHolder.size());
systemName=systemNamesHolder.get(systemNameIndex);
systemNamesHolder.remove(systemNameIndex);
while (planetIndex < planetDistribution[systemCount] && !planetNamesHolder.isEmpty()){
planet = new Planet();
planetNameIndex = Randomizer.nextInt(planetNamesHolder.size());
planetName=planetNamesHolder.get(planetNameIndex);
planetNamesHolder.remove(planetNameIndex);
planet.setPlanetarySystem(system);
planet.setName(planetName);
planet.setX(planetPositions.get(planetIndex)[0]);
planet.setY(planetPositions.get(planetIndex)[1]);
planet.setEvent(Event.NO_EVENT);
planet.setTechnologyLevel((TechnologyLevel) Randomizer.randEnum((TechnologyLevel.class)));
planet.setResourceType((ResourceType) Randomizer.randEnum((ResourceType.class)));
planet.setPoliticalSystem((PoliticalSystem) Randomizer.randEnum((PoliticalSystem.class)));
planet.setMarket(new MarketPlace(planet));
planets.put(planet.getName(), planet);
systemPlanets.put(planet.getName(),planet);
planetIndex++;
}
system.setX(systemDimensions.get(quadrantIndex).get(systemIndex)[0]+quadrantXDimension*(quadrantIndex%uniRows));
system.setY(systemDimensions.get(quadrantIndex).get(systemIndex)[1]+quadrantYDimension*(quadrantIndex/uniRows));
system.setName(systemName);
system.setPlanets(systemPlanets);
systems.put(system.getName(),system);
systemCount++;
systemIndex++;
}
quadrantIndex++;
}
}
public static int getNumberOfPlanets(){
return planets.size();
}
public static int getNumberOfSystem(){
return systems.size();
}
}
| false | true | public static void createUniverse(List<String> planetNames,List<String> planetarySystemNames, int numPlanets,int numSystems,int systemRows, int systemCols, int uniRows, int uniCols,int quadrantXDimension,int quadrantYDimension,int minDistance){
planets = new HashMap<String, Planet>();
systems= new HashMap<String,PlanetarySystem>();
Map<String,Planet> systemPlanets=new HashMap<String,Planet>();
Planet planet;
PlanetarySystem system;
int planetNameIndex,systemNameIndex;
String planetName,systemName;
List<String> planetNamesHolder = new ArrayList<String>(planetNames);
List<String> systemNamesHolder = new ArrayList<String>(planetarySystemNames);
int systemDistribution[]=Randomizer.distributeNumber(uniRows*uniCols,numSystems);
int planetDistribution[]=Randomizer.distributeNumber(numSystems, numPlanets);
List<Integer[]> planetPositions;
Map<Integer,List<Integer[]>> systemDimensions=new HashMap<Integer,List<Integer[]>>(numSystems);
for (int i=0;i<uniRows*uniCols;i++)
{
systemDimensions.put(i,Randomizer.generateDimensionsRange(systemDistribution[i],quadrantXDimension,quadrantYDimension, minDistance));
}
int quadrantIndex=0;
int systemIndex=0;
int planetIndex=0;
int systemCount=0;
while (quadrantIndex < uniRows*uniCols && !systemNamesHolder.isEmpty() && !planetNamesHolder.isEmpty()){
systemIndex=0;
while (systemIndex < systemDistribution[quadrantIndex] && !systemNamesHolder.isEmpty() && !planetNamesHolder.isEmpty()){
planetIndex=0;
system=new PlanetarySystem();
planetPositions=Randomizer.generateDimensions(planetDistribution[systemCount], systemRows, systemCols);
systemNameIndex=Randomizer.nextInt(systemNamesHolder.size());
systemName=systemNamesHolder.get(systemNameIndex);
systemNamesHolder.remove(systemNameIndex);
while (planetIndex < planetDistribution[systemCount] && !planetNamesHolder.isEmpty()){
planet = new Planet();
planetNameIndex = Randomizer.nextInt(planetNamesHolder.size());
planetName=planetNamesHolder.get(planetNameIndex);
planetNamesHolder.remove(planetNameIndex);
planet.setPlanetarySystem(system);
planet.setName(planetName);
planet.setX(planetPositions.get(planetIndex)[0]);
planet.setY(planetPositions.get(planetIndex)[1]);
planet.setEvent(Event.NO_EVENT);
planet.setTechnologyLevel((TechnologyLevel) Randomizer.randEnum((TechnologyLevel.class)));
planet.setResourceType((ResourceType) Randomizer.randEnum((ResourceType.class)));
planet.setPoliticalSystem((PoliticalSystem) Randomizer.randEnum((PoliticalSystem.class)));
planet.setMarket(new MarketPlace(planet));
planets.put(planet.getName(), planet);
systemPlanets.put(planet.getName(),planet);
planetIndex++;
}
system.setX(systemDimensions.get(quadrantIndex).get(systemIndex)[0]+quadrantXDimension*(quadrantIndex%uniRows));
system.setY(systemDimensions.get(quadrantIndex).get(systemIndex)[1]+quadrantYDimension*(quadrantIndex/uniRows));
system.setName(systemName);
system.setPlanets(systemPlanets);
systems.put(system.getName(),system);
systemCount++;
systemIndex++;
}
quadrantIndex++;
}
}
| public static void createUniverse(List<String> planetNames,List<String> planetarySystemNames, int numPlanets,int numSystems,int systemRows, int systemCols, int uniRows, int uniCols,int quadrantXDimension,int quadrantYDimension,int minDistance){
planets = new HashMap<String, Planet>();
systems= new HashMap<String,PlanetarySystem>();
Map<String,Planet> systemPlanets;
Planet planet;
PlanetarySystem system;
int planetNameIndex,systemNameIndex;
String planetName,systemName;
List<String> planetNamesHolder = new ArrayList<String>(planetNames);
List<String> systemNamesHolder = new ArrayList<String>(planetarySystemNames);
int systemDistribution[]=Randomizer.distributeNumber(uniRows*uniCols,numSystems);
int planetDistribution[]=Randomizer.distributeNumber(numSystems, numPlanets);
List<Integer[]> planetPositions;
Map<Integer,List<Integer[]>> systemDimensions=new HashMap<Integer,List<Integer[]>>(numSystems);
for (int i=0;i<uniRows*uniCols;i++)
{
systemDimensions.put(i,Randomizer.generateDimensionsRange(systemDistribution[i],quadrantXDimension,quadrantYDimension, minDistance));
}
int quadrantIndex=0;
int systemIndex=0;
int planetIndex=0;
int systemCount=0;
while (quadrantIndex < uniRows*uniCols && !systemNamesHolder.isEmpty() && !planetNamesHolder.isEmpty()){
systemIndex=0;
while (systemIndex < systemDistribution[quadrantIndex] && !systemNamesHolder.isEmpty() && !planetNamesHolder.isEmpty()){
planetIndex=0;
system=new PlanetarySystem();
systemPlanets=new HashMap<String,Planet>();
planetPositions=Randomizer.generateDimensions(planetDistribution[systemCount], systemRows, systemCols);
systemNameIndex=Randomizer.nextInt(systemNamesHolder.size());
systemName=systemNamesHolder.get(systemNameIndex);
systemNamesHolder.remove(systemNameIndex);
while (planetIndex < planetDistribution[systemCount] && !planetNamesHolder.isEmpty()){
planet = new Planet();
planetNameIndex = Randomizer.nextInt(planetNamesHolder.size());
planetName=planetNamesHolder.get(planetNameIndex);
planetNamesHolder.remove(planetNameIndex);
planet.setPlanetarySystem(system);
planet.setName(planetName);
planet.setX(planetPositions.get(planetIndex)[0]);
planet.setY(planetPositions.get(planetIndex)[1]);
planet.setEvent(Event.NO_EVENT);
planet.setTechnologyLevel((TechnologyLevel) Randomizer.randEnum((TechnologyLevel.class)));
planet.setResourceType((ResourceType) Randomizer.randEnum((ResourceType.class)));
planet.setPoliticalSystem((PoliticalSystem) Randomizer.randEnum((PoliticalSystem.class)));
planet.setMarket(new MarketPlace(planet));
planets.put(planet.getName(), planet);
systemPlanets.put(planet.getName(),planet);
planetIndex++;
}
system.setX(systemDimensions.get(quadrantIndex).get(systemIndex)[0]+quadrantXDimension*(quadrantIndex%uniRows));
system.setY(systemDimensions.get(quadrantIndex).get(systemIndex)[1]+quadrantYDimension*(quadrantIndex/uniRows));
system.setName(systemName);
system.setPlanets(systemPlanets);
systems.put(system.getName(),system);
systemCount++;
systemIndex++;
}
quadrantIndex++;
}
}
|
diff --git a/yaogan-web/src/main/java/com/rockontrol/yaogan/spring/ext/ServiceProperties.java b/yaogan-web/src/main/java/com/rockontrol/yaogan/spring/ext/ServiceProperties.java
index 055e243..9a2dbf0 100644
--- a/yaogan-web/src/main/java/com/rockontrol/yaogan/spring/ext/ServiceProperties.java
+++ b/yaogan-web/src/main/java/com/rockontrol/yaogan/spring/ext/ServiceProperties.java
@@ -1,112 +1,110 @@
package com.rockontrol.yaogan.spring.ext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class ServiceProperties implements InitializingBean {
public static final String DEFAULT_CAS_ARTIFACT_PARAMETER = "ticket";
public static final String DEFAULT_CAS_SERVICE_PARAMETER = "service";
// ~ Instance fields
// ================================================================================================
private String service;
private boolean sendRenew = false;
private String artifactParameter = DEFAULT_CAS_ARTIFACT_PARAMETER;
private String serviceParameter = DEFAULT_CAS_SERVICE_PARAMETER;
// ~ Methods
// ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.hasLength(this.service, "service must be specified.");
Assert.hasLength(this.artifactParameter, "artifactParameter cannot be empty.");
Assert.hasLength(this.serviceParameter, "serviceParameter cannot be empty.");
}
/**
* Represents the service the user is authenticating to.
* <p>
* This service is the callback URL belonging to the local Spring Security
* System for Spring secured application. For example,
*
* <pre>
* https://www.mycompany.com/application/j_spring_cas_security_check
* </pre>
*
* @return the URL of the service the user is authenticating to
*/
public final String getService() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
String host = request.getHeader("HOST");
StringBuilder sb = new StringBuilder();
- sb.append("http://").append(host)
- .append(request.getServerPort() == 80 ? "" : ":" + request.getServerPort())
- .append(request.getContextPath()).append(service.startsWith("/") ? "" : "/")
- .append(service);
+ sb.append("http://").append(host).append(request.getContextPath())
+ .append(service.startsWith("/") ? "" : "/").append(service);
return sb.toString();
}
/**
* Indicates whether the <code>renew</code> parameter should be sent to the
* CAS login URL and CAS validation URL.
* <p>
* If <code>true</code>, it will force CAS to authenticate the user again
* (even if the user has previously authenticated). During ticket validation
* it will require the ticket was generated as a consequence of an explicit
* login. High security applications would probably set this to
* <code>true</code>. Defaults to <code>false</code>, providing automated
* single sign on.
*
* @return whether to send the <code>renew</code> parameter to CAS
*/
public final boolean isSendRenew() {
return this.sendRenew;
}
public final void setSendRenew(final boolean sendRenew) {
this.sendRenew = sendRenew;
}
public final void setService(final String service) {
this.service = service;
}
public final String getArtifactParameter() {
return this.artifactParameter;
}
/**
* Configures the Request Parameter to look for when attempting to see if a
* CAS ticket was sent from the server.
*
* @param artifactParameter
* the id to use. Default is "ticket".
*/
public final void setArtifactParameter(final String artifactParameter) {
this.artifactParameter = artifactParameter;
}
/**
* Configures the Request parameter to look for when attempting to send a
* request to CAS.
*
* @return the service parameter to use. Default is "service".
*/
public final String getServiceParameter() {
return serviceParameter;
}
public final void setServiceParameter(final String serviceParameter) {
this.serviceParameter = serviceParameter;
}
}
| true | true | public final String getService() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
String host = request.getHeader("HOST");
StringBuilder sb = new StringBuilder();
sb.append("http://").append(host)
.append(request.getServerPort() == 80 ? "" : ":" + request.getServerPort())
.append(request.getContextPath()).append(service.startsWith("/") ? "" : "/")
.append(service);
return sb.toString();
}
| public final String getService() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
String host = request.getHeader("HOST");
StringBuilder sb = new StringBuilder();
sb.append("http://").append(host).append(request.getContextPath())
.append(service.startsWith("/") ? "" : "/").append(service);
return sb.toString();
}
|
diff --git a/src/main/java/com/censoredsoftware/Demigods/Engine/Object/Deity/Deity.java b/src/main/java/com/censoredsoftware/Demigods/Engine/Object/Deity/Deity.java
index 25d53870..2f64f930 100644
--- a/src/main/java/com/censoredsoftware/Demigods/Engine/Object/Deity/Deity.java
+++ b/src/main/java/com/censoredsoftware/Demigods/Engine/Object/Deity/Deity.java
@@ -1,102 +1,103 @@
package com.censoredsoftware.Demigods.Engine.Object.Deity;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.censoredsoftware.Demigods.Engine.Demigods;
import com.censoredsoftware.Demigods.Engine.Object.Ability.Ability;
import com.censoredsoftware.Demigods.Engine.Object.Player.PlayerCharacter;
import com.censoredsoftware.Demigods.Engine.Object.Player.PlayerWrapper;
public abstract class Deity
{
private DeityInfo info;
private Set<Ability> abilities;
public Deity(DeityInfo info, Set<Ability> abilities)
{
this.info = info;
this.abilities = abilities;
}
public DeityInfo getInfo()
{
return info;
}
public Set<Ability> getAbilities()
{
return abilities;
}
public enum Type
{
DEMO, TIER1, TIER2, TIER3
}
@Override
public String toString()
{
return info.getName();
}
public static Set<String> getLoadedDeityAlliances()
{
return new HashSet<String>()
{
{
for(Deity deity : Demigods.getLoadedDeities())
{
if(!contains(deity.getInfo().getAlliance())) add(deity.getInfo().getAlliance());
}
}
};
}
public static Set<Deity> getAllDeitiesInAlliance(final String alliance)
{
return new HashSet<Deity>()
{
{
for(Deity deity : Demigods.getLoadedDeities())
{
if(deity.getInfo().getAlliance().equalsIgnoreCase(alliance)) add(deity);
}
}
};
}
public static Deity getDeity(String deity)
{
for(Deity loaded : Demigods.getLoadedDeities())
{
if(loaded.getInfo().getName().equalsIgnoreCase(deity)) return loaded;
}
return null;
}
public static boolean canUseDeity(Player player, String deity)
{
PlayerCharacter character = PlayerWrapper.getPlayer(player).getCurrent();
+ if(character == null) return false;
if(!character.isDeity(deity))
{
player.sendMessage(ChatColor.RED + "You haven't claimed " + deity + "! You can't do that!");
return false;
}
else if(!character.isImmortal())
{
player.sendMessage(ChatColor.RED + "You can't do that, mortal!");
return false;
}
return true;
}
public static boolean canUseDeitySilent(Player player, String deity)
{
PlayerCharacter character = PlayerWrapper.getPlayer(player).getCurrent();
return character != null && character.isDeity(deity) && character.isImmortal();
}
}
| true | true | public static boolean canUseDeity(Player player, String deity)
{
PlayerCharacter character = PlayerWrapper.getPlayer(player).getCurrent();
if(!character.isDeity(deity))
{
player.sendMessage(ChatColor.RED + "You haven't claimed " + deity + "! You can't do that!");
return false;
}
else if(!character.isImmortal())
{
player.sendMessage(ChatColor.RED + "You can't do that, mortal!");
return false;
}
return true;
}
| public static boolean canUseDeity(Player player, String deity)
{
PlayerCharacter character = PlayerWrapper.getPlayer(player).getCurrent();
if(character == null) return false;
if(!character.isDeity(deity))
{
player.sendMessage(ChatColor.RED + "You haven't claimed " + deity + "! You can't do that!");
return false;
}
else if(!character.isImmortal())
{
player.sendMessage(ChatColor.RED + "You can't do that, mortal!");
return false;
}
return true;
}
|
diff --git a/modules/unsupported/ogr/src/test/java/org/geotools/data/ogr/OGRDataStoreFactoryTest.java b/modules/unsupported/ogr/src/test/java/org/geotools/data/ogr/OGRDataStoreFactoryTest.java
index 6bc614efb..44fead8a4 100644
--- a/modules/unsupported/ogr/src/test/java/org/geotools/data/ogr/OGRDataStoreFactoryTest.java
+++ b/modules/unsupported/ogr/src/test/java/org/geotools/data/ogr/OGRDataStoreFactoryTest.java
@@ -1,53 +1,53 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2007-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.data.ogr;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
public class OGRDataStoreFactoryTest extends TestCaseSupport {
public OGRDataStoreFactoryTest(String name) throws IOException {
super(name);
}
public void testLookup() throws Exception {
Map map = new HashMap();
map.put(OGRDataStoreFactory.OGR_NAME.key, getAbsolutePath(STATE_POP));
DataStore ds = DataStoreFinder.getDataStore(map);
assertNotNull(ds);
assertTrue(ds instanceof OGRDataStore);
}
public void testNamespace() throws Exception {
OGRDataStoreFactory factory = new OGRDataStoreFactory();
Map map = new HashMap();
URI namespace = new URI("http://jesse.com");
map.put(OGRDataStoreFactory.NAMESPACEP.key, namespace);
map.put(OGRDataStoreFactory.OGR_NAME.key, getAbsolutePath(STATE_POP));
DataStore store = factory.createDataStore(map);
- assertEquals(namespace, store.getSchema(
+ assertEquals(namespace.toString(), store.getSchema(
STATE_POP.substring(STATE_POP.lastIndexOf('/') + 1, STATE_POP.lastIndexOf('.')))
.getName().getNamespaceURI());
}
}
| true | true | public void testNamespace() throws Exception {
OGRDataStoreFactory factory = new OGRDataStoreFactory();
Map map = new HashMap();
URI namespace = new URI("http://jesse.com");
map.put(OGRDataStoreFactory.NAMESPACEP.key, namespace);
map.put(OGRDataStoreFactory.OGR_NAME.key, getAbsolutePath(STATE_POP));
DataStore store = factory.createDataStore(map);
assertEquals(namespace, store.getSchema(
STATE_POP.substring(STATE_POP.lastIndexOf('/') + 1, STATE_POP.lastIndexOf('.')))
.getName().getNamespaceURI());
}
| public void testNamespace() throws Exception {
OGRDataStoreFactory factory = new OGRDataStoreFactory();
Map map = new HashMap();
URI namespace = new URI("http://jesse.com");
map.put(OGRDataStoreFactory.NAMESPACEP.key, namespace);
map.put(OGRDataStoreFactory.OGR_NAME.key, getAbsolutePath(STATE_POP));
DataStore store = factory.createDataStore(map);
assertEquals(namespace.toString(), store.getSchema(
STATE_POP.substring(STATE_POP.lastIndexOf('/') + 1, STATE_POP.lastIndexOf('.')))
.getName().getNamespaceURI());
}
|
diff --git a/odata4j-core/src/main/java/org/odata4j/producer/jpa/JPAProducer.java b/odata4j-core/src/main/java/org/odata4j/producer/jpa/JPAProducer.java
index ba32b784..034da4b4 100644
--- a/odata4j-core/src/main/java/org/odata4j/producer/jpa/JPAProducer.java
+++ b/odata4j-core/src/main/java/org/odata4j/producer/jpa/JPAProducer.java
@@ -1,1186 +1,1186 @@
package org.odata4j.producer.jpa;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.persistence.CascadeType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.OneToMany;
import javax.persistence.Query;
import javax.persistence.metamodel.Attribute;
import javax.persistence.metamodel.Attribute.PersistentAttributeType;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.ManagedType;
import javax.persistence.metamodel.PluralAttribute;
import javax.persistence.metamodel.SingularAttribute;
import org.core4j.CoreUtils;
import org.core4j.Enumerable;
import org.core4j.Func1;
import org.core4j.Predicate1;
import org.odata4j.core.OEntities;
import org.odata4j.core.OEntity;
import org.odata4j.core.OEntityKey;
import org.odata4j.core.OLink;
import org.odata4j.core.OLinks;
import org.odata4j.core.OProperties;
import org.odata4j.core.OProperty;
import org.odata4j.core.ORelatedEntitiesLinkInline;
import org.odata4j.core.ORelatedEntityLink;
import org.odata4j.core.ORelatedEntityLinkInline;
import org.odata4j.edm.EdmDataServices;
import org.odata4j.edm.EdmEntitySet;
import org.odata4j.edm.EdmMultiplicity;
import org.odata4j.edm.EdmNavigationProperty;
import org.odata4j.edm.EdmProperty;
import org.odata4j.expression.BoolCommonExpression;
import org.odata4j.expression.EntitySimpleProperty;
import org.odata4j.expression.Expression;
import org.odata4j.expression.ExpressionParser;
import org.odata4j.expression.ExpressionParser.Token;
import org.odata4j.expression.ExpressionParser.TokenType;
import org.odata4j.expression.OrderByExpression;
import org.odata4j.expression.StringLiteral;
import org.odata4j.internal.TypeConverter;
import org.odata4j.producer.BaseResponse;
import org.odata4j.producer.EntitiesResponse;
import org.odata4j.producer.EntityResponse;
import org.odata4j.producer.InlineCount;
import org.odata4j.producer.ODataProducer;
import org.odata4j.producer.PropertyResponse;
import org.odata4j.producer.QueryInfo;
import org.odata4j.producer.Responses;
import org.odata4j.producer.resources.OptionsQueryParser;
public class JPAProducer implements ODataProducer {
private final EntityManagerFactory emf;
private final EntityManager em;
private final EdmDataServices metadata;
private final int maxResults;
public JPAProducer(
EntityManagerFactory emf,
EdmDataServices metadata,
int maxResults) {
this.emf = emf;
this.maxResults = maxResults;
this.metadata = metadata;
em = emf.createEntityManager(); // necessary for metamodel
}
public JPAProducer(
EntityManagerFactory emf,
String namespace,
int maxResults) {
this(emf, new JPAEdmGenerator().buildEdm(emf, namespace), maxResults);
}
@Override
public void close() {
em.close();
emf.close();
}
@Override
public EdmDataServices getMetadata() {
return metadata;
}
@Override
public EntityResponse getEntity(String entitySetName, Object entityKey) {
return common(entitySetName, entityKey, null,
new Func1<Context, EntityResponse>() {
public EntityResponse apply(Context input) {
return getEntity(input);
}
});
}
@Override
public EntitiesResponse getEntities(String entitySetName, QueryInfo queryInfo) {
return common(entitySetName, null, queryInfo,
new Func1<Context, EntitiesResponse>() {
public EntitiesResponse apply(Context input) {
return getEntities(input);
}
});
}
@Override
public BaseResponse getNavProperty(
final String entitySetName,
final Object entityKey,
final String navProp,
final QueryInfo queryInfo) {
return common(
entitySetName,
entityKey,
queryInfo,
new Func1<Context, BaseResponse>() {
public BaseResponse apply(Context input) {
return getNavProperty(input, navProp);
}
});
}
private static class Context {
EntityManager em;
EdmEntitySet ees;
EntityType<?> jpaEntityType;
String keyPropertyName;
Object typeSafeEntityKey;
QueryInfo query;
}
private EntityResponse getEntity(final Context context) {
Object jpaEntity = context.em.find(
context.jpaEntityType.getJavaType(),
context.typeSafeEntityKey);
if (jpaEntity == null) {
throw new EntityNotFoundException(
context.jpaEntityType.getJavaType()
+ " not found with key "
+ context.typeSafeEntityKey);
}
OEntity entity = makeEntity(
context,
jpaEntity);
return Responses.entity(entity);
}
private OEntity makeEntity(
Context context,
final Object jpaEntity) {
return jpaEntityToOEntity(
context.ees,
context.jpaEntityType,
jpaEntity,
context.query == null ? null : context.query.expand,
context.query == null ? null : context.query.select);
}
private EntitiesResponse getEntities(final Context context) {
final DynamicEntitiesResponse response = enumJpaEntities(
context,
null);
return Responses.entities(
response.entities,
context.ees,
response.inlineCount,
response.skipToken);
}
private BaseResponse getNavProperty(final Context context,String navProp) {
DynamicEntitiesResponse response = enumJpaEntities(context,navProp);
if (response.responseType.equals(PropertyResponse.class))
return Responses.property(response.property);
if (response.responseType.equals(EntityResponse.class))
return Responses.entity(response.entity);
if (response.responseType.equals(EntitiesResponse.class))
return Responses.entities(
response.entities,
context.ees,
response.inlineCount,
response.skipToken);
throw new UnsupportedOperationException("Unknown responseType: " + response.responseType.getName());
}
private <T> T common(
final String entitySetName,
Object entityKey,
QueryInfo query,
Func1<Context, T> fn) {
Context context = new Context();
context.em = emf.createEntityManager();
try {
context.ees = metadata.getEdmEntitySet(entitySetName);
context.jpaEntityType = findJPAEntityType(
context.em,
context.ees.type.name);
context.keyPropertyName = context.ees.type.keys.get(0);
context.typeSafeEntityKey = typeSafeEntityKey(
context.em,
context.jpaEntityType,
entityKey);
context.query = query;
return fn.apply(context);
} finally {
context.em.close();
}
}
private OEntity jpaEntityToOEntity(
EdmEntitySet ees,
EntityType<?> entityType,
Object jpaEntity,
List<EntitySimpleProperty> expand,
List<EntitySimpleProperty> select) {
List<OProperty<?>> properties = new ArrayList<OProperty<?>>();
List<OLink> links = new ArrayList<OLink>();
try {
SingularAttribute<?, ?> idAtt = JPAEdmGenerator.getId(entityType);
boolean hasEmbeddedCompositeKey =
idAtt.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED;
Object id = getIdValue(jpaEntity, idAtt, null);
// get properties
for (EdmProperty ep : ees.type.properties) {
if (!isSelected(ep.name, select)) {
continue;
}
// we have a embedded composite key and we want a property from
// that key
if (hasEmbeddedCompositeKey && ees.type.keys.contains(ep.name)) {
Object value = getIdValue(jpaEntity, idAtt, ep.name);
properties.add(OProperties.simple(
ep.name,
ep.type,
value,
true));
} else {
// get the simple attribute
Attribute<?, ?> att = entityType.getAttribute(ep.name);
Member member = att.getJavaMember();
Object value = getValue(jpaEntity, member);
properties.add(OProperties.simple(
ep.name,
ep.type,
value,
true));
}
}
for (final EdmNavigationProperty ep : ees.type.navigationProperties) {
ep.selected = isSelected(ep.name, select);
}
// get the collections if necessary
if (expand != null && !expand.isEmpty()) {
for (final EntitySimpleProperty propPath : expand) {
// split the property path into the first and remaining
// parts
String[] props = propPath.getPropertyName().split("/", 2);
String prop = props[0];
List<EntitySimpleProperty> remainingPropPath = props.length > 1
? Arrays.asList(org.odata4j.expression.Expression
.simpleProperty(props[1])) : null;
Attribute<?, ?> att = entityType.getAttribute(prop);
if (att.getPersistentAttributeType() == PersistentAttributeType.ONE_TO_MANY
|| att.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_MANY) {
Collection<?> value = getValue(
jpaEntity,
att.getJavaMember());
List<OEntity> relatedEntities = new ArrayList<OEntity>();
for (Object relatedEntity : value) {
EntityType<?> elementEntityType = (EntityType<?>) ((PluralAttribute<?, ?, ?>) att)
.getElementType();
EdmEntitySet elementEntitySet = metadata
.getEdmEntitySet(JPAEdmGenerator.getEntitySetName(elementEntityType));
relatedEntities.add(jpaEntityToOEntity(
elementEntitySet,
elementEntityType,
relatedEntity,
remainingPropPath,
null));
}
links.add(OLinks.relatedEntitiesInline(
null,
prop,
null,
relatedEntities));
} else if (att.getPersistentAttributeType() == PersistentAttributeType.ONE_TO_ONE
|| att.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_ONE) {
EntityType<?> relatedEntityType =
(EntityType<?>) ((SingularAttribute<?, ?>) att)
.getType();
EdmEntitySet relatedEntitySet =
metadata.getEdmEntitySet(JPAEdmGenerator
.getEntitySetName(relatedEntityType));
Object relatedEntity = getValue(
jpaEntity,
att.getJavaMember());
if( relatedEntity == null )
{
links.add(OLinks.relatedEntityInline(
null,
prop,
null,
null));
}else
{
links.add(OLinks.relatedEntityInline(
null,
prop,
null,
jpaEntityToOEntity(
relatedEntitySet,
relatedEntityType,
relatedEntity,
remainingPropPath,
null)));
}
}
}
}
return OEntities.create(ees, OEntityKey.create(id), properties, links);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static boolean isSelected(
String name,
List<EntitySimpleProperty> select) {
if (select != null && !select.isEmpty()) {
for (EntitySimpleProperty prop : select) {
String sname = prop.getPropertyName();
if (name.equals(sname)) {
return true;
}
}
return false;
}
return true;
}
private static Object getIdValue(
Object jpaEntity,
SingularAttribute<?, ?> idAtt,
String propName) {
try {
// get the composite id
Member member = idAtt.getJavaMember();
Object key = getValue(jpaEntity, member);
if (propName == null) {
return key;
}
// get the property from the key
ManagedType<?> keyType = (ManagedType<?>) idAtt.getType();
Attribute<?, ?> att = keyType.getAttribute(propName);
member = att.getJavaMember();
if (member == null) { // http://wiki.eclipse.org/EclipseLink/Development/JPA_2.0/metamodel_api#DI_95:_20091017:_Attribute.getJavaMember.28.29_returns_null_for_a_BasicType_on_a_MappedSuperclass_because_of_an_uninitialized_accessor
member = getJavaMember(key.getClass(), propName);
}
return getValue(key, member);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private static <T> T getValue(Object obj, Member member) throws Exception {
if (member instanceof Field) {
Field field = (Field) member;
field.setAccessible(true);
return (T) field.get(obj);
} else if (member instanceof Method) {
Method method = (Method) member;
method.setAccessible(true);
return (T) method.invoke(obj);
} else {
throw new UnsupportedOperationException("Implement member" + member);
}
}
private static void setValue(Object obj, Member member, Object value) throws Exception {
if (member instanceof Field) {
Field field = (Field) member;
field.setAccessible(true);
field.set(obj, value);
} else if (member instanceof Method) {
throw new UnsupportedOperationException("Implement member"
+ member + " as field");
} else {
throw new UnsupportedOperationException("Implement member" + member);
}
}
private <T extends Annotation> T getAnnotation(Member member, Class<T> annotationClass) {
if (member instanceof Method) {
Method method = (Method) member;
return method.getAnnotation(annotationClass);
} else if (member instanceof Field) {
Field field = (Field) member;
return field.getAnnotation(annotationClass);
} else
throw new IllegalArgumentException("only methods and fields are allowed");
}
private static Member getJavaMember(Class<?> type, String name) {
try {
Field field = CoreUtils.getField(type, name);
field.setAccessible(true);
return field;
} catch (Exception ignore) {
}
String methodName = "get" + Character.toUpperCase(name.charAt(0))
+ name.substring(1);
while (!type.equals(Object.class)) {
try {
Method method = type.getDeclaredMethod(methodName);
method.setAccessible(true);
return method;
} catch (Exception ignore) {
}
type = type.getSuperclass();
}
return null;
}
private static EntityType<?> findJPAEntityType(
EntityManager em,
String jpaEntityTypeName) {
for (EntityType<?> et : em.getMetamodel().getEntities()) {
if (JPAEdmGenerator.getEntitySetName(et).equals(jpaEntityTypeName)) {
return et;
}
}
throw new RuntimeException(
"JPA Entity type " + jpaEntityTypeName + " not found");
}
private static class DynamicEntitiesResponse {
public final Class<?> responseType;
public final OProperty<?> property;
public final OEntity entity;
public final List<OEntity> entities;
public final Integer inlineCount;
public final String skipToken;
public static DynamicEntitiesResponse property(OProperty<?> property){
return new DynamicEntitiesResponse(PropertyResponse.class,property,null,null,null,null);
}
@SuppressWarnings("unused") // TODO when to call?
public static DynamicEntitiesResponse entity(OEntity entity){
return new DynamicEntitiesResponse(EntityResponse.class,null,entity,null,null,null);
}
public static DynamicEntitiesResponse entities(List<OEntity> entityList,Integer inlineCount,String skipToken){
return new DynamicEntitiesResponse(EntitiesResponse.class,null,null,entityList,inlineCount,skipToken);
}
private DynamicEntitiesResponse(
Class<?> responseType,
OProperty<?> property,
OEntity entity,
List<OEntity> entityList,
Integer inlineCount,
String skipToken) {
this.responseType = responseType;
this.property = property;
this.entity = entity;
this.entities = entityList;
this.inlineCount = inlineCount;
this.skipToken = skipToken;
}
}
private DynamicEntitiesResponse enumJpaEntities(final Context context, final String navProp) {
String alias = "t0";
String from = context.jpaEntityType.getName() + " " + alias;
String where = null;
Object edmObj = null;
if (navProp != null) {
where = String.format(
"(%s.%s = %s)",
alias,
context.keyPropertyName,
context.typeSafeEntityKey);
String prop = null;
int propCount = 0;
for (String pn : navProp.split("/")) {
String[] propSplit = pn.split("\\(");
prop = propSplit[0];
propCount++;
if (edmObj instanceof EdmProperty) {
throw new UnsupportedOperationException(
String.format(
"The request URI is not valid. Since the segment '%s' "
+ "refers to a collection, this must be the last segment "
+ "in the request URI. All intermediate segments must refer "
+ "to a single resource.",
alias));
}
edmObj = metadata.findEdmProperty(prop);
if (edmObj instanceof EdmNavigationProperty) {
EdmNavigationProperty propInfo = (EdmNavigationProperty) edmObj;
context.jpaEntityType = findJPAEntityType(
context.em,
propInfo.toRole.type.name);
context.ees = metadata.findEdmEntitySet(JPAEdmGenerator.getEntitySetName(context.jpaEntityType));
prop = alias + "." + prop;
alias = "t" + Integer.toString(propCount);
from = String.format("%s JOIN %s %s", from, prop, alias);
if (propSplit.length > 1) {
Object entityKey = OptionsQueryParser.parseIdObject(
"(" + propSplit[1]);
context.keyPropertyName = JPAEdmGenerator
.getId(context.jpaEntityType).getName();
context.typeSafeEntityKey = typeSafeEntityKey(
em,
context.jpaEntityType,
entityKey);
where = String.format(
"(%s.%s = %s)",
alias,
context.keyPropertyName,
context.typeSafeEntityKey);
}
} else if (edmObj instanceof EdmProperty) {
EdmProperty propInfo = (EdmProperty) edmObj;
alias = alias + "." + propInfo.name;
// TODO
context.ees = null;
}
if (edmObj == null) {
throw new EntityNotFoundException(
String.format(
"Resource not found for the segment '%s'.",
pn));
}
}
}
String jpql = String.format("SELECT %s FROM %s", alias, from);
JPQLGenerator jpqlGen = new JPQLGenerator(context.keyPropertyName, alias);
if (context.query.filter != null) {
String filterPredicate = jpqlGen.toJpql(context.query.filter);
where = addWhereExpression(where, filterPredicate, "AND");
}
if (context.query.skipToken != null) {
String skipPredicate = jpqlGen.toJpql(parseSkipToken(jpqlGen, context.query.orderBy, context.query.skipToken));
where = addWhereExpression(where, skipPredicate, "AND");
}
if (where != null) {
jpql = String.format("%s WHERE %s", jpql, where);
}
if (context.query.orderBy != null) {
String orders = "";
for (OrderByExpression orderBy : context.query.orderBy) {
String field = jpqlGen.toJpql(orderBy.getExpression());
if (orderBy.isAscending()) {
orders = orders + field + ",";
} else {
orders = String.format("%s%s DESC,", orders, field);
}
}
jpql = jpql + " ORDER BY " + orders.substring(0, orders.length() - 1);
}
- Query tq = em.createQuery(jpql);
+ Query tq = context.em.createQuery(jpql);
Integer inlineCount = context.query.inlineCount == InlineCount.ALLPAGES
? tq.getResultList().size()
: null;
int queryMaxResult = maxResults;
if (context.query.top != null) {
if (context.query.top.equals(0)) {
return DynamicEntitiesResponse.entities(
null,
inlineCount,
null);
}
if (context.query.top < maxResults) {
queryMaxResult = context.query.top;
}
}
tq = tq.setMaxResults(queryMaxResult + 1);
if (context.query.skip != null) {
tq = tq.setFirstResult(context.query.skip);
}
@SuppressWarnings("unchecked")
List<Object> results = tq.getResultList();
List<OEntity> entities = new LinkedList<OEntity>();
if (edmObj instanceof EdmProperty) {
EdmProperty propInfo = (EdmProperty) edmObj;
if (results.size() != 1)
throw new RuntimeException("Expected one and only one result for property, found " + results.size());
Object value = results.get(0);
OProperty<?> op = OProperties.simple(
((EdmProperty) propInfo).name,
((EdmProperty) propInfo).type,
value);
return DynamicEntitiesResponse.property(op);
} else {
entities = Enumerable.create(results)
.take(queryMaxResult)
.select(new Func1<Object, OEntity>() {
public OEntity apply(final Object input) {
return makeEntity(context, input);
}
}).toList();
}
boolean useSkipToken = context.query.top != null
? context.query.top > maxResults
&& results.size() > queryMaxResult
: results.size() > queryMaxResult;
String skipToken = null;
if (useSkipToken) {
OEntity last = Enumerable.create(entities).last();
skipToken = createSkipToken(context, last);
}
return DynamicEntitiesResponse.entities(
entities,
inlineCount,
skipToken);
}
private static String addWhereExpression(
String expression,
String nextExpression,
String condition) {
return expression == null
? nextExpression
: String.format(
"%s %s %s",
expression,
condition,
nextExpression);
}
private static String createSkipToken(Context context, OEntity lastEntity) {
List<String> values = new LinkedList<String>();
if (context.query.orderBy != null) {
for (OrderByExpression ord : context.query.orderBy) {
String field = ((EntitySimpleProperty) ord.getExpression())
.getPropertyName();
Object value = lastEntity.getProperty(field).getValue();
if (value instanceof String) {
value = "'" + value + "'";
}
values.add(value.toString());
}
}
values.add(lastEntity.getEntityKey().asSingleValue().toString());
return Enumerable.create(values).join(",");
}
private static BoolCommonExpression parseSkipToken(JPQLGenerator jpqlGen, List<OrderByExpression> orderByList, String skipToken) {
if (skipToken == null) {
return null;
}
skipToken = skipToken.replace("'", "");
BoolCommonExpression result = null;
if (orderByList == null) {
result = Expression.gt(
Expression.simpleProperty(jpqlGen.getPrimaryKeyName()),
Expression.string(skipToken));
} else {
String[] skipTokens = skipToken.split(",");
for (int i = 0; i < orderByList.size(); i++) {
OrderByExpression exp = orderByList.get(i);
StringLiteral value = Expression.string(skipTokens[i]);
BoolCommonExpression ordExp = null;
if (exp.isAscending()) {
ordExp = Expression.ge(exp.getExpression(), value);
} else {
ordExp = Expression.le(exp.getExpression(), value);
}
if (result == null) {
result = ordExp;
} else {
result = Expression.and(
Expression.boolParen(
Expression.or(ordExp, result)),
result);
}
}
result = Expression.and(
Expression.ne(
Expression.simpleProperty(jpqlGen.getPrimaryKeyName()),
Expression.string(skipTokens[skipTokens.length - 1])),
result);
}
return result;
}
private Object createNewJPAEntity(
EntityManager em,
EntityType<?> jpaEntityType,
OEntity oentity,
boolean withLinks) {
try {
Constructor<?> ctor = jpaEntityType.getJavaType()
.getDeclaredConstructor();
ctor.setAccessible(true);
Object jpaEntity = ctor.newInstance();
applyOProperties(jpaEntityType, oentity.getProperties(), jpaEntity);
if (withLinks) {
applyOLinks(em, jpaEntityType, oentity.getLinks(), jpaEntity);
}
return jpaEntity;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void applyOLinks(EntityManager em, EntityType<?> jpaEntityType,
List<OLink> links, Object jpaEntity) {
try {
for (final OLink link : links) {
String[] propNameSplit = link.getRelation().split("/");
String propName = propNameSplit[propNameSplit.length - 1];
if (link instanceof ORelatedEntitiesLinkInline) {
PluralAttribute<?, ?, ?> att = (PluralAttribute<?, ?, ?>)jpaEntityType.getAttribute(propName);
Member member = att.getJavaMember();
EntityType<?> collJpaEntityType = (EntityType<?>)att.getElementType();
OneToMany oneToMany = getAnnotation(member, OneToMany.class);
Member backRef = null;
if (oneToMany != null
&& oneToMany.mappedBy() != null
&& !oneToMany.mappedBy().isEmpty()) {
backRef = collJpaEntityType
.getAttribute(oneToMany.mappedBy())
.getJavaMember();
}
@SuppressWarnings("unchecked")
Collection<Object> coll = (Collection<Object>)getValue(jpaEntity, member);
for (OEntity oentity : ((ORelatedEntitiesLinkInline)link).getRelatedEntities()) {
Object collJpaEntity = createNewJPAEntity(em, collJpaEntityType, oentity, true);
if (backRef != null) {
setValue(collJpaEntity, backRef, jpaEntity);
}
em.persist(collJpaEntity);
coll.add(collJpaEntity);
}
} else if (link instanceof ORelatedEntityLinkInline ) {
SingularAttribute<?, ?> att = jpaEntityType.getSingularAttribute(propName);
Member member = att.getJavaMember();
EntityType<?> relJpaEntityType = (EntityType<?>)att.getType();
Object relJpaEntity = createNewJPAEntity(em, relJpaEntityType,
((ORelatedEntityLinkInline)link).getRelatedEntity(), true);
em.persist(relJpaEntity);
setValue(jpaEntity, member, relJpaEntity);
} else if (link instanceof ORelatedEntityLink ) {
SingularAttribute<?, ?> att = jpaEntityType.getSingularAttribute(propName);
Member member = att.getJavaMember();
EntityType<?> relJpaEntityType = (EntityType<?>)att.getType();
Object key = typeSafeEntityKey(em, relJpaEntityType, link.getHref());
Object relEntity = em.find(relJpaEntityType.getJavaType(), key);
setValue(jpaEntity, member, relEntity);
} else {
throw new UnsupportedOperationException("binding the new entity to many entities is not supported");
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void applyOProperties(EntityType<?> jpaEntityType,
List<OProperty<?>> properties, Object jpaEntity) {
try {
for (OProperty<?> prop : properties) {
// EdmProperty ep = findProperty(ees,prop.getName());
Attribute<?, ?> att = jpaEntityType
.getAttribute(prop.getName());
Member member = att.getJavaMember();
if (!(member instanceof Field)) {
throw new UnsupportedOperationException("Implement member"
+ member);
}
Field field = (Field) member;
field.setAccessible(true);
Object value = getPropertyValue(prop, field);
field.set(jpaEntity, value);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public EntityResponse createEntity(String entitySetName, OEntity entity) {
final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName);
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name);
Object jpaEntity = createNewJPAEntity(
em,
jpaEntityType,
entity,
true);
em.persist(jpaEntity);
em.getTransaction().commit();
// reread the entity in case we had links. This should insure
// we get the implicitly set foreign keys. E.g in the Northwind model
// creating a new Product with a link to the Category should return
// the CategoryID.
if (entity.getLinks() != null
&& !entity.getLinks().isEmpty()) {
em.getTransaction().begin();
try {
em.refresh(jpaEntity);
em.getTransaction().commit();
} finally {
if (em.getTransaction().isActive())
em.getTransaction().rollback();
}
}
final OEntity responseEntity = jpaEntityToOEntity(
ees,
jpaEntityType,
jpaEntity,
null,
null);
return Responses.entity(responseEntity);
} finally {
em.close();
}
}
@Override
public EntityResponse createEntity(String entitySetName, Object entityKey,
final String navProp, OEntity entity) {
// get the EdmEntitySet for the parent (fromRole) entity
final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName);
// get the navigation property
EdmNavigationProperty edmNavProperty = ees.type.getNavigationProperty(navProp);
// check whether the navProperty is valid
if (edmNavProperty == null
|| edmNavProperty.toRole.multiplicity != EdmMultiplicity.MANY) {
throw new IllegalArgumentException("unknown navigation property "
+ navProp + " or navigation property toRole Multiplicity is not '*'" );
}
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
// get the entity we want the new entity add to
EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name);
Object typeSafeEntityKey = typeSafeEntityKey(em, jpaEntityType,
entityKey);
Object jpaEntity = em.find(jpaEntityType.getJavaType(),
typeSafeEntityKey);
// create the new entity
EntityType<?> newJpaEntityType = findJPAEntityType(em,
edmNavProperty.toRole.type.name);
Object newJpaEntity = createNewJPAEntity(em, newJpaEntityType, entity,
true);
// get the collection attribute and add the new entity to the parent entity
@SuppressWarnings({ "rawtypes", "unchecked" })
PluralAttribute attr = Enumerable.create(
jpaEntityType.getPluralAttributes())
.firstOrNull(new Predicate1() {
@Override
public boolean apply(Object input) {
PluralAttribute<?, ?, ?> pa = (PluralAttribute<?, ?, ?>)input;
System.out.println("pa: " + pa.getName());
return pa.getName().equals(navProp);
}
});
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object> )getValue(jpaEntity, attr.getJavaMember());
collection.add(newJpaEntity);
// TODO handle ManyToMany relationships
// set the backreference in bidirectional relationships
OneToMany oneToMany = getAnnotation(attr.getJavaMember(),
OneToMany.class);
if (oneToMany != null
&& oneToMany.mappedBy() != null
&& !oneToMany.mappedBy().isEmpty()) {
setValue(newJpaEntity, newJpaEntityType
.getAttribute(oneToMany.mappedBy())
.getJavaMember(), jpaEntity);
}
// check whether the EntitManager will persist the
// new entity or should we do it
if (oneToMany != null
&& oneToMany.cascade() != null) {
List<CascadeType> cascadeTypes = Arrays.asList(oneToMany.cascade());
if (!cascadeTypes.contains(CascadeType.ALL)
&& !cascadeTypes.contains(CascadeType.PERSIST)) {
em.persist(newJpaEntity);
}
}
em.getTransaction().commit();
// prepare the response
final EdmEntitySet toRoleees = getMetadata()
.getEdmEntitySet(edmNavProperty.toRole.type);
final OEntity responseEntity = jpaEntityToOEntity(toRoleees,
newJpaEntityType, newJpaEntity, null, null);
return Responses.entity(responseEntity);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
em.close();
}
}
@Override
public void deleteEntity(String entitySetName, Object entityKey) {
final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName);
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name);
Object typeSafeEntityKey = typeSafeEntityKey(
em,
jpaEntityType,
entityKey);
Object jpaEntity = em.find(
jpaEntityType.getJavaType(),
typeSafeEntityKey);
em.remove(jpaEntity);
em.getTransaction().commit();
} finally {
em.close();
}
}
@Override
public void mergeEntity(String entitySetName, Object entityKey,
OEntity entity) {
final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName);
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name);
Object typeSafeEntityKey = typeSafeEntityKey(
em,
jpaEntityType,
entityKey);
Object jpaEntity = em.find(
jpaEntityType.getJavaType(),
typeSafeEntityKey);
applyOProperties(jpaEntityType, entity.getProperties(), jpaEntity);
em.getTransaction().commit();
} finally {
em.close();
}
}
@Override
public void updateEntity(
String entitySetName,
Object entityKey,
OEntity entity) {
final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName);
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name);
Object jpaEntity = createNewJPAEntity(
em,
jpaEntityType,
entity,
true);
em.merge(jpaEntity);
em.getTransaction().commit();
} finally {
em.close();
}
}
private static Object typeSafeEntityKey(
EntityManager em,
EntityType<?> jpaEntityType,
Object entityKey) {
return TypeConverter.convert(
entityKey,
em.getMetamodel()
.entity(jpaEntityType.getJavaType())
.getIdType()
.getJavaType());
}
private Object typeSafeEntityKey(EntityManager em,
EntityType<?> jpaEntityType, String href) throws Exception {
String keyString = href.substring(href.lastIndexOf('(') + 1,
href.length() - 1);
List<Token> keyToken = ExpressionParser.tokenize(keyString);
if( keyToken.size() !=0 &&
( keyToken.get(0).type == TokenType.QUOTED_STRING ||
keyToken.get(0).type == TokenType.NUMBER ) ) {
Object key;
if (keyToken.get(0).type == TokenType.QUOTED_STRING) {
String entityKeyStr = keyToken.get(0).value;
if (entityKeyStr.length() < 2) {
throw new IllegalArgumentException("invalid entity key "
+ keyToken);
}
// cut off the quotes
key = entityKeyStr.substring(1, entityKeyStr.length() - 1);
} else if (keyToken.get(0).type == TokenType.NUMBER) {
key = NumberFormat.getInstance(Locale.US)
.parseObject(keyToken.get(0).value);
} else {
throw new IllegalArgumentException(
"unsupported key type " + keyString);
}
return TypeConverter.convert(key,
em.getMetamodel()
.entity(jpaEntityType.getJavaType())
.getIdType()
.getJavaType());
} else {
throw new IllegalArgumentException(
"only simple entity keys are supported yet");
}
}
protected static Object getPropertyValue(OProperty<?> prop, Field field) {
Object value = prop.getValue();
try {
return TypeConverter.convert(value, field.getType());
} catch (UnsupportedOperationException ex) {
// let java complain
return value;
}
}
}
| true | true | private DynamicEntitiesResponse enumJpaEntities(final Context context, final String navProp) {
String alias = "t0";
String from = context.jpaEntityType.getName() + " " + alias;
String where = null;
Object edmObj = null;
if (navProp != null) {
where = String.format(
"(%s.%s = %s)",
alias,
context.keyPropertyName,
context.typeSafeEntityKey);
String prop = null;
int propCount = 0;
for (String pn : navProp.split("/")) {
String[] propSplit = pn.split("\\(");
prop = propSplit[0];
propCount++;
if (edmObj instanceof EdmProperty) {
throw new UnsupportedOperationException(
String.format(
"The request URI is not valid. Since the segment '%s' "
+ "refers to a collection, this must be the last segment "
+ "in the request URI. All intermediate segments must refer "
+ "to a single resource.",
alias));
}
edmObj = metadata.findEdmProperty(prop);
if (edmObj instanceof EdmNavigationProperty) {
EdmNavigationProperty propInfo = (EdmNavigationProperty) edmObj;
context.jpaEntityType = findJPAEntityType(
context.em,
propInfo.toRole.type.name);
context.ees = metadata.findEdmEntitySet(JPAEdmGenerator.getEntitySetName(context.jpaEntityType));
prop = alias + "." + prop;
alias = "t" + Integer.toString(propCount);
from = String.format("%s JOIN %s %s", from, prop, alias);
if (propSplit.length > 1) {
Object entityKey = OptionsQueryParser.parseIdObject(
"(" + propSplit[1]);
context.keyPropertyName = JPAEdmGenerator
.getId(context.jpaEntityType).getName();
context.typeSafeEntityKey = typeSafeEntityKey(
em,
context.jpaEntityType,
entityKey);
where = String.format(
"(%s.%s = %s)",
alias,
context.keyPropertyName,
context.typeSafeEntityKey);
}
} else if (edmObj instanceof EdmProperty) {
EdmProperty propInfo = (EdmProperty) edmObj;
alias = alias + "." + propInfo.name;
// TODO
context.ees = null;
}
if (edmObj == null) {
throw new EntityNotFoundException(
String.format(
"Resource not found for the segment '%s'.",
pn));
}
}
}
String jpql = String.format("SELECT %s FROM %s", alias, from);
JPQLGenerator jpqlGen = new JPQLGenerator(context.keyPropertyName, alias);
if (context.query.filter != null) {
String filterPredicate = jpqlGen.toJpql(context.query.filter);
where = addWhereExpression(where, filterPredicate, "AND");
}
if (context.query.skipToken != null) {
String skipPredicate = jpqlGen.toJpql(parseSkipToken(jpqlGen, context.query.orderBy, context.query.skipToken));
where = addWhereExpression(where, skipPredicate, "AND");
}
if (where != null) {
jpql = String.format("%s WHERE %s", jpql, where);
}
if (context.query.orderBy != null) {
String orders = "";
for (OrderByExpression orderBy : context.query.orderBy) {
String field = jpqlGen.toJpql(orderBy.getExpression());
if (orderBy.isAscending()) {
orders = orders + field + ",";
} else {
orders = String.format("%s%s DESC,", orders, field);
}
}
jpql = jpql + " ORDER BY " + orders.substring(0, orders.length() - 1);
}
Query tq = em.createQuery(jpql);
Integer inlineCount = context.query.inlineCount == InlineCount.ALLPAGES
? tq.getResultList().size()
: null;
int queryMaxResult = maxResults;
if (context.query.top != null) {
if (context.query.top.equals(0)) {
return DynamicEntitiesResponse.entities(
null,
inlineCount,
null);
}
if (context.query.top < maxResults) {
queryMaxResult = context.query.top;
}
}
tq = tq.setMaxResults(queryMaxResult + 1);
if (context.query.skip != null) {
tq = tq.setFirstResult(context.query.skip);
}
@SuppressWarnings("unchecked")
List<Object> results = tq.getResultList();
List<OEntity> entities = new LinkedList<OEntity>();
if (edmObj instanceof EdmProperty) {
EdmProperty propInfo = (EdmProperty) edmObj;
if (results.size() != 1)
throw new RuntimeException("Expected one and only one result for property, found " + results.size());
Object value = results.get(0);
OProperty<?> op = OProperties.simple(
((EdmProperty) propInfo).name,
((EdmProperty) propInfo).type,
value);
return DynamicEntitiesResponse.property(op);
} else {
entities = Enumerable.create(results)
.take(queryMaxResult)
.select(new Func1<Object, OEntity>() {
public OEntity apply(final Object input) {
return makeEntity(context, input);
}
}).toList();
}
boolean useSkipToken = context.query.top != null
? context.query.top > maxResults
&& results.size() > queryMaxResult
: results.size() > queryMaxResult;
String skipToken = null;
if (useSkipToken) {
OEntity last = Enumerable.create(entities).last();
skipToken = createSkipToken(context, last);
}
return DynamicEntitiesResponse.entities(
entities,
inlineCount,
skipToken);
}
| private DynamicEntitiesResponse enumJpaEntities(final Context context, final String navProp) {
String alias = "t0";
String from = context.jpaEntityType.getName() + " " + alias;
String where = null;
Object edmObj = null;
if (navProp != null) {
where = String.format(
"(%s.%s = %s)",
alias,
context.keyPropertyName,
context.typeSafeEntityKey);
String prop = null;
int propCount = 0;
for (String pn : navProp.split("/")) {
String[] propSplit = pn.split("\\(");
prop = propSplit[0];
propCount++;
if (edmObj instanceof EdmProperty) {
throw new UnsupportedOperationException(
String.format(
"The request URI is not valid. Since the segment '%s' "
+ "refers to a collection, this must be the last segment "
+ "in the request URI. All intermediate segments must refer "
+ "to a single resource.",
alias));
}
edmObj = metadata.findEdmProperty(prop);
if (edmObj instanceof EdmNavigationProperty) {
EdmNavigationProperty propInfo = (EdmNavigationProperty) edmObj;
context.jpaEntityType = findJPAEntityType(
context.em,
propInfo.toRole.type.name);
context.ees = metadata.findEdmEntitySet(JPAEdmGenerator.getEntitySetName(context.jpaEntityType));
prop = alias + "." + prop;
alias = "t" + Integer.toString(propCount);
from = String.format("%s JOIN %s %s", from, prop, alias);
if (propSplit.length > 1) {
Object entityKey = OptionsQueryParser.parseIdObject(
"(" + propSplit[1]);
context.keyPropertyName = JPAEdmGenerator
.getId(context.jpaEntityType).getName();
context.typeSafeEntityKey = typeSafeEntityKey(
em,
context.jpaEntityType,
entityKey);
where = String.format(
"(%s.%s = %s)",
alias,
context.keyPropertyName,
context.typeSafeEntityKey);
}
} else if (edmObj instanceof EdmProperty) {
EdmProperty propInfo = (EdmProperty) edmObj;
alias = alias + "." + propInfo.name;
// TODO
context.ees = null;
}
if (edmObj == null) {
throw new EntityNotFoundException(
String.format(
"Resource not found for the segment '%s'.",
pn));
}
}
}
String jpql = String.format("SELECT %s FROM %s", alias, from);
JPQLGenerator jpqlGen = new JPQLGenerator(context.keyPropertyName, alias);
if (context.query.filter != null) {
String filterPredicate = jpqlGen.toJpql(context.query.filter);
where = addWhereExpression(where, filterPredicate, "AND");
}
if (context.query.skipToken != null) {
String skipPredicate = jpqlGen.toJpql(parseSkipToken(jpqlGen, context.query.orderBy, context.query.skipToken));
where = addWhereExpression(where, skipPredicate, "AND");
}
if (where != null) {
jpql = String.format("%s WHERE %s", jpql, where);
}
if (context.query.orderBy != null) {
String orders = "";
for (OrderByExpression orderBy : context.query.orderBy) {
String field = jpqlGen.toJpql(orderBy.getExpression());
if (orderBy.isAscending()) {
orders = orders + field + ",";
} else {
orders = String.format("%s%s DESC,", orders, field);
}
}
jpql = jpql + " ORDER BY " + orders.substring(0, orders.length() - 1);
}
Query tq = context.em.createQuery(jpql);
Integer inlineCount = context.query.inlineCount == InlineCount.ALLPAGES
? tq.getResultList().size()
: null;
int queryMaxResult = maxResults;
if (context.query.top != null) {
if (context.query.top.equals(0)) {
return DynamicEntitiesResponse.entities(
null,
inlineCount,
null);
}
if (context.query.top < maxResults) {
queryMaxResult = context.query.top;
}
}
tq = tq.setMaxResults(queryMaxResult + 1);
if (context.query.skip != null) {
tq = tq.setFirstResult(context.query.skip);
}
@SuppressWarnings("unchecked")
List<Object> results = tq.getResultList();
List<OEntity> entities = new LinkedList<OEntity>();
if (edmObj instanceof EdmProperty) {
EdmProperty propInfo = (EdmProperty) edmObj;
if (results.size() != 1)
throw new RuntimeException("Expected one and only one result for property, found " + results.size());
Object value = results.get(0);
OProperty<?> op = OProperties.simple(
((EdmProperty) propInfo).name,
((EdmProperty) propInfo).type,
value);
return DynamicEntitiesResponse.property(op);
} else {
entities = Enumerable.create(results)
.take(queryMaxResult)
.select(new Func1<Object, OEntity>() {
public OEntity apply(final Object input) {
return makeEntity(context, input);
}
}).toList();
}
boolean useSkipToken = context.query.top != null
? context.query.top > maxResults
&& results.size() > queryMaxResult
: results.size() > queryMaxResult;
String skipToken = null;
if (useSkipToken) {
OEntity last = Enumerable.create(entities).last();
skipToken = createSkipToken(context, last);
}
return DynamicEntitiesResponse.entities(
entities,
inlineCount,
skipToken);
}
|
diff --git a/navit/navit/android/src/org/navitproject/navit/Navit.java b/navit/navit/android/src/org/navitproject/navit/Navit.java
index cac593ed..65cd037a 100644
--- a/navit/navit/android/src/org/navitproject/navit/Navit.java
+++ b/navit/navit/android/src/org/navitproject/navit/Navit.java
@@ -1,781 +1,783 @@
/**
* Navit, a modular navigation system.
* Copyright (C) 2005-2008 Navit Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package org.navitproject.navit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.PowerManager;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Navit extends Activity
{
public static final class NavitAddress
{
String result_type; // TWN,STR,SHN
String item_id; // H<ddddd>L<ddddd> -> item.id_hi item.id_lo
float lat;
float lon;
String addr;
}
public NavitDialogs dialogs;
private PowerManager.WakeLock wl;
private NavitActivityResult ActivityResults[];
public static InputMethodManager mgr = null;
public static DisplayMetrics metrics = null;
public static Boolean show_soft_keyboard = false;
public static Boolean show_soft_keyboard_now_showing = false;
public static long last_pressed_menu_key = 0L;
public static long time_pressed_menu_key = 0L;
private static Intent startup_intent = null;
private static long startup_intent_timestamp = 0L;
public static String my_display_density = "mdpi";
private boolean searchBoxShown = false;
public static final int ADDRESS_RESULTS_DIALOG_MAX = 10;
public static final int NavitDownloaderPriSelectMap_id = 967;
public static final int NavitDownloaderSecSelectMap_id = 968;
public static int search_results_towns = 0;
public static int search_results_streets = 0;
public static int search_results_streets_hn = 0;
public static final int MAP_NUM_PRIMARY = 11;
public static final int NavitAddressSearch_id = 70;
public static final int NavitAddressResultList_id = 71;
public static List<NavitAddress> NavitAddressResultList_foundItems = new ArrayList<NavitAddress>();
public static final int MAP_NUM_SECONDARY = 12;
static final String MAP_FILENAME_PATH = "/sdcard/navit/";
static final String NAVIT_DATA_DIR = "/data/data/org.navitproject.navit";
static final String NAVIT_DATA_SHARE_DIR = NAVIT_DATA_DIR + "/share";
static final String FIRST_STARTUP_FILE = NAVIT_DATA_SHARE_DIR + "/has_run_once.txt";
public static final String NAVIT_PREFS = "NavitPrefs";
public static String get_text(String in)
{
return NavitTextTranslations.get_text(in);
}
private boolean extractRes(String resname, String result)
{
int slash = -1;
boolean needs_update = false;
File resultfile;
Resources res = getResources();
Log.e("Navit", "Res Name " + resname);
Log.e("Navit", "result " + result);
int id = res.getIdentifier(resname, "raw", "org.navitproject.navit");
Log.e("Navit", "Res ID " + id);
if (id == 0)
return false;
while ((slash = result.indexOf("/", slash + 1)) != -1)
{
if (slash != 0)
{
Log.e("Navit", "Checking " + result.substring(0, slash));
resultfile = new File(result.substring(0, slash));
if (!resultfile.exists())
{
Log.e("Navit", "Creating dir");
if (!resultfile.mkdir())
return false;
needs_update = true;
}
}
}
resultfile = new File(result);
if (!resultfile.exists())
needs_update = true;
if (!needs_update)
{
try
{
InputStream resourcestream = res.openRawResource(id);
FileInputStream resultfilestream = new FileInputStream(resultfile);
byte[] resourcebuf = new byte[1024];
byte[] resultbuf = new byte[1024];
int i = 0;
while ((i = resourcestream.read(resourcebuf)) != -1)
{
if (resultfilestream.read(resultbuf) != i)
{
Log.e("Navit", "Result is too short");
needs_update = true;
break;
}
for (int j = 0; j < i; j++)
{
if (resourcebuf[j] != resultbuf[j])
{
Log.e("Navit", "Result is different");
needs_update = true;
break;
}
}
if (needs_update) break;
}
if (!needs_update && resultfilestream.read(resultbuf) != -1)
{
Log.e("Navit", "Result is too long");
needs_update = true;
}
}
catch (Exception e)
{
Log.e("Navit", "Exception " + e.getMessage());
return false;
}
}
if (needs_update)
{
Log.e("Navit", "Extracting resource");
try
{
InputStream resourcestream = res.openRawResource(id);
FileOutputStream resultfilestream = new FileOutputStream(resultfile);
byte[] buf = new byte[1024];
int i = 0;
while ((i = resourcestream.read(buf)) != -1)
{
resultfilestream.write(buf, 0, i);
}
}
catch (Exception e)
{
Log.e("Navit", "Exception " + e.getMessage());
return false;
}
}
return true;
}
private void showInfos()
{
SharedPreferences settings = getSharedPreferences(NAVIT_PREFS, MODE_PRIVATE);
boolean firstStart = settings.getBoolean("firstStart", true);
if (firstStart)
{
AlertDialog.Builder infobox = new AlertDialog.Builder(this);
infobox.setTitle(NavitTextTranslations.INFO_BOX_TITLE); // TRANS
infobox.setCancelable(false);
final TextView message = new TextView(this);
message.setFadingEdgeLength(20);
message.setVerticalFadingEdgeEnabled(true);
// message.setVerticalScrollBarEnabled(true);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
message.setLayoutParams(rlp);
final SpannableString s = new SpannableString(NavitTextTranslations.INFO_BOX_TEXT); // TRANS
Linkify.addLinks(s, Linkify.WEB_URLS);
message.setText(s);
message.setMovementMethod(LinkMovementMethod.getInstance());
infobox.setView(message);
// TRANS
infobox.setPositiveButton(Navit.get_text("Ok"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Log.e("Navit", "Ok, user saw the infobox");
}
});
// TRANS
infobox.setNeutralButton(NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Log.e("Navit", "user wants more info, show the website");
String url = "http://wiki.navit-project.org/index.php/Navit_on_Android";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
infobox.show();
SharedPreferences.Editor edit_settings = settings.edit();
edit_settings.putBoolean("firstStart", false);
edit_settings.commit();
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
dialogs = new NavitDialogs(this);
// only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.)
Navit.startup_intent = this.getIntent();
// hack! remeber timstamp, and only allow 4 secs. later in onResume to set target!
Navit.startup_intent_timestamp = System.currentTimeMillis();
Log.e("Navit", "**1**A " + startup_intent.getAction());
Log.e("Navit", "**1**D " + startup_intent.getDataString());
// init translated text
NavitTextTranslations.init();
- // Setup a notification in the android notification bar, remove it in the exit() function
- NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- Notification notification = new Notification(R.drawable.icon,"Navit is running",0);
- notification.flags = Notification.FLAG_NO_CLEAR;
+ // NOTIFICATION
+ // Setup the status bar notification
+ // This notification is removed in the exit() function
+ NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Grab a handle to the NotificationManager
+ Notification NavitNotification = new Notification(R.drawable.icon,"Navit started",System.currentTimeMillis()); // Create a new notification, with the text string to show when the notification first appears
PendingIntent appIntent = PendingIntent.getActivity(getApplicationContext(), 0, getIntent(), 0);
- notification.setLatestEventInfo(getApplicationContext(), "Navit running", "Navit still running", appIntent);
- nm.notify(R.string.app_name, notification);
+ NavitNotification.setLatestEventInfo(getApplicationContext(), "Navit", "Navit running", appIntent); // Set the text in the notification
+ NavitNotification.flags|=Notification.FLAG_ONGOING_EVENT; // Ensure that the notification appears in Ongoing
+ nm.notify(R.string.app_name, NavitNotification); // Set the notification
// get the local language -------------
Locale locale = java.util.Locale.getDefault();
String lang = locale.getLanguage();
String langu = lang;
String langc = lang;
Log.e("Navit", "lang=" + lang);
int pos = langu.indexOf('_');
if (pos != -1)
{
langc = langu.substring(0, pos);
langu = langc + langu.substring(pos).toUpperCase(locale);
Log.e("Navit", "substring lang " + langu.substring(pos).toUpperCase(locale));
// set lang. for translation
NavitTextTranslations.main_language = langc;
NavitTextTranslations.sub_language = langu.substring(pos).toUpperCase(locale);
}
else
{
String country = locale.getCountry();
Log.e("Navit", "Country1 " + country);
Log.e("Navit", "Country2 " + country.toUpperCase(locale));
langu = langc + "_" + country.toUpperCase(locale);
// set lang. for translation
NavitTextTranslations.main_language = langc;
NavitTextTranslations.sub_language = country.toUpperCase(locale);
}
Log.e("Navit", "Language " + lang);
// get the local language -------------
// make sure the new path for the navitmap.bin file(s) exist!!
File navit_maps_dir = new File(MAP_FILENAME_PATH);
navit_maps_dir.mkdirs();
// make sure the share dir exists
File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR);
navit_data_share_dir.mkdirs();
// hardcoded strings for now, use routine down below later!!
if (lang.compareTo("de") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_de;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_de;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_de;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_de;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_de;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_de;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_de;
}
else if (lang.compareTo("fr") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_fr;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_fr;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_fr;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_fr;
}
else if (lang.compareTo("nl") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_nl;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_nl;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_nl;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_nl;
}
Display display_ = getWindowManager().getDefaultDisplay();
int width_ = display_.getWidth();
int height_ = display_.getHeight();
metrics = new DisplayMetrics();
display_.getMetrics(Navit.metrics);
int densityDpi = (int)(( Navit.metrics.density*160)+.5f);
Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_);
Log.e("Navit", "Navit -> dpi=" + densityDpi);
Log.e("Navit", "Navit -> density=" + Navit.metrics.density);
Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity);
ActivityResults = new NavitActivityResult[16];
setVolumeControlStream(AudioManager.STREAM_MUSIC);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"NavitDoNotDimScreen");
if (!extractRes(langc, NAVIT_DATA_DIR + "/locale/" + langc + "/LC_MESSAGES/navit.mo"))
{
Log.e("Navit", "Failed to extract language resource " + langc);
}
if (densityDpi <= 120)
{
my_display_density = "ldpi";
}
else if (densityDpi <= 160)
{
my_display_density = "mdpi";
}
else if (densityDpi < 320)
{
my_display_density = "hdpi";
}
else
{
Log.e("Navit", "found xhdpi device, this is not fully supported!!");
Log.e("Navit", "using hdpi values");
my_display_density = "hdpi";
}
if (!extractRes("navit" + my_display_density, NAVIT_DATA_DIR + "/share/navit.xml"))
{
Log.e("Navit", "Failed to extract navit.xml for " + my_display_density);
}
// --> dont use android.os.Build.VERSION.SDK_INT, needs API >= 4
Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK));
NavitMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density, NAVIT_DATA_DIR+"/bin/navit");
showInfos();
Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// unpack some localized Strings
// a test now, later we will unpack all needed string for java, here at this point!!
String x = NavitGraphics.getLocalizedString("Austria");
Log.e("Navit", "x=" + x);
}
@Override
public void onResume()
{
super.onResume();
Log.e("Navit", "OnResume");
//InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// DEBUG
// intent_data = "google.navigation:q=Wien Burggasse 27";
// intent_data = "google.navigation:q=48.25676,16.643";
// intent_data = "google.navigation:ll=48.25676,16.643&q=blabla-strasse";
// intent_data = "google.navigation:ll=48.25676,16.643";
if (startup_intent != null)
{
if (System.currentTimeMillis() <= Navit.startup_intent_timestamp + 4000L)
{
Log.e("Navit", "**2**A " + startup_intent.getAction());
Log.e("Navit", "**2**D " + startup_intent.getDataString());
String navi_scheme = startup_intent.getScheme();
if ( navi_scheme != null && navi_scheme.equals("google.navigation")) {
parseNavigationURI(startup_intent.getData().getSchemeSpecificPart());
}
}
else {
Log.e("Navit", "timestamp for navigate_to expired! not using data");
}
}
}
private void parseNavigationURI(String schemeSpecificPart) {
String naviData[]= schemeSpecificPart.split("&");
Pattern p = Pattern.compile("(.*)=(.*)");
Map<String,String> params = new HashMap<String,String>();
for (int count=0; count < naviData.length; count++) {
Matcher m = p.matcher(naviData[count]);
if (m.matches()) {
params.put(m.group(1), m.group(2));
}
}
// d: google.navigation:q=blabla-strasse # (this happens when you are offline, or from contacts)
// a: google.navigation:ll=48.25676,16.643&q=blabla-strasse
// c: google.navigation:ll=48.25676,16.643
// b: google.navigation:q=48.25676,16.643
Float lat;
Float lon;
Bundle b = new Bundle();
String geoString = params.get("ll");
if (geoString != null) {
String address = params.get("q");
if (address != null) b.putString("q", address);
}
else {
geoString = params.get("q");
}
if ( geoString != null) {
if (geoString.matches("^[+-]{0,1}\\d+(|\\.\\d*),[+-]{0,1}\\d+(|\\.\\d*)$")) {
String geo[] = geoString.split(",");
if (geo.length == 2) {
try {
lat = Float.valueOf(geo[0]);
lon = Float.valueOf(geo[1]);
b.putFloat("lat", lat);
b.putFloat("lon", lon);
Message msg = Message.obtain(N_NavitGraphics.callback_handler, NavitGraphics.msg_type.CLB_SET_DESTINATION.ordinal());
msg.setData(b);
msg.sendToTarget();
Log.e("Navit", "target found (b): " + geoString);
} catch (NumberFormatException e) { } // nothing to do here
}
}
else {
start_targetsearch_from_intent(geoString);
}
}
}
public void setActivityResult(int requestCode, NavitActivityResult ActivityResult)
{
//Log.e("Navit", "setActivityResult " + requestCode);
ActivityResults[requestCode] = ActivityResult;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
//Log.e("Navit","onPrepareOptionsMenu");
// this gets called every time the menu is opened!!
// change menu items here!
menu.clear();
// group-id,item-id,sort order number
menu.add(1, 1, 100, get_text("zoom in")); //TRANS
menu.add(1, 2, 200, get_text("zoom out")); //TRANS
menu.add(1, 3, 300, NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map); //TRANS
menu.add(1, 5, 400, NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI); //TRANS
menu.add(1, 6, 500, get_text("address search")); //TRANS
menu.add(1, 4, 600, NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map); //TRANS
menu.add(1, 88, 800, "--");
menu.add(1, 99, 900, get_text("exit navit")); //TRANS
return true;
}
// define callback id here
public static NavitGraphics N_NavitGraphics = null;
// callback id gets set here when called from NavitGraphics
public static void setKeypressCallback(int kp_cb_id, NavitGraphics ng)
{
//Log.e("Navit", "setKeypressCallback -> id1=" + kp_cb_id);
//Log.e("Navit", "setKeypressCallback -> ng=" + String.valueOf(ng));
//N_KeypressCallbackID = kp_cb_id;
N_NavitGraphics = ng;
}
public static void setMotionCallback(int mo_cb_id, NavitGraphics ng)
{
//Log.e("Navit", "setKeypressCallback -> id2=" + mo_cb_id);
//Log.e("Navit", "setKeypressCallback -> ng=" + String.valueOf(ng));
//N_MotionCallbackID = mo_cb_id;
N_NavitGraphics = ng;
}
//public native void KeypressCallback(int id, String s);
public void start_targetsearch_from_intent(String target_address)
{
NavitDialogs.Navit_last_address_partial_match = false;
NavitDialogs.Navit_last_address_search_string = target_address;
// clear results
Navit.NavitAddressResultList_foundItems.clear();
if (NavitDialogs.Navit_last_address_search_string.equals(""))
{
// empty search string entered
Toast.makeText(getApplicationContext(), Navit.get_text("No address found"), Toast.LENGTH_LONG).show(); //TRANS
}
else
{
// show dialog
dialogs.obtainMessage(NavitDialogs.MSG_SEARCH).sendToTarget();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case 1 :
// zoom in
Message.obtain(N_NavitGraphics.callback_handler, NavitGraphics.msg_type.CLB_ZOOM_IN.ordinal()).sendToTarget();
// if we zoom, hide the bubble
Log.e("Navit", "onOptionsItemSelected -> zoom in");
break;
case 2 :
// zoom out
Message.obtain(N_NavitGraphics.callback_handler, NavitGraphics.msg_type.CLB_ZOOM_OUT.ordinal()).sendToTarget();
// if we zoom, hide the bubble
Log.e("Navit", "onOptionsItemSelected -> zoom out");
break;
case 3 :
// map download menu for primary
Intent map_download_list_activity = new Intent(this, NavitDownloadSelectMapActivity.class);
startActivityForResult(map_download_list_activity, Navit.NavitDownloaderPriSelectMap_id);
break;
case 4 :
// map download menu for second map
Intent map_download_list_activity2 = new Intent(this, NavitDownloadSelectMapActivity.class);
startActivityForResult(map_download_list_activity2, Navit.NavitDownloaderSecSelectMap_id);
break;
case 5 :
// toggle the normal POI layers (to avoid double POIs)
Message msg = Message.obtain(N_NavitGraphics.callback_handler, NavitGraphics.msg_type.CLB_CALL_CMD.ordinal());
Bundle b = new Bundle();
b.putString("cmd", "toggle_layer(\"POI Symbols\");");
msg.setData(b);
msg.sendToTarget();
// toggle full POI icons on/off
msg = Message.obtain(N_NavitGraphics.callback_handler, NavitGraphics.msg_type.CLB_CALL_CMD.ordinal());
b = new Bundle();
b.putString("cmd", "toggle_layer(\"Android-POI-Icons-full\");");
msg.setData(b);
msg.sendToTarget();
break;
case 6 :
// ok startup address search activity
Intent search_intent = new Intent(this, NavitAddressSearchActivity.class);
search_intent.putExtra("title", Navit.get_text("Enter: City and Street")); //TRANS
search_intent.putExtra("address_string", NavitDialogs.Navit_last_address_search_string);
search_intent.putExtra("partial_match", NavitDialogs.Navit_last_address_partial_match);
this.startActivityForResult(search_intent, NavitAddressSearch_id);
break;
case 88 :
// dummy entry, just to make "breaks" in the menu
break;
case 99 :
// exit
this.onStop();
this.exit();
break;
}
return true;
}
void setDestination(float latitude, float longitude, String address) {
Toast.makeText( getApplicationContext(),Navit.get_text("setting destination to") + "\n" + address, Toast.LENGTH_LONG).show(); //TRANS
Message msg = Message.obtain(N_NavitGraphics.callback_handler, NavitGraphics.msg_type.CLB_SET_DESTINATION.ordinal());
Bundle b = new Bundle();
b.putFloat("lat", latitude);
b.putFloat("lon", longitude);
b.putString("q", address);
msg.setData(b);
msg.sendToTarget();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case Navit.NavitDownloaderPriSelectMap_id :
case Navit.NavitDownloaderSecSelectMap_id :
if (resultCode == Activity.RESULT_OK)
{
Message msg = dialogs.obtainMessage(NavitDialogs.MSG_START_MAP_DOWNLOAD
, data.getIntExtra("selected_id", -1)
, requestCode == Navit.NavitDownloaderSecSelectMap_id ? 2 : 0);
msg.sendToTarget();
}
break;
case NavitAddressSearch_id :
if (resultCode == Activity.RESULT_OK) {
Boolean addr_selected = data.getBooleanExtra("addr_selected", false);
// address already choosen, or do we have to search?
if (addr_selected) {
setDestination( NavitAddressResultList_foundItems .get(0).lat
, NavitAddressResultList_foundItems.get(0).lon
, NavitAddressResultList_foundItems.get(0).addr);
} else {
String addr = data.getStringExtra("address_string");
Boolean partial_match = data.getBooleanExtra("partial_match", false);
String country = data.getStringExtra("country");
NavitDialogs.Navit_last_address_partial_match = partial_match;
NavitDialogs.Navit_last_address_search_string = addr;
NavitDialogs.Navit_last_country = country;
// clear results
Navit.NavitAddressResultList_foundItems.clear();
Navit.search_results_towns = 0;
Navit.search_results_streets = 0;
Navit.search_results_streets_hn = 0;
if (addr.equals("")) {
// empty search string entered
Toast.makeText(getApplicationContext(),Navit.get_text("No search string entered"), Toast.LENGTH_LONG).show(); //TRANS
} else {
// show dialog, and start search for the results
// make it indirect, to give our activity a chance to startup
// (remember we come straight from another activity and ours is still paused!)
dialogs.obtainMessage(NavitDialogs.MSG_SEARCH).sendToTarget();
}
}
}
break;
case Navit.NavitAddressResultList_id :
try
{
if (resultCode == Activity.RESULT_OK)
{
int destination_id = data.getIntExtra("selected_id", 0);
setDestination( NavitAddressResultList_foundItems .get(destination_id).lat
, NavitAddressResultList_foundItems.get(destination_id).lon
, NavitAddressResultList_foundItems.get(destination_id).addr);
}
}
catch (Exception e)
{
Log.d("Navit", "error on onActivityResult");
}
break;
default :
//Log.e("Navit", "onActivityResult " + requestCode + " " + resultCode);
ActivityResults[requestCode].onActivityResult(requestCode, resultCode, data);
break;
}
}
protected Dialog onCreateDialog(int id)
{
return dialogs.createDialog(id);
}
@Override
public void onDestroy()
{
super.onDestroy();
Log.e("Navit", "OnDestroy");
// TODO next call will kill our app the hard way. This should not be necessary, but ensures navit is
// properly restarted and no resources are wasted with navit in background. Remove this call after
// code review
NavitDestroy();
}
public void disableSuspend()
{
wl.acquire();
wl.release();
}
public void exit()
{
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(R.string.app_name);
NavitVehicle.removeListener();
finish();
}
public native void NavitMain(Navit x, String lang, int version, String display_density_string, String path);
public native void NavitDestroy();
/*
* this is used to load the 'navit' native library on
* application startup. The library has already been unpacked at
* installation time by the package manager.
*/
static
{
System.loadLibrary("navit");
}
/*
* Show a search activity with the string "search" filled in
*/
private void executeSearch(String search)
{
Intent search_intent = new Intent(this, NavitAddressSearchActivity.class);
search_intent.putExtra("title", Navit.get_text("Enter: City and Street")); //TRANS
search_intent.putExtra("address_string", search);
search_intent.putExtra("partial_match", NavitDialogs.Navit_last_address_partial_match);
this.startActivityForResult(search_intent, NavitAddressSearch_id);
}
}
| false | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
dialogs = new NavitDialogs(this);
// only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.)
Navit.startup_intent = this.getIntent();
// hack! remeber timstamp, and only allow 4 secs. later in onResume to set target!
Navit.startup_intent_timestamp = System.currentTimeMillis();
Log.e("Navit", "**1**A " + startup_intent.getAction());
Log.e("Navit", "**1**D " + startup_intent.getDataString());
// init translated text
NavitTextTranslations.init();
// Setup a notification in the android notification bar, remove it in the exit() function
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,"Navit is running",0);
notification.flags = Notification.FLAG_NO_CLEAR;
PendingIntent appIntent = PendingIntent.getActivity(getApplicationContext(), 0, getIntent(), 0);
notification.setLatestEventInfo(getApplicationContext(), "Navit running", "Navit still running", appIntent);
nm.notify(R.string.app_name, notification);
// get the local language -------------
Locale locale = java.util.Locale.getDefault();
String lang = locale.getLanguage();
String langu = lang;
String langc = lang;
Log.e("Navit", "lang=" + lang);
int pos = langu.indexOf('_');
if (pos != -1)
{
langc = langu.substring(0, pos);
langu = langc + langu.substring(pos).toUpperCase(locale);
Log.e("Navit", "substring lang " + langu.substring(pos).toUpperCase(locale));
// set lang. for translation
NavitTextTranslations.main_language = langc;
NavitTextTranslations.sub_language = langu.substring(pos).toUpperCase(locale);
}
else
{
String country = locale.getCountry();
Log.e("Navit", "Country1 " + country);
Log.e("Navit", "Country2 " + country.toUpperCase(locale));
langu = langc + "_" + country.toUpperCase(locale);
// set lang. for translation
NavitTextTranslations.main_language = langc;
NavitTextTranslations.sub_language = country.toUpperCase(locale);
}
Log.e("Navit", "Language " + lang);
// get the local language -------------
// make sure the new path for the navitmap.bin file(s) exist!!
File navit_maps_dir = new File(MAP_FILENAME_PATH);
navit_maps_dir.mkdirs();
// make sure the share dir exists
File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR);
navit_data_share_dir.mkdirs();
// hardcoded strings for now, use routine down below later!!
if (lang.compareTo("de") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_de;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_de;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_de;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_de;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_de;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_de;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_de;
}
else if (lang.compareTo("fr") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_fr;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_fr;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_fr;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_fr;
}
else if (lang.compareTo("nl") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_nl;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_nl;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_nl;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_nl;
}
Display display_ = getWindowManager().getDefaultDisplay();
int width_ = display_.getWidth();
int height_ = display_.getHeight();
metrics = new DisplayMetrics();
display_.getMetrics(Navit.metrics);
int densityDpi = (int)(( Navit.metrics.density*160)+.5f);
Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_);
Log.e("Navit", "Navit -> dpi=" + densityDpi);
Log.e("Navit", "Navit -> density=" + Navit.metrics.density);
Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity);
ActivityResults = new NavitActivityResult[16];
setVolumeControlStream(AudioManager.STREAM_MUSIC);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"NavitDoNotDimScreen");
if (!extractRes(langc, NAVIT_DATA_DIR + "/locale/" + langc + "/LC_MESSAGES/navit.mo"))
{
Log.e("Navit", "Failed to extract language resource " + langc);
}
if (densityDpi <= 120)
{
my_display_density = "ldpi";
}
else if (densityDpi <= 160)
{
my_display_density = "mdpi";
}
else if (densityDpi < 320)
{
my_display_density = "hdpi";
}
else
{
Log.e("Navit", "found xhdpi device, this is not fully supported!!");
Log.e("Navit", "using hdpi values");
my_display_density = "hdpi";
}
if (!extractRes("navit" + my_display_density, NAVIT_DATA_DIR + "/share/navit.xml"))
{
Log.e("Navit", "Failed to extract navit.xml for " + my_display_density);
}
// --> dont use android.os.Build.VERSION.SDK_INT, needs API >= 4
Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK));
NavitMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density, NAVIT_DATA_DIR+"/bin/navit");
showInfos();
Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// unpack some localized Strings
// a test now, later we will unpack all needed string for java, here at this point!!
String x = NavitGraphics.getLocalizedString("Austria");
Log.e("Navit", "x=" + x);
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
dialogs = new NavitDialogs(this);
// only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.)
Navit.startup_intent = this.getIntent();
// hack! remeber timstamp, and only allow 4 secs. later in onResume to set target!
Navit.startup_intent_timestamp = System.currentTimeMillis();
Log.e("Navit", "**1**A " + startup_intent.getAction());
Log.e("Navit", "**1**D " + startup_intent.getDataString());
// init translated text
NavitTextTranslations.init();
// NOTIFICATION
// Setup the status bar notification
// This notification is removed in the exit() function
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Grab a handle to the NotificationManager
Notification NavitNotification = new Notification(R.drawable.icon,"Navit started",System.currentTimeMillis()); // Create a new notification, with the text string to show when the notification first appears
PendingIntent appIntent = PendingIntent.getActivity(getApplicationContext(), 0, getIntent(), 0);
NavitNotification.setLatestEventInfo(getApplicationContext(), "Navit", "Navit running", appIntent); // Set the text in the notification
NavitNotification.flags|=Notification.FLAG_ONGOING_EVENT; // Ensure that the notification appears in Ongoing
nm.notify(R.string.app_name, NavitNotification); // Set the notification
// get the local language -------------
Locale locale = java.util.Locale.getDefault();
String lang = locale.getLanguage();
String langu = lang;
String langc = lang;
Log.e("Navit", "lang=" + lang);
int pos = langu.indexOf('_');
if (pos != -1)
{
langc = langu.substring(0, pos);
langu = langc + langu.substring(pos).toUpperCase(locale);
Log.e("Navit", "substring lang " + langu.substring(pos).toUpperCase(locale));
// set lang. for translation
NavitTextTranslations.main_language = langc;
NavitTextTranslations.sub_language = langu.substring(pos).toUpperCase(locale);
}
else
{
String country = locale.getCountry();
Log.e("Navit", "Country1 " + country);
Log.e("Navit", "Country2 " + country.toUpperCase(locale));
langu = langc + "_" + country.toUpperCase(locale);
// set lang. for translation
NavitTextTranslations.main_language = langc;
NavitTextTranslations.sub_language = country.toUpperCase(locale);
}
Log.e("Navit", "Language " + lang);
// get the local language -------------
// make sure the new path for the navitmap.bin file(s) exist!!
File navit_maps_dir = new File(MAP_FILENAME_PATH);
navit_maps_dir.mkdirs();
// make sure the share dir exists
File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR);
navit_data_share_dir.mkdirs();
// hardcoded strings for now, use routine down below later!!
if (lang.compareTo("de") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_de;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_de;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_de;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_de;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_de;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_de;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_de;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_de;
}
else if (lang.compareTo("fr") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_fr;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_fr;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_fr;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_fr;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_fr;
}
else if (lang.compareTo("nl") == 0)
{
NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_first_map_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map = NavitTextTranslations.NAVIT_JAVA_MENU_download_second_map_nl;
NavitTextTranslations.INFO_BOX_TITLE = NavitTextTranslations.INFO_BOX_TITLE_nl;
NavitTextTranslations.INFO_BOX_TEXT = NavitTextTranslations.INFO_BOX_TEXT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO = NavitTextTranslations.NAVIT_JAVA_MENU_MOREINFO_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMIN_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT = NavitTextTranslations.NAVIT_JAVA_MENU_ZOOMOUT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_EXIT = NavitTextTranslations.NAVIT_JAVA_MENU_EXIT_nl;
NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI = NavitTextTranslations.NAVIT_JAVA_MENU_TOGGLE_POI_nl;
NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE = NavitTextTranslations.NAVIT_JAVA_OVERLAY_BUBBLE_DRIVEHERE_nl;
}
Display display_ = getWindowManager().getDefaultDisplay();
int width_ = display_.getWidth();
int height_ = display_.getHeight();
metrics = new DisplayMetrics();
display_.getMetrics(Navit.metrics);
int densityDpi = (int)(( Navit.metrics.density*160)+.5f);
Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_);
Log.e("Navit", "Navit -> dpi=" + densityDpi);
Log.e("Navit", "Navit -> density=" + Navit.metrics.density);
Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity);
ActivityResults = new NavitActivityResult[16];
setVolumeControlStream(AudioManager.STREAM_MUSIC);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"NavitDoNotDimScreen");
if (!extractRes(langc, NAVIT_DATA_DIR + "/locale/" + langc + "/LC_MESSAGES/navit.mo"))
{
Log.e("Navit", "Failed to extract language resource " + langc);
}
if (densityDpi <= 120)
{
my_display_density = "ldpi";
}
else if (densityDpi <= 160)
{
my_display_density = "mdpi";
}
else if (densityDpi < 320)
{
my_display_density = "hdpi";
}
else
{
Log.e("Navit", "found xhdpi device, this is not fully supported!!");
Log.e("Navit", "using hdpi values");
my_display_density = "hdpi";
}
if (!extractRes("navit" + my_display_density, NAVIT_DATA_DIR + "/share/navit.xml"))
{
Log.e("Navit", "Failed to extract navit.xml for " + my_display_density);
}
// --> dont use android.os.Build.VERSION.SDK_INT, needs API >= 4
Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK));
NavitMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density, NAVIT_DATA_DIR+"/bin/navit");
showInfos();
Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// unpack some localized Strings
// a test now, later we will unpack all needed string for java, here at this point!!
String x = NavitGraphics.getLocalizedString("Austria");
Log.e("Navit", "x=" + x);
}
|
diff --git a/pact/pact-compiler/src/main/java/eu/stratosphere/pact/compiler/plandump/PlanJSONDumpGenerator.java b/pact/pact-compiler/src/main/java/eu/stratosphere/pact/compiler/plandump/PlanJSONDumpGenerator.java
index 019ab6cba..5c14076e5 100644
--- a/pact/pact-compiler/src/main/java/eu/stratosphere/pact/compiler/plandump/PlanJSONDumpGenerator.java
+++ b/pact/pact-compiler/src/main/java/eu/stratosphere/pact/compiler/plandump/PlanJSONDumpGenerator.java
@@ -1,642 +1,645 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************/
package eu.stratosphere.pact.compiler.plandump;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import eu.stratosphere.pact.common.contract.CompilerHints;
import eu.stratosphere.pact.common.util.FieldSet;
import eu.stratosphere.pact.compiler.CompilerException;
import eu.stratosphere.pact.compiler.dataproperties.GlobalProperties;
import eu.stratosphere.pact.compiler.dataproperties.LocalProperties;
import eu.stratosphere.pact.compiler.plan.BinaryUnionNode;
import eu.stratosphere.pact.compiler.plan.BulkIterationNode;
import eu.stratosphere.pact.compiler.plan.DataSinkNode;
import eu.stratosphere.pact.compiler.plan.DataSourceNode;
import eu.stratosphere.pact.compiler.plan.OptimizerNode;
import eu.stratosphere.pact.compiler.plan.PactConnection;
import eu.stratosphere.pact.compiler.plan.TempMode;
import eu.stratosphere.pact.compiler.plan.WorksetIterationNode;
import eu.stratosphere.pact.compiler.plan.candidate.BulkIterationPlanNode;
import eu.stratosphere.pact.compiler.plan.candidate.Channel;
import eu.stratosphere.pact.compiler.plan.candidate.OptimizedPlan;
import eu.stratosphere.pact.compiler.plan.candidate.PlanNode;
import eu.stratosphere.pact.compiler.plan.candidate.SingleInputPlanNode;
import eu.stratosphere.pact.compiler.plan.candidate.SinkPlanNode;
import eu.stratosphere.pact.compiler.plan.candidate.UnionPlanNode;
import eu.stratosphere.pact.compiler.plan.candidate.WorksetIterationPlanNode;
import eu.stratosphere.pact.compiler.util.Utils;
import eu.stratosphere.pact.runtime.shipping.ShipStrategyType;
import eu.stratosphere.pact.runtime.task.DriverStrategy;
/**
*
*/
public class PlanJSONDumpGenerator {
private Map<DumpableNode<?>, Integer> nodeIds; // resolves pact nodes to ids
private int nodeCnt;
// --------------------------------------------------------------------------------------------
public void dumpPactPlanAsJSON(List<DataSinkNode> nodes, PrintWriter writer) {
@SuppressWarnings("unchecked")
List<DumpableNode<?>> n = (List<DumpableNode<?>>) (List<?>) nodes;
compilePlanToJSON(n, writer);
}
public String getPactPlanAsJSON(List<DataSinkNode> nodes) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
dumpPactPlanAsJSON(nodes, pw);
return sw.toString();
}
public void dumpOptimizerPlanAsJSON(OptimizedPlan plan, File toFile) throws IOException {
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(toFile), false);
dumpOptimizerPlanAsJSON(plan, pw);
pw.flush();
} finally {
if (pw != null) {
pw.close();
}
}
}
public String getOptimizerPlanAsJSON(OptimizedPlan plan) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
dumpOptimizerPlanAsJSON(plan, pw);
return sw.toString();
}
public void dumpOptimizerPlanAsJSON(OptimizedPlan plan, PrintWriter writer) {
Collection<SinkPlanNode> sinks = plan.getDataSinks();
if (sinks instanceof List) {
dumpOptimizerPlanAsJSON((List<SinkPlanNode>) sinks, writer);
} else {
List<SinkPlanNode> n = new ArrayList<SinkPlanNode>();
n.addAll(sinks);
dumpOptimizerPlanAsJSON(n, writer);
}
}
public void dumpOptimizerPlanAsJSON(List<SinkPlanNode> nodes, PrintWriter writer) {
@SuppressWarnings("unchecked")
List<DumpableNode<?>> n = (List<DumpableNode<?>>) (List<?>) nodes;
compilePlanToJSON(n, writer);
}
// --------------------------------------------------------------------------------------------
private void compilePlanToJSON(List<DumpableNode<?>> nodes, PrintWriter writer) {
// initialization to assign node ids
this.nodeIds = new HashMap<DumpableNode<?>, Integer>();
this.nodeCnt = 0;
// JSON header
writer.print("{\n\t\"nodes\": [\n\n");
// Generate JSON for plan
for (int i = 0; i < nodes.size(); i++) {
visit(nodes.get(i), writer, i == 0);
}
// JSON Footer
writer.println("\n\t]\n}");
}
private void visit(DumpableNode<?> node, PrintWriter writer, boolean first) {
// check for duplicate traversal
if (this.nodeIds.containsKey(node)) {
return;
}
// assign an id first
this.nodeIds.put(node, this.nodeCnt++);
// then recurse
for (Iterator<? extends DumpableNode<?>> children = node.getPredecessors(); children.hasNext(); ) {
final DumpableNode<?> child = children.next();
visit(child, writer, first);
first = false;
}
// check if this node should be skipped from the dump
final OptimizerNode n = node.getOptimizerNode();
// ------------------ dump after the ascend ---------------------
// start a new node and output node id
if (!first) {
writer.print(",\n");
}
// open the node
writer.print("\t{\n");
// recurse, it is is an iteration node
if (node instanceof BulkIterationNode || node instanceof BulkIterationPlanNode) {
DumpableNode<?> innerChild = node instanceof BulkIterationNode ?
((BulkIterationNode) node).getNextPartialSolution() :
((BulkIterationPlanNode) node).getRootOfStepFunction();
DumpableNode<?> begin = node instanceof BulkIterationNode ?
((BulkIterationNode) node).getPartialSolution() :
((BulkIterationPlanNode) node).getPartialSolutionPlanNode();
writer.print("\t\t\"step_function\": [\n");
visit(innerChild, writer, true);
writer.print("\n\t\t],\n");
writer.print("\t\t\"partial_solution\": " + this.nodeIds.get(begin) + ",\n");
writer.print("\t\t\"next_partial_solution\": " + this.nodeIds.get(innerChild) + ",\n");
} else if (node instanceof WorksetIterationNode || node instanceof WorksetIterationPlanNode) {
DumpableNode<?> worksetRoot = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getNextWorkset() :
((WorksetIterationPlanNode) node).getNextWorkSetPlanNode();
DumpableNode<?> solutionDelta = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getSolutionSetDelta() :
((WorksetIterationPlanNode) node).getSolutionSetDeltaPlanNode();
DumpableNode<?> workset = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getWorksetNode() :
((WorksetIterationPlanNode) node).getWorksetPlanNode();
DumpableNode<?> solutionSet = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getSolutionSetNode() :
((WorksetIterationPlanNode) node).getSolutionSetPlanNode();
writer.print("\t\t\"step_function\": [\n");
visit(worksetRoot, writer, true);
visit(solutionDelta, writer, false);
writer.print("\n\t\t],\n");
writer.print("\t\t\"workset\": " + this.nodeIds.get(workset) + ",\n");
writer.print("\t\t\"solution_set\": " + this.nodeIds.get(solutionSet) + ",\n");
writer.print("\t\t\"next_workset\": " + this.nodeIds.get(worksetRoot) + ",\n");
writer.print("\t\t\"solution_delta\": " + this.nodeIds.get(solutionDelta) + ",\n");
}
// print the id
writer.print("\t\t\"id\": " + this.nodeIds.get(node));
final String type;
final String contents;
if (n instanceof DataSinkNode) {
type = "sink";
contents = n.getPactContract().toString();
} else if (n instanceof DataSourceNode) {
type = "source";
contents = n.getPactContract().toString();
} else if (n instanceof BulkIterationNode) {
type = "bulk_iteration";
contents = n.getPactContract().getName();
} else if (n instanceof WorksetIterationNode) {
type = "workset_iteration";
contents = n.getPactContract().getName();
} else if (n instanceof BinaryUnionNode) {
type = "pact";
contents = "";
} else {
type = "pact";
contents = n.getPactContract().getName();
}
String name = n.getName();
if (name.equals("Reduce") && (node instanceof SingleInputPlanNode) &&
((SingleInputPlanNode) node).getDriverStrategy() == DriverStrategy.PARTIAL_GROUP) {
name = "Combine";
}
// output the type identifier
writer.print(",\n\t\t\"type\": \"" + type + "\"");
// output node name
writer.print(",\n\t\t\"pact\": \"" + name + "\"");
// output node contents
writer.print(",\n\t\t\"contents\": \"" + contents + "\"");
// degree of parallelism
writer.print(",\n\t\t\"parallelism\": \""
+ (n.getDegreeOfParallelism() >= 1 ? n.getDegreeOfParallelism() : "default") + "\"");
writer.print(",\n\t\t\"subtasks_per_instance\": \""
+ (n.getSubtasksPerInstance() >= 1 ? n.getSubtasksPerInstance() : "default") + "\"");
// output node predecessors
Iterator<? extends DumpableConnection<?>> inConns = node.getDumpableInputs();
String child1name = "", child2name = "";
if (inConns != null && inConns.hasNext()) {
// start predecessor list
writer.print(",\n\t\t\"predecessors\": [");
int connNum = 0;
int inputNum = 0;
while (inConns.hasNext()) {
final DumpableConnection<?> conn = inConns.next();
final Collection<DumpableConnection<?>> inConnsForInput;
if (conn.getSource() instanceof UnionPlanNode) {
inConnsForInput = new ArrayList<DumpableConnection<?>>();
for (Iterator<? extends DumpableConnection<?>> inputOfUnion = conn.getSource().getDumpableInputs(); inputOfUnion.hasNext();) {
inConnsForInput.add(inputOfUnion.next());
}
}
else {
inConnsForInput = Collections.<DumpableConnection<?>>singleton(conn);
}
for (DumpableConnection<?> inConn : inConnsForInput) {
final DumpableNode<?> source = inConn.getSource();
writer.print(connNum == 0 ? "\n" : ",\n");
if (connNum == 0) {
child1name += child1name.length() > 0 ? ", " : "";
child1name += source.getOptimizerNode().getPactContract().getName();
} else if (connNum == 1) {
child2name += child2name.length() > 0 ? ", " : "";
child2name = source.getOptimizerNode().getPactContract().getName();
}
// output predecessor id
writer.print("\t\t\t{\"id\": " + this.nodeIds.get(source));
// output connection side
if (inConns.hasNext() || inputNum > 0) {
writer.print(", \"side\": \"" + (inputNum == 0 ? "first" : "second") + "\"");
}
// output shipping strategy and channel type
final Channel channel = (inConn instanceof Channel) ? (Channel) inConn : null;
final ShipStrategyType shipType = channel != null ? channel.getShipStrategy() :
((PactConnection) inConn).getShipStrategy();
String shipStrategy = null;
if (shipType != null) {
switch (shipType) {
case NONE:
// nothing
break;
case FORWARD:
shipStrategy = "Forward";
break;
case BROADCAST:
shipStrategy = "Broadcast";
break;
case PARTITION_HASH:
shipStrategy = "Hash Partition";
break;
case PARTITION_RANGE:
shipStrategy = "Range Partition";
break;
case PARTITION_LOCAL_HASH:
shipStrategy = "Hash Partition (local)";
break;
case PARTITION_RANDOM:
shipStrategy = "Redistribute";
break;
default:
throw new CompilerException("Unknown ship strategy '" + conn.getShipStrategy().name()
+ "' in JSON generator.");
}
}
if (channel != null && channel.getShipStrategyKeys() != null && channel.getShipStrategyKeys().size() > 0) {
shipStrategy += " on " + (channel.getShipStrategySortOrder() == null ?
channel.getShipStrategyKeys().toString() :
Utils.createOrdering(channel.getShipStrategyKeys(), channel.getShipStrategySortOrder()).toString());
}
if (shipStrategy != null) {
writer.print(", \"ship_strategy\": \"" + shipStrategy + "\"");
}
if (channel != null) {
String localStrategy = null;
switch (channel.getLocalStrategy()) {
case NONE:
break;
case SORT:
localStrategy = "Sort";
break;
case COMBININGSORT:
localStrategy = "Sort (combining)";
break;
default:
throw new CompilerException("Unknown local strategy " + channel.getLocalStrategy().name());
}
if (channel != null && channel.getLocalStrategyKeys() != null && channel.getLocalStrategyKeys().size() > 0) {
localStrategy += " on " + (channel.getLocalStrategySortOrder() == null ?
channel.getLocalStrategyKeys().toString() :
Utils.createOrdering(channel.getLocalStrategyKeys(), channel.getLocalStrategySortOrder()).toString());
}
if (localStrategy != null) {
writer.print(", \"local_strategy\": \"" + localStrategy + "\"");
}
if (channel != null && channel.getTempMode() != TempMode.NONE) {
String tempMode = channel.getTempMode().toString();
writer.print(", \"temp_mode\": \"" + tempMode + "\"");
}
}
writer.print('}');
connNum++;
}
inputNum++;
}
// finish predecessors
writer.print("\n\t\t]");
}
//---------------------------------------------------------------------------------------
// the part below here is relevant only to plan nodes with concrete strategies, etc
//---------------------------------------------------------------------------------------
final PlanNode p = node.getPlanNode();
if (p == null) {
// finish node
writer.print("\n\t}");
return;
}
// local strategy
String locString = null;
if (p.getDriverStrategy() != null) {
switch (p.getDriverStrategy()) {
case NONE:
break;
case MAP:
locString = "Map";
break;
case PARTIAL_GROUP:
locString = "Ordered Partial Grouping";
break;
case SORTED_GROUP:
locString = "Ordered Grouping";
break;
+ case ALL_GROUP:
+ locString = "Group all into a single group";
+ break;
case HYBRIDHASH_BUILD_FIRST:
locString = "Hybrid Hash (build: " + child1name + ")";
break;
case HYBRIDHASH_BUILD_SECOND:
locString = "Hybrid Hash (build: " + child2name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_FIRST:
locString = "Nested Loops (Blocked Outer: " + child1name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_SECOND:
locString = "Nested Loops (Blocked Outer: " + child2name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_FIRST:
locString = "Nested Loops (Streamed Outer: " + child1name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_SECOND:
locString = "Nested Loops (Streamed Outer: " + child2name + ")";
break;
case MERGE:
locString = "Merge";
break;
case CO_GROUP:
locString = "Co-Group";
break;
default:
throw new CompilerException("Unknown local strategy '" + p.getDriverStrategy().name()
+ "' in JSON generator.");
}
if (locString != null) {
writer.print(",\n\t\t\"driver_strategy\": \"");
writer.print(locString);
writer.print("\"");
}
}
{
// output node global properties
final GlobalProperties gp = p.getGlobalProperties();
writer.print(",\n\t\t\"global_properties\": [\n");
addProperty(writer, "Partitioning", gp.getPartitioning().name(), true);
if (gp.getPartitioningFields() != null) {
addProperty(writer, "Partitioned on", gp.getPartitioningFields().toString(), false);
}
if (gp.getPartitioningOrdering() != null) {
addProperty(writer, "Partitioning Order", gp.getPartitioningOrdering().toString(), false);
}
else {
addProperty(writer, "Partitioning Order", "(none)", false);
}
if (n.getUniqueFields() == null || n.getUniqueFields().size() == 0) {
addProperty(writer, "Uniqueness", "not unique", false);
}
else {
addProperty(writer, "Uniqueness", n.getUniqueFields().toString(), false);
}
writer.print("\n\t\t]");
}
{
// output node local properties
LocalProperties lp = p.getLocalProperties();
writer.print(",\n\t\t\"local_properties\": [\n");
if (lp.getOrdering() != null) {
addProperty(writer, "Order", lp.getOrdering().toString(), true);
}
else {
addProperty(writer, "Order", "(none)", true);
}
if (lp.getGroupedFields() != null && lp.getGroupedFields().size() > 0) {
addProperty(writer, "Grouped on", lp.getGroupedFields().toString(), false);
} else {
addProperty(writer, "Grouping", "not grouped", false);
}
if (n.getUniqueFields() == null || n.getUniqueFields().size() == 0) {
addProperty(writer, "Uniqueness", "not unique", false);
}
else {
addProperty(writer, "Uniqueness", n.getUniqueFields().toString(), false);
}
writer.print("\n\t\t]");
}
// output node size estimates
writer.print(",\n\t\t\"estimates\": [\n");
addProperty(writer, "Est. Output Size", n.getEstimatedOutputSize() == -1 ? "(unknown)"
: formatNumber(n.getEstimatedOutputSize(), "B"), true);
addProperty(writer, "Est. Cardinality", n.getEstimatedNumRecords() == -1 ? "(unknown)"
: formatNumber(n.getEstimatedNumRecords()), false);
String estCardinality = "(unknown)";
if (n.getEstimatedCardinalities().size() > 0) {
estCardinality = "";
for (Entry<FieldSet, Long> entry : n.getEstimatedCardinalities().entrySet()) {
estCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(writer, "Est. Cardinality/fields", estCardinality, false);
writer.print("\t\t]");
// output node cost
if (p.getNodeCosts() != null) {
writer.print(",\n\t\t\"costs\": [\n");
addProperty(writer, "Network", p.getNodeCosts().getNetworkCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getNetworkCost(), "B"), true);
addProperty(writer, "Disk I/O", p.getNodeCosts().getDiskCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getDiskCost(), "B"), false);
addProperty(writer, "CPU", p.getNodeCosts().getCpuCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getCpuCost(), ""), false);
addProperty(writer, "Cumulative Network",
p.getCumulativeCosts().getNetworkCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getNetworkCost(), "B"), false);
addProperty(writer, "Cumulative Disk I/O",
p.getCumulativeCosts().getDiskCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getDiskCost(), "B"), false);
addProperty(writer, "Cumulative CPU",
p.getCumulativeCosts().getCpuCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getCpuCost(), ""), false);
writer.print("\n\t\t]");
}
// output the node compiler hints
if (n.getPactContract().getCompilerHints() != null) {
CompilerHints hints = n.getPactContract().getCompilerHints();
CompilerHints defaults = new CompilerHints();
writer.print(",\n\t\t\"compiler_hints\": [\n");
String hintCardinality;
if (hints.getDistinctCounts().size() > 0) {
hintCardinality = "";
for (Entry<FieldSet, Long> entry : hints.getDistinctCounts().entrySet()) {
hintCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
} else {
hintCardinality = "(none)";
}
addProperty(writer, "Cardinality", hintCardinality, true);
addProperty(writer, "Avg. Records/StubCall", hints.getAvgRecordsEmittedPerStubCall() == defaults.
getAvgRecordsEmittedPerStubCall() ? "(none)" : String.valueOf(hints.getAvgRecordsEmittedPerStubCall()), false);
String valuesKey;
if (hints.getAvgNumRecordsPerDistinctFields().size() > 0) {
valuesKey = "";
for (Entry<FieldSet, Float> entry : hints.getAvgNumRecordsPerDistinctFields().entrySet()) {
valuesKey += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
} else {
valuesKey = "(none)";
}
addProperty(writer, "Avg. Values/Distinct fields", valuesKey, false);
addProperty(writer, "Avg. Width (bytes)", hints.getAvgBytesPerRecord() == defaults
.getAvgBytesPerRecord() ? "(none)" : String.valueOf(hints.getAvgBytesPerRecord()), false);
writer.print("\t\t]");
}
// finish node
writer.print("\n\t}");
}
private void addProperty(PrintWriter writer, String name, String value, boolean first) {
if (!first) {
writer.print(",\n");
}
writer.print("\t\t\t{ \"name\": \"");
writer.print(name);
writer.print("\", \"value\": \"");
writer.print(value);
writer.print("\" }");
}
public static final String formatNumber(long number) {
return formatNumber(number, "");
}
public static final String formatNumber(long number, String suffix) {
final int fractionalDigits = 2;
StringBuilder bld = new StringBuilder();
bld.append(number);
int len = bld.length();
// get the power of 10 / 3
int pot = (len - (bld.charAt(0) == '-' ? 2 : 1)) / 3;
if (pot >= SIZE_SUFFIXES.length) {
pot = SIZE_SUFFIXES.length - 1;
} else if (pot < 0) {
pot = 0;
}
int beforeDecimal = len - pot * 3;
if (len > beforeDecimal + fractionalDigits) {
bld.setLength(beforeDecimal + fractionalDigits);
}
// insert decimal point
if (pot > 0) {
bld.insert(beforeDecimal, '.');
}
// insert number grouping before decimal point
for (int pos = beforeDecimal - 3; pos > 0; pos -= 3) {
bld.insert(pos, ',');
}
// append the suffix
bld.append(' ');
if (pot > 0) {
bld.append(SIZE_SUFFIXES[pot]);
}
bld.append(suffix);
return bld.toString();
}
private static final char[] SIZE_SUFFIXES = { 0, 'K', 'M', 'G', 'T' };
}
| true | true | private void visit(DumpableNode<?> node, PrintWriter writer, boolean first) {
// check for duplicate traversal
if (this.nodeIds.containsKey(node)) {
return;
}
// assign an id first
this.nodeIds.put(node, this.nodeCnt++);
// then recurse
for (Iterator<? extends DumpableNode<?>> children = node.getPredecessors(); children.hasNext(); ) {
final DumpableNode<?> child = children.next();
visit(child, writer, first);
first = false;
}
// check if this node should be skipped from the dump
final OptimizerNode n = node.getOptimizerNode();
// ------------------ dump after the ascend ---------------------
// start a new node and output node id
if (!first) {
writer.print(",\n");
}
// open the node
writer.print("\t{\n");
// recurse, it is is an iteration node
if (node instanceof BulkIterationNode || node instanceof BulkIterationPlanNode) {
DumpableNode<?> innerChild = node instanceof BulkIterationNode ?
((BulkIterationNode) node).getNextPartialSolution() :
((BulkIterationPlanNode) node).getRootOfStepFunction();
DumpableNode<?> begin = node instanceof BulkIterationNode ?
((BulkIterationNode) node).getPartialSolution() :
((BulkIterationPlanNode) node).getPartialSolutionPlanNode();
writer.print("\t\t\"step_function\": [\n");
visit(innerChild, writer, true);
writer.print("\n\t\t],\n");
writer.print("\t\t\"partial_solution\": " + this.nodeIds.get(begin) + ",\n");
writer.print("\t\t\"next_partial_solution\": " + this.nodeIds.get(innerChild) + ",\n");
} else if (node instanceof WorksetIterationNode || node instanceof WorksetIterationPlanNode) {
DumpableNode<?> worksetRoot = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getNextWorkset() :
((WorksetIterationPlanNode) node).getNextWorkSetPlanNode();
DumpableNode<?> solutionDelta = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getSolutionSetDelta() :
((WorksetIterationPlanNode) node).getSolutionSetDeltaPlanNode();
DumpableNode<?> workset = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getWorksetNode() :
((WorksetIterationPlanNode) node).getWorksetPlanNode();
DumpableNode<?> solutionSet = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getSolutionSetNode() :
((WorksetIterationPlanNode) node).getSolutionSetPlanNode();
writer.print("\t\t\"step_function\": [\n");
visit(worksetRoot, writer, true);
visit(solutionDelta, writer, false);
writer.print("\n\t\t],\n");
writer.print("\t\t\"workset\": " + this.nodeIds.get(workset) + ",\n");
writer.print("\t\t\"solution_set\": " + this.nodeIds.get(solutionSet) + ",\n");
writer.print("\t\t\"next_workset\": " + this.nodeIds.get(worksetRoot) + ",\n");
writer.print("\t\t\"solution_delta\": " + this.nodeIds.get(solutionDelta) + ",\n");
}
// print the id
writer.print("\t\t\"id\": " + this.nodeIds.get(node));
final String type;
final String contents;
if (n instanceof DataSinkNode) {
type = "sink";
contents = n.getPactContract().toString();
} else if (n instanceof DataSourceNode) {
type = "source";
contents = n.getPactContract().toString();
} else if (n instanceof BulkIterationNode) {
type = "bulk_iteration";
contents = n.getPactContract().getName();
} else if (n instanceof WorksetIterationNode) {
type = "workset_iteration";
contents = n.getPactContract().getName();
} else if (n instanceof BinaryUnionNode) {
type = "pact";
contents = "";
} else {
type = "pact";
contents = n.getPactContract().getName();
}
String name = n.getName();
if (name.equals("Reduce") && (node instanceof SingleInputPlanNode) &&
((SingleInputPlanNode) node).getDriverStrategy() == DriverStrategy.PARTIAL_GROUP) {
name = "Combine";
}
// output the type identifier
writer.print(",\n\t\t\"type\": \"" + type + "\"");
// output node name
writer.print(",\n\t\t\"pact\": \"" + name + "\"");
// output node contents
writer.print(",\n\t\t\"contents\": \"" + contents + "\"");
// degree of parallelism
writer.print(",\n\t\t\"parallelism\": \""
+ (n.getDegreeOfParallelism() >= 1 ? n.getDegreeOfParallelism() : "default") + "\"");
writer.print(",\n\t\t\"subtasks_per_instance\": \""
+ (n.getSubtasksPerInstance() >= 1 ? n.getSubtasksPerInstance() : "default") + "\"");
// output node predecessors
Iterator<? extends DumpableConnection<?>> inConns = node.getDumpableInputs();
String child1name = "", child2name = "";
if (inConns != null && inConns.hasNext()) {
// start predecessor list
writer.print(",\n\t\t\"predecessors\": [");
int connNum = 0;
int inputNum = 0;
while (inConns.hasNext()) {
final DumpableConnection<?> conn = inConns.next();
final Collection<DumpableConnection<?>> inConnsForInput;
if (conn.getSource() instanceof UnionPlanNode) {
inConnsForInput = new ArrayList<DumpableConnection<?>>();
for (Iterator<? extends DumpableConnection<?>> inputOfUnion = conn.getSource().getDumpableInputs(); inputOfUnion.hasNext();) {
inConnsForInput.add(inputOfUnion.next());
}
}
else {
inConnsForInput = Collections.<DumpableConnection<?>>singleton(conn);
}
for (DumpableConnection<?> inConn : inConnsForInput) {
final DumpableNode<?> source = inConn.getSource();
writer.print(connNum == 0 ? "\n" : ",\n");
if (connNum == 0) {
child1name += child1name.length() > 0 ? ", " : "";
child1name += source.getOptimizerNode().getPactContract().getName();
} else if (connNum == 1) {
child2name += child2name.length() > 0 ? ", " : "";
child2name = source.getOptimizerNode().getPactContract().getName();
}
// output predecessor id
writer.print("\t\t\t{\"id\": " + this.nodeIds.get(source));
// output connection side
if (inConns.hasNext() || inputNum > 0) {
writer.print(", \"side\": \"" + (inputNum == 0 ? "first" : "second") + "\"");
}
// output shipping strategy and channel type
final Channel channel = (inConn instanceof Channel) ? (Channel) inConn : null;
final ShipStrategyType shipType = channel != null ? channel.getShipStrategy() :
((PactConnection) inConn).getShipStrategy();
String shipStrategy = null;
if (shipType != null) {
switch (shipType) {
case NONE:
// nothing
break;
case FORWARD:
shipStrategy = "Forward";
break;
case BROADCAST:
shipStrategy = "Broadcast";
break;
case PARTITION_HASH:
shipStrategy = "Hash Partition";
break;
case PARTITION_RANGE:
shipStrategy = "Range Partition";
break;
case PARTITION_LOCAL_HASH:
shipStrategy = "Hash Partition (local)";
break;
case PARTITION_RANDOM:
shipStrategy = "Redistribute";
break;
default:
throw new CompilerException("Unknown ship strategy '" + conn.getShipStrategy().name()
+ "' in JSON generator.");
}
}
if (channel != null && channel.getShipStrategyKeys() != null && channel.getShipStrategyKeys().size() > 0) {
shipStrategy += " on " + (channel.getShipStrategySortOrder() == null ?
channel.getShipStrategyKeys().toString() :
Utils.createOrdering(channel.getShipStrategyKeys(), channel.getShipStrategySortOrder()).toString());
}
if (shipStrategy != null) {
writer.print(", \"ship_strategy\": \"" + shipStrategy + "\"");
}
if (channel != null) {
String localStrategy = null;
switch (channel.getLocalStrategy()) {
case NONE:
break;
case SORT:
localStrategy = "Sort";
break;
case COMBININGSORT:
localStrategy = "Sort (combining)";
break;
default:
throw new CompilerException("Unknown local strategy " + channel.getLocalStrategy().name());
}
if (channel != null && channel.getLocalStrategyKeys() != null && channel.getLocalStrategyKeys().size() > 0) {
localStrategy += " on " + (channel.getLocalStrategySortOrder() == null ?
channel.getLocalStrategyKeys().toString() :
Utils.createOrdering(channel.getLocalStrategyKeys(), channel.getLocalStrategySortOrder()).toString());
}
if (localStrategy != null) {
writer.print(", \"local_strategy\": \"" + localStrategy + "\"");
}
if (channel != null && channel.getTempMode() != TempMode.NONE) {
String tempMode = channel.getTempMode().toString();
writer.print(", \"temp_mode\": \"" + tempMode + "\"");
}
}
writer.print('}');
connNum++;
}
inputNum++;
}
// finish predecessors
writer.print("\n\t\t]");
}
//---------------------------------------------------------------------------------------
// the part below here is relevant only to plan nodes with concrete strategies, etc
//---------------------------------------------------------------------------------------
final PlanNode p = node.getPlanNode();
if (p == null) {
// finish node
writer.print("\n\t}");
return;
}
// local strategy
String locString = null;
if (p.getDriverStrategy() != null) {
switch (p.getDriverStrategy()) {
case NONE:
break;
case MAP:
locString = "Map";
break;
case PARTIAL_GROUP:
locString = "Ordered Partial Grouping";
break;
case SORTED_GROUP:
locString = "Ordered Grouping";
break;
case HYBRIDHASH_BUILD_FIRST:
locString = "Hybrid Hash (build: " + child1name + ")";
break;
case HYBRIDHASH_BUILD_SECOND:
locString = "Hybrid Hash (build: " + child2name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_FIRST:
locString = "Nested Loops (Blocked Outer: " + child1name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_SECOND:
locString = "Nested Loops (Blocked Outer: " + child2name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_FIRST:
locString = "Nested Loops (Streamed Outer: " + child1name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_SECOND:
locString = "Nested Loops (Streamed Outer: " + child2name + ")";
break;
case MERGE:
locString = "Merge";
break;
case CO_GROUP:
locString = "Co-Group";
break;
default:
throw new CompilerException("Unknown local strategy '" + p.getDriverStrategy().name()
+ "' in JSON generator.");
}
if (locString != null) {
writer.print(",\n\t\t\"driver_strategy\": \"");
writer.print(locString);
writer.print("\"");
}
}
{
// output node global properties
final GlobalProperties gp = p.getGlobalProperties();
writer.print(",\n\t\t\"global_properties\": [\n");
addProperty(writer, "Partitioning", gp.getPartitioning().name(), true);
if (gp.getPartitioningFields() != null) {
addProperty(writer, "Partitioned on", gp.getPartitioningFields().toString(), false);
}
if (gp.getPartitioningOrdering() != null) {
addProperty(writer, "Partitioning Order", gp.getPartitioningOrdering().toString(), false);
}
else {
addProperty(writer, "Partitioning Order", "(none)", false);
}
if (n.getUniqueFields() == null || n.getUniqueFields().size() == 0) {
addProperty(writer, "Uniqueness", "not unique", false);
}
else {
addProperty(writer, "Uniqueness", n.getUniqueFields().toString(), false);
}
writer.print("\n\t\t]");
}
{
// output node local properties
LocalProperties lp = p.getLocalProperties();
writer.print(",\n\t\t\"local_properties\": [\n");
if (lp.getOrdering() != null) {
addProperty(writer, "Order", lp.getOrdering().toString(), true);
}
else {
addProperty(writer, "Order", "(none)", true);
}
if (lp.getGroupedFields() != null && lp.getGroupedFields().size() > 0) {
addProperty(writer, "Grouped on", lp.getGroupedFields().toString(), false);
} else {
addProperty(writer, "Grouping", "not grouped", false);
}
if (n.getUniqueFields() == null || n.getUniqueFields().size() == 0) {
addProperty(writer, "Uniqueness", "not unique", false);
}
else {
addProperty(writer, "Uniqueness", n.getUniqueFields().toString(), false);
}
writer.print("\n\t\t]");
}
// output node size estimates
writer.print(",\n\t\t\"estimates\": [\n");
addProperty(writer, "Est. Output Size", n.getEstimatedOutputSize() == -1 ? "(unknown)"
: formatNumber(n.getEstimatedOutputSize(), "B"), true);
addProperty(writer, "Est. Cardinality", n.getEstimatedNumRecords() == -1 ? "(unknown)"
: formatNumber(n.getEstimatedNumRecords()), false);
String estCardinality = "(unknown)";
if (n.getEstimatedCardinalities().size() > 0) {
estCardinality = "";
for (Entry<FieldSet, Long> entry : n.getEstimatedCardinalities().entrySet()) {
estCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(writer, "Est. Cardinality/fields", estCardinality, false);
writer.print("\t\t]");
// output node cost
if (p.getNodeCosts() != null) {
writer.print(",\n\t\t\"costs\": [\n");
addProperty(writer, "Network", p.getNodeCosts().getNetworkCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getNetworkCost(), "B"), true);
addProperty(writer, "Disk I/O", p.getNodeCosts().getDiskCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getDiskCost(), "B"), false);
addProperty(writer, "CPU", p.getNodeCosts().getCpuCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getCpuCost(), ""), false);
addProperty(writer, "Cumulative Network",
p.getCumulativeCosts().getNetworkCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getNetworkCost(), "B"), false);
addProperty(writer, "Cumulative Disk I/O",
p.getCumulativeCosts().getDiskCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getDiskCost(), "B"), false);
addProperty(writer, "Cumulative CPU",
p.getCumulativeCosts().getCpuCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getCpuCost(), ""), false);
writer.print("\n\t\t]");
}
// output the node compiler hints
if (n.getPactContract().getCompilerHints() != null) {
CompilerHints hints = n.getPactContract().getCompilerHints();
CompilerHints defaults = new CompilerHints();
writer.print(",\n\t\t\"compiler_hints\": [\n");
String hintCardinality;
if (hints.getDistinctCounts().size() > 0) {
hintCardinality = "";
for (Entry<FieldSet, Long> entry : hints.getDistinctCounts().entrySet()) {
hintCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
} else {
hintCardinality = "(none)";
}
addProperty(writer, "Cardinality", hintCardinality, true);
addProperty(writer, "Avg. Records/StubCall", hints.getAvgRecordsEmittedPerStubCall() == defaults.
getAvgRecordsEmittedPerStubCall() ? "(none)" : String.valueOf(hints.getAvgRecordsEmittedPerStubCall()), false);
String valuesKey;
if (hints.getAvgNumRecordsPerDistinctFields().size() > 0) {
valuesKey = "";
for (Entry<FieldSet, Float> entry : hints.getAvgNumRecordsPerDistinctFields().entrySet()) {
valuesKey += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
} else {
valuesKey = "(none)";
}
addProperty(writer, "Avg. Values/Distinct fields", valuesKey, false);
addProperty(writer, "Avg. Width (bytes)", hints.getAvgBytesPerRecord() == defaults
.getAvgBytesPerRecord() ? "(none)" : String.valueOf(hints.getAvgBytesPerRecord()), false);
writer.print("\t\t]");
}
// finish node
writer.print("\n\t}");
}
| private void visit(DumpableNode<?> node, PrintWriter writer, boolean first) {
// check for duplicate traversal
if (this.nodeIds.containsKey(node)) {
return;
}
// assign an id first
this.nodeIds.put(node, this.nodeCnt++);
// then recurse
for (Iterator<? extends DumpableNode<?>> children = node.getPredecessors(); children.hasNext(); ) {
final DumpableNode<?> child = children.next();
visit(child, writer, first);
first = false;
}
// check if this node should be skipped from the dump
final OptimizerNode n = node.getOptimizerNode();
// ------------------ dump after the ascend ---------------------
// start a new node and output node id
if (!first) {
writer.print(",\n");
}
// open the node
writer.print("\t{\n");
// recurse, it is is an iteration node
if (node instanceof BulkIterationNode || node instanceof BulkIterationPlanNode) {
DumpableNode<?> innerChild = node instanceof BulkIterationNode ?
((BulkIterationNode) node).getNextPartialSolution() :
((BulkIterationPlanNode) node).getRootOfStepFunction();
DumpableNode<?> begin = node instanceof BulkIterationNode ?
((BulkIterationNode) node).getPartialSolution() :
((BulkIterationPlanNode) node).getPartialSolutionPlanNode();
writer.print("\t\t\"step_function\": [\n");
visit(innerChild, writer, true);
writer.print("\n\t\t],\n");
writer.print("\t\t\"partial_solution\": " + this.nodeIds.get(begin) + ",\n");
writer.print("\t\t\"next_partial_solution\": " + this.nodeIds.get(innerChild) + ",\n");
} else if (node instanceof WorksetIterationNode || node instanceof WorksetIterationPlanNode) {
DumpableNode<?> worksetRoot = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getNextWorkset() :
((WorksetIterationPlanNode) node).getNextWorkSetPlanNode();
DumpableNode<?> solutionDelta = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getSolutionSetDelta() :
((WorksetIterationPlanNode) node).getSolutionSetDeltaPlanNode();
DumpableNode<?> workset = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getWorksetNode() :
((WorksetIterationPlanNode) node).getWorksetPlanNode();
DumpableNode<?> solutionSet = node instanceof WorksetIterationNode ?
((WorksetIterationNode) node).getSolutionSetNode() :
((WorksetIterationPlanNode) node).getSolutionSetPlanNode();
writer.print("\t\t\"step_function\": [\n");
visit(worksetRoot, writer, true);
visit(solutionDelta, writer, false);
writer.print("\n\t\t],\n");
writer.print("\t\t\"workset\": " + this.nodeIds.get(workset) + ",\n");
writer.print("\t\t\"solution_set\": " + this.nodeIds.get(solutionSet) + ",\n");
writer.print("\t\t\"next_workset\": " + this.nodeIds.get(worksetRoot) + ",\n");
writer.print("\t\t\"solution_delta\": " + this.nodeIds.get(solutionDelta) + ",\n");
}
// print the id
writer.print("\t\t\"id\": " + this.nodeIds.get(node));
final String type;
final String contents;
if (n instanceof DataSinkNode) {
type = "sink";
contents = n.getPactContract().toString();
} else if (n instanceof DataSourceNode) {
type = "source";
contents = n.getPactContract().toString();
} else if (n instanceof BulkIterationNode) {
type = "bulk_iteration";
contents = n.getPactContract().getName();
} else if (n instanceof WorksetIterationNode) {
type = "workset_iteration";
contents = n.getPactContract().getName();
} else if (n instanceof BinaryUnionNode) {
type = "pact";
contents = "";
} else {
type = "pact";
contents = n.getPactContract().getName();
}
String name = n.getName();
if (name.equals("Reduce") && (node instanceof SingleInputPlanNode) &&
((SingleInputPlanNode) node).getDriverStrategy() == DriverStrategy.PARTIAL_GROUP) {
name = "Combine";
}
// output the type identifier
writer.print(",\n\t\t\"type\": \"" + type + "\"");
// output node name
writer.print(",\n\t\t\"pact\": \"" + name + "\"");
// output node contents
writer.print(",\n\t\t\"contents\": \"" + contents + "\"");
// degree of parallelism
writer.print(",\n\t\t\"parallelism\": \""
+ (n.getDegreeOfParallelism() >= 1 ? n.getDegreeOfParallelism() : "default") + "\"");
writer.print(",\n\t\t\"subtasks_per_instance\": \""
+ (n.getSubtasksPerInstance() >= 1 ? n.getSubtasksPerInstance() : "default") + "\"");
// output node predecessors
Iterator<? extends DumpableConnection<?>> inConns = node.getDumpableInputs();
String child1name = "", child2name = "";
if (inConns != null && inConns.hasNext()) {
// start predecessor list
writer.print(",\n\t\t\"predecessors\": [");
int connNum = 0;
int inputNum = 0;
while (inConns.hasNext()) {
final DumpableConnection<?> conn = inConns.next();
final Collection<DumpableConnection<?>> inConnsForInput;
if (conn.getSource() instanceof UnionPlanNode) {
inConnsForInput = new ArrayList<DumpableConnection<?>>();
for (Iterator<? extends DumpableConnection<?>> inputOfUnion = conn.getSource().getDumpableInputs(); inputOfUnion.hasNext();) {
inConnsForInput.add(inputOfUnion.next());
}
}
else {
inConnsForInput = Collections.<DumpableConnection<?>>singleton(conn);
}
for (DumpableConnection<?> inConn : inConnsForInput) {
final DumpableNode<?> source = inConn.getSource();
writer.print(connNum == 0 ? "\n" : ",\n");
if (connNum == 0) {
child1name += child1name.length() > 0 ? ", " : "";
child1name += source.getOptimizerNode().getPactContract().getName();
} else if (connNum == 1) {
child2name += child2name.length() > 0 ? ", " : "";
child2name = source.getOptimizerNode().getPactContract().getName();
}
// output predecessor id
writer.print("\t\t\t{\"id\": " + this.nodeIds.get(source));
// output connection side
if (inConns.hasNext() || inputNum > 0) {
writer.print(", \"side\": \"" + (inputNum == 0 ? "first" : "second") + "\"");
}
// output shipping strategy and channel type
final Channel channel = (inConn instanceof Channel) ? (Channel) inConn : null;
final ShipStrategyType shipType = channel != null ? channel.getShipStrategy() :
((PactConnection) inConn).getShipStrategy();
String shipStrategy = null;
if (shipType != null) {
switch (shipType) {
case NONE:
// nothing
break;
case FORWARD:
shipStrategy = "Forward";
break;
case BROADCAST:
shipStrategy = "Broadcast";
break;
case PARTITION_HASH:
shipStrategy = "Hash Partition";
break;
case PARTITION_RANGE:
shipStrategy = "Range Partition";
break;
case PARTITION_LOCAL_HASH:
shipStrategy = "Hash Partition (local)";
break;
case PARTITION_RANDOM:
shipStrategy = "Redistribute";
break;
default:
throw new CompilerException("Unknown ship strategy '" + conn.getShipStrategy().name()
+ "' in JSON generator.");
}
}
if (channel != null && channel.getShipStrategyKeys() != null && channel.getShipStrategyKeys().size() > 0) {
shipStrategy += " on " + (channel.getShipStrategySortOrder() == null ?
channel.getShipStrategyKeys().toString() :
Utils.createOrdering(channel.getShipStrategyKeys(), channel.getShipStrategySortOrder()).toString());
}
if (shipStrategy != null) {
writer.print(", \"ship_strategy\": \"" + shipStrategy + "\"");
}
if (channel != null) {
String localStrategy = null;
switch (channel.getLocalStrategy()) {
case NONE:
break;
case SORT:
localStrategy = "Sort";
break;
case COMBININGSORT:
localStrategy = "Sort (combining)";
break;
default:
throw new CompilerException("Unknown local strategy " + channel.getLocalStrategy().name());
}
if (channel != null && channel.getLocalStrategyKeys() != null && channel.getLocalStrategyKeys().size() > 0) {
localStrategy += " on " + (channel.getLocalStrategySortOrder() == null ?
channel.getLocalStrategyKeys().toString() :
Utils.createOrdering(channel.getLocalStrategyKeys(), channel.getLocalStrategySortOrder()).toString());
}
if (localStrategy != null) {
writer.print(", \"local_strategy\": \"" + localStrategy + "\"");
}
if (channel != null && channel.getTempMode() != TempMode.NONE) {
String tempMode = channel.getTempMode().toString();
writer.print(", \"temp_mode\": \"" + tempMode + "\"");
}
}
writer.print('}');
connNum++;
}
inputNum++;
}
// finish predecessors
writer.print("\n\t\t]");
}
//---------------------------------------------------------------------------------------
// the part below here is relevant only to plan nodes with concrete strategies, etc
//---------------------------------------------------------------------------------------
final PlanNode p = node.getPlanNode();
if (p == null) {
// finish node
writer.print("\n\t}");
return;
}
// local strategy
String locString = null;
if (p.getDriverStrategy() != null) {
switch (p.getDriverStrategy()) {
case NONE:
break;
case MAP:
locString = "Map";
break;
case PARTIAL_GROUP:
locString = "Ordered Partial Grouping";
break;
case SORTED_GROUP:
locString = "Ordered Grouping";
break;
case ALL_GROUP:
locString = "Group all into a single group";
break;
case HYBRIDHASH_BUILD_FIRST:
locString = "Hybrid Hash (build: " + child1name + ")";
break;
case HYBRIDHASH_BUILD_SECOND:
locString = "Hybrid Hash (build: " + child2name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_FIRST:
locString = "Nested Loops (Blocked Outer: " + child1name + ")";
break;
case NESTEDLOOP_BLOCKED_OUTER_SECOND:
locString = "Nested Loops (Blocked Outer: " + child2name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_FIRST:
locString = "Nested Loops (Streamed Outer: " + child1name + ")";
break;
case NESTEDLOOP_STREAMED_OUTER_SECOND:
locString = "Nested Loops (Streamed Outer: " + child2name + ")";
break;
case MERGE:
locString = "Merge";
break;
case CO_GROUP:
locString = "Co-Group";
break;
default:
throw new CompilerException("Unknown local strategy '" + p.getDriverStrategy().name()
+ "' in JSON generator.");
}
if (locString != null) {
writer.print(",\n\t\t\"driver_strategy\": \"");
writer.print(locString);
writer.print("\"");
}
}
{
// output node global properties
final GlobalProperties gp = p.getGlobalProperties();
writer.print(",\n\t\t\"global_properties\": [\n");
addProperty(writer, "Partitioning", gp.getPartitioning().name(), true);
if (gp.getPartitioningFields() != null) {
addProperty(writer, "Partitioned on", gp.getPartitioningFields().toString(), false);
}
if (gp.getPartitioningOrdering() != null) {
addProperty(writer, "Partitioning Order", gp.getPartitioningOrdering().toString(), false);
}
else {
addProperty(writer, "Partitioning Order", "(none)", false);
}
if (n.getUniqueFields() == null || n.getUniqueFields().size() == 0) {
addProperty(writer, "Uniqueness", "not unique", false);
}
else {
addProperty(writer, "Uniqueness", n.getUniqueFields().toString(), false);
}
writer.print("\n\t\t]");
}
{
// output node local properties
LocalProperties lp = p.getLocalProperties();
writer.print(",\n\t\t\"local_properties\": [\n");
if (lp.getOrdering() != null) {
addProperty(writer, "Order", lp.getOrdering().toString(), true);
}
else {
addProperty(writer, "Order", "(none)", true);
}
if (lp.getGroupedFields() != null && lp.getGroupedFields().size() > 0) {
addProperty(writer, "Grouped on", lp.getGroupedFields().toString(), false);
} else {
addProperty(writer, "Grouping", "not grouped", false);
}
if (n.getUniqueFields() == null || n.getUniqueFields().size() == 0) {
addProperty(writer, "Uniqueness", "not unique", false);
}
else {
addProperty(writer, "Uniqueness", n.getUniqueFields().toString(), false);
}
writer.print("\n\t\t]");
}
// output node size estimates
writer.print(",\n\t\t\"estimates\": [\n");
addProperty(writer, "Est. Output Size", n.getEstimatedOutputSize() == -1 ? "(unknown)"
: formatNumber(n.getEstimatedOutputSize(), "B"), true);
addProperty(writer, "Est. Cardinality", n.getEstimatedNumRecords() == -1 ? "(unknown)"
: formatNumber(n.getEstimatedNumRecords()), false);
String estCardinality = "(unknown)";
if (n.getEstimatedCardinalities().size() > 0) {
estCardinality = "";
for (Entry<FieldSet, Long> entry : n.getEstimatedCardinalities().entrySet()) {
estCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
}
addProperty(writer, "Est. Cardinality/fields", estCardinality, false);
writer.print("\t\t]");
// output node cost
if (p.getNodeCosts() != null) {
writer.print(",\n\t\t\"costs\": [\n");
addProperty(writer, "Network", p.getNodeCosts().getNetworkCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getNetworkCost(), "B"), true);
addProperty(writer, "Disk I/O", p.getNodeCosts().getDiskCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getDiskCost(), "B"), false);
addProperty(writer, "CPU", p.getNodeCosts().getCpuCost() == -1 ? "(unknown)"
: formatNumber(p.getNodeCosts().getCpuCost(), ""), false);
addProperty(writer, "Cumulative Network",
p.getCumulativeCosts().getNetworkCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getNetworkCost(), "B"), false);
addProperty(writer, "Cumulative Disk I/O",
p.getCumulativeCosts().getDiskCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getDiskCost(), "B"), false);
addProperty(writer, "Cumulative CPU",
p.getCumulativeCosts().getCpuCost() == -1 ? "(unknown)" : formatNumber(p
.getCumulativeCosts().getCpuCost(), ""), false);
writer.print("\n\t\t]");
}
// output the node compiler hints
if (n.getPactContract().getCompilerHints() != null) {
CompilerHints hints = n.getPactContract().getCompilerHints();
CompilerHints defaults = new CompilerHints();
writer.print(",\n\t\t\"compiler_hints\": [\n");
String hintCardinality;
if (hints.getDistinctCounts().size() > 0) {
hintCardinality = "";
for (Entry<FieldSet, Long> entry : hints.getDistinctCounts().entrySet()) {
hintCardinality += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
} else {
hintCardinality = "(none)";
}
addProperty(writer, "Cardinality", hintCardinality, true);
addProperty(writer, "Avg. Records/StubCall", hints.getAvgRecordsEmittedPerStubCall() == defaults.
getAvgRecordsEmittedPerStubCall() ? "(none)" : String.valueOf(hints.getAvgRecordsEmittedPerStubCall()), false);
String valuesKey;
if (hints.getAvgNumRecordsPerDistinctFields().size() > 0) {
valuesKey = "";
for (Entry<FieldSet, Float> entry : hints.getAvgNumRecordsPerDistinctFields().entrySet()) {
valuesKey += "[" + entry.getKey().toString() + "->" + entry.getValue() + "]";
}
} else {
valuesKey = "(none)";
}
addProperty(writer, "Avg. Values/Distinct fields", valuesKey, false);
addProperty(writer, "Avg. Width (bytes)", hints.getAvgBytesPerRecord() == defaults
.getAvgBytesPerRecord() ? "(none)" : String.valueOf(hints.getAvgBytesPerRecord()), false);
writer.print("\t\t]");
}
// finish node
writer.print("\n\t}");
}
|
diff --git a/issues/jira/src/main/java/uk/org/sappho/code/heatmap/issues/jira/JiraService.java b/issues/jira/src/main/java/uk/org/sappho/code/heatmap/issues/jira/JiraService.java
index d57ba9a..378b2b2 100644
--- a/issues/jira/src/main/java/uk/org/sappho/code/heatmap/issues/jira/JiraService.java
+++ b/issues/jira/src/main/java/uk/org/sappho/code/heatmap/issues/jira/JiraService.java
@@ -1,196 +1,190 @@
package uk.org.sappho.code.heatmap.issues.jira;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.atlassian.jira.rpc.soap.client.RemoteIssue;
import com.atlassian.jira.rpc.soap.client.RemoteVersion;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import uk.org.sappho.code.heatmap.config.Configuration;
import uk.org.sappho.code.heatmap.config.ConfigurationException;
import uk.org.sappho.code.heatmap.issues.IssueManagement;
import uk.org.sappho.code.heatmap.issues.IssueManagementException;
import uk.org.sappho.code.heatmap.issues.IssueWrapper;
import uk.org.sappho.code.heatmap.issues.Releases;
import uk.org.sappho.code.heatmap.warnings.Warnings;
import uk.org.sappho.jira4j.soap.JiraSoapService;
@Singleton
public class JiraService implements IssueManagement {
protected JiraSoapService jiraSoapService = null;
protected Map<String, IssueWrapper> allowedIssues = new HashMap<String, IssueWrapper>();
protected Map<String, String> warnedIssues = new HashMap<String, String>();
protected Map<String, String> releases = new HashMap<String, String>();
protected Map<String, String> versionWarnings = new HashMap<String, String>();
protected Map<String, String> issueTypes = new HashMap<String, String>();
protected Map<String, Integer> issueTypeWeightMultipliers = new HashMap<String, Integer>();
protected Warnings warnings;
protected Configuration config;
protected static final Pattern SIMPLE_JIRA_REGEX = Pattern.compile("^([a-zA-Z]{2,}-\\d+):.*$");
private static final Logger LOG = Logger.getLogger(JiraService.class);
protected static final String ISSUE_FIELDS = "Issue fields";
@Inject
public JiraService(Warnings warnings, Configuration config) throws IssueManagementException {
LOG.info("Using Jira issue management plugin");
this.warnings = warnings;
this.config = config;
connect();
getAllowedIssues();
}
protected void connect() throws IssueManagementException {
String url = config.getProperty("jira.url", "http://example.com");
String username = config.getProperty("jira.username", "nobody");
String password = config.getProperty("jira.password", "nopassword");
LOG.info("Connecting to " + url + " as " + username);
try {
jiraSoapService = new JiraSoapService(url, username, password);
} catch (Throwable t) {
throw new IssueManagementException("Unable to log in to Jira at " + url + " as user " + username, t);
}
}
protected void getAllowedIssues() throws IssueManagementException {
/**
* note: this is a bit rubbish but because jira's soap interface doesn't have a getParent function it's the only way to fake it
* making this better will require an installed plugin
* **/
LOG.info("Getting list of allowed issues");
try {
// get all tasks we're prepared to deal with
String jql = config.getProperty("jira.filter.issues.allowed");
LOG.info("Running Jira query: " + jql);
RemoteIssue[] remoteIssues = jiraSoapService.getService().getIssuesFromJqlSearch(
jiraSoapService.getToken(), jql, 5000);
LOG.info("Processing " + remoteIssues.length + " issues returned by query");
// map all subtasks back to their parents
Map<String, RemoteIssue> mappedRemoteIssues = new HashMap<String, RemoteIssue>();
Map<String, String> subTaskParents = new HashMap<String, String>();
for (RemoteIssue remoteIssue : remoteIssues) {
String issueKey = remoteIssue.getKey();
if (mappedRemoteIssues.get(issueKey) == null) {
mappedRemoteIssues.put(issueKey, remoteIssue);
}
RemoteIssue[] subTasks = jiraSoapService.getService().getIssuesFromJqlSearch(
jiraSoapService.getToken(), "parent = " + issueKey, 200);
for (RemoteIssue subTask : subTasks) {
String subTaskKey = subTask.getKey();
warnings.add("Issue subtask mapping", subTaskKey + " --> " + issueKey);
if (mappedRemoteIssues.get(subTaskKey) == null) {
mappedRemoteIssues.put(subTaskKey, subTask);
}
subTaskParents.put(subTaskKey, issueKey);
}
}
// create issue wrappers for all allowed root (non-subtask) issues
for (String issueKey : mappedRemoteIssues.keySet()) {
String parentKey = subTaskParents.get(issueKey);
IssueWrapper issueWrapper = parentKey != null ?
createIssueWrapper(mappedRemoteIssues.get(parentKey), issueKey) :
createIssueWrapper(mappedRemoteIssues.get(issueKey), null);
allowedIssues.put(issueKey, issueWrapper);
}
LOG.info("Processed " + mappedRemoteIssues.size()
+ " issues - added subtasks might have inflated this figure");
} catch (Throwable t) {
throw new IssueManagementException("Unable to get list of allowed issues", t);
}
}
protected IssueWrapper createIssueWrapper(RemoteIssue issue, String subTaskKey) throws IssueManagementException {
Releases issueReleases = new Releases();
Map<String, String> issueReleaseMap = new HashMap<String, String>();
for (RemoteVersion remoteVersion : issue.getFixVersions()) {
String remoteVersionName = remoteVersion.getName();
- String versionWarning = versionWarnings.get(remoteVersionName);
- if (versionWarning == null) {
- versionWarning = config.getProperty("jira.version.status." + remoteVersionName, "");
- versionWarnings.put(remoteVersionName, versionWarning);
- if (versionWarning.length() > 0) {
- warnings.add("Issue version", remoteVersionName + " " + versionWarning);
- }
- }
- if (versionWarning.length() > 0) {
- issueReleases.addWarning(remoteVersionName + " " + versionWarning);
- }
String release = releases.get(remoteVersionName);
if (release == null) {
try {
- release = config.getProperty("jira.version.map.name." + remoteVersionName);
+ release = config.getProperty("jira.version.map.release." + remoteVersionName);
+ warnings.add("Version mapping", remoteVersionName + " --> release " + release);
+ releases.put(remoteVersionName, release);
} catch (ConfigurationException e) {
- release = remoteVersionName;
+ if (versionWarnings.get(remoteVersionName) == null) {
+ warnings.add("Issue version", remoteVersionName + " will be ignored");
+ versionWarnings.put(remoteVersionName, remoteVersionName);
+ }
}
- warnings.add("Version mapping", remoteVersionName + " --> " + release);
- releases.put(remoteVersionName, release);
}
- issueReleaseMap.put(release, release);
+ if (release != null) {
+ issueReleaseMap.put(release, release);
+ }
}
for (String release : issueReleaseMap.keySet()) {
issueReleases.addRelease(release);
}
if (issueReleases.getReleases().size() == 0) {
warnings.add(ISSUE_FIELDS, issue.getKey() + " has no fix version");
} else if (issueReleases.getReleases().size() > 1) {
warnings.add(ISSUE_FIELDS, issue.getKey() + " has more than one fix version");
}
String typeId = issue.getType();
String typeName = issueTypes.get(typeId);
if (typeName == null) {
typeName = config.getProperty("jira.type.map.id." + typeId, "housekeeping");
warnings.add("Issue type mapping", typeId + " --> " + typeName);
issueTypes.put(typeId, typeName);
}
Integer weight = issueTypeWeightMultipliers.get(typeName);
if (weight == null) {
String typeNameKey = "jira.type.multiplier." + typeName;
try {
weight = Integer.parseInt(config.getProperty(typeNameKey, "0"));
} catch (Throwable t) {
throw new IssueManagementException(
"Issue type weight configuration \"" + typeNameKey + "\" is invalid", t);
}
warnings.add("Issue type weight", typeName + " = " + weight);
issueTypeWeightMultipliers.put(typeName, weight);
}
return new JiraIssueWrapper(issue, subTaskKey, issueReleases, weight);
}
protected String getIssueKeyFromCommitComment(String commitComment) {
String key = null;
Matcher matcher = SIMPLE_JIRA_REGEX.matcher(commitComment.split("\n")[0]);
if (matcher.matches()) {
key = matcher.group(1);
} else {
warnings.add(ISSUE_FIELDS, "No Jira issue key found in commit comment: " + commitComment);
}
return key;
}
public IssueWrapper getIssue(String commitComment) {
IssueWrapper issue = null;
String key = getIssueKeyFromCommitComment(commitComment);
if (key != null) {
issue = allowedIssues.get(key);
if (issue == null && warnedIssues.get(key) == null) {
warnings.add(ISSUE_FIELDS, "No Jira issue found for " + key
+ " - query specified in jira.filter.issues.allowed configuration too restrictive?");
warnedIssues.put(key, key);
}
}
return issue;
}
}
| false | true | protected IssueWrapper createIssueWrapper(RemoteIssue issue, String subTaskKey) throws IssueManagementException {
Releases issueReleases = new Releases();
Map<String, String> issueReleaseMap = new HashMap<String, String>();
for (RemoteVersion remoteVersion : issue.getFixVersions()) {
String remoteVersionName = remoteVersion.getName();
String versionWarning = versionWarnings.get(remoteVersionName);
if (versionWarning == null) {
versionWarning = config.getProperty("jira.version.status." + remoteVersionName, "");
versionWarnings.put(remoteVersionName, versionWarning);
if (versionWarning.length() > 0) {
warnings.add("Issue version", remoteVersionName + " " + versionWarning);
}
}
if (versionWarning.length() > 0) {
issueReleases.addWarning(remoteVersionName + " " + versionWarning);
}
String release = releases.get(remoteVersionName);
if (release == null) {
try {
release = config.getProperty("jira.version.map.name." + remoteVersionName);
} catch (ConfigurationException e) {
release = remoteVersionName;
}
warnings.add("Version mapping", remoteVersionName + " --> " + release);
releases.put(remoteVersionName, release);
}
issueReleaseMap.put(release, release);
}
for (String release : issueReleaseMap.keySet()) {
issueReleases.addRelease(release);
}
if (issueReleases.getReleases().size() == 0) {
warnings.add(ISSUE_FIELDS, issue.getKey() + " has no fix version");
} else if (issueReleases.getReleases().size() > 1) {
warnings.add(ISSUE_FIELDS, issue.getKey() + " has more than one fix version");
}
String typeId = issue.getType();
String typeName = issueTypes.get(typeId);
if (typeName == null) {
typeName = config.getProperty("jira.type.map.id." + typeId, "housekeeping");
warnings.add("Issue type mapping", typeId + " --> " + typeName);
issueTypes.put(typeId, typeName);
}
Integer weight = issueTypeWeightMultipliers.get(typeName);
if (weight == null) {
String typeNameKey = "jira.type.multiplier." + typeName;
try {
weight = Integer.parseInt(config.getProperty(typeNameKey, "0"));
} catch (Throwable t) {
throw new IssueManagementException(
"Issue type weight configuration \"" + typeNameKey + "\" is invalid", t);
}
warnings.add("Issue type weight", typeName + " = " + weight);
issueTypeWeightMultipliers.put(typeName, weight);
}
return new JiraIssueWrapper(issue, subTaskKey, issueReleases, weight);
}
| protected IssueWrapper createIssueWrapper(RemoteIssue issue, String subTaskKey) throws IssueManagementException {
Releases issueReleases = new Releases();
Map<String, String> issueReleaseMap = new HashMap<String, String>();
for (RemoteVersion remoteVersion : issue.getFixVersions()) {
String remoteVersionName = remoteVersion.getName();
String release = releases.get(remoteVersionName);
if (release == null) {
try {
release = config.getProperty("jira.version.map.release." + remoteVersionName);
warnings.add("Version mapping", remoteVersionName + " --> release " + release);
releases.put(remoteVersionName, release);
} catch (ConfigurationException e) {
if (versionWarnings.get(remoteVersionName) == null) {
warnings.add("Issue version", remoteVersionName + " will be ignored");
versionWarnings.put(remoteVersionName, remoteVersionName);
}
}
}
if (release != null) {
issueReleaseMap.put(release, release);
}
}
for (String release : issueReleaseMap.keySet()) {
issueReleases.addRelease(release);
}
if (issueReleases.getReleases().size() == 0) {
warnings.add(ISSUE_FIELDS, issue.getKey() + " has no fix version");
} else if (issueReleases.getReleases().size() > 1) {
warnings.add(ISSUE_FIELDS, issue.getKey() + " has more than one fix version");
}
String typeId = issue.getType();
String typeName = issueTypes.get(typeId);
if (typeName == null) {
typeName = config.getProperty("jira.type.map.id." + typeId, "housekeeping");
warnings.add("Issue type mapping", typeId + " --> " + typeName);
issueTypes.put(typeId, typeName);
}
Integer weight = issueTypeWeightMultipliers.get(typeName);
if (weight == null) {
String typeNameKey = "jira.type.multiplier." + typeName;
try {
weight = Integer.parseInt(config.getProperty(typeNameKey, "0"));
} catch (Throwable t) {
throw new IssueManagementException(
"Issue type weight configuration \"" + typeNameKey + "\" is invalid", t);
}
warnings.add("Issue type weight", typeName + " = " + weight);
issueTypeWeightMultipliers.put(typeName, weight);
}
return new JiraIssueWrapper(issue, subTaskKey, issueReleases, weight);
}
|
diff --git a/core/src/main/java/tripleplay/util/Randoms.java b/core/src/main/java/tripleplay/util/Randoms.java
index f95f92ed..415c1def 100644
--- a/core/src/main/java/tripleplay/util/Randoms.java
+++ b/core/src/main/java/tripleplay/util/Randoms.java
@@ -1,286 +1,282 @@
//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Random;
import java.util.RandomAccess;
/**
* Provides utility routines to simplify obtaining randomized values.
*/
public class Randoms
{
/**
* A factory to create a new Randoms object.
*/
public static Randoms with (Random rand) {
return new Randoms(rand);
}
/**
* Returns a pseudorandom, uniformly distributed {@code int} value between {@code 0}
* (inclusive) and {@code high} (exclusive).
*
* @param high the high value limiting the random number sought.
*
* @throws IllegalArgumentException if {@code high} is not positive.
*/
public int getInt (int high) {
return _r.nextInt(high);
}
/**
* Returns a pseudorandom, uniformly distributed {@code int} value between {@code low}
* (inclusive) and {@code high} (exclusive).
*
* @throws IllegalArgumentException if {@code high - low} is not positive.
*/
public int getInRange (int low, int high) {
return low + _r.nextInt(high - low);
}
/**
* Returns a pseudorandom, uniformly distributed {@code float} value between {@code 0.0}
* (inclusive) and the {@code high} (exclusive).
*
* @param high the high value limiting the random number sought.
*/
public float getFloat (float high) {
return _r.nextFloat() * high;
}
/**
* Returns a pseudorandom, uniformly distributed {@code float} value between {@code low}
* (inclusive) and {@code high} (exclusive).
*/
public float getInRange (float low, float high) {
return low + (_r.nextFloat() * (high - low));
}
/**
* Returns true approximately one in {@code n} times.
*
* @throws IllegalArgumentException if {@code n} is not positive.
*/
public boolean getChance (int n) {
return (0 == _r.nextInt(n));
}
/**
* Has a probability {@code p} of returning true.
*/
public boolean getProbability (float p) {
return _r.nextFloat() < p;
}
/**
* Returns {@code true} or {@code false} with approximately even probability.
*/
public boolean getBoolean () {
return _r.nextBoolean();
}
/**
* Returns a pseudorandom, normally distributed {@code float} value around the {@code mean}
* with the standard deviation {@code dev}.
*/
public float getNormal (float mean, float dev) {
return (float)_r.nextGaussian() * dev + mean;
}
/**
* Shuffle the specified list using our Random.
*/
public <T> void shuffle (List<T> list) {
// we can't use Collections.shuffle here because GWT doesn't implement it
int size = list.size();
if (list instanceof RandomAccess) {
for (int ii = size; ii > 1; ii--) {
swap(list, ii-1, _r.nextInt(ii));
}
} else {
Object[] array = list.toArray();
for (int ii = size; ii > 1; ii--) {
swap(array, ii-1, _r.nextInt(ii));
}
ListIterator<T> it = list.listIterator();
for (int ii = 0; ii < size; ii++) {
it.next();
@SuppressWarnings("unchecked") T elem = (T)array[ii];
it.set(elem);
}
}
}
/**
* Pick a random element from the specified Iterator, or return {@code ifEmpty} if it is empty.
*
* <p><b>Implementation note:</b> because the total size of the Iterator is not known,
* the random number generator is queried after the second element and every element
* thereafter.
*
* @throws NullPointerException if the iterator is null.
*/
public <T> T pick (Iterator<? extends T> iterator, T ifEmpty) {
if (!iterator.hasNext()) {
return ifEmpty;
}
T pick = iterator.next();
for (int count = 2; iterator.hasNext(); count++) {
T next = iterator.next();
if (0 == _r.nextInt(count)) {
pick = next;
}
}
return pick;
}
/**
* Pick a random element from the specified Iterable, or return {@code ifEmpty} if it is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, it behaves as if calling {@link #pick(Iterator, Object)}
* with the Iterable's Iterator.
*
* @throws NullPointerException if the iterable is null.
*/
public <T> T pick (Iterable<? extends T> iterable, T ifEmpty) {
return pickPluck(iterable, ifEmpty, false);
}
/**
* Pick a random <em>key</em> from the specified mapping of weight values, or return {@code
* ifEmpty} if no mapping has a weight greater than {@code 0}. Each weight value is evaluated
* as a double.
*
* <p><b>Implementation note:</b> a random number is generated for every entry with a
* non-zero weight after the first such entry.
*
* @throws NullPointerException if the map is null.
* @throws IllegalArgumentException if any weight is less than 0.
*/
public <T> T pick (Map<? extends T, ? extends Number> weightMap, T ifEmpty) {
T pick = ifEmpty;
double total = 0.0;
for (Map.Entry<? extends T, ? extends Number> entry : weightMap.entrySet()) {
double weight = entry.getValue().doubleValue();
if (weight > 0.0) {
total += weight;
if ((total == weight) || ((_r.nextDouble() * total) < weight)) {
pick = entry.getKey();
}
} else if (weight < 0.0) {
throw new IllegalArgumentException("Weight less than 0: " + entry);
} // else: weight == 0.0 is OK
}
return pick;
}
/**
* Pluck (remove) a random element from the specified Iterable, or return {@code ifEmpty} if it
* is empty.
*
* <p><b>Implementation note:</b> optimized implementations are used if the Iterable
* is a List or Collection. Otherwise, two Iterators are created from the Iterable
* and a random number is generated after the second element and all beyond.
*
* @throws NullPointerException if the iterable is null.
* @throws UnsupportedOperationException if the iterable is unmodifiable or its Iterator
* does not support {@link Iterator#remove()}.
*/
public <T> T pluck (Iterable<? extends T> iterable, T ifEmpty) {
return pickPluck(iterable, ifEmpty, true);
}
/**
* Construct a Randoms.
*/
protected Randoms (Random rand) {
_r = rand;
}
/**
* Shared code for pick and pluck.
*/
protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove) {
if (iterable instanceof Collection) {
// optimized path for Collection
- @SuppressWarnings("unchecked")
Collection<? extends T> coll = (Collection<? extends T>)iterable;
int size = coll.size();
if (size == 0) {
return ifEmpty;
}
if (coll instanceof List) {
// extra-special optimized path for Lists
- @SuppressWarnings("unchecked") List<? extends T> list = (List<? extends T>)coll;
+ List<? extends T> list = (List<? extends T>)coll;
int idx = _r.nextInt(size);
- if (remove) { // ternary conditional causes warning here with javac 1.6, :(
- return list.remove(idx);
- }
- return list.get(idx);
+ return remove ? list.remove(idx) : list.get(idx);
}
// for other Collections, we must iterate
Iterator<? extends T> it = coll.iterator();
for (int idx = _r.nextInt(size); idx > 0; idx--) {
it.next();
}
try {
return it.next();
} finally {
if (remove) {
it.remove();
}
}
}
if (!remove) {
return pick(iterable.iterator(), ifEmpty);
}
// from here on out, we're doing a pluck with a complicated two-iterator solution
Iterator<? extends T> it = iterable.iterator();
if (!it.hasNext()) {
return ifEmpty;
}
Iterator<? extends T> lagIt = iterable.iterator();
T pick = it.next();
lagIt.next();
for (int count = 2, lag = 1; it.hasNext(); count++, lag++) {
T next = it.next();
if (0 == _r.nextInt(count)) {
pick = next;
// catch up lagIt so that it has just returned 'pick' as well
for ( ; lag > 0; lag--) {
lagIt.next();
}
}
}
lagIt.remove(); // remove 'pick' from the lagging iterator
return pick;
}
/** Helper for {@link #shuffle}. */
protected static <T> void swap (List<T> list, int ii, int jj) {
list.set(ii, list.set(jj, list.get(ii)));
}
/** Helper for {@link #shuffle}. */
protected static void swap (Object[] array, int ii, int jj) {
Object tmp = array[ii];
array[ii] = array[jj];
array[jj] = tmp;
}
/** The random number generator. */
protected final Random _r;
}
| false | true | protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove) {
if (iterable instanceof Collection) {
// optimized path for Collection
@SuppressWarnings("unchecked")
Collection<? extends T> coll = (Collection<? extends T>)iterable;
int size = coll.size();
if (size == 0) {
return ifEmpty;
}
if (coll instanceof List) {
// extra-special optimized path for Lists
@SuppressWarnings("unchecked") List<? extends T> list = (List<? extends T>)coll;
int idx = _r.nextInt(size);
if (remove) { // ternary conditional causes warning here with javac 1.6, :(
return list.remove(idx);
}
return list.get(idx);
}
// for other Collections, we must iterate
Iterator<? extends T> it = coll.iterator();
for (int idx = _r.nextInt(size); idx > 0; idx--) {
it.next();
}
try {
return it.next();
} finally {
if (remove) {
it.remove();
}
}
}
if (!remove) {
return pick(iterable.iterator(), ifEmpty);
}
// from here on out, we're doing a pluck with a complicated two-iterator solution
Iterator<? extends T> it = iterable.iterator();
if (!it.hasNext()) {
return ifEmpty;
}
Iterator<? extends T> lagIt = iterable.iterator();
T pick = it.next();
lagIt.next();
for (int count = 2, lag = 1; it.hasNext(); count++, lag++) {
T next = it.next();
if (0 == _r.nextInt(count)) {
pick = next;
// catch up lagIt so that it has just returned 'pick' as well
for ( ; lag > 0; lag--) {
lagIt.next();
}
}
}
lagIt.remove(); // remove 'pick' from the lagging iterator
return pick;
}
| protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove) {
if (iterable instanceof Collection) {
// optimized path for Collection
Collection<? extends T> coll = (Collection<? extends T>)iterable;
int size = coll.size();
if (size == 0) {
return ifEmpty;
}
if (coll instanceof List) {
// extra-special optimized path for Lists
List<? extends T> list = (List<? extends T>)coll;
int idx = _r.nextInt(size);
return remove ? list.remove(idx) : list.get(idx);
}
// for other Collections, we must iterate
Iterator<? extends T> it = coll.iterator();
for (int idx = _r.nextInt(size); idx > 0; idx--) {
it.next();
}
try {
return it.next();
} finally {
if (remove) {
it.remove();
}
}
}
if (!remove) {
return pick(iterable.iterator(), ifEmpty);
}
// from here on out, we're doing a pluck with a complicated two-iterator solution
Iterator<? extends T> it = iterable.iterator();
if (!it.hasNext()) {
return ifEmpty;
}
Iterator<? extends T> lagIt = iterable.iterator();
T pick = it.next();
lagIt.next();
for (int count = 2, lag = 1; it.hasNext(); count++, lag++) {
T next = it.next();
if (0 == _r.nextInt(count)) {
pick = next;
// catch up lagIt so that it has just returned 'pick' as well
for ( ; lag > 0; lag--) {
lagIt.next();
}
}
}
lagIt.remove(); // remove 'pick' from the lagging iterator
return pick;
}
|
diff --git a/public/java/test/org/broadinstitute/sting/gatk/walkers/indels/RealignerTargetCreatorIntegrationTest.java b/public/java/test/org/broadinstitute/sting/gatk/walkers/indels/RealignerTargetCreatorIntegrationTest.java
index cc67c354a..f5ed69476 100755
--- a/public/java/test/org/broadinstitute/sting/gatk/walkers/indels/RealignerTargetCreatorIntegrationTest.java
+++ b/public/java/test/org/broadinstitute/sting/gatk/walkers/indels/RealignerTargetCreatorIntegrationTest.java
@@ -1,31 +1,31 @@
package org.broadinstitute.sting.gatk.walkers.indels;
import org.broadinstitute.sting.WalkerTest;
import org.testng.annotations.Test;
import java.util.Arrays;
public class RealignerTargetCreatorIntegrationTest extends WalkerTest {
@Test
public void testIntervals() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -R " + b36KGReference + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam --mismatchFraction 0.15 -L 1:10,000,000-10,050,000 -o %s",
1,
Arrays.asList("e7accfa58415d6da80383953b1a3a986"));
executeTest("test standard", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -B:dbsnp,vcf " + GATKDataLocation + "dbsnp_132.b36.excluding_sites_after_129.vcf -R " + b36KGReference + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -L 1:10,000,000-10,050,000 -o %s",
1,
- Arrays.asList("f23ba17ee0f9573dd307708175d90cd2"));
- //executeTest("test dbsnp", spec2);
+ Arrays.asList("0367d39a122c8ac0899fb868a82ef728"));
+ executeTest("test dbsnp", spec2);
WalkerTest.WalkerTestSpec spec3 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -R " + b36KGReference + " -B:indels,VCF " + validationDataLocation + "NA12878.chr1_10mb_11mb.slx.indels.vcf4 -BTI indels -o %s",
1,
Arrays.asList("5206cee6c01b299417bf2feeb8b3dc96"));
executeTest("test rods only", spec3);
}
}
| true | true | public void testIntervals() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -R " + b36KGReference + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam --mismatchFraction 0.15 -L 1:10,000,000-10,050,000 -o %s",
1,
Arrays.asList("e7accfa58415d6da80383953b1a3a986"));
executeTest("test standard", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -B:dbsnp,vcf " + GATKDataLocation + "dbsnp_132.b36.excluding_sites_after_129.vcf -R " + b36KGReference + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -L 1:10,000,000-10,050,000 -o %s",
1,
Arrays.asList("f23ba17ee0f9573dd307708175d90cd2"));
//executeTest("test dbsnp", spec2);
WalkerTest.WalkerTestSpec spec3 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -R " + b36KGReference + " -B:indels,VCF " + validationDataLocation + "NA12878.chr1_10mb_11mb.slx.indels.vcf4 -BTI indels -o %s",
1,
Arrays.asList("5206cee6c01b299417bf2feeb8b3dc96"));
executeTest("test rods only", spec3);
}
| public void testIntervals() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -R " + b36KGReference + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam --mismatchFraction 0.15 -L 1:10,000,000-10,050,000 -o %s",
1,
Arrays.asList("e7accfa58415d6da80383953b1a3a986"));
executeTest("test standard", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -B:dbsnp,vcf " + GATKDataLocation + "dbsnp_132.b36.excluding_sites_after_129.vcf -R " + b36KGReference + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -L 1:10,000,000-10,050,000 -o %s",
1,
Arrays.asList("0367d39a122c8ac0899fb868a82ef728"));
executeTest("test dbsnp", spec2);
WalkerTest.WalkerTestSpec spec3 = new WalkerTest.WalkerTestSpec(
"-T RealignerTargetCreator -R " + b36KGReference + " -B:indels,VCF " + validationDataLocation + "NA12878.chr1_10mb_11mb.slx.indels.vcf4 -BTI indels -o %s",
1,
Arrays.asList("5206cee6c01b299417bf2feeb8b3dc96"));
executeTest("test rods only", spec3);
}
|
diff --git a/src/com/android/settings/deviceinfo/Status.java b/src/com/android/settings/deviceinfo/Status.java
index a16575410..7d22d913a 100644
--- a/src/com/android/settings/deviceinfo/Status.java
+++ b/src/com/android/settings/deviceinfo/Status.java
@@ -1,402 +1,420 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.deviceinfo;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.PhoneStateIntentReceiver;
import com.android.internal.telephony.TelephonyProperties;
import com.android.settings.R;
import java.lang.ref.WeakReference;
/**
* Display the following information
* # Phone Number
* # Network
* # Roaming
* # Device Id (IMEI in GSM and MEID in CDMA)
* # Network type
* # Signal Strength
* # Battery Strength : TODO
* # Uptime
* # Awake Time
* # XMPP/buzz/tickle status : TODO
*
*/
public class Status extends PreferenceActivity {
private static final String KEY_WIFI_MAC_ADDRESS = "wifi_mac_address";
private static final String KEY_BT_ADDRESS = "bt_address";
private static final int EVENT_SIGNAL_STRENGTH_CHANGED = 200;
private static final int EVENT_SERVICE_STATE_CHANGED = 300;
private static final int EVENT_UPDATE_STATS = 500;
private TelephonyManager mTelephonyManager;
private Phone mPhone = null;
private PhoneStateIntentReceiver mPhoneStateReceiver;
private Resources mRes;
private Preference mSignalStrength;
private Preference mUptime;
private static String sUnknown;
private Preference mBatteryStatus;
private Preference mBatteryLevel;
private Handler mHandler;
private static class MyHandler extends Handler {
private WeakReference<Status> mStatus;
public MyHandler(Status activity) {
mStatus = new WeakReference<Status>(activity);
}
@Override
public void handleMessage(Message msg) {
Status status = mStatus.get();
if (status == null) {
return;
}
switch (msg.what) {
case EVENT_SIGNAL_STRENGTH_CHANGED:
status.updateSignalStrength();
break;
case EVENT_SERVICE_STATE_CHANGED:
ServiceState serviceState = status.mPhoneStateReceiver.getServiceState();
status.updateServiceState(serviceState);
break;
case EVENT_UPDATE_STATS:
status.updateTimes();
sendEmptyMessageDelayed(EVENT_UPDATE_STATS, 1000);
break;
}
}
}
private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
mBatteryLevel.setSummary(String.valueOf(level * 100 / scale) + "%");
int plugType = intent.getIntExtra("plugged", 0);
int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String statusString;
if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
statusString = getString(R.string.battery_info_status_charging);
if (plugType > 0) {
statusString = statusString + " " + getString(
(plugType == BatteryManager.BATTERY_PLUGGED_AC)
? R.string.battery_info_status_charging_ac
: R.string.battery_info_status_charging_usb);
}
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
statusString = getString(R.string.battery_info_status_discharging);
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
statusString = getString(R.string.battery_info_status_not_charging);
} else if (status == BatteryManager.BATTERY_STATUS_FULL) {
statusString = getString(R.string.battery_info_status_full);
} else {
statusString = getString(R.string.battery_info_status_unknown);
}
mBatteryStatus.setSummary(statusString);
}
}
};
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onDataConnectionStateChanged(int state) {
updateDataState();
updateNetworkType();
}
};
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
+ Preference removablePref;
mHandler = new MyHandler(this);
mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
addPreferencesFromResource(R.xml.device_info_status);
mBatteryLevel = findPreference("battery_level");
mBatteryStatus = findPreference("battery_status");
mRes = getResources();
if (sUnknown == null) {
sUnknown = mRes.getString(R.string.device_info_default);
}
mPhone = PhoneFactory.getDefaultPhone();
// Note - missing in zaku build, be careful later...
mSignalStrength = findPreference("signal_strength");
mUptime = findPreference("up_time");
//NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA
if (mPhone.getPhoneName().equals("CDMA")) {
setSummaryText("meid_number", mPhone.getMeid());
setSummaryText("min_number", mPhone.getCdmaMin());
setSummaryText("prl_version", mPhone.getCdmaPrlVersion());
// device is not GSM/UMTS, do not display GSM/UMTS features
- getPreferenceScreen().removePreference(findPreference("imei"));
- getPreferenceScreen().removePreference(findPreference("imei_sv"));
+ // check Null in case no specified preference in overlay xml
+ removablePref = findPreference("imei");
+ if (removablePref != null) {
+ getPreferenceScreen().removePreference(removablePref);
+ }
+ removablePref = findPreference("imei_sv");
+ if (removablePref != null) {
+ getPreferenceScreen().removePreference(removablePref);
+ }
} else {
setSummaryText("imei", mPhone.getDeviceId());
setSummaryText("imei_sv",
((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getDeviceSoftwareVersion());
// device is not CDMA, do not display CDMA features
- getPreferenceScreen().removePreference(findPreference("prl_version"));
- getPreferenceScreen().removePreference(findPreference("meid_number"));
- getPreferenceScreen().removePreference(findPreference("min_number"));
+ // check Null in case no specified preference in overlay xml
+ removablePref = findPreference("prl_version");
+ if (removablePref != null) {
+ getPreferenceScreen().removePreference(removablePref);
+ }
+ removablePref = findPreference("meid_number");
+ if (removablePref != null) {
+ getPreferenceScreen().removePreference(removablePref);
+ }
+ removablePref = findPreference("min_number");
+ if (removablePref != null) {
+ getPreferenceScreen().removePreference(removablePref);
+ }
}
setSummaryText("number", mPhone.getLine1Number());
mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler);
mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED);
setWifiStatus();
setBtStatus();
}
@Override
protected void onResume() {
super.onResume();
mPhoneStateReceiver.registerIntent();
registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
updateSignalStrength();
updateServiceState(mPhone.getServiceState());
updateDataState();
mTelephonyManager.listen(mPhoneStateListener,
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
mHandler.sendEmptyMessage(EVENT_UPDATE_STATS);
}
@Override
public void onPause() {
super.onPause();
mPhoneStateReceiver.unregisterIntent();
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
unregisterReceiver(mBatteryInfoReceiver);
mHandler.removeMessages(EVENT_UPDATE_STATS);
}
/**
* @param preference The key for the Preference item
* @param property The system property to fetch
* @param alt The default value, if the property doesn't exist
*/
private void setSummary(String preference, String property, String alt) {
try {
findPreference(preference).setSummary(
SystemProperties.get(property, alt));
} catch (RuntimeException e) {
}
}
private void setSummaryText(String preference, String text) {
if (TextUtils.isEmpty(text)) {
text = sUnknown;
}
// some preferences may be missing
if (findPreference(preference) != null) {
findPreference(preference).setSummary(text);
}
}
private void updateNetworkType() {
// Whether EDGE, UMTS, etc...
setSummary("network_type", TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE, sUnknown);
}
private void updateDataState() {
int state = mTelephonyManager.getDataState();
String display = mRes.getString(R.string.radioInfo_unknown);
switch (state) {
case TelephonyManager.DATA_CONNECTED:
display = mRes.getString(R.string.radioInfo_data_connected);
break;
case TelephonyManager.DATA_SUSPENDED:
display = mRes.getString(R.string.radioInfo_data_suspended);
break;
case TelephonyManager.DATA_CONNECTING:
display = mRes.getString(R.string.radioInfo_data_connecting);
break;
case TelephonyManager.DATA_DISCONNECTED:
display = mRes.getString(R.string.radioInfo_data_disconnected);
break;
}
setSummaryText("data_state", display);
}
private void updateServiceState(ServiceState serviceState) {
int state = serviceState.getState();
String display = mRes.getString(R.string.radioInfo_unknown);
switch (state) {
case ServiceState.STATE_IN_SERVICE:
display = mRes.getString(R.string.radioInfo_service_in);
break;
case ServiceState.STATE_OUT_OF_SERVICE:
case ServiceState.STATE_EMERGENCY_ONLY:
display = mRes.getString(R.string.radioInfo_service_out);
break;
case ServiceState.STATE_POWER_OFF:
display = mRes.getString(R.string.radioInfo_service_off);
break;
}
setSummaryText("service_state", display);
if (serviceState.getRoaming()) {
setSummaryText("roaming_state", mRes.getString(R.string.radioInfo_roaming_in));
} else {
setSummaryText("roaming_state", mRes.getString(R.string.radioInfo_roaming_not));
}
setSummaryText("operator_name", serviceState.getOperatorAlphaLong());
}
void updateSignalStrength() {
// TODO PhoneStateIntentReceiver is deprecated and PhoneStateListener
// should probably used instead.
// not loaded in some versions of the code (e.g., zaku)
if (mSignalStrength != null) {
int state =
mPhoneStateReceiver.getServiceState().getState();
Resources r = getResources();
if ((ServiceState.STATE_OUT_OF_SERVICE == state) ||
(ServiceState.STATE_POWER_OFF == state)) {
mSignalStrength.setSummary("0");
}
int signalDbm = mPhoneStateReceiver.getSignalStrengthDbm();
if (-1 == signalDbm) signalDbm = 0;
int signalAsu = mPhoneStateReceiver.getSignalStrength();
if (-1 == signalAsu) signalAsu = 0;
mSignalStrength.setSummary(String.valueOf(signalDbm) + " "
+ r.getString(R.string.radioInfo_display_dbm) + " "
+ String.valueOf(signalAsu) + " "
+ r.getString(R.string.radioInfo_display_asu));
}
}
private void setWifiStatus() {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
Preference wifiMacAddressPref = findPreference(KEY_WIFI_MAC_ADDRESS);
String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
: getString(R.string.status_unavailable));
}
private void setBtStatus() {
BluetoothDevice bluetooth = (BluetoothDevice) getSystemService(BLUETOOTH_SERVICE);
Preference btAddressPref = findPreference(KEY_BT_ADDRESS);
if (bluetooth == null) {
// device not BT capable
getPreferenceScreen().removePreference(btAddressPref);
} else {
String address = bluetooth.isEnabled() ? bluetooth.getAddress() : null;
btAddressPref.setSummary(!TextUtils.isEmpty(address) ? address
: getString(R.string.status_unavailable));
}
}
void updateTimes() {
long at = SystemClock.uptimeMillis() / 1000;
long ut = SystemClock.elapsedRealtime() / 1000;
long st = ut - at;
if (ut == 0) {
ut = 1;
}
mUptime.setSummary(convert(ut));
}
private String pad(int n) {
if (n >= 10) {
return String.valueOf(n);
} else {
return "0" + String.valueOf(n);
}
}
private String convert(long t) {
int s = (int)(t % 60);
int m = (int)((t / 60) % 60);
int h = (int)((t / 3600));
return h + ":" + pad(m) + ":" + pad(s);
}
}
| false | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mHandler = new MyHandler(this);
mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
addPreferencesFromResource(R.xml.device_info_status);
mBatteryLevel = findPreference("battery_level");
mBatteryStatus = findPreference("battery_status");
mRes = getResources();
if (sUnknown == null) {
sUnknown = mRes.getString(R.string.device_info_default);
}
mPhone = PhoneFactory.getDefaultPhone();
// Note - missing in zaku build, be careful later...
mSignalStrength = findPreference("signal_strength");
mUptime = findPreference("up_time");
//NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA
if (mPhone.getPhoneName().equals("CDMA")) {
setSummaryText("meid_number", mPhone.getMeid());
setSummaryText("min_number", mPhone.getCdmaMin());
setSummaryText("prl_version", mPhone.getCdmaPrlVersion());
// device is not GSM/UMTS, do not display GSM/UMTS features
getPreferenceScreen().removePreference(findPreference("imei"));
getPreferenceScreen().removePreference(findPreference("imei_sv"));
} else {
setSummaryText("imei", mPhone.getDeviceId());
setSummaryText("imei_sv",
((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getDeviceSoftwareVersion());
// device is not CDMA, do not display CDMA features
getPreferenceScreen().removePreference(findPreference("prl_version"));
getPreferenceScreen().removePreference(findPreference("meid_number"));
getPreferenceScreen().removePreference(findPreference("min_number"));
}
setSummaryText("number", mPhone.getLine1Number());
mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler);
mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED);
setWifiStatus();
setBtStatus();
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Preference removablePref;
mHandler = new MyHandler(this);
mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
addPreferencesFromResource(R.xml.device_info_status);
mBatteryLevel = findPreference("battery_level");
mBatteryStatus = findPreference("battery_status");
mRes = getResources();
if (sUnknown == null) {
sUnknown = mRes.getString(R.string.device_info_default);
}
mPhone = PhoneFactory.getDefaultPhone();
// Note - missing in zaku build, be careful later...
mSignalStrength = findPreference("signal_strength");
mUptime = findPreference("up_time");
//NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA
if (mPhone.getPhoneName().equals("CDMA")) {
setSummaryText("meid_number", mPhone.getMeid());
setSummaryText("min_number", mPhone.getCdmaMin());
setSummaryText("prl_version", mPhone.getCdmaPrlVersion());
// device is not GSM/UMTS, do not display GSM/UMTS features
// check Null in case no specified preference in overlay xml
removablePref = findPreference("imei");
if (removablePref != null) {
getPreferenceScreen().removePreference(removablePref);
}
removablePref = findPreference("imei_sv");
if (removablePref != null) {
getPreferenceScreen().removePreference(removablePref);
}
} else {
setSummaryText("imei", mPhone.getDeviceId());
setSummaryText("imei_sv",
((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getDeviceSoftwareVersion());
// device is not CDMA, do not display CDMA features
// check Null in case no specified preference in overlay xml
removablePref = findPreference("prl_version");
if (removablePref != null) {
getPreferenceScreen().removePreference(removablePref);
}
removablePref = findPreference("meid_number");
if (removablePref != null) {
getPreferenceScreen().removePreference(removablePref);
}
removablePref = findPreference("min_number");
if (removablePref != null) {
getPreferenceScreen().removePreference(removablePref);
}
}
setSummaryText("number", mPhone.getLine1Number());
mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler);
mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED);
setWifiStatus();
setBtStatus();
}
|
diff --git a/src/nayuki/huffmancoding/CircularDictionary.java b/src/nayuki/huffmancoding/CircularDictionary.java
index fc22092..7341fac 100644
--- a/src/nayuki/huffmancoding/CircularDictionary.java
+++ b/src/nayuki/huffmancoding/CircularDictionary.java
@@ -1,40 +1,40 @@
package nayuki.huffmancoding;
import java.io.IOException;
import java.io.OutputStream;
public final class CircularDictionary {
private byte[] data;
private int index;
public CircularDictionary() {
data = new byte[32 * 1024];
index = 0;
}
public void append(int b) {
data[index] = (byte)b;
index = (index + 1) % data.length;
}
public void copy(int dist, int len, OutputStream out) throws IOException {
- if (len < 0 || dist < 1 || dist >= data.length)
+ if (len < 0 || dist < 1 || dist > data.length)
throw new IllegalArgumentException();
int readIndex = (index - dist + data.length) % data.length;
for (int i = 0; i < len; i++) {
out.write(data[readIndex]);
data[index] = data[readIndex];
readIndex = (readIndex + 1) % data.length;
index = (index + 1) % data.length;
}
}
}
| true | true | public void copy(int dist, int len, OutputStream out) throws IOException {
if (len < 0 || dist < 1 || dist >= data.length)
throw new IllegalArgumentException();
int readIndex = (index - dist + data.length) % data.length;
for (int i = 0; i < len; i++) {
out.write(data[readIndex]);
data[index] = data[readIndex];
readIndex = (readIndex + 1) % data.length;
index = (index + 1) % data.length;
}
}
| public void copy(int dist, int len, OutputStream out) throws IOException {
if (len < 0 || dist < 1 || dist > data.length)
throw new IllegalArgumentException();
int readIndex = (index - dist + data.length) % data.length;
for (int i = 0; i < len; i++) {
out.write(data[readIndex]);
data[index] = data[readIndex];
readIndex = (readIndex + 1) % data.length;
index = (index + 1) % data.length;
}
}
|
diff --git a/src/com/android/browser/BrowserDownloadAdapter.java b/src/com/android/browser/BrowserDownloadAdapter.java
index 68d3a832..16cb9828 100644
--- a/src/com/android/browser/BrowserDownloadAdapter.java
+++ b/src/com/android/browser/BrowserDownloadAdapter.java
@@ -1,221 +1,222 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.drm.mobile1.DrmRawContent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.Downloads;
import android.text.format.Formatter;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import java.io.File;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
/**
* This class is used to represent the data for the download list box. The only
* real work done by this class is to construct a custom view for the line
* items.
*/
public class BrowserDownloadAdapter extends ResourceCursorAdapter {
private int mFilenameColumnId;
private int mTitleColumnId;
private int mDescColumnId;
private int mStatusColumnId;
private int mTotalBytesColumnId;
private int mCurrentBytesColumnId;
private int mMimetypeColumnId;
private int mDateColumnId;
public BrowserDownloadAdapter(Context context, int layout, Cursor c) {
super(context, layout, c);
mFilenameColumnId = c.getColumnIndexOrThrow(Downloads._DATA);
mTitleColumnId = c.getColumnIndexOrThrow(Downloads.COLUMN_TITLE);
mDescColumnId = c.getColumnIndexOrThrow(Downloads.COLUMN_DESCRIPTION);
mStatusColumnId = c.getColumnIndexOrThrow(Downloads.COLUMN_STATUS);
mTotalBytesColumnId = c.getColumnIndexOrThrow(Downloads.COLUMN_TOTAL_BYTES);
mCurrentBytesColumnId =
c.getColumnIndexOrThrow(Downloads.COLUMN_CURRENT_BYTES);
mMimetypeColumnId = c.getColumnIndexOrThrow(Downloads.COLUMN_MIME_TYPE);
mDateColumnId = c.getColumnIndexOrThrow(Downloads.COLUMN_LAST_MODIFICATION);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
Resources r = context.getResources();
// Retrieve the icon for this download
String mimeType = cursor.getString(mMimetypeColumnId);
ImageView iv = (ImageView) view.findViewById(R.id.download_icon);
if (DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(mimeType)) {
iv.setImageResource(R.drawable.ic_launcher_drm_file);
} else if (mimeType == null) {
iv.setVisibility(View.INVISIBLE);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromParts("file", "", null), mimeType);
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
Drawable icon = list.get(0).activityInfo.loadIcon(pm);
iv.setImageDrawable(icon);
iv.setVisibility(View.VISIBLE);
} else {
iv.setVisibility(View.INVISIBLE);
}
}
TextView tv = (TextView) view.findViewById(R.id.download_title);
String title = cursor.getString(mTitleColumnId);
if (title == null) {
String fullFilename = cursor.getString(mFilenameColumnId);
if (fullFilename == null) {
title = r.getString(R.string.download_unknown_filename);
} else {
// We have a filename, so we can build a title from that
title = new File(fullFilename).getName();
ContentValues values = new ContentValues();
values.put(Downloads.COLUMN_TITLE, title);
// assume "_id" is the first column for the cursor
context.getContentResolver().update(
ContentUris.withAppendedId(Downloads.CONTENT_URI,
cursor.getLong(0)), values, null, null);
}
}
tv.setText(title);
tv = (TextView) view.findViewById(R.id.domain);
tv.setText(cursor.getString(mDescColumnId));
long totalBytes = cursor.getLong(mTotalBytesColumnId);
int status = cursor.getInt(mStatusColumnId);
if (Downloads.isStatusCompleted(status)) { // Download stopped
View v = view.findViewById(R.id.progress_text);
v.setVisibility(View.GONE);
v = view.findViewById(R.id.download_progress);
v.setVisibility(View.GONE);
tv = (TextView) view.findViewById(R.id.complete_text);
tv.setVisibility(View.VISIBLE);
if (Downloads.isStatusError(status)) {
tv.setText(getErrorText(status));
} else {
tv.setText(r.getString(R.string.download_success,
Formatter.formatFileSize(mContext, totalBytes)));
}
long time = cursor.getLong(mDateColumnId);
Date d = new Date(time);
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
tv = (TextView) view.findViewById(R.id.complete_date);
tv.setVisibility(View.VISIBLE);
tv.setText(df.format(d));
} else { // Download is still running
tv = (TextView) view.findViewById(R.id.progress_text);
tv.setVisibility(View.VISIBLE);
View progress = view.findViewById(R.id.download_progress);
progress.setVisibility(View.VISIBLE);
View v = view.findViewById(R.id.complete_date);
v.setVisibility(View.GONE);
v = view.findViewById(R.id.complete_text);
v.setVisibility(View.GONE);
if (status == Downloads.STATUS_PENDING) {
tv.setText(r.getText(R.string.download_pending));
} else if (status == Downloads.STATUS_PENDING_PAUSED) {
tv.setText(r.getText(R.string.download_pending_network));
} else {
ProgressBar pb = (ProgressBar) progress;
StringBuilder sb = new StringBuilder();
if (status == Downloads.STATUS_RUNNING) {
sb.append(r.getText(R.string.download_running));
} else {
sb.append(r.getText(R.string.download_running_paused));
}
if (totalBytes > 0) {
long currentBytes = cursor.getLong(mCurrentBytesColumnId);
int progressAmount = (int)(currentBytes * 100 / totalBytes);
sb.append(' ');
sb.append(progressAmount);
sb.append("% (");
sb.append(Formatter.formatFileSize(mContext, currentBytes));
sb.append("/");
sb.append(Formatter.formatFileSize(mContext, totalBytes));
sb.append(")");
+ pb.setIndeterminate(false);
pb.setProgress(progressAmount);
} else {
pb.setIndeterminate(true);
}
tv.setText(sb.toString());
}
}
}
/**
* Provide the resource id for the error string.
* @param status status of the download item
* @return resource id for the error string.
*/
public static int getErrorText(int status) {
switch (status) {
case Downloads.STATUS_NOT_ACCEPTABLE:
return R.string.download_not_acceptable;
case Downloads.STATUS_LENGTH_REQUIRED:
return R.string.download_length_required;
case Downloads.STATUS_PRECONDITION_FAILED:
return R.string.download_precondition_failed;
case Downloads.STATUS_CANCELED:
return R.string.download_canceled;
case Downloads.STATUS_FILE_ERROR:
return R.string.download_file_error;
case Downloads.STATUS_BAD_REQUEST:
case Downloads.STATUS_UNKNOWN_ERROR:
default:
return R.string.download_error;
}
}
}
| true | true | public void bindView(View view, Context context, Cursor cursor) {
Resources r = context.getResources();
// Retrieve the icon for this download
String mimeType = cursor.getString(mMimetypeColumnId);
ImageView iv = (ImageView) view.findViewById(R.id.download_icon);
if (DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(mimeType)) {
iv.setImageResource(R.drawable.ic_launcher_drm_file);
} else if (mimeType == null) {
iv.setVisibility(View.INVISIBLE);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromParts("file", "", null), mimeType);
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
Drawable icon = list.get(0).activityInfo.loadIcon(pm);
iv.setImageDrawable(icon);
iv.setVisibility(View.VISIBLE);
} else {
iv.setVisibility(View.INVISIBLE);
}
}
TextView tv = (TextView) view.findViewById(R.id.download_title);
String title = cursor.getString(mTitleColumnId);
if (title == null) {
String fullFilename = cursor.getString(mFilenameColumnId);
if (fullFilename == null) {
title = r.getString(R.string.download_unknown_filename);
} else {
// We have a filename, so we can build a title from that
title = new File(fullFilename).getName();
ContentValues values = new ContentValues();
values.put(Downloads.COLUMN_TITLE, title);
// assume "_id" is the first column for the cursor
context.getContentResolver().update(
ContentUris.withAppendedId(Downloads.CONTENT_URI,
cursor.getLong(0)), values, null, null);
}
}
tv.setText(title);
tv = (TextView) view.findViewById(R.id.domain);
tv.setText(cursor.getString(mDescColumnId));
long totalBytes = cursor.getLong(mTotalBytesColumnId);
int status = cursor.getInt(mStatusColumnId);
if (Downloads.isStatusCompleted(status)) { // Download stopped
View v = view.findViewById(R.id.progress_text);
v.setVisibility(View.GONE);
v = view.findViewById(R.id.download_progress);
v.setVisibility(View.GONE);
tv = (TextView) view.findViewById(R.id.complete_text);
tv.setVisibility(View.VISIBLE);
if (Downloads.isStatusError(status)) {
tv.setText(getErrorText(status));
} else {
tv.setText(r.getString(R.string.download_success,
Formatter.formatFileSize(mContext, totalBytes)));
}
long time = cursor.getLong(mDateColumnId);
Date d = new Date(time);
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
tv = (TextView) view.findViewById(R.id.complete_date);
tv.setVisibility(View.VISIBLE);
tv.setText(df.format(d));
} else { // Download is still running
tv = (TextView) view.findViewById(R.id.progress_text);
tv.setVisibility(View.VISIBLE);
View progress = view.findViewById(R.id.download_progress);
progress.setVisibility(View.VISIBLE);
View v = view.findViewById(R.id.complete_date);
v.setVisibility(View.GONE);
v = view.findViewById(R.id.complete_text);
v.setVisibility(View.GONE);
if (status == Downloads.STATUS_PENDING) {
tv.setText(r.getText(R.string.download_pending));
} else if (status == Downloads.STATUS_PENDING_PAUSED) {
tv.setText(r.getText(R.string.download_pending_network));
} else {
ProgressBar pb = (ProgressBar) progress;
StringBuilder sb = new StringBuilder();
if (status == Downloads.STATUS_RUNNING) {
sb.append(r.getText(R.string.download_running));
} else {
sb.append(r.getText(R.string.download_running_paused));
}
if (totalBytes > 0) {
long currentBytes = cursor.getLong(mCurrentBytesColumnId);
int progressAmount = (int)(currentBytes * 100 / totalBytes);
sb.append(' ');
sb.append(progressAmount);
sb.append("% (");
sb.append(Formatter.formatFileSize(mContext, currentBytes));
sb.append("/");
sb.append(Formatter.formatFileSize(mContext, totalBytes));
sb.append(")");
pb.setProgress(progressAmount);
} else {
pb.setIndeterminate(true);
}
tv.setText(sb.toString());
}
}
}
| public void bindView(View view, Context context, Cursor cursor) {
Resources r = context.getResources();
// Retrieve the icon for this download
String mimeType = cursor.getString(mMimetypeColumnId);
ImageView iv = (ImageView) view.findViewById(R.id.download_icon);
if (DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(mimeType)) {
iv.setImageResource(R.drawable.ic_launcher_drm_file);
} else if (mimeType == null) {
iv.setVisibility(View.INVISIBLE);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromParts("file", "", null), mimeType);
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
Drawable icon = list.get(0).activityInfo.loadIcon(pm);
iv.setImageDrawable(icon);
iv.setVisibility(View.VISIBLE);
} else {
iv.setVisibility(View.INVISIBLE);
}
}
TextView tv = (TextView) view.findViewById(R.id.download_title);
String title = cursor.getString(mTitleColumnId);
if (title == null) {
String fullFilename = cursor.getString(mFilenameColumnId);
if (fullFilename == null) {
title = r.getString(R.string.download_unknown_filename);
} else {
// We have a filename, so we can build a title from that
title = new File(fullFilename).getName();
ContentValues values = new ContentValues();
values.put(Downloads.COLUMN_TITLE, title);
// assume "_id" is the first column for the cursor
context.getContentResolver().update(
ContentUris.withAppendedId(Downloads.CONTENT_URI,
cursor.getLong(0)), values, null, null);
}
}
tv.setText(title);
tv = (TextView) view.findViewById(R.id.domain);
tv.setText(cursor.getString(mDescColumnId));
long totalBytes = cursor.getLong(mTotalBytesColumnId);
int status = cursor.getInt(mStatusColumnId);
if (Downloads.isStatusCompleted(status)) { // Download stopped
View v = view.findViewById(R.id.progress_text);
v.setVisibility(View.GONE);
v = view.findViewById(R.id.download_progress);
v.setVisibility(View.GONE);
tv = (TextView) view.findViewById(R.id.complete_text);
tv.setVisibility(View.VISIBLE);
if (Downloads.isStatusError(status)) {
tv.setText(getErrorText(status));
} else {
tv.setText(r.getString(R.string.download_success,
Formatter.formatFileSize(mContext, totalBytes)));
}
long time = cursor.getLong(mDateColumnId);
Date d = new Date(time);
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
tv = (TextView) view.findViewById(R.id.complete_date);
tv.setVisibility(View.VISIBLE);
tv.setText(df.format(d));
} else { // Download is still running
tv = (TextView) view.findViewById(R.id.progress_text);
tv.setVisibility(View.VISIBLE);
View progress = view.findViewById(R.id.download_progress);
progress.setVisibility(View.VISIBLE);
View v = view.findViewById(R.id.complete_date);
v.setVisibility(View.GONE);
v = view.findViewById(R.id.complete_text);
v.setVisibility(View.GONE);
if (status == Downloads.STATUS_PENDING) {
tv.setText(r.getText(R.string.download_pending));
} else if (status == Downloads.STATUS_PENDING_PAUSED) {
tv.setText(r.getText(R.string.download_pending_network));
} else {
ProgressBar pb = (ProgressBar) progress;
StringBuilder sb = new StringBuilder();
if (status == Downloads.STATUS_RUNNING) {
sb.append(r.getText(R.string.download_running));
} else {
sb.append(r.getText(R.string.download_running_paused));
}
if (totalBytes > 0) {
long currentBytes = cursor.getLong(mCurrentBytesColumnId);
int progressAmount = (int)(currentBytes * 100 / totalBytes);
sb.append(' ');
sb.append(progressAmount);
sb.append("% (");
sb.append(Formatter.formatFileSize(mContext, currentBytes));
sb.append("/");
sb.append(Formatter.formatFileSize(mContext, totalBytes));
sb.append(")");
pb.setIndeterminate(false);
pb.setProgress(progressAmount);
} else {
pb.setIndeterminate(true);
}
tv.setText(sb.toString());
}
}
}
|
diff --git a/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNNotifyPrinter.java b/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNNotifyPrinter.java
index 30ae33c3b..52bf9fd0e 100644
--- a/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNNotifyPrinter.java
+++ b/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNNotifyPrinter.java
@@ -1,590 +1,587 @@
/*
* ====================================================================
* Copyright (c) 2004-2009 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.cli.svn;
import java.io.File;
import java.io.PrintStream;
import org.tmatesoft.svn.cli.SVNCommandUtil;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNMergeRange;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.internal.util.SVNFormatUtil;
import org.tmatesoft.svn.core.internal.wc.patch.SVNPatchHunk;
import org.tmatesoft.svn.core.internal.wc.patch.SVNPatchHunkInfo;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.util.SVNDebugLog;
import org.tmatesoft.svn.util.SVNLogType;
/**
* @version 1.3
* @author TMate Software Ltd.
*/
public class SVNNotifyPrinter implements ISVNEventHandler {
private SVNCommandEnvironment myEnvironment;
private boolean myIsInExternal;
private boolean myIsChangesReceived;
private boolean myIsDeltaSent;
private boolean myIsCheckout;
private boolean myIsExport;
private boolean myIsSuppressLastLine;
private int myTextConflicts = 0;
private int myPropConflicts = 0;
private int myTreeConflicts = 0;
private int mySkippedPaths = 0;
private int myExternalTextConflicts = 0;
private int myExternalPropConflicts = 0;
private int myExternalTreeConflicts = 0;
private int myExternalSkippedPaths = 0;
private boolean myHasExternalErrors;
private boolean myHasLockingError;
private boolean myIsWcToReposCopy;
public SVNNotifyPrinter(SVNCommandEnvironment env) {
this(env, false, false, false);
}
public SVNNotifyPrinter(SVNCommandEnvironment env, boolean isCheckout, boolean isExport, boolean suppressLastLine) {
myEnvironment = env;
myIsCheckout = isCheckout;
myIsExport = isExport;
myIsSuppressLastLine = suppressLastLine;
}
public void setWcToReposCopy(boolean wcToReposCopy) {
myIsWcToReposCopy = wcToReposCopy;
}
public boolean isWcToReposCopy() {
return myIsWcToReposCopy;
}
public boolean hasExternalErrors() {
return myHasExternalErrors;
}
public boolean hasLockingErrors() {
return myHasLockingError;
}
public void handleEvent(SVNEvent event, double progress) throws SVNException {
File file = event.getFile();
String path = null;
if (file != null) {
path = myEnvironment.getRelativePath(file);
path = SVNCommandUtil.getLocalPath(path);
}
PrintStream out = myEnvironment.getOut();
StringBuffer buffer = new StringBuffer();
if (event.getAction() == SVNEventAction.STATUS_EXTERNAL) {
buffer.append("\nPerforming status on external item at '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.STATUS_COMPLETED) {
String revStr = Long.toString(event.getRevision());
buffer.append("Status against revision: " + SVNFormatUtil.formatString(revStr, 6, false) + "\n");
} else if (event.getAction() == SVNEventAction.SKIP) {
if (event.getErrorMessage() != null && event.getExpectedAction() == SVNEventAction.UPDATE_EXTERNAL) {
// hack to let external test #14 work.
myEnvironment.getErr().println(event.getErrorMessage());
}
if (myIsInExternal) {
myExternalSkippedPaths++;
} else {
mySkippedPaths++;
}
if (event.getContentsStatus() == SVNStatusType.MISSING) {
buffer.append("Skipped missing target: '" + path + "'\n");
} else if (path != null) {
buffer.append("Skipped '" + path + "'\n");
}
- myIsSuppressLastLine = true;
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_OBSTRUCTION) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- An obstructing working copy was found\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_WORKING_ONLY) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Has no versioned parent\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_ACCESS_DENINED) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Access denied\n");
} else if (event.getAction() == SVNEventAction.SKIP_CONFLICTED) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Node remains in conflict\n");
} else if (event.getAction() == SVNEventAction.UPDATE_DELETE) {
myIsChangesReceived = true;
buffer.append("D " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_REPLACE) {
myIsChangesReceived = true;
buffer.append("R " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_ADD) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append("C " + path + "\n");
} else {
buffer.append("A " + path + "\n");
}
} else if (event.getAction() == SVNEventAction.UPDATE_EXISTS) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else {
buffer.append('E');
}
if (event.getPropertiesStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalPropConflicts++;
} else {
myPropConflicts++;
}
buffer.append('C');
} else if (event.getPropertiesStatus() == SVNStatusType.MERGED) {
buffer.append('G');
} else {
buffer.append(' ');
}
buffer.append(" " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_UPDATE) {
SVNStatusType propStatus = event.getPropertiesStatus();
if (event.getNodeKind() == SVNNodeKind.DIR &&
(propStatus == SVNStatusType.INAPPLICABLE || propStatus == SVNStatusType.UNKNOWN || propStatus == SVNStatusType.UNCHANGED)) {
return;
}
if (event.getNodeKind() == SVNNodeKind.FILE) {
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else if (event.getContentsStatus() == SVNStatusType.MERGED){
buffer.append('G');
} else if (event.getContentsStatus() == SVNStatusType.CHANGED){
buffer.append('U');
} else {
buffer.append(' ');
}
} else {
buffer.append(' ');
}
if (event.getPropertiesStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalPropConflicts++;
} else {
myPropConflicts++;
}
buffer.append('C');
} else if (event.getPropertiesStatus() == SVNStatusType.MERGED){
buffer.append('G');
} else if (event.getPropertiesStatus() == SVNStatusType.CHANGED){
buffer.append('U');
} else {
buffer.append(' ');
}
if (buffer.toString().trim().length() > 0) {
myIsChangesReceived = true;
}
if (event.getLockStatus() == SVNStatusType.LOCK_UNLOCKED) {
buffer.append('B');
} else {
buffer.append(' ');
}
if (buffer.toString().trim().length() == 0) {
return;
}
buffer.append(" " + path + "\n");
} else if (event.getAction() == SVNEventAction.MERGE_BEGIN) {
SVNMergeRange range = event.getMergeRange();
if (range == null) {
buffer.append("--- Merging differences between repository URLs into '" + path + "':\n");
} else {
long start = range.getStartRevision();
long end = range.getEndRevision();
if (start == end || start == end - 1) {
buffer.append("--- Merging r" + end + " into '" + path + "':\n");
} else if (start - 1 == end) {
buffer.append("--- Reverse-merging r" + start + " into '" + path + "':\n");
} else if (start < end) {
buffer.append("--- Merging r" + (start + 1) + " through r" + end + " into '" + path + "':\n");
} else {
buffer.append("--- Reverse-merging r" + start + " through r" + (end + 1) + " into '" + path + "':\n");
}
}
} else if (event.getAction() == SVNEventAction.FOREIGN_MERGE_BEGIN) {
SVNMergeRange range = event.getMergeRange();
if (range == null) {
buffer.append("--- Merging differences between foreign repository URLs into '" + path + "':\n");
} else {
long start = range.getStartRevision();
long end = range.getEndRevision();
if (start == end || start == end - 1) {
buffer.append("--- Merging (from foreign repository) r" + end + " into '" + path + "':\n");
} else if (start - 1 == end) {
buffer.append("--- Reverse-merging (from foreign repository) r" + start + " into '" + path + "':\n");
} else if (start < end) {
buffer.append("--- Merging (from foreign repository) r" + (start + 1) + " through r" + end + " into '" + path + "':\n");
} else {
buffer.append("--- Reverse-merging (from foreign repository) r" + start + " through r" + (end + 1) + " into '" + path + "':\n");
}
}
} else if (event.getAction() == SVNEventAction.TREE_CONFLICT) {
if (myIsInExternal) {
myExternalTreeConflicts++;
} else {
myTreeConflicts++;
}
buffer.append(" C ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_ADD) {
myIsChangesReceived = true;
buffer.append(" A ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_UPDATE) {
myIsChangesReceived = true;
buffer.append(" U ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_DELETE) {
myIsChangesReceived = true;
buffer.append(" D ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.RESTORE) {
buffer.append("Restored '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.RESTORE) {
buffer.append("Restored '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.UPDATE_EXTERNAL) {
myIsInExternal = true;
buffer.append("\nFetching external item into '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.UPDATE_EXTERNAL_REMOVED) {
buffer.append("Removed external '" + path + "'");
if (event.getErrorMessage() != null) {
buffer.append(": " + event.getErrorMessage().getMessage());
}
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.FAILED_EXTERNAL) {
myHasExternalErrors = true;
if (myIsInExternal) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() },
myEnvironment.isQuiet());
myIsInExternal = false;
myExternalPropConflicts = 0;
myExternalSkippedPaths = 0;
myExternalTextConflicts = 0;
myExternalTreeConflicts = 0;
return;
}
SVNErrorMessage warnMessage = SVNErrorMessage.create(SVNErrorCode.CL_ERROR_PROCESSING_EXTERNALS, "Error handling externals definition for ''{0}'':", path);
myEnvironment.handleWarning(warnMessage, new SVNErrorCode[] { warnMessage.getErrorCode() },
myEnvironment.isQuiet());
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() },
myEnvironment.isQuiet());
return;
} else if(event.getAction() == SVNEventAction.UPDATE_STARTED) {
if (! (myIsSuppressLastLine || myIsInExternal || myIsCheckout || myIsExport)) {
buffer.append("Updating '"+path+"':\n");
}
} else if (event.getAction() == SVNEventAction.UPDATE_COMPLETED) {
if (!myIsSuppressLastLine) {
long rev = event.getRevision();
if (rev >= 0) {
if (myIsExport) {
buffer.append(myIsInExternal ? "Exported external at revision " + rev + ".\n" : "Exported revision " + rev + ".\n");
} else if (myIsCheckout) {
buffer.append(myIsInExternal ? "Checked out external at revision " + rev + ".\n" : "Checked out revision " + rev + ".\n");
} else {
if (myIsChangesReceived) {
buffer.append(myIsInExternal ? "Updated external to revision " + rev + ".\n" : "Updated to revision " + rev + ".\n");
} else {
buffer.append(myIsInExternal ? "External at revision " + rev + ".\n" : "At revision " + rev + ".\n");
}
}
} else {
if (myIsExport) {
buffer.append(myIsInExternal ? "External export complete.\n" : "Export complete.\n");
} else if (myIsCheckout) {
buffer.append(myIsInExternal ? "External checkout complete.\n" : "Checkout complete.\n");
- } else {
- buffer.append(myIsInExternal ? "External update complete.\n" : "Update complete.\n");
- }
+ }
}
}
printConflictStatus(buffer);
if (myIsInExternal) {
buffer.append('\n');
myIsInExternal = false;
myExternalPropConflicts = 0;
myExternalSkippedPaths = 0;
myExternalTextConflicts = 0;
myExternalTreeConflicts = 0;
} else {
myPropConflicts = 0;
mySkippedPaths = 0;
myTextConflicts = 0;
myTreeConflicts = 0;
}
} else if (event.getAction() == SVNEventAction.MERGE_COMPLETE) {
printConflictStatus(buffer);
myTextConflicts = 0;
myPropConflicts = 0;
myTreeConflicts = 0;
mySkippedPaths = 0;
} else if (event.getAction() == SVNEventAction.COMMIT_MODIFIED) {
buffer.append((!isWcToReposCopy() ? "Sending " : "Sending copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_ADDED) {
if (SVNProperty.isBinaryMimeType(event.getMimeType())) {
buffer.append((!isWcToReposCopy() ? "Adding (bin) " : "Adding copy of (bin) ") + path + "\n");
} else {
buffer.append((!isWcToReposCopy() ? "Adding " : "Adding copy of ") + path + "\n");
}
} else if (event.getAction() == SVNEventAction.COMMIT_DELETED) {
buffer.append((!isWcToReposCopy() ? "Deleting " : "Deleting copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_REPLACED) {
buffer.append((!isWcToReposCopy() ? "Replacing " : "Replacing copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_DELTA_SENT) {
if (!myIsDeltaSent) {
myIsDeltaSent = true;
buffer.append("Transmitting file data ");
}
buffer.append('.');
} else if (event.getAction() == SVNEventAction.ADD) {
if (SVNProperty.isBinaryMimeType(event.getMimeType())) {
buffer.append("A (bin) " + path + "\n");
} else {
buffer.append("A " + path + "\n");
}
} else if (event.getAction() == SVNEventAction.DELETE) {
buffer.append("D " + path + "\n");
} else if (event.getAction() == SVNEventAction.REVERT) {
buffer.append("Reverted '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.FAILED_REVERT) {
buffer.append("Failed to revert '" + path + "' -- try updating instead.\n");
} else if (event.getAction() == SVNEventAction.LOCKED) {
buffer.append("'" + path + "' locked by user '" + event.getLock().getOwner() + "'.\n");
} else if (event.getAction() == SVNEventAction.UNLOCKED) {
buffer.append("'" + path + "' unlocked.\n");
} else if (event.getAction() == SVNEventAction.LOCK_FAILED ||
event.getAction() == SVNEventAction.UNLOCK_FAILED) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] {event.getErrorMessage().getErrorCode()},
myEnvironment.isQuiet());
myHasLockingError = true;
return;
} else if (event.getAction() == SVNEventAction.RESOLVED) {
buffer.append("Resolved conflicted state of '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_SET) {
buffer.append("Path '" + path + "' is now a member of changelist '" + event.getChangelistName() + "'.\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_CLEAR) {
buffer.append("Path '" + path + "' is no longer a member of a changelist.\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_MOVED) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] {
event.getErrorMessage().getErrorCode() }, myEnvironment.isQuiet());
return;
} else if (event.getAction() == SVNEventAction.PATCH) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else if (event.getNodeKind() == SVNNodeKind.FILE) {
if (event.getContentsStatus() == SVNStatusType.MERGED) {
buffer.append('G');
} else if (event.getContentsStatus() == SVNStatusType.CHANGED) {
buffer.append('U');
}
}
if (buffer.length() > 0) {
buffer.append(' ');
buffer.append(path);
}
} else if (event.getAction() == SVNEventAction.PATCH_APPLIED_HUNK) {
myIsChangesReceived = true;
final Object info = event.getInfo();
if (info == null || !(info instanceof SVNPatchHunkInfo)) {
return;
}
final SVNPatchHunkInfo hi = (SVNPatchHunkInfo) info;
final SVNPatchHunk hunk = hi.getHunk();
if (hunk.getOriginal().getStart() != hi.getMatchedLine()) {
long off;
String minus;
if (hi.getMatchedLine() > hunk.getOriginal().getStart()) {
off = hi.getMatchedLine() - hunk.getOriginal().getStart();
minus = null;
} else {
off = hunk.getOriginal().getStart() - hi.getMatchedLine();
minus = "-";
}
buffer.append("> applied hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@ with offset ");
if (null != minus) {
buffer.append(minus);
}
buffer.append(off);
if (hi.getFuzz() > 0) {
buffer.append(" and fuzz ");
buffer.append(hi.getFuzz());
}
buffer.append("\n");
} else if (hi.getFuzz() > 0) {
buffer.append("> applied hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@ with fuzz ");
buffer.append(hi.getFuzz());
buffer.append("\n");
}
} else if (event.getAction() == SVNEventAction.PATCH_REJECTED_HUNK) {
myIsChangesReceived = true;
final Object info = event.getInfo();
if (info == null || !(info instanceof SVNPatchHunkInfo)) {
return;
}
final SVNPatchHunkInfo hi = (SVNPatchHunkInfo) info;
final SVNPatchHunk hunk = hi.getHunk();
buffer.append("> rejected hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@\n");
}
if (buffer.length() > 0) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.CLIENT, buffer.toString());
out.print(buffer);
}
}
public void checkCancelled() throws SVNCancelException {
myEnvironment.checkCancelled();
}
private void printConflictStatus(StringBuffer buffer) {
int textConflicts = 0;
int propConflicts = 0;
int treeConflicts = 0;
int skippedPaths = 0;
String header = null;
if (myIsInExternal) {
header = "Summary of conflicts in external item:\n";
textConflicts = myExternalTextConflicts;
propConflicts = myExternalPropConflicts;
treeConflicts = myExternalTreeConflicts;
skippedPaths = myExternalSkippedPaths;
} else {
header = "Summary of conflicts:\n";
textConflicts = myTextConflicts;
propConflicts = myPropConflicts;
treeConflicts = myTreeConflicts;
skippedPaths = mySkippedPaths;
}
if (textConflicts > 0 || propConflicts > 0 || treeConflicts > 0 || skippedPaths > 0) {
buffer.append(header);
}
if (textConflicts > 0) {
buffer.append(" Text conflicts: ");
buffer.append(textConflicts);
buffer.append("\n");
}
if (propConflicts > 0) {
buffer.append(" Property conflicts: ");
buffer.append(propConflicts);
buffer.append("\n");
}
if (treeConflicts > 0) {
buffer.append(" Tree conflicts: ");
buffer.append(treeConflicts);
buffer.append("\n");
}
if (skippedPaths > 0) {
buffer.append(" Skipped paths: ");
buffer.append(skippedPaths);
buffer.append("\n");
}
}
}
| false | true | public void handleEvent(SVNEvent event, double progress) throws SVNException {
File file = event.getFile();
String path = null;
if (file != null) {
path = myEnvironment.getRelativePath(file);
path = SVNCommandUtil.getLocalPath(path);
}
PrintStream out = myEnvironment.getOut();
StringBuffer buffer = new StringBuffer();
if (event.getAction() == SVNEventAction.STATUS_EXTERNAL) {
buffer.append("\nPerforming status on external item at '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.STATUS_COMPLETED) {
String revStr = Long.toString(event.getRevision());
buffer.append("Status against revision: " + SVNFormatUtil.formatString(revStr, 6, false) + "\n");
} else if (event.getAction() == SVNEventAction.SKIP) {
if (event.getErrorMessage() != null && event.getExpectedAction() == SVNEventAction.UPDATE_EXTERNAL) {
// hack to let external test #14 work.
myEnvironment.getErr().println(event.getErrorMessage());
}
if (myIsInExternal) {
myExternalSkippedPaths++;
} else {
mySkippedPaths++;
}
if (event.getContentsStatus() == SVNStatusType.MISSING) {
buffer.append("Skipped missing target: '" + path + "'\n");
} else if (path != null) {
buffer.append("Skipped '" + path + "'\n");
}
myIsSuppressLastLine = true;
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_OBSTRUCTION) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- An obstructing working copy was found\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_WORKING_ONLY) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Has no versioned parent\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_ACCESS_DENINED) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Access denied\n");
} else if (event.getAction() == SVNEventAction.SKIP_CONFLICTED) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Node remains in conflict\n");
} else if (event.getAction() == SVNEventAction.UPDATE_DELETE) {
myIsChangesReceived = true;
buffer.append("D " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_REPLACE) {
myIsChangesReceived = true;
buffer.append("R " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_ADD) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append("C " + path + "\n");
} else {
buffer.append("A " + path + "\n");
}
} else if (event.getAction() == SVNEventAction.UPDATE_EXISTS) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else {
buffer.append('E');
}
if (event.getPropertiesStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalPropConflicts++;
} else {
myPropConflicts++;
}
buffer.append('C');
} else if (event.getPropertiesStatus() == SVNStatusType.MERGED) {
buffer.append('G');
} else {
buffer.append(' ');
}
buffer.append(" " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_UPDATE) {
SVNStatusType propStatus = event.getPropertiesStatus();
if (event.getNodeKind() == SVNNodeKind.DIR &&
(propStatus == SVNStatusType.INAPPLICABLE || propStatus == SVNStatusType.UNKNOWN || propStatus == SVNStatusType.UNCHANGED)) {
return;
}
if (event.getNodeKind() == SVNNodeKind.FILE) {
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else if (event.getContentsStatus() == SVNStatusType.MERGED){
buffer.append('G');
} else if (event.getContentsStatus() == SVNStatusType.CHANGED){
buffer.append('U');
} else {
buffer.append(' ');
}
} else {
buffer.append(' ');
}
if (event.getPropertiesStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalPropConflicts++;
} else {
myPropConflicts++;
}
buffer.append('C');
} else if (event.getPropertiesStatus() == SVNStatusType.MERGED){
buffer.append('G');
} else if (event.getPropertiesStatus() == SVNStatusType.CHANGED){
buffer.append('U');
} else {
buffer.append(' ');
}
if (buffer.toString().trim().length() > 0) {
myIsChangesReceived = true;
}
if (event.getLockStatus() == SVNStatusType.LOCK_UNLOCKED) {
buffer.append('B');
} else {
buffer.append(' ');
}
if (buffer.toString().trim().length() == 0) {
return;
}
buffer.append(" " + path + "\n");
} else if (event.getAction() == SVNEventAction.MERGE_BEGIN) {
SVNMergeRange range = event.getMergeRange();
if (range == null) {
buffer.append("--- Merging differences between repository URLs into '" + path + "':\n");
} else {
long start = range.getStartRevision();
long end = range.getEndRevision();
if (start == end || start == end - 1) {
buffer.append("--- Merging r" + end + " into '" + path + "':\n");
} else if (start - 1 == end) {
buffer.append("--- Reverse-merging r" + start + " into '" + path + "':\n");
} else if (start < end) {
buffer.append("--- Merging r" + (start + 1) + " through r" + end + " into '" + path + "':\n");
} else {
buffer.append("--- Reverse-merging r" + start + " through r" + (end + 1) + " into '" + path + "':\n");
}
}
} else if (event.getAction() == SVNEventAction.FOREIGN_MERGE_BEGIN) {
SVNMergeRange range = event.getMergeRange();
if (range == null) {
buffer.append("--- Merging differences between foreign repository URLs into '" + path + "':\n");
} else {
long start = range.getStartRevision();
long end = range.getEndRevision();
if (start == end || start == end - 1) {
buffer.append("--- Merging (from foreign repository) r" + end + " into '" + path + "':\n");
} else if (start - 1 == end) {
buffer.append("--- Reverse-merging (from foreign repository) r" + start + " into '" + path + "':\n");
} else if (start < end) {
buffer.append("--- Merging (from foreign repository) r" + (start + 1) + " through r" + end + " into '" + path + "':\n");
} else {
buffer.append("--- Reverse-merging (from foreign repository) r" + start + " through r" + (end + 1) + " into '" + path + "':\n");
}
}
} else if (event.getAction() == SVNEventAction.TREE_CONFLICT) {
if (myIsInExternal) {
myExternalTreeConflicts++;
} else {
myTreeConflicts++;
}
buffer.append(" C ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_ADD) {
myIsChangesReceived = true;
buffer.append(" A ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_UPDATE) {
myIsChangesReceived = true;
buffer.append(" U ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_DELETE) {
myIsChangesReceived = true;
buffer.append(" D ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.RESTORE) {
buffer.append("Restored '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.RESTORE) {
buffer.append("Restored '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.UPDATE_EXTERNAL) {
myIsInExternal = true;
buffer.append("\nFetching external item into '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.UPDATE_EXTERNAL_REMOVED) {
buffer.append("Removed external '" + path + "'");
if (event.getErrorMessage() != null) {
buffer.append(": " + event.getErrorMessage().getMessage());
}
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.FAILED_EXTERNAL) {
myHasExternalErrors = true;
if (myIsInExternal) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() },
myEnvironment.isQuiet());
myIsInExternal = false;
myExternalPropConflicts = 0;
myExternalSkippedPaths = 0;
myExternalTextConflicts = 0;
myExternalTreeConflicts = 0;
return;
}
SVNErrorMessage warnMessage = SVNErrorMessage.create(SVNErrorCode.CL_ERROR_PROCESSING_EXTERNALS, "Error handling externals definition for ''{0}'':", path);
myEnvironment.handleWarning(warnMessage, new SVNErrorCode[] { warnMessage.getErrorCode() },
myEnvironment.isQuiet());
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() },
myEnvironment.isQuiet());
return;
} else if(event.getAction() == SVNEventAction.UPDATE_STARTED) {
if (! (myIsSuppressLastLine || myIsInExternal || myIsCheckout || myIsExport)) {
buffer.append("Updating '"+path+"':\n");
}
} else if (event.getAction() == SVNEventAction.UPDATE_COMPLETED) {
if (!myIsSuppressLastLine) {
long rev = event.getRevision();
if (rev >= 0) {
if (myIsExport) {
buffer.append(myIsInExternal ? "Exported external at revision " + rev + ".\n" : "Exported revision " + rev + ".\n");
} else if (myIsCheckout) {
buffer.append(myIsInExternal ? "Checked out external at revision " + rev + ".\n" : "Checked out revision " + rev + ".\n");
} else {
if (myIsChangesReceived) {
buffer.append(myIsInExternal ? "Updated external to revision " + rev + ".\n" : "Updated to revision " + rev + ".\n");
} else {
buffer.append(myIsInExternal ? "External at revision " + rev + ".\n" : "At revision " + rev + ".\n");
}
}
} else {
if (myIsExport) {
buffer.append(myIsInExternal ? "External export complete.\n" : "Export complete.\n");
} else if (myIsCheckout) {
buffer.append(myIsInExternal ? "External checkout complete.\n" : "Checkout complete.\n");
} else {
buffer.append(myIsInExternal ? "External update complete.\n" : "Update complete.\n");
}
}
}
printConflictStatus(buffer);
if (myIsInExternal) {
buffer.append('\n');
myIsInExternal = false;
myExternalPropConflicts = 0;
myExternalSkippedPaths = 0;
myExternalTextConflicts = 0;
myExternalTreeConflicts = 0;
} else {
myPropConflicts = 0;
mySkippedPaths = 0;
myTextConflicts = 0;
myTreeConflicts = 0;
}
} else if (event.getAction() == SVNEventAction.MERGE_COMPLETE) {
printConflictStatus(buffer);
myTextConflicts = 0;
myPropConflicts = 0;
myTreeConflicts = 0;
mySkippedPaths = 0;
} else if (event.getAction() == SVNEventAction.COMMIT_MODIFIED) {
buffer.append((!isWcToReposCopy() ? "Sending " : "Sending copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_ADDED) {
if (SVNProperty.isBinaryMimeType(event.getMimeType())) {
buffer.append((!isWcToReposCopy() ? "Adding (bin) " : "Adding copy of (bin) ") + path + "\n");
} else {
buffer.append((!isWcToReposCopy() ? "Adding " : "Adding copy of ") + path + "\n");
}
} else if (event.getAction() == SVNEventAction.COMMIT_DELETED) {
buffer.append((!isWcToReposCopy() ? "Deleting " : "Deleting copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_REPLACED) {
buffer.append((!isWcToReposCopy() ? "Replacing " : "Replacing copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_DELTA_SENT) {
if (!myIsDeltaSent) {
myIsDeltaSent = true;
buffer.append("Transmitting file data ");
}
buffer.append('.');
} else if (event.getAction() == SVNEventAction.ADD) {
if (SVNProperty.isBinaryMimeType(event.getMimeType())) {
buffer.append("A (bin) " + path + "\n");
} else {
buffer.append("A " + path + "\n");
}
} else if (event.getAction() == SVNEventAction.DELETE) {
buffer.append("D " + path + "\n");
} else if (event.getAction() == SVNEventAction.REVERT) {
buffer.append("Reverted '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.FAILED_REVERT) {
buffer.append("Failed to revert '" + path + "' -- try updating instead.\n");
} else if (event.getAction() == SVNEventAction.LOCKED) {
buffer.append("'" + path + "' locked by user '" + event.getLock().getOwner() + "'.\n");
} else if (event.getAction() == SVNEventAction.UNLOCKED) {
buffer.append("'" + path + "' unlocked.\n");
} else if (event.getAction() == SVNEventAction.LOCK_FAILED ||
event.getAction() == SVNEventAction.UNLOCK_FAILED) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] {event.getErrorMessage().getErrorCode()},
myEnvironment.isQuiet());
myHasLockingError = true;
return;
} else if (event.getAction() == SVNEventAction.RESOLVED) {
buffer.append("Resolved conflicted state of '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_SET) {
buffer.append("Path '" + path + "' is now a member of changelist '" + event.getChangelistName() + "'.\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_CLEAR) {
buffer.append("Path '" + path + "' is no longer a member of a changelist.\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_MOVED) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] {
event.getErrorMessage().getErrorCode() }, myEnvironment.isQuiet());
return;
} else if (event.getAction() == SVNEventAction.PATCH) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else if (event.getNodeKind() == SVNNodeKind.FILE) {
if (event.getContentsStatus() == SVNStatusType.MERGED) {
buffer.append('G');
} else if (event.getContentsStatus() == SVNStatusType.CHANGED) {
buffer.append('U');
}
}
if (buffer.length() > 0) {
buffer.append(' ');
buffer.append(path);
}
} else if (event.getAction() == SVNEventAction.PATCH_APPLIED_HUNK) {
myIsChangesReceived = true;
final Object info = event.getInfo();
if (info == null || !(info instanceof SVNPatchHunkInfo)) {
return;
}
final SVNPatchHunkInfo hi = (SVNPatchHunkInfo) info;
final SVNPatchHunk hunk = hi.getHunk();
if (hunk.getOriginal().getStart() != hi.getMatchedLine()) {
long off;
String minus;
if (hi.getMatchedLine() > hunk.getOriginal().getStart()) {
off = hi.getMatchedLine() - hunk.getOriginal().getStart();
minus = null;
} else {
off = hunk.getOriginal().getStart() - hi.getMatchedLine();
minus = "-";
}
buffer.append("> applied hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@ with offset ");
if (null != minus) {
buffer.append(minus);
}
buffer.append(off);
if (hi.getFuzz() > 0) {
buffer.append(" and fuzz ");
buffer.append(hi.getFuzz());
}
buffer.append("\n");
} else if (hi.getFuzz() > 0) {
buffer.append("> applied hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@ with fuzz ");
buffer.append(hi.getFuzz());
buffer.append("\n");
}
} else if (event.getAction() == SVNEventAction.PATCH_REJECTED_HUNK) {
myIsChangesReceived = true;
final Object info = event.getInfo();
if (info == null || !(info instanceof SVNPatchHunkInfo)) {
return;
}
final SVNPatchHunkInfo hi = (SVNPatchHunkInfo) info;
final SVNPatchHunk hunk = hi.getHunk();
buffer.append("> rejected hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@\n");
}
if (buffer.length() > 0) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.CLIENT, buffer.toString());
out.print(buffer);
}
}
| public void handleEvent(SVNEvent event, double progress) throws SVNException {
File file = event.getFile();
String path = null;
if (file != null) {
path = myEnvironment.getRelativePath(file);
path = SVNCommandUtil.getLocalPath(path);
}
PrintStream out = myEnvironment.getOut();
StringBuffer buffer = new StringBuffer();
if (event.getAction() == SVNEventAction.STATUS_EXTERNAL) {
buffer.append("\nPerforming status on external item at '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.STATUS_COMPLETED) {
String revStr = Long.toString(event.getRevision());
buffer.append("Status against revision: " + SVNFormatUtil.formatString(revStr, 6, false) + "\n");
} else if (event.getAction() == SVNEventAction.SKIP) {
if (event.getErrorMessage() != null && event.getExpectedAction() == SVNEventAction.UPDATE_EXTERNAL) {
// hack to let external test #14 work.
myEnvironment.getErr().println(event.getErrorMessage());
}
if (myIsInExternal) {
myExternalSkippedPaths++;
} else {
mySkippedPaths++;
}
if (event.getContentsStatus() == SVNStatusType.MISSING) {
buffer.append("Skipped missing target: '" + path + "'\n");
} else if (path != null) {
buffer.append("Skipped '" + path + "'\n");
}
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_OBSTRUCTION) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- An obstructing working copy was found\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_WORKING_ONLY) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Has no versioned parent\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SKIP_ACCESS_DENINED) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Access denied\n");
} else if (event.getAction() == SVNEventAction.SKIP_CONFLICTED) {
mySkippedPaths++;
buffer.append("Skipped '" + path + "' -- Node remains in conflict\n");
} else if (event.getAction() == SVNEventAction.UPDATE_DELETE) {
myIsChangesReceived = true;
buffer.append("D " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_REPLACE) {
myIsChangesReceived = true;
buffer.append("R " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_ADD) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append("C " + path + "\n");
} else {
buffer.append("A " + path + "\n");
}
} else if (event.getAction() == SVNEventAction.UPDATE_EXISTS) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else {
buffer.append('E');
}
if (event.getPropertiesStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalPropConflicts++;
} else {
myPropConflicts++;
}
buffer.append('C');
} else if (event.getPropertiesStatus() == SVNStatusType.MERGED) {
buffer.append('G');
} else {
buffer.append(' ');
}
buffer.append(" " + path + "\n");
} else if (event.getAction() == SVNEventAction.UPDATE_UPDATE) {
SVNStatusType propStatus = event.getPropertiesStatus();
if (event.getNodeKind() == SVNNodeKind.DIR &&
(propStatus == SVNStatusType.INAPPLICABLE || propStatus == SVNStatusType.UNKNOWN || propStatus == SVNStatusType.UNCHANGED)) {
return;
}
if (event.getNodeKind() == SVNNodeKind.FILE) {
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else if (event.getContentsStatus() == SVNStatusType.MERGED){
buffer.append('G');
} else if (event.getContentsStatus() == SVNStatusType.CHANGED){
buffer.append('U');
} else {
buffer.append(' ');
}
} else {
buffer.append(' ');
}
if (event.getPropertiesStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalPropConflicts++;
} else {
myPropConflicts++;
}
buffer.append('C');
} else if (event.getPropertiesStatus() == SVNStatusType.MERGED){
buffer.append('G');
} else if (event.getPropertiesStatus() == SVNStatusType.CHANGED){
buffer.append('U');
} else {
buffer.append(' ');
}
if (buffer.toString().trim().length() > 0) {
myIsChangesReceived = true;
}
if (event.getLockStatus() == SVNStatusType.LOCK_UNLOCKED) {
buffer.append('B');
} else {
buffer.append(' ');
}
if (buffer.toString().trim().length() == 0) {
return;
}
buffer.append(" " + path + "\n");
} else if (event.getAction() == SVNEventAction.MERGE_BEGIN) {
SVNMergeRange range = event.getMergeRange();
if (range == null) {
buffer.append("--- Merging differences between repository URLs into '" + path + "':\n");
} else {
long start = range.getStartRevision();
long end = range.getEndRevision();
if (start == end || start == end - 1) {
buffer.append("--- Merging r" + end + " into '" + path + "':\n");
} else if (start - 1 == end) {
buffer.append("--- Reverse-merging r" + start + " into '" + path + "':\n");
} else if (start < end) {
buffer.append("--- Merging r" + (start + 1) + " through r" + end + " into '" + path + "':\n");
} else {
buffer.append("--- Reverse-merging r" + start + " through r" + (end + 1) + " into '" + path + "':\n");
}
}
} else if (event.getAction() == SVNEventAction.FOREIGN_MERGE_BEGIN) {
SVNMergeRange range = event.getMergeRange();
if (range == null) {
buffer.append("--- Merging differences between foreign repository URLs into '" + path + "':\n");
} else {
long start = range.getStartRevision();
long end = range.getEndRevision();
if (start == end || start == end - 1) {
buffer.append("--- Merging (from foreign repository) r" + end + " into '" + path + "':\n");
} else if (start - 1 == end) {
buffer.append("--- Reverse-merging (from foreign repository) r" + start + " into '" + path + "':\n");
} else if (start < end) {
buffer.append("--- Merging (from foreign repository) r" + (start + 1) + " through r" + end + " into '" + path + "':\n");
} else {
buffer.append("--- Reverse-merging (from foreign repository) r" + start + " through r" + (end + 1) + " into '" + path + "':\n");
}
}
} else if (event.getAction() == SVNEventAction.TREE_CONFLICT) {
if (myIsInExternal) {
myExternalTreeConflicts++;
} else {
myTreeConflicts++;
}
buffer.append(" C ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_ADD) {
myIsChangesReceived = true;
buffer.append(" A ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_UPDATE) {
myIsChangesReceived = true;
buffer.append(" U ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_DELETE) {
myIsChangesReceived = true;
buffer.append(" D ");
buffer.append(path);
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.RESTORE) {
buffer.append("Restored '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.RESTORE) {
buffer.append("Restored '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.UPDATE_EXTERNAL) {
myIsInExternal = true;
buffer.append("\nFetching external item into '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.UPDATE_EXTERNAL_REMOVED) {
buffer.append("Removed external '" + path + "'");
if (event.getErrorMessage() != null) {
buffer.append(": " + event.getErrorMessage().getMessage());
}
buffer.append("\n");
} else if (event.getAction() == SVNEventAction.FAILED_EXTERNAL) {
myHasExternalErrors = true;
if (myIsInExternal) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() },
myEnvironment.isQuiet());
myIsInExternal = false;
myExternalPropConflicts = 0;
myExternalSkippedPaths = 0;
myExternalTextConflicts = 0;
myExternalTreeConflicts = 0;
return;
}
SVNErrorMessage warnMessage = SVNErrorMessage.create(SVNErrorCode.CL_ERROR_PROCESSING_EXTERNALS, "Error handling externals definition for ''{0}'':", path);
myEnvironment.handleWarning(warnMessage, new SVNErrorCode[] { warnMessage.getErrorCode() },
myEnvironment.isQuiet());
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() },
myEnvironment.isQuiet());
return;
} else if(event.getAction() == SVNEventAction.UPDATE_STARTED) {
if (! (myIsSuppressLastLine || myIsInExternal || myIsCheckout || myIsExport)) {
buffer.append("Updating '"+path+"':\n");
}
} else if (event.getAction() == SVNEventAction.UPDATE_COMPLETED) {
if (!myIsSuppressLastLine) {
long rev = event.getRevision();
if (rev >= 0) {
if (myIsExport) {
buffer.append(myIsInExternal ? "Exported external at revision " + rev + ".\n" : "Exported revision " + rev + ".\n");
} else if (myIsCheckout) {
buffer.append(myIsInExternal ? "Checked out external at revision " + rev + ".\n" : "Checked out revision " + rev + ".\n");
} else {
if (myIsChangesReceived) {
buffer.append(myIsInExternal ? "Updated external to revision " + rev + ".\n" : "Updated to revision " + rev + ".\n");
} else {
buffer.append(myIsInExternal ? "External at revision " + rev + ".\n" : "At revision " + rev + ".\n");
}
}
} else {
if (myIsExport) {
buffer.append(myIsInExternal ? "External export complete.\n" : "Export complete.\n");
} else if (myIsCheckout) {
buffer.append(myIsInExternal ? "External checkout complete.\n" : "Checkout complete.\n");
}
}
}
printConflictStatus(buffer);
if (myIsInExternal) {
buffer.append('\n');
myIsInExternal = false;
myExternalPropConflicts = 0;
myExternalSkippedPaths = 0;
myExternalTextConflicts = 0;
myExternalTreeConflicts = 0;
} else {
myPropConflicts = 0;
mySkippedPaths = 0;
myTextConflicts = 0;
myTreeConflicts = 0;
}
} else if (event.getAction() == SVNEventAction.MERGE_COMPLETE) {
printConflictStatus(buffer);
myTextConflicts = 0;
myPropConflicts = 0;
myTreeConflicts = 0;
mySkippedPaths = 0;
} else if (event.getAction() == SVNEventAction.COMMIT_MODIFIED) {
buffer.append((!isWcToReposCopy() ? "Sending " : "Sending copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_ADDED) {
if (SVNProperty.isBinaryMimeType(event.getMimeType())) {
buffer.append((!isWcToReposCopy() ? "Adding (bin) " : "Adding copy of (bin) ") + path + "\n");
} else {
buffer.append((!isWcToReposCopy() ? "Adding " : "Adding copy of ") + path + "\n");
}
} else if (event.getAction() == SVNEventAction.COMMIT_DELETED) {
buffer.append((!isWcToReposCopy() ? "Deleting " : "Deleting copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_REPLACED) {
buffer.append((!isWcToReposCopy() ? "Replacing " : "Replacing copy of ") + path + "\n");
} else if (event.getAction() == SVNEventAction.COMMIT_DELTA_SENT) {
if (!myIsDeltaSent) {
myIsDeltaSent = true;
buffer.append("Transmitting file data ");
}
buffer.append('.');
} else if (event.getAction() == SVNEventAction.ADD) {
if (SVNProperty.isBinaryMimeType(event.getMimeType())) {
buffer.append("A (bin) " + path + "\n");
} else {
buffer.append("A " + path + "\n");
}
} else if (event.getAction() == SVNEventAction.DELETE) {
buffer.append("D " + path + "\n");
} else if (event.getAction() == SVNEventAction.REVERT) {
buffer.append("Reverted '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.FAILED_REVERT) {
buffer.append("Failed to revert '" + path + "' -- try updating instead.\n");
} else if (event.getAction() == SVNEventAction.LOCKED) {
buffer.append("'" + path + "' locked by user '" + event.getLock().getOwner() + "'.\n");
} else if (event.getAction() == SVNEventAction.UNLOCKED) {
buffer.append("'" + path + "' unlocked.\n");
} else if (event.getAction() == SVNEventAction.LOCK_FAILED ||
event.getAction() == SVNEventAction.UNLOCK_FAILED) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] {event.getErrorMessage().getErrorCode()},
myEnvironment.isQuiet());
myHasLockingError = true;
return;
} else if (event.getAction() == SVNEventAction.RESOLVED) {
buffer.append("Resolved conflicted state of '" + path + "'\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_SET) {
buffer.append("Path '" + path + "' is now a member of changelist '" + event.getChangelistName() + "'.\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_CLEAR) {
buffer.append("Path '" + path + "' is no longer a member of a changelist.\n");
} else if (event.getAction() == SVNEventAction.CHANGELIST_MOVED) {
myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] {
event.getErrorMessage().getErrorCode() }, myEnvironment.isQuiet());
return;
} else if (event.getAction() == SVNEventAction.PATCH) {
myIsChangesReceived = true;
if (event.getContentsStatus() == SVNStatusType.CONFLICTED) {
if (myIsInExternal) {
myExternalTextConflicts++;
} else {
myTextConflicts++;
}
buffer.append('C');
} else if (event.getNodeKind() == SVNNodeKind.FILE) {
if (event.getContentsStatus() == SVNStatusType.MERGED) {
buffer.append('G');
} else if (event.getContentsStatus() == SVNStatusType.CHANGED) {
buffer.append('U');
}
}
if (buffer.length() > 0) {
buffer.append(' ');
buffer.append(path);
}
} else if (event.getAction() == SVNEventAction.PATCH_APPLIED_HUNK) {
myIsChangesReceived = true;
final Object info = event.getInfo();
if (info == null || !(info instanceof SVNPatchHunkInfo)) {
return;
}
final SVNPatchHunkInfo hi = (SVNPatchHunkInfo) info;
final SVNPatchHunk hunk = hi.getHunk();
if (hunk.getOriginal().getStart() != hi.getMatchedLine()) {
long off;
String minus;
if (hi.getMatchedLine() > hunk.getOriginal().getStart()) {
off = hi.getMatchedLine() - hunk.getOriginal().getStart();
minus = null;
} else {
off = hunk.getOriginal().getStart() - hi.getMatchedLine();
minus = "-";
}
buffer.append("> applied hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@ with offset ");
if (null != minus) {
buffer.append(minus);
}
buffer.append(off);
if (hi.getFuzz() > 0) {
buffer.append(" and fuzz ");
buffer.append(hi.getFuzz());
}
buffer.append("\n");
} else if (hi.getFuzz() > 0) {
buffer.append("> applied hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@ with fuzz ");
buffer.append(hi.getFuzz());
buffer.append("\n");
}
} else if (event.getAction() == SVNEventAction.PATCH_REJECTED_HUNK) {
myIsChangesReceived = true;
final Object info = event.getInfo();
if (info == null || !(info instanceof SVNPatchHunkInfo)) {
return;
}
final SVNPatchHunkInfo hi = (SVNPatchHunkInfo) info;
final SVNPatchHunk hunk = hi.getHunk();
buffer.append("> rejected hunk @@ -");
buffer.append(hunk.getOriginal().getStart());
buffer.append(",");
buffer.append(hunk.getOriginal().getLength());
buffer.append(" +");
buffer.append(hunk.getModified().getStart());
buffer.append(",");
buffer.append(hunk.getModified().getLength());
buffer.append(" @@\n");
}
if (buffer.length() > 0) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.CLIENT, buffer.toString());
out.print(buffer);
}
}
|
diff --git a/org/lateralgm/main/Listener.java b/org/lateralgm/main/Listener.java
index 52a73f32..71143267 100644
--- a/org/lateralgm/main/Listener.java
+++ b/org/lateralgm/main/Listener.java
@@ -1,451 +1,459 @@
/*
* Copyright (C) 2007, 2008, 2009, 2010 IsmAvatar <[email protected]>
* Copyright (C) 2007 TGMG <[email protected]>
* Copyright (C) 2007, 2008 Clam <[email protected]>
* Copyright (C) 2008, 2009 Quadduc <[email protected]>
*
* This file is part of LateralGM.
* LateralGM is free software and comes with ABSOLUTELY NO WARRANTY.
* See LICENSE for details.
*/
package org.lateralgm.main;
import static org.lateralgm.main.Util.deRef;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;
import java.util.HashSet;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.tree.TreePath;
import org.lateralgm.components.AboutBox;
import org.lateralgm.components.impl.ResNode;
import org.lateralgm.file.ResourceList;
import org.lateralgm.messages.Messages;
import org.lateralgm.resources.Resource;
import org.lateralgm.resources.ResourceReference;
public class Listener extends TransferHandler implements ActionListener,CellEditorListener
{
private static final long serialVersionUID = 1L;
MListener mListener = new MListener();
public FileChooser fc = new FileChooser();
private Listener()
{
}
private static final class LazyHolder
{
public static final Listener INSTANCE = new Listener();
}
public static Listener getInstance()
{
return LazyHolder.INSTANCE;
}
public static class ResourceAdder implements ActionListener
{
public boolean insert;
public Class<?> k;
public ResourceAdder(boolean insert, Class<?> k)
{
this.insert = insert;
this.k = k;
}
public void actionPerformed(ActionEvent e)
{
if (insert)
Listener.insertResource(LGM.tree,k);
else
Listener.addResource(LGM.tree,k);
}
}
public static void addResource(JTree tree, Class<?> r)
{
addResource(tree,r,null);
}
protected static void addResource(JTree tree, Class<?> r, Resource<?,?> res)
{
ResNode node = (ResNode) tree.getLastSelectedPathComponent();
if (node == null) return;
ResNode parent;
int pos;
if (node.getAllowsChildren())
{
parent = node;
pos = parent.getChildCount();
}
else
{
parent = (ResNode) node.getParent();
pos = parent.getIndex(node) + 1;
}
putNode(tree,node,parent,r,pos,res);
}
public static void insertResource(JTree tree, Class<?> r)
{
insertResource(tree,r,null);
}
protected static void insertResource(JTree tree, Class<?> r, Resource<?,?> res)
{
ResNode node = (ResNode) tree.getLastSelectedPathComponent();
if (node == null) return;
ResNode parent = (ResNode) node.getParent();
if (parent.isRoot())
{
addResource(tree,r,res);
return;
}
int pos = parent.getIndex(node);
putNode(tree,node,parent,r,pos,res);
}
public static void putNode(JTree tree, ResNode node, ResNode parent, Class<?> r, int pos,
Resource<?,?> res)
{
if (r == null)
{
String msg = Messages.getString("Listener.INPUT_GROUPNAME"); //$NON-NLS-1$
String name = JOptionPane.showInputDialog(msg,
Messages.getString("Listener.DEFAULT_GROUPNAME")); //$NON-NLS-1$
if (name == null || name.isEmpty()) return;
ResNode g = new ResNode(name,ResNode.STATUS_GROUP,parent.kind);
parent.insert(g,pos);
tree.expandPath(new TreePath(parent.getPath()));
tree.setSelectionPath(new TreePath(g.getPath()));
tree.updateUI();
return;
}
if (node.kind != r)
{
parent = getPrimaryParent(r);
pos = parent.getChildCount();
}
Resource<?,?> resource = res == null ? LGM.currentFile.resMap.get(parent.kind).getResource()
: res;
ResNode g = new ResNode(resource.getName(),ResNode.STATUS_SECONDARY,parent.kind,
resource.reference);
parent.insert(g,pos);
tree.expandPath(new TreePath(parent.getPath()));
tree.setSelectionPath(new TreePath(g.getPath()));
tree.updateUI();
g.openFrame(true);
}
protected static void deleteSelectedResource(JTree tree)
{
ResNode me = (ResNode) tree.getLastSelectedPathComponent();
if (me == null || !me.isInstantiable() || me.status == ResNode.STATUS_PRIMARY) return;
String msg = Messages.getString("Listener.CONFIRM_DELETERESOURCE"); //$NON-NLS-1$
if (JOptionPane.showConfirmDialog(null,msg,
Messages.getString("Listener.CONFIRM_DELETERESOURCE_TITLE"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION) == 0)
{
ResNode next = (ResNode) me.getNextSibling();
if (next == null) next = (ResNode) me.getParent();
if (next.isRoot()) next = (ResNode) next.getFirstChild();
tree.setSelectionPath(new TreePath(next.getPath()));
Enumeration<?> nodes = me.depthFirstEnumeration();
// Calling dispose() on a resource modifies the tree and invalidates
// the enumeration, so we need to wait until after traversal.
HashSet<Resource<?,?>> rs = new HashSet<Resource<?,?>>();
while (nodes.hasMoreElements())
{
ResNode node = (ResNode) nodes.nextElement();
if (node.frame != null) node.frame.dispose();
if (node.status == ResNode.STATUS_SECONDARY)
{
Resource<?,?> res = deRef((ResourceReference<?>) node.getRes());
if (res != null) rs.add(res);
((ResourceList<?>) LGM.currentFile.resMap.get(node.kind)).remove(res);
}
}
for (Resource<?,?> r : rs)
r.dispose();
me.removeFromParent();
tree.updateUI();
}
}
public void actionPerformed(ActionEvent e)
{
JTree tree = LGM.tree;
String[] args = e.getActionCommand().split(" "); //$NON-NLS-1$
String com = args[0];
if (com.endsWith(".NEW")) //$NON-NLS-1$
{
String title = Messages.getString("Listener.CONFIRM_NEW_TITLE"); //$NON-NLS-1$
String message = Messages.getString("Listener.CONFIRM_NEW"); //$NON-NLS-1$
int opt = JOptionPane.showConfirmDialog(LGM.frame,message,title,JOptionPane.YES_NO_OPTION);
//I'd love to default to "No", but apparently that's not an option.
if (opt == JOptionPane.YES_OPTION) fc.newFile();
return;
}
if (com.endsWith(".OPEN")) //$NON-NLS-1$
{
try
{
fc.open(args.length > 1 ? new URI(args[1]) : null);
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
return;
}
if (com.endsWith(".SAVE")) //$NON-NLS-1$
{
fc.save(LGM.currentFile.uri,LGM.currentFile.format);
return;
}
if (com.endsWith(".SAVEAS")) //$NON-NLS-1$
{
fc.saveNewFile();
return;
}
if (com.endsWith(".EVENT_BUTTON")) //$NON-NLS-1$
{
Object o = e.getSource();
if (o instanceof JToggleButton) LGM.eventSelect.setVisible(((JToggleButton) o).isSelected());
return;
}
if (com.endsWith(".EXIT")) //$NON-NLS-1$
{
System.exit(0);
return;
}
if (com.contains(".INSERT_") || com.contains(".ADD_")) //$NON-NLS-1$ //$NON-NLS-2$
{
- //we no longer do it this way
+ if (com.endsWith("GROUP")) //$NON-NLS-1$
+ {
+ if (com.contains(".INSERT_"))
+ insertResource(tree,null);
+ else
+ addResource(tree,null);
+ return;
+ }
+ //we no longer do it this way for resources
throw new UnsupportedOperationException(com);
}
if (com.endsWith(".RENAME")) //$NON-NLS-1$
{
if (tree.getCellEditor().isCellEditable(null))
tree.startEditingAtPath(tree.getLeadSelectionPath());
return;
}
if (com.endsWith(".DELETE")) //$NON-NLS-1$
{
deleteSelectedResource(tree);
return;
}
if (com.endsWith(".DEFRAGIDS")) //$NON-NLS-1$
{
String msg = Messages.getString("Listener.CONFIRM_DEFRAGIDS"); //$NON-NLS-1$
if (JOptionPane.showConfirmDialog(LGM.frame,msg,
Messages.getString("Listener.CONFIRM_DEFRAGIDS_TITLE"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION) == 0) LGM.currentFile.defragIds();
}
if (com.endsWith(".EXPAND")) //$NON-NLS-1$
{
for (int m = 0; m < tree.getRowCount(); m++)
tree.expandRow(m);
return;
}
if (com.endsWith(".COLLAPSE")) //$NON-NLS-1$
{
for (int m = tree.getRowCount() - 1; m >= 0; m--)
tree.collapseRow(m);
return;
}
if (com.endsWith(".ABOUT")) //$NON-NLS-1$
{
new AboutBox(LGM.frame).setVisible(true);
return;
}
}
public static ResNode getPrimaryParent(Class<?> kind)
{
for (int i = 0; i < LGM.root.getChildCount(); i++)
if (((ResNode) LGM.root.getChildAt(i)).kind == kind) return (ResNode) LGM.root.getChildAt(i);
return null;
}
protected Transferable createTransferable(JComponent c)
{
ResNode n = (ResNode) ((JTree) c).getLastSelectedPathComponent();
if (n.status == ResNode.STATUS_PRIMARY) return null;
if (!n.isInstantiable()) return null;
return n;
}
public int getSourceActions(JComponent c)
{
return MOVE;
}
public boolean canImport(TransferHandler.TransferSupport support)
{
if (!support.isDataFlavorSupported(ResNode.NODE_FLAVOR)) return false;
// the above method uses equals(), which does not work as expected
for (DataFlavor f : support.getDataFlavors())
if (f != ResNode.NODE_FLAVOR) return false;
TreePath drop = ((JTree.DropLocation) support.getDropLocation()).getPath();
if (drop == null) return false;
ResNode dropNode = (ResNode) drop.getLastPathComponent();
ResNode dragNode = (ResNode) ((JTree) support.getComponent()).getLastSelectedPathComponent();
if (dragNode == dropNode) return false;
if (dragNode.isNodeDescendant(dropNode)) return false;
if (Prefs.groupKind && dropNode.kind != dragNode.kind) return false;
if (dropNode.status == ResNode.STATUS_SECONDARY) return false;
return true;
}
public boolean importData(TransferHandler.TransferSupport support)
{
if (!canImport(support)) return false;
JTree.DropLocation drop = (JTree.DropLocation) support.getDropLocation();
int dropIndex = drop.getChildIndex();
ResNode dropNode = (ResNode) drop.getPath().getLastPathComponent();
ResNode dragNode = (ResNode) ((JTree) support.getComponent()).getLastSelectedPathComponent();
if (dropIndex == -1)
{
dropIndex = dropNode.getChildCount();
}
if (dropNode == dragNode.getParent() && dropIndex > dragNode.getParent().getIndex(dragNode))
dropIndex--;
dropNode.insert(dragNode,dropIndex);
LGM.tree.expandPath(new TreePath(dropNode.getPath()));
LGM.tree.updateUI();
return true;
}
public static class NodeMenuListener implements ActionListener
{
ResNode node;
public NodeMenuListener(ResNode node)
{
this.node = node;
}
public void actionPerformed(ActionEvent e)
{
JTree tree = LGM.tree;
String com = e.getActionCommand().substring(e.getActionCommand().lastIndexOf('_') + 1);
if (com.equals("EDIT")) //$NON-NLS-1$
{
if (node.status == ResNode.STATUS_SECONDARY) node.openFrame();
return;
}
if (com.equals("DELETE")) //$NON-NLS-1$
{
deleteSelectedResource(tree);
return;
}
if (com.equals("RENAME")) //$NON-NLS-1$
{
if (tree.getCellEditor().isCellEditable(null))
tree.startEditingAtPath(tree.getLeadSelectionPath());
return;
}
if (com.equals("GROUP")) //$NON-NLS-1$
{
if (node.status == ResNode.STATUS_SECONDARY)
insertResource(tree,null);
else
addResource(tree,null);
return;
}
if (com.equals("INSERT")) //$NON-NLS-1$
{
insertResource(tree,node.kind);
return;
}
if (com.equals("ADD")) //$NON-NLS-1$
{
addResource(tree,node.kind);
return;
}
if (com.equals("DUPLICATE")) //$NON-NLS-1$
{
ResourceList<?> rl = (ResourceList<?>) LGM.currentFile.resMap.get(node.kind);
if (node.frame != null) node.frame.commitChanges();
Resource<?,?> resource = rl.duplicate(node.getRes().get());
Listener.addResource(tree,node.kind,resource);
return;
}
}
}
private static class MListener extends MouseAdapter
{
public MListener()
{
super();
}
public void mousePressed(MouseEvent e)
{
int selRow = LGM.tree.getRowForLocation(e.getX(),e.getY());
TreePath selPath = LGM.tree.getPathForLocation(e.getX(),e.getY());
if (selRow != -1 && e.getModifiers() == InputEvent.BUTTON3_MASK)
LGM.tree.setSelectionPath(selPath);
}
public void mouseReleased(MouseEvent e)
{
ResNode node = (ResNode) LGM.tree.getLastSelectedPathComponent();
if (e.getX() >= LGM.tree.getWidth() && e.getY() >= LGM.tree.getHeight() || node == null)
return;
if (e.getModifiers() == InputEvent.BUTTON3_MASK
//Isn't Java supposed to handle ctrl+click for us? For some reason it doesn't.
|| (e.getClickCount() == 1 && e.isControlDown()))
{
node.showMenu(e);
return;
}
if (e.getClickCount() == 2)
{
// kind must be a Resource kind
if (node.status != ResNode.STATUS_SECONDARY) return;
node.openFrame();
return;
}
}
}
public void editingCanceled(ChangeEvent e)
{ //Unused
}
public void editingStopped(ChangeEvent e)
{
ResNode node = (ResNode) LGM.tree.getLastSelectedPathComponent();
if (node.status == ResNode.STATUS_SECONDARY && node.isEditable())
{
String txt = ((String) node.getUserObject()).replaceAll("\\W","").replaceAll("^([0-9]+)",""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
Resource<?,?> r = deRef((ResourceReference<?>) node.getRes());
if (r != null) r.setName(txt);
}
}
}
| true | true | public void actionPerformed(ActionEvent e)
{
JTree tree = LGM.tree;
String[] args = e.getActionCommand().split(" "); //$NON-NLS-1$
String com = args[0];
if (com.endsWith(".NEW")) //$NON-NLS-1$
{
String title = Messages.getString("Listener.CONFIRM_NEW_TITLE"); //$NON-NLS-1$
String message = Messages.getString("Listener.CONFIRM_NEW"); //$NON-NLS-1$
int opt = JOptionPane.showConfirmDialog(LGM.frame,message,title,JOptionPane.YES_NO_OPTION);
//I'd love to default to "No", but apparently that's not an option.
if (opt == JOptionPane.YES_OPTION) fc.newFile();
return;
}
if (com.endsWith(".OPEN")) //$NON-NLS-1$
{
try
{
fc.open(args.length > 1 ? new URI(args[1]) : null);
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
return;
}
if (com.endsWith(".SAVE")) //$NON-NLS-1$
{
fc.save(LGM.currentFile.uri,LGM.currentFile.format);
return;
}
if (com.endsWith(".SAVEAS")) //$NON-NLS-1$
{
fc.saveNewFile();
return;
}
if (com.endsWith(".EVENT_BUTTON")) //$NON-NLS-1$
{
Object o = e.getSource();
if (o instanceof JToggleButton) LGM.eventSelect.setVisible(((JToggleButton) o).isSelected());
return;
}
if (com.endsWith(".EXIT")) //$NON-NLS-1$
{
System.exit(0);
return;
}
if (com.contains(".INSERT_") || com.contains(".ADD_")) //$NON-NLS-1$ //$NON-NLS-2$
{
//we no longer do it this way
throw new UnsupportedOperationException(com);
}
if (com.endsWith(".RENAME")) //$NON-NLS-1$
{
if (tree.getCellEditor().isCellEditable(null))
tree.startEditingAtPath(tree.getLeadSelectionPath());
return;
}
if (com.endsWith(".DELETE")) //$NON-NLS-1$
{
deleteSelectedResource(tree);
return;
}
if (com.endsWith(".DEFRAGIDS")) //$NON-NLS-1$
{
String msg = Messages.getString("Listener.CONFIRM_DEFRAGIDS"); //$NON-NLS-1$
if (JOptionPane.showConfirmDialog(LGM.frame,msg,
Messages.getString("Listener.CONFIRM_DEFRAGIDS_TITLE"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION) == 0) LGM.currentFile.defragIds();
}
if (com.endsWith(".EXPAND")) //$NON-NLS-1$
{
for (int m = 0; m < tree.getRowCount(); m++)
tree.expandRow(m);
return;
}
if (com.endsWith(".COLLAPSE")) //$NON-NLS-1$
{
for (int m = tree.getRowCount() - 1; m >= 0; m--)
tree.collapseRow(m);
return;
}
if (com.endsWith(".ABOUT")) //$NON-NLS-1$
{
new AboutBox(LGM.frame).setVisible(true);
return;
}
}
| public void actionPerformed(ActionEvent e)
{
JTree tree = LGM.tree;
String[] args = e.getActionCommand().split(" "); //$NON-NLS-1$
String com = args[0];
if (com.endsWith(".NEW")) //$NON-NLS-1$
{
String title = Messages.getString("Listener.CONFIRM_NEW_TITLE"); //$NON-NLS-1$
String message = Messages.getString("Listener.CONFIRM_NEW"); //$NON-NLS-1$
int opt = JOptionPane.showConfirmDialog(LGM.frame,message,title,JOptionPane.YES_NO_OPTION);
//I'd love to default to "No", but apparently that's not an option.
if (opt == JOptionPane.YES_OPTION) fc.newFile();
return;
}
if (com.endsWith(".OPEN")) //$NON-NLS-1$
{
try
{
fc.open(args.length > 1 ? new URI(args[1]) : null);
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
return;
}
if (com.endsWith(".SAVE")) //$NON-NLS-1$
{
fc.save(LGM.currentFile.uri,LGM.currentFile.format);
return;
}
if (com.endsWith(".SAVEAS")) //$NON-NLS-1$
{
fc.saveNewFile();
return;
}
if (com.endsWith(".EVENT_BUTTON")) //$NON-NLS-1$
{
Object o = e.getSource();
if (o instanceof JToggleButton) LGM.eventSelect.setVisible(((JToggleButton) o).isSelected());
return;
}
if (com.endsWith(".EXIT")) //$NON-NLS-1$
{
System.exit(0);
return;
}
if (com.contains(".INSERT_") || com.contains(".ADD_")) //$NON-NLS-1$ //$NON-NLS-2$
{
if (com.endsWith("GROUP")) //$NON-NLS-1$
{
if (com.contains(".INSERT_"))
insertResource(tree,null);
else
addResource(tree,null);
return;
}
//we no longer do it this way for resources
throw new UnsupportedOperationException(com);
}
if (com.endsWith(".RENAME")) //$NON-NLS-1$
{
if (tree.getCellEditor().isCellEditable(null))
tree.startEditingAtPath(tree.getLeadSelectionPath());
return;
}
if (com.endsWith(".DELETE")) //$NON-NLS-1$
{
deleteSelectedResource(tree);
return;
}
if (com.endsWith(".DEFRAGIDS")) //$NON-NLS-1$
{
String msg = Messages.getString("Listener.CONFIRM_DEFRAGIDS"); //$NON-NLS-1$
if (JOptionPane.showConfirmDialog(LGM.frame,msg,
Messages.getString("Listener.CONFIRM_DEFRAGIDS_TITLE"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION) == 0) LGM.currentFile.defragIds();
}
if (com.endsWith(".EXPAND")) //$NON-NLS-1$
{
for (int m = 0; m < tree.getRowCount(); m++)
tree.expandRow(m);
return;
}
if (com.endsWith(".COLLAPSE")) //$NON-NLS-1$
{
for (int m = tree.getRowCount() - 1; m >= 0; m--)
tree.collapseRow(m);
return;
}
if (com.endsWith(".ABOUT")) //$NON-NLS-1$
{
new AboutBox(LGM.frame).setVisible(true);
return;
}
}
|
diff --git a/src/com/android/browser/Controller.java b/src/com/android/browser/Controller.java
index 9710669f..9402a77d 100644
--- a/src/com/android/browser/Controller.java
+++ b/src/com/android/browser/Controller.java
@@ -1,2779 +1,2787 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.SearchManager;
import android.content.ClipboardManager;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceActivity;
import android.provider.Browser;
import android.provider.BrowserContract;
import android.provider.BrowserContract.Images;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Intents.Insert;
import android.speech.RecognizerIntent;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.MimeTypeMap;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebIconDatabase;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import com.android.browser.IntentHandler.UrlData;
import com.android.browser.UI.ComboViews;
import com.android.browser.UI.DropdownChangeListener;
import com.android.browser.provider.BrowserProvider;
import com.android.browser.provider.BrowserProvider2.Thumbnails;
import com.android.browser.provider.SnapshotProvider.Snapshots;
import com.android.browser.search.SearchEngine;
import com.android.common.Search;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Controller for browser
*/
public class Controller
implements WebViewController, UiController {
private static final String LOGTAG = "Controller";
private static final String SEND_APP_ID_EXTRA =
"android.speech.extras.SEND_APPLICATION_ID_EXTRA";
private static final String INCOGNITO_URI = "browser:incognito";
// public message ids
public final static int LOAD_URL = 1001;
public final static int STOP_LOAD = 1002;
// Message Ids
private static final int FOCUS_NODE_HREF = 102;
private static final int RELEASE_WAKELOCK = 107;
static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
private static final int OPEN_BOOKMARKS = 201;
private static final int EMPTY_MENU = -1;
// activity requestCode
final static int COMBO_VIEW = 1;
final static int PREFERENCES_PAGE = 3;
final static int FILE_SELECTED = 4;
final static int AUTOFILL_SETUP = 5;
private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
// As the ids are dynamically created, we can't guarantee that they will
// be in sequence, so this static array maps ids to a window number.
final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
{ R.id.window_one_menu_id, R.id.window_two_menu_id,
R.id.window_three_menu_id, R.id.window_four_menu_id,
R.id.window_five_menu_id, R.id.window_six_menu_id,
R.id.window_seven_menu_id, R.id.window_eight_menu_id };
// "source" parameter for Google search through search key
final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
// "source" parameter for Google search through simplily type
final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
// "no-crash-recovery" parameter in intent to suppress crash recovery
final static String NO_CRASH_RECOVERY = "no-crash-recovery";
// A bitmap that is re-used in createScreenshot as scratch space
private static Bitmap sThumbnailBitmap;
private Activity mActivity;
private UI mUi;
private TabControl mTabControl;
private BrowserSettings mSettings;
private WebViewFactory mFactory;
private WakeLock mWakeLock;
private UrlHandler mUrlHandler;
private UploadHandler mUploadHandler;
private IntentHandler mIntentHandler;
private PageDialogsHandler mPageDialogsHandler;
private NetworkStateHandler mNetworkHandler;
private Message mAutoFillSetupMessage;
private boolean mShouldShowErrorConsole;
private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
// FIXME, temp address onPrepareMenu performance problem.
// When we move everything out of view, we should rewrite this.
private int mCurrentMenuState = 0;
private int mMenuState = R.id.MAIN_MENU;
private int mOldMenuState = EMPTY_MENU;
private Menu mCachedMenu;
private boolean mMenuIsDown;
// For select and find, we keep track of the ActionMode so that
// finish() can be called as desired.
private ActionMode mActionMode;
/**
* Only meaningful when mOptionsMenuOpen is true. This variable keeps track
* of whether the configuration has changed. The first onMenuOpened call
* after a configuration change is simply a reopening of the same menu
* (i.e. mIconView did not change).
*/
private boolean mConfigChanged;
/**
* Keeps track of whether the options menu is open. This is important in
* determining whether to show or hide the title bar overlay
*/
private boolean mOptionsMenuOpen;
/**
* Whether or not the options menu is in its bigger, popup menu form. When
* true, we want the title bar overlay to be gone. When false, we do not.
* Only meaningful if mOptionsMenuOpen is true.
*/
private boolean mExtendedMenuOpen;
private boolean mInLoad;
private boolean mActivityPaused = true;
private boolean mLoadStopped;
private Handler mHandler;
// Checks to see when the bookmarks database has changed, and updates the
// Tabs' notion of whether they represent bookmarked sites.
private ContentObserver mBookmarksObserver;
private CrashRecoveryHandler mCrashRecoveryHandler;
private boolean mBlockEvents;
public Controller(Activity browser, boolean preloadCrashState) {
mActivity = browser;
mSettings = BrowserSettings.getInstance();
mTabControl = new TabControl(this);
mSettings.setController(this);
mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
if (preloadCrashState) {
mCrashRecoveryHandler.preloadCrashState();
}
mFactory = new BrowserWebViewFactory(browser);
mUrlHandler = new UrlHandler(this);
mIntentHandler = new IntentHandler(mActivity, this);
mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
startHandler();
mBookmarksObserver = new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange) {
int size = mTabControl.getTabCount();
for (int i = 0; i < size; i++) {
mTabControl.getTab(i).updateBookmarkedStatus();
}
}
};
browser.getContentResolver().registerContentObserver(
BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
mNetworkHandler = new NetworkStateHandler(mActivity, this);
// Start watching the default geolocation permissions
mSystemAllowGeolocationOrigins =
new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
mSystemAllowGeolocationOrigins.start();
openIconDatabase();
}
void start(final Bundle icicle, final Intent intent) {
boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
if (icicle != null || noCrashRecovery) {
doStart(icicle, intent, false);
} else {
mCrashRecoveryHandler.startRecovery(intent);
}
}
void doStart(final Bundle icicle, final Intent intent, final boolean fromCrash) {
// Unless the last browser usage was within 24 hours, destroy any
// remaining incognito tabs.
Calendar lastActiveDate = icicle != null ?
(Calendar) icicle.getSerializable("lastActiveDate") : null;
Calendar today = Calendar.getInstance();
Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DATE, -1);
final boolean restoreIncognitoTabs = !(lastActiveDate == null
|| lastActiveDate.before(yesterday)
|| lastActiveDate.after(today));
// Find out if we will restore any state and remember the tab.
final long currentTabId =
mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
if (currentTabId == -1) {
// Not able to restore so we go ahead and clear session cookies. We
// must do this before trying to login the user as we don't want to
// clear any session cookies set during login.
CookieManager.getInstance().removeSessionCookie();
}
GoogleAccountLogin.startLoginIfNeeded(mActivity,
new Runnable() {
@Override public void run() {
onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs,
fromCrash);
}
});
}
private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
boolean restoreIncognitoTabs, boolean fromCrash) {
if (currentTabId == -1) {
BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
final Bundle extra = intent.getExtras();
// Create an initial tab.
// If the intent is ACTION_VIEW and data is not null, the Browser is
// invoked to view the content by another application. In this case,
// the tab will be close when exit.
UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Tab t = null;
if (urlData.isEmpty()) {
t = openTabToHomePage();
} else {
t = openTab(urlData);
}
if (t != null) {
t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
}
WebView webView = t.getWebView();
if (extra != null) {
int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
if (scale > 0 && scale <= 1000) {
webView.setInitialScale(scale);
}
}
mUi.updateTabs(mTabControl.getTabs());
} else {
mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
mUi.needsRestoreAllTabs());
List<Tab> tabs = mTabControl.getTabs();
ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
for (Tab t : tabs) {
restoredTabs.add(t.getId());
}
BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
if (tabs.size() == 0) {
openTabToHomePage();
}
mUi.updateTabs(tabs);
// TabControl.restoreState() will create a new tab even if
// restoring the state fails.
setActiveTab(mTabControl.getCurrentTab());
// Handle the intent if needed. If icicle != null, we are restoring
// and the intent will be stale - ignore it.
if (icicle == null || fromCrash) {
mIntentHandler.onNewIntent(intent);
}
}
// Read JavaScript flags if it exists.
String jsFlags = getSettings().getJsEngineFlags();
if (jsFlags.trim().length() != 0) {
getCurrentWebView().setJsFlags(jsFlags);
}
if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
}
}
private static class PruneThumbnails implements Runnable {
private Context mContext;
private List<Long> mIds;
PruneThumbnails(Context context, List<Long> preserveIds) {
mContext = context.getApplicationContext();
mIds = preserveIds;
}
@Override
public void run() {
ContentResolver cr = mContext.getContentResolver();
if (mIds == null || mIds.size() == 0) {
cr.delete(Thumbnails.CONTENT_URI, null, null);
} else {
int length = mIds.size();
StringBuilder where = new StringBuilder();
where.append(Thumbnails._ID);
where.append(" not in (");
for (int i = 0; i < length; i++) {
where.append(mIds.get(i));
if (i < (length - 1)) {
where.append(",");
}
}
where.append(")");
cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
}
}
}
@Override
public WebViewFactory getWebViewFactory() {
return mFactory;
}
@Override
public void onSetWebView(Tab tab, WebView view) {
mUi.onSetWebView(tab, view);
}
@Override
public void createSubWindow(Tab tab) {
endActionMode();
WebView mainView = tab.getWebView();
WebView subView = mFactory.createWebView((mainView == null)
? false
: mainView.isPrivateBrowsingEnabled());
mUi.createSubWindow(tab, subView);
}
@Override
public Context getContext() {
return mActivity;
}
@Override
public Activity getActivity() {
return mActivity;
}
void setUi(UI ui) {
mUi = ui;
}
BrowserSettings getSettings() {
return mSettings;
}
IntentHandler getIntentHandler() {
return mIntentHandler;
}
@Override
public UI getUi() {
return mUi;
}
int getMaxTabs() {
return mActivity.getResources().getInteger(R.integer.max_tabs);
}
@Override
public TabControl getTabControl() {
return mTabControl;
}
@Override
public List<Tab> getTabs() {
return mTabControl.getTabs();
}
// Open the icon database.
private void openIconDatabase() {
// We have to call getInstance on the UI thread
final WebIconDatabase instance = WebIconDatabase.getInstance();
BackgroundHandler.execute(new Runnable() {
@Override
public void run() {
instance.open(mActivity.getDir("icons", 0).getPath());
}
});
}
private void startHandler() {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case OPEN_BOOKMARKS:
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
break;
case FOCUS_NODE_HREF:
{
String url = (String) msg.getData().get("url");
String title = (String) msg.getData().get("title");
String src = (String) msg.getData().get("src");
if (url == "") url = src; // use image if no anchor
if (TextUtils.isEmpty(url)) {
break;
}
HashMap focusNodeMap = (HashMap) msg.obj;
WebView view = (WebView) focusNodeMap.get("webview");
// Only apply the action if the top window did not change.
if (getCurrentTopWebView() != view) {
break;
}
switch (msg.arg1) {
case R.id.open_context_menu_id:
loadUrlFromContext(url);
break;
case R.id.view_image_context_menu_id:
loadUrlFromContext(src);
break;
case R.id.open_newtab_context_menu_id:
final Tab parent = mTabControl.getCurrentTab();
openTab(url, parent,
!mSettings.openInBackground(), true);
break;
case R.id.copy_link_context_menu_id:
copy(url);
break;
case R.id.save_link_context_menu_id:
case R.id.download_context_menu_id:
DownloadHandler.onDownloadStartNoStream(
mActivity, url, null, null, null,
view.isPrivateBrowsingEnabled());
break;
}
break;
}
case LOAD_URL:
loadUrlFromContext((String) msg.obj);
break;
case STOP_LOAD:
stopLoading();
break;
case RELEASE_WAKELOCK:
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
// if we reach here, Browser should be still in the
// background loading after WAKELOCK_TIMEOUT (5-min).
// To avoid burning the battery, stop loading.
mTabControl.stopAllLoading();
}
break;
case UPDATE_BOOKMARK_THUMBNAIL:
Tab tab = (Tab) msg.obj;
if (tab != null) {
updateScreenshot(tab);
}
break;
}
}
};
}
@Override
public Tab getCurrentTab() {
return mTabControl.getCurrentTab();
}
@Override
public void shareCurrentPage() {
shareCurrentPage(mTabControl.getCurrentTab());
}
private void shareCurrentPage(Tab tab) {
if (tab != null) {
sharePage(mActivity, tab.getTitle(),
tab.getUrl(), tab.getFavicon(),
createScreenshot(tab.getWebView(),
getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity)));
}
}
/**
* Share a page, providing the title, url, favicon, and a screenshot. Uses
* an {@link Intent} to launch the Activity chooser.
* @param c Context used to launch a new Activity.
* @param title Title of the page. Stored in the Intent with
* {@link Intent#EXTRA_SUBJECT}
* @param url URL of the page. Stored in the Intent with
* {@link Intent#EXTRA_TEXT}
* @param favicon Bitmap of the favicon for the page. Stored in the Intent
* with {@link Browser#EXTRA_SHARE_FAVICON}
* @param screenshot Bitmap of a screenshot of the page. Stored in the
* Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
*/
static final void sharePage(Context c, String title, String url,
Bitmap favicon, Bitmap screenshot) {
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
send.putExtra(Intent.EXTRA_TEXT, url);
send.putExtra(Intent.EXTRA_SUBJECT, title);
send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
try {
c.startActivity(Intent.createChooser(send, c.getString(
R.string.choosertitle_sharevia)));
} catch(android.content.ActivityNotFoundException ex) {
// if no app handles it, do nothing
}
}
private void copy(CharSequence text) {
ClipboardManager cm = (ClipboardManager) mActivity
.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(text);
}
// lifecycle
protected void onConfgurationChanged(Configuration config) {
mConfigChanged = true;
if (mPageDialogsHandler != null) {
mPageDialogsHandler.onConfigurationChanged(config);
}
mUi.onConfigurationChanged(config);
}
@Override
public void handleNewIntent(Intent intent) {
if (!mUi.isWebShowing()) {
mUi.showWeb(false);
}
mIntentHandler.onNewIntent(intent);
}
protected void onPause() {
if (mUi.isCustomViewShowing()) {
hideCustomView();
}
if (mActivityPaused) {
Log.e(LOGTAG, "BrowserActivity is already paused.");
return;
}
mActivityPaused = true;
Tab tab = mTabControl.getCurrentTab();
if (tab != null) {
tab.pause();
if (!pauseWebViewTimers(tab)) {
if (mWakeLock == null) {
PowerManager pm = (PowerManager) mActivity
.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
}
mWakeLock.acquire();
mHandler.sendMessageDelayed(mHandler
.obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
}
}
mUi.onPause();
mNetworkHandler.onPause();
WebView.disablePlatformNotifications();
NfcHandler.unregister(mActivity);
if (sThumbnailBitmap != null) {
sThumbnailBitmap.recycle();
sThumbnailBitmap = null;
}
}
void onSaveInstanceState(Bundle outState) {
// the default implementation requires each view to have an id. As the
// browser handles the state itself and it doesn't use id for the views,
// don't call the default implementation. Otherwise it will trigger the
// warning like this, "couldn't save which view has focus because the
// focused view XXX has no id".
// Save all the tabs
mTabControl.saveState(outState);
if (!outState.isEmpty()) {
// Save time so that we know how old incognito tabs (if any) are.
outState.putSerializable("lastActiveDate", Calendar.getInstance());
}
}
void onResume() {
if (!mActivityPaused) {
Log.e(LOGTAG, "BrowserActivity is already resumed.");
return;
}
mActivityPaused = false;
Tab current = mTabControl.getCurrentTab();
if (current != null) {
current.resume();
resumeWebViewTimers(current);
}
releaseWakeLock();
mUi.onResume();
mNetworkHandler.onResume();
WebView.enablePlatformNotifications();
NfcHandler.register(mActivity, this);
}
private void releaseWakeLock() {
if (mWakeLock != null && mWakeLock.isHeld()) {
mHandler.removeMessages(RELEASE_WAKELOCK);
mWakeLock.release();
}
}
/**
* resume all WebView timers using the WebView instance of the given tab
* @param tab guaranteed non-null
*/
private void resumeWebViewTimers(Tab tab) {
boolean inLoad = tab.inPageLoad();
if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
CookieSyncManager.getInstance().startSync();
WebView w = tab.getWebView();
WebViewTimersControl.getInstance().onBrowserActivityResume(w);
}
}
/**
* Pause all WebView timers using the WebView of the given tab
* @param tab
* @return true if the timers are paused or tab is null
*/
private boolean pauseWebViewTimers(Tab tab) {
if (tab == null) {
return true;
} else if (!tab.inPageLoad()) {
CookieSyncManager.getInstance().stopSync();
WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
return true;
}
return false;
}
void onDestroy() {
if (mUploadHandler != null && !mUploadHandler.handled()) {
mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
mUploadHandler = null;
}
if (mTabControl == null) return;
mUi.onDestroy();
// Remove the current tab and sub window
Tab t = mTabControl.getCurrentTab();
if (t != null) {
dismissSubWindow(t);
removeTab(t);
}
mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
// Destroy all the tabs
mTabControl.destroy();
WebIconDatabase.getInstance().close();
// Stop watching the default geolocation permissions
mSystemAllowGeolocationOrigins.stop();
mSystemAllowGeolocationOrigins = null;
}
protected boolean isActivityPaused() {
return mActivityPaused;
}
protected void onLowMemory() {
mTabControl.freeMemory();
}
@Override
public boolean shouldShowErrorConsole() {
return mShouldShowErrorConsole;
}
protected void setShouldShowErrorConsole(boolean show) {
if (show == mShouldShowErrorConsole) {
// Nothing to do.
return;
}
mShouldShowErrorConsole = show;
Tab t = mTabControl.getCurrentTab();
if (t == null) {
// There is no current tab so we cannot toggle the error console
return;
}
mUi.setShouldShowErrorConsole(t, show);
}
@Override
public void stopLoading() {
mLoadStopped = true;
Tab tab = mTabControl.getCurrentTab();
WebView w = getCurrentTopWebView();
w.stopLoading();
mUi.onPageStopped(tab);
}
boolean didUserStopLoading() {
return mLoadStopped;
}
// WebViewController
@Override
public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
// We've started to load a new page. If there was a pending message
// to save a screenshot then we will now take the new page and save
// an incorrect screenshot. Therefore, remove any pending thumbnail
// messages from the queue.
mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
tab);
// reset sync timer to avoid sync starts during loading a page
CookieSyncManager.getInstance().resetSync();
if (!mNetworkHandler.isNetworkUp()) {
view.setNetworkAvailable(false);
}
// when BrowserActivity just starts, onPageStarted may be called before
// onResume as it is triggered from onCreate. Call resumeWebViewTimers
// to start the timer. As we won't switch tabs while an activity is in
// pause state, we can ensure calling resume and pause in pair.
if (mActivityPaused) {
resumeWebViewTimers(tab);
}
mLoadStopped = false;
endActionMode();
mUi.onTabDataChanged(tab);
String url = tab.getUrl();
// update the bookmark database for favicon
maybeUpdateFavicon(tab, null, url, favicon);
Performance.tracePageStart(url);
// Performance probe
if (false) {
Performance.onPageStarted();
}
}
@Override
public void onPageFinished(Tab tab) {
mUi.onTabDataChanged(tab);
if (!tab.isPrivateBrowsingEnabled()
&& !TextUtils.isEmpty(tab.getUrl())
&& !tab.isSnapshot()) {
// Only update the bookmark screenshot if the user did not
// cancel the load early and there is not already
// a pending update for the tab.
if (tab.inForeground() && !didUserStopLoading()
|| !tab.inForeground()) {
if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(
UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
500);
}
}
}
// pause the WebView timer and release the wake lock if it is finished
// while BrowserActivity is in pause state.
if (mActivityPaused && pauseWebViewTimers(tab)) {
releaseWakeLock();
}
// Performance probe
if (false) {
Performance.onPageFinished(tab.getUrl());
}
Performance.tracePageFinished();
}
@Override
public void onProgressChanged(Tab tab) {
mCrashRecoveryHandler.backupState();
int newProgress = tab.getLoadProgress();
if (newProgress == 100) {
CookieSyncManager.getInstance().sync();
// onProgressChanged() may continue to be called after the main
// frame has finished loading, as any remaining sub frames continue
// to load. We'll only get called once though with newProgress as
// 100 when everything is loaded. (onPageFinished is called once
// when the main frame completes loading regardless of the state of
// any sub frames so calls to onProgressChanges may continue after
// onPageFinished has executed)
if (mInLoad) {
mInLoad = false;
updateInLoadMenuItems(mCachedMenu);
}
} else {
if (!mInLoad) {
// onPageFinished may have already been called but a subframe is
// still loading and updating the progress. Reset mInLoad and
// update the menu items.
mInLoad = true;
updateInLoadMenuItems(mCachedMenu);
}
}
mUi.onProgressChanged(tab);
}
@Override
public void onUpdatedSecurityState(Tab tab) {
mUi.onTabDataChanged(tab);
}
@Override
public void onReceivedTitle(Tab tab, final String title) {
mUi.onTabDataChanged(tab);
final String pageUrl = tab.getOriginalUrl();
if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
>= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
return;
}
// Update the title in the history database if not in private browsing mode
if (!tab.isPrivateBrowsingEnabled()) {
DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
}
}
@Override
public void onFavicon(Tab tab, WebView view, Bitmap icon) {
mUi.onTabDataChanged(tab);
maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
}
@Override
public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
}
@Override
public boolean shouldOverrideKeyEvent(KeyEvent event) {
if (mMenuIsDown) {
// only check shortcut key when MENU is held
return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
event);
} else {
return false;
}
}
@Override
public void onUnhandledKeyEvent(KeyEvent event) {
if (!isActivityPaused()) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
mActivity.onKeyDown(event.getKeyCode(), event);
} else {
mActivity.onKeyUp(event.getKeyCode(), event);
}
}
}
@Override
public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
// Don't save anything in private browsing mode
if (tab.isPrivateBrowsingEnabled()) return;
String url = tab.getOriginalUrl();
if (TextUtils.isEmpty(url)
|| url.regionMatches(true, 0, "about:", 0, 6)) {
return;
}
DataController.getInstance(mActivity).updateVisitedHistory(url);
mCrashRecoveryHandler.backupState();
}
@Override
public void getVisitedHistory(final ValueCallback<String[]> callback) {
AsyncTask<Void, Void, String[]> task =
new AsyncTask<Void, Void, String[]>() {
@Override
public String[] doInBackground(Void... unused) {
return Browser.getVisitedHistory(mActivity.getContentResolver());
}
@Override
public void onPostExecute(String[] result) {
callback.onReceiveValue(result);
}
};
task.execute();
}
@Override
public void onReceivedHttpAuthRequest(Tab tab, WebView view,
final HttpAuthHandler handler, final String host,
final String realm) {
String username = null;
String password = null;
boolean reuseHttpAuthUsernamePassword
= handler.useHttpAuthUsernamePassword();
if (reuseHttpAuthUsernamePassword && view != null) {
String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
if (credentials != null && credentials.length == 2) {
username = credentials[0];
password = credentials[1];
}
}
if (username != null && password != null) {
handler.proceed(username, password);
} else {
if (tab.inForeground() && !handler.suppressDialog()) {
mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
} else {
handler.cancel();
}
}
}
@Override
public void onDownloadStart(Tab tab, String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
WebView w = tab.getWebView();
DownloadHandler.onDownloadStart(mActivity, url, userAgent,
contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
if (w.copyBackForwardList().getSize() == 0) {
// This Tab was opened for the sole purpose of downloading a
// file. Remove it.
if (tab == mTabControl.getCurrentTab()) {
// In this case, the Tab is still on top.
goBackOnePageOrQuit();
} else {
// In this case, it is not.
closeTab(tab);
}
}
}
@Override
public Bitmap getDefaultVideoPoster() {
return mUi.getDefaultVideoPoster();
}
@Override
public View getVideoLoadingProgressView() {
return mUi.getVideoLoadingProgressView();
}
@Override
public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
SslError error) {
mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
}
@Override
public void showAutoLogin(Tab tab) {
assert tab.inForeground();
// Update the title bar to show the auto-login request.
mUi.showAutoLogin(tab);
}
@Override
public void hideAutoLogin(Tab tab) {
assert tab.inForeground();
mUi.hideAutoLogin(tab);
}
// helper method
/*
* Update the favorites icon if the private browsing isn't enabled and the
* icon is valid.
*/
private void maybeUpdateFavicon(Tab tab, final String originalUrl,
final String url, Bitmap favicon) {
if (favicon == null) {
return;
}
if (!tab.isPrivateBrowsingEnabled()) {
Bookmarks.updateFavicon(mActivity
.getContentResolver(), originalUrl, url, favicon);
}
}
@Override
public void bookmarkedStatusHasChanged(Tab tab) {
// TODO: Switch to using onTabDataChanged after b/3262950 is fixed
mUi.bookmarkedStatusHasChanged(tab);
}
// end WebViewController
protected void pageUp() {
getCurrentTopWebView().pageUp(false);
}
protected void pageDown() {
getCurrentTopWebView().pageDown(false);
}
// callback from phone title bar
public void editUrl() {
if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
mUi.editUrl(false);
}
public void startVoiceSearch() {
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
mActivity.getComponentName().flattenToString());
intent.putExtra(SEND_APP_ID_EXTRA, false);
intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
mActivity.startActivity(intent);
}
@Override
public void activateVoiceSearchMode(String title, List<String> results) {
mUi.showVoiceTitleBar(title, results);
}
public void revertVoiceSearchMode(Tab tab) {
mUi.revertVoiceTitleBar(tab);
}
public boolean supportsVoiceSearch() {
SearchEngine searchEngine = getSettings().getSearchEngine();
return (searchEngine != null && searchEngine.supportsVoiceSearch());
}
public void showCustomView(Tab tab, View view, int requestedOrientation,
WebChromeClient.CustomViewCallback callback) {
if (tab.inForeground()) {
if (mUi.isCustomViewShowing()) {
callback.onCustomViewHidden();
return;
}
mUi.showCustomView(view, requestedOrientation, callback);
// Save the menu state and set it to empty while the custom
// view is showing.
mOldMenuState = mMenuState;
mMenuState = EMPTY_MENU;
mActivity.invalidateOptionsMenu();
}
}
@Override
public void hideCustomView() {
if (mUi.isCustomViewShowing()) {
mUi.onHideCustomView();
// Reset the old menu state.
mMenuState = mOldMenuState;
mOldMenuState = EMPTY_MENU;
mActivity.invalidateOptionsMenu();
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (getCurrentTopWebView() == null) return;
switch (requestCode) {
case PREFERENCES_PAGE:
if (resultCode == Activity.RESULT_OK && intent != null) {
String action = intent.getStringExtra(Intent.EXTRA_TEXT);
if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
mTabControl.removeParentChildRelationShips();
}
}
break;
case FILE_SELECTED:
// Chose a file from the file picker.
if (null == mUploadHandler) break;
mUploadHandler.onResult(resultCode, intent);
break;
case AUTOFILL_SETUP:
// Determine whether a profile was actually set up or not
// and if so, send the message back to the WebTextView to
// fill the form with the new profile.
if (getSettings().getAutoFillProfile() != null) {
mAutoFillSetupMessage.sendToTarget();
mAutoFillSetupMessage = null;
}
break;
case COMBO_VIEW:
if (intent == null || resultCode != Activity.RESULT_OK) {
break;
}
mUi.showWeb(false);
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Tab t = getCurrentTab();
Uri uri = intent.getData();
loadUrl(t, uri.toString());
} else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
String[] urls = intent.getStringArrayExtra(
ComboViewActivity.EXTRA_OPEN_ALL);
Tab parent = getCurrentTab();
for (String url : urls) {
parent = openTab(url, parent,
!mSettings.openInBackground(), true);
}
} else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
long id = intent.getLongExtra(
ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
if (id >= 0) {
createNewSnapshotTab(id, true);
}
}
break;
default:
break;
}
getCurrentTopWebView().requestFocus();
}
/**
* Open the Go page.
* @param startWithHistory If true, open starting on the history tab.
* Otherwise, start with the bookmarks tab.
*/
@Override
public void bookmarksOrHistoryPicker(ComboViews startView) {
if (mTabControl.getCurrentWebView() == null) {
return;
}
// clear action mode
if (isInCustomActionMode()) {
endActionMode();
}
Bundle extras = new Bundle();
// Disable opening in a new window if we have maxed out the windows
extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
!mTabControl.canCreateNewTab());
mUi.showComboView(startView, extras);
}
// combo view callbacks
// key handling
protected void onBackKey() {
if (!mUi.onBackKey()) {
WebView subwindow = mTabControl.getCurrentSubWindow();
if (subwindow != null) {
if (subwindow.canGoBack()) {
subwindow.goBack();
} else {
dismissSubWindow(mTabControl.getCurrentTab());
}
} else {
goBackOnePageOrQuit();
}
}
}
protected boolean onMenuKey() {
return mUi.onMenuKey();
}
// menu handling and state
// TODO: maybe put into separate handler
protected boolean onCreateOptionsMenu(Menu menu) {
if (mMenuState == EMPTY_MENU) {
return false;
}
MenuInflater inflater = mActivity.getMenuInflater();
inflater.inflate(R.menu.browser, menu);
return true;
}
protected void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v instanceof TitleBar) {
return;
}
if (!(v instanceof WebView)) {
return;
}
final WebView webview = (WebView) v;
WebView.HitTestResult result = webview.getHitTestResult();
if (result == null) {
return;
}
int type = result.getType();
if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
Log.w(LOGTAG,
"We should not show context menu when nothing is touched");
return;
}
if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
// let TextView handles context menu
return;
}
// Note, http://b/issue?id=1106666 is requesting that
// an inflated menu can be used again. This is not available
// yet, so inflate each time (yuk!)
MenuInflater inflater = mActivity.getMenuInflater();
inflater.inflate(R.menu.browsercontext, menu);
// Show the correct menu group
final String extra = result.getExtra();
menu.setGroupVisible(R.id.PHONE_MENU,
type == WebView.HitTestResult.PHONE_TYPE);
menu.setGroupVisible(R.id.EMAIL_MENU,
type == WebView.HitTestResult.EMAIL_TYPE);
menu.setGroupVisible(R.id.GEO_MENU,
type == WebView.HitTestResult.GEO_TYPE);
menu.setGroupVisible(R.id.IMAGE_MENU,
type == WebView.HitTestResult.IMAGE_TYPE
|| type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
menu.setGroupVisible(R.id.ANCHOR_MENU,
type == WebView.HitTestResult.SRC_ANCHOR_TYPE
|| type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
|| type == WebView.HitTestResult.PHONE_TYPE
|| type == WebView.HitTestResult.EMAIL_TYPE
|| type == WebView.HitTestResult.GEO_TYPE;
menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
if (hitText) {
menu.findItem(R.id.select_text_menu_id)
.setOnMenuItemClickListener(new SelectText(webview));
}
// Setup custom handling depending on the type
switch (type) {
case WebView.HitTestResult.PHONE_TYPE:
menu.setHeaderTitle(Uri.decode(extra));
menu.findItem(R.id.dial_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_TEL + extra)));
Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
menu.findItem(R.id.add_contact_context_menu_id).setIntent(
addIntent);
menu.findItem(R.id.copy_phone_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.EMAIL_TYPE:
menu.setHeaderTitle(extra);
menu.findItem(R.id.email_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_MAILTO + extra)));
menu.findItem(R.id.copy_mail_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.GEO_TYPE:
menu.setHeaderTitle(extra);
menu.findItem(R.id.map_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_GEO
+ URLEncoder.encode(extra))));
menu.findItem(R.id.copy_geo_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.SRC_ANCHOR_TYPE:
case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
menu.setHeaderTitle(extra);
// decide whether to show the open link in new tab option
boolean showNewTab = mTabControl.canCreateNewTab();
MenuItem newTabItem
= menu.findItem(R.id.open_newtab_context_menu_id);
newTabItem.setTitle(getSettings().openInBackground()
? R.string.contextmenu_openlink_newwindow_background
: R.string.contextmenu_openlink_newwindow);
newTabItem.setVisible(showNewTab);
if (showNewTab) {
if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
newTabItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final HashMap<String, WebView> hrefMap =
new HashMap<String, WebView>();
hrefMap.put("webview", webview);
final Message msg = mHandler.obtainMessage(
FOCUS_NODE_HREF,
R.id.open_newtab_context_menu_id,
0, hrefMap);
webview.requestFocusNodeHref(msg);
return true;
}
});
} else {
newTabItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final Tab parent = mTabControl.getCurrentTab();
openTab(extra, parent,
!mSettings.openInBackground(),
true);
return true;
}
});
}
}
if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
break;
}
// otherwise fall through to handle image part
case WebView.HitTestResult.IMAGE_TYPE:
if (type == WebView.HitTestResult.IMAGE_TYPE) {
menu.setHeaderTitle(extra);
}
menu.findItem(R.id.view_image_context_menu_id)
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
openTab(extra, mTabControl.getCurrentTab(), true, true);
return false;
}
});
menu.findItem(R.id.download_context_menu_id).
setOnMenuItemClickListener(
new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
menu.findItem(R.id.set_wallpaper_context_menu_id).
setOnMenuItemClickListener(new WallpaperHandler(mActivity,
extra));
break;
default:
Log.w(LOGTAG, "We should not get here.");
break;
}
//update the ui
mUi.onContextMenuCreated(menu);
}
/**
* As the menu can be open when loading state changes
* we must manually update the state of the stop/reload menu
* item
*/
private void updateInLoadMenuItems(Menu menu) {
if (menu == null) {
return;
}
MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
MenuItem src = mInLoad ?
menu.findItem(R.id.stop_menu_id):
menu.findItem(R.id.reload_menu_id);
if (src != null) {
dest.setIcon(src.getIcon());
dest.setTitle(src.getTitle());
}
}
boolean onPrepareOptionsMenu(Menu menu) {
updateInLoadMenuItems(menu);
// hold on to the menu reference here; it is used by the page callbacks
// to update the menu based on loading state
mCachedMenu = menu;
// Note: setVisible will decide whether an item is visible; while
// setEnabled() will decide whether an item is enabled, which also means
// whether the matching shortcut key will function.
switch (mMenuState) {
case EMPTY_MENU:
if (mCurrentMenuState != mMenuState) {
menu.setGroupVisible(R.id.MAIN_MENU, false);
menu.setGroupEnabled(R.id.MAIN_MENU, false);
menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
}
break;
default:
if (mCurrentMenuState != mMenuState) {
menu.setGroupVisible(R.id.MAIN_MENU, true);
menu.setGroupEnabled(R.id.MAIN_MENU, true);
menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
}
updateMenuState(getCurrentTab(), menu);
break;
}
mCurrentMenuState = mMenuState;
return mUi.onPrepareOptionsMenu(menu);
}
@Override
public void updateMenuState(Tab tab, Menu menu) {
boolean canGoBack = false;
boolean canGoForward = false;
boolean isHome = false;
boolean isDesktopUa = false;
boolean isLive = false;
if (tab != null) {
canGoBack = tab.canGoBack();
canGoForward = tab.canGoForward();
isHome = mSettings.getHomePage().equals(tab.getUrl());
isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
isLive = !tab.isSnapshot();
}
final MenuItem back = menu.findItem(R.id.back_menu_id);
back.setEnabled(canGoBack);
final MenuItem home = menu.findItem(R.id.homepage_menu_id);
home.setEnabled(!isHome);
final MenuItem forward = menu.findItem(R.id.forward_menu_id);
forward.setEnabled(canGoForward);
final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
if (source != null && dest != null) {
dest.setTitle(source.getTitle());
dest.setIcon(source.getIcon());
}
menu.setGroupVisible(R.id.NAV_MENU, isLive);
// decide whether to show the share link option
PackageManager pm = mActivity.getPackageManager();
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
ResolveInfo ri = pm.resolveActivity(send,
PackageManager.MATCH_DEFAULT_ONLY);
menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
boolean isNavDump = mSettings.enableNavDump();
final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
nav.setVisible(isNavDump);
nav.setEnabled(isNavDump);
boolean showDebugSettings = mSettings.isDebugEnabled();
final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
counter.setVisible(showDebugSettings);
counter.setEnabled(showDebugSettings);
final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
uaSwitcher.setChecked(isDesktopUa);
menu.setGroupVisible(R.id.LIVE_MENU, isLive);
menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
menu.setGroupVisible(R.id.COMBO_MENU, false);
mUi.updateMenuState(tab, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
if (mUi.onOptionsItemSelected(item)) {
// ui callback handled it
return true;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
break;
case R.id.history_menu_id:
bookmarksOrHistoryPicker(ComboViews.History);
break;
case R.id.snapshots_menu_id:
bookmarksOrHistoryPicker(ComboViews.Snapshots);
break;
case R.id.add_bookmark_menu_id:
Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
if (bookmarkIntent != null) {
mActivity.startActivity(bookmarkIntent);
}
break;
case R.id.stop_reload_menu_id:
if (mInLoad) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTab().goBack();
break;
case R.id.forward_menu_id:
getCurrentTab().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
loadUrl(current, mSettings.getHomePage());
break;
case R.id.preferences_menu_id:
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
getCurrentTopWebView().getUrl());
mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
break;
case R.id.find_menu_id:
getCurrentTopWebView().showFindDialog(null, true);
break;
case R.id.save_snapshot_menu_id:
final Tab source = getTabControl().getCurrentTab();
if (source == null) break;
final ContentResolver cr = mActivity.getContentResolver();
final ContentValues values = source.createSnapshotValues();
if (values != null) {
new AsyncTask<Tab, Void, Long>() {
@Override
protected Long doInBackground(Tab... params) {
Uri result = cr.insert(Snapshots.CONTENT_URI, values);
+ if (result == null) {
+ return null;
+ }
long id = ContentUris.parseId(result);
return id;
}
@Override
protected void onPostExecute(Long id) {
+ if (id == null) {
+ Toast.makeText(mActivity, R.string.snapshot_failed,
+ Toast.LENGTH_SHORT).show();
+ return;
+ }
Bundle b = new Bundle();
b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
mUi.showComboView(ComboViews.Snapshots, b);
};
}.execute(source);
} else {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
}
break;
case R.id.page_info_menu_id:
showPageInfo();
break;
case R.id.snapshot_go_live:
goLive();
return true;
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.dump_counters_menu_id:
getCurrentTopWebView().dumpV8Counters();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.ua_desktop_menu_id:
WebView web = getCurrentWebView();
mSettings.toggleDesktopUseragent(web);
web.loadUrl(web.getOriginalUrl());
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(desiredTab);
}
break;
}
}
}
break;
default:
return false;
}
return true;
}
private void goLive() {
Tab t = getCurrentTab();
t.loadUrl(t.getUrl(), null);
}
@Override
public void showPageInfo() {
mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
}
public boolean onContextItemSelected(MenuItem item) {
// Let the History and Bookmark fragments handle menus they created.
if (item.getGroupId() == R.id.CONTEXT_MENU) {
return false;
}
int id = item.getItemId();
boolean result = true;
switch (id) {
// -- Browser context menu
case R.id.open_context_menu_id:
case R.id.save_link_context_menu_id:
case R.id.copy_link_context_menu_id:
final WebView webView = getCurrentTopWebView();
if (null == webView) {
result = false;
break;
}
final HashMap<String, WebView> hrefMap =
new HashMap<String, WebView>();
hrefMap.put("webview", webView);
final Message msg = mHandler.obtainMessage(
FOCUS_NODE_HREF, id, 0, hrefMap);
webView.requestFocusNodeHref(msg);
break;
default:
// For other context menus
result = onOptionsItemSelected(item);
}
return result;
}
/**
* support programmatically opening the context menu
*/
public void openContextMenu(View view) {
mActivity.openContextMenu(view);
}
/**
* programmatically open the options menu
*/
public void openOptionsMenu() {
mActivity.openOptionsMenu();
}
public boolean onMenuOpened(int featureId, Menu menu) {
if (mOptionsMenuOpen) {
if (mConfigChanged) {
// We do not need to make any changes to the state of the
// title bar, since the only thing that happened was a
// change in orientation
mConfigChanged = false;
} else {
if (!mExtendedMenuOpen) {
mExtendedMenuOpen = true;
mUi.onExtendedMenuOpened();
} else {
// Switching the menu back to icon view, so show the
// title bar once again.
mExtendedMenuOpen = false;
mUi.onExtendedMenuClosed(mInLoad);
}
}
} else {
// The options menu is closed, so open it, and show the title
mOptionsMenuOpen = true;
mConfigChanged = false;
mExtendedMenuOpen = false;
mUi.onOptionsMenuOpened();
}
return true;
}
public void onOptionsMenuClosed(Menu menu) {
mOptionsMenuOpen = false;
mUi.onOptionsMenuClosed(mInLoad);
}
public void onContextMenuClosed(Menu menu) {
mUi.onContextMenuClosed(menu, mInLoad);
}
// Helper method for getting the top window.
@Override
public WebView getCurrentTopWebView() {
return mTabControl.getCurrentTopWebView();
}
@Override
public WebView getCurrentWebView() {
return mTabControl.getCurrentWebView();
}
/*
* This method is called as a result of the user selecting the options
* menu to see the download window. It shows the download window on top of
* the current window.
*/
void viewDownloads() {
Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
mActivity.startActivity(intent);
}
int getActionModeHeight() {
TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
actionBarSizeTypedArray.recycle();
return size;
}
// action mode
void onActionModeStarted(ActionMode mode) {
mUi.onActionModeStarted(mode);
mActionMode = mode;
}
/*
* True if a custom ActionMode (i.e. find or select) is in use.
*/
@Override
public boolean isInCustomActionMode() {
return mActionMode != null;
}
/*
* End the current ActionMode.
*/
@Override
public void endActionMode() {
if (mActionMode != null) {
mActionMode.finish();
}
}
/*
* Called by find and select when they are finished. Replace title bars
* as necessary.
*/
public void onActionModeFinished(ActionMode mode) {
if (!isInCustomActionMode()) return;
mUi.onActionModeFinished(mInLoad);
mActionMode = null;
}
boolean isInLoad() {
return mInLoad;
}
// bookmark handling
/**
* add the current page as a bookmark to the given folder id
* @param folderId use -1 for the default folder
* @param editExisting If true, check to see whether the site is already
* bookmarked, and if it is, edit that bookmark. If false, and
* the site is already bookmarked, do not attempt to edit the
* existing bookmark.
*/
@Override
public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
WebView w = getCurrentTopWebView();
if (w == null) {
return null;
}
Intent i = new Intent(mActivity,
AddBookmarkPage.class);
i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
String touchIconUrl = w.getTouchIconUrl();
if (touchIconUrl != null) {
i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
WebSettings settings = w.getSettings();
if (settings != null) {
i.putExtra(AddBookmarkPage.USER_AGENT,
settings.getUserAgentString());
}
}
i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
createScreenshot(w, getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity)));
i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
if (editExisting) {
i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
}
// Put the dialog at the upper right of the screen, covering the
// star on the title bar.
i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
return i;
}
// file chooser
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadHandler = new UploadHandler(this);
mUploadHandler.openFileChooser(uploadMsg, acceptType);
}
// thumbnails
/**
* Return the desired width for thumbnail screenshots, which are stored in
* the database, and used on the bookmarks screen.
* @param context Context for finding out the density of the screen.
* @return desired width for thumbnail screenshot.
*/
static int getDesiredThumbnailWidth(Context context) {
return context.getResources().getDimensionPixelOffset(
R.dimen.bookmarkThumbnailWidth);
}
/**
* Return the desired height for thumbnail screenshots, which are stored in
* the database, and used on the bookmarks screen.
* @param context Context for finding out the density of the screen.
* @return desired height for thumbnail screenshot.
*/
static int getDesiredThumbnailHeight(Context context) {
return context.getResources().getDimensionPixelOffset(
R.dimen.bookmarkThumbnailHeight);
}
static Bitmap createScreenshot(WebView view, int width, int height) {
if (view == null || view.getContentHeight() == 0
|| view.getContentWidth() == 0) {
return null;
}
// We render to a bitmap 2x the desired size so that we can then
// re-scale it with filtering since canvas.scale doesn't filter
// This helps reduce aliasing at the cost of being slightly blurry
final int filter_scale = 2;
int scaledWidth = width * filter_scale;
int scaledHeight = height * filter_scale;
if (sThumbnailBitmap == null || sThumbnailBitmap.getWidth() != scaledWidth
|| sThumbnailBitmap.getHeight() != scaledHeight) {
if (sThumbnailBitmap != null) {
sThumbnailBitmap.recycle();
sThumbnailBitmap = null;
}
sThumbnailBitmap =
Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(sThumbnailBitmap);
int contentWidth = view.getContentWidth();
float overviewScale = scaledWidth / (view.getScale() * contentWidth);
if (view instanceof BrowserWebView) {
int dy = -((BrowserWebView)view).getTitleHeight();
canvas.translate(0, dy * overviewScale);
}
canvas.scale(overviewScale, overviewScale);
if (view instanceof BrowserWebView) {
((BrowserWebView)view).drawContent(canvas);
} else {
view.draw(canvas);
}
Bitmap ret = Bitmap.createScaledBitmap(sThumbnailBitmap,
width, height, true);
canvas.setBitmap(null);
return ret;
}
private void updateScreenshot(Tab tab) {
// If this is a bookmarked site, add a screenshot to the database.
// FIXME: Would like to make sure there is actually something to
// draw, but the API for that (WebViewCore.pictureReady()) is not
// currently accessible here.
WebView view = tab.getWebView();
if (view == null) {
// Tab was destroyed
return;
}
final String url = tab.getUrl();
final String originalUrl = view.getOriginalUrl();
if (TextUtils.isEmpty(url)) {
return;
}
// Only update thumbnails for web urls (http(s)://), not for
// about:, javascript:, data:, etc...
// Unless it is a bookmarked site, then always update
if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
return;
}
final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity));
if (bm == null) {
return;
}
final ContentResolver cr = mActivity.getContentResolver();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... unused) {
Cursor cursor = null;
try {
// TODO: Clean this up
cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
if (cursor != null && cursor.moveToFirst()) {
final ByteArrayOutputStream os =
new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, os);
ContentValues values = new ContentValues();
values.put(Images.THUMBNAIL, os.toByteArray());
do {
values.put(Images.URL, cursor.getString(0));
cr.update(Images.CONTENT_URI, values, null, null);
} while (cursor.moveToNext());
}
} catch (IllegalStateException e) {
// Ignore
} finally {
if (cursor != null) cursor.close();
}
return null;
}
}.execute();
}
private class Copy implements OnMenuItemClickListener {
private CharSequence mText;
public boolean onMenuItemClick(MenuItem item) {
copy(mText);
return true;
}
public Copy(CharSequence toCopy) {
mText = toCopy;
}
}
private static class Download implements OnMenuItemClickListener {
private Activity mActivity;
private String mText;
private boolean mPrivateBrowsing;
private static final String FALLBACK_EXTENSION = "dat";
private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
public boolean onMenuItemClick(MenuItem item) {
if (DataUri.isDataUri(mText)) {
saveDataUri();
} else {
DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
null, null, mPrivateBrowsing);
}
return true;
}
public Download(Activity activity, String toDownload, boolean privateBrowsing) {
mActivity = activity;
mText = toDownload;
mPrivateBrowsing = privateBrowsing;
}
/**
* Treats mText as a data URI and writes its contents to a file
* based on the current time.
*/
private void saveDataUri() {
FileOutputStream outputStream = null;
try {
DataUri uri = new DataUri(mText);
File target = getTarget(uri);
outputStream = new FileOutputStream(target);
outputStream.write(uri.getData());
final DownloadManager manager =
(DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
manager.addCompletedDownload(target.getName(),
mActivity.getTitle().toString(), false,
uri.getMimeType(), target.getAbsolutePath(),
(long)uri.getData().length, false);
} catch (IOException e) {
Log.e(LOGTAG, "Could not save data URL");
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
// ignore close errors
}
}
}
}
/**
* Creates a File based on the current time stamp and uses
* the mime type of the DataUri to get the extension.
*/
private File getTarget(DataUri uri) throws IOException {
File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT);
String nameBase = format.format(new Date());
String mimeType = uri.getMimeType();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
if (extension == null) {
Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
extension = FALLBACK_EXTENSION;
}
extension = "." + extension; // createTempFile needs the '.'
File targetFile = File.createTempFile(nameBase, extension, dir);
return targetFile;
}
}
private static class SelectText implements OnMenuItemClickListener {
private WebView mWebView;
public boolean onMenuItemClick(MenuItem item) {
if (mWebView != null) {
return mWebView.selectText();
}
return false;
}
public SelectText(WebView webView) {
mWebView = webView;
}
}
/********************** TODO: UI stuff *****************************/
// these methods have been copied, they still need to be cleaned up
/****************** tabs ***************************************************/
// basic tab interactions:
// it is assumed that tabcontrol already knows about the tab
protected void addTab(Tab tab) {
mUi.addTab(tab);
}
protected void removeTab(Tab tab) {
mUi.removeTab(tab);
mTabControl.removeTab(tab);
mCrashRecoveryHandler.backupState();
}
@Override
public void setActiveTab(Tab tab) {
// monkey protection against delayed start
if (tab != null) {
mTabControl.setCurrentTab(tab);
// the tab is guaranteed to have a webview after setCurrentTab
mUi.setActiveTab(tab);
}
}
protected void closeEmptyTab() {
Tab current = mTabControl.getCurrentTab();
if (current != null
&& current.getWebView().copyBackForwardList().getSize() == 0) {
closeCurrentTab();
}
}
protected void reuseTab(Tab appTab, UrlData urlData) {
// Dismiss the subwindow if applicable.
dismissSubWindow(appTab);
// Since we might kill the WebView, remove it from the
// content view first.
mUi.detachTab(appTab);
// Recreate the main WebView after destroying the old one.
mTabControl.recreateWebView(appTab);
// TODO: analyze why the remove and add are necessary
mUi.attachTab(appTab);
if (mTabControl.getCurrentTab() != appTab) {
switchToTab(appTab);
loadUrlDataIn(appTab, urlData);
} else {
// If the tab was the current tab, we have to attach
// it to the view system again.
setActiveTab(appTab);
loadUrlDataIn(appTab, urlData);
}
}
// Remove the sub window if it exists. Also called by TabControl when the
// user clicks the 'X' to dismiss a sub window.
public void dismissSubWindow(Tab tab) {
removeSubWindow(tab);
// dismiss the subwindow. This will destroy the WebView.
tab.dismissSubWindow();
getCurrentTopWebView().requestFocus();
}
@Override
public void removeSubWindow(Tab t) {
if (t.getSubWebView() != null) {
mUi.removeSubWindow(t.getSubViewContainer());
}
}
@Override
public void attachSubWindow(Tab tab) {
if (tab.getSubWebView() != null) {
mUi.attachSubWindow(tab.getSubViewContainer());
getCurrentTopWebView().requestFocus();
}
}
private Tab showPreloadedTab(final UrlData urlData) {
if (!urlData.isPreloaded()) {
return null;
}
final PreloadedTabControl tabControl = urlData.getPreloadedTab();
final String sbQuery = urlData.getSearchBoxQueryToSubmit();
if (sbQuery != null) {
if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
// Could not submit query. Fallback to regular tab creation
tabControl.destroy();
return null;
}
}
// check tab count and make room for new tab
if (!mTabControl.canCreateNewTab()) {
Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
if (leastUsed != null) {
closeTab(leastUsed);
}
}
Tab t = tabControl.getTab();
t.refreshIdAfterPreload();
mTabControl.addPreloadedTab(t);
addTab(t);
setActiveTab(t);
return t;
}
// open a non inconito tab with the given url data
// and set as active tab
public Tab openTab(UrlData urlData) {
Tab tab = showPreloadedTab(urlData);
if (tab == null) {
tab = createNewTab(false, true, true);
if ((tab != null) && !urlData.isEmpty()) {
loadUrlDataIn(tab, urlData);
}
}
return tab;
}
@Override
public Tab openTabToHomePage() {
return openTab(mSettings.getHomePage(), false, true, false);
}
@Override
public Tab openIncognitoTab() {
return openTab(INCOGNITO_URI, true, true, false);
}
@Override
public Tab openTab(String url, boolean incognito, boolean setActive,
boolean useCurrent) {
return openTab(url, incognito, setActive, useCurrent, null);
}
@Override
public Tab openTab(String url, Tab parent, boolean setActive,
boolean useCurrent) {
return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
setActive, useCurrent, parent);
}
public Tab openTab(String url, boolean incognito, boolean setActive,
boolean useCurrent, Tab parent) {
Tab tab = createNewTab(incognito, setActive, useCurrent);
if (tab != null) {
if (parent != null && parent != tab) {
parent.addChildTab(tab);
}
if (url != null) {
loadUrl(tab, url);
}
}
return tab;
}
// this method will attempt to create a new tab
// incognito: private browsing tab
// setActive: ste tab as current tab
// useCurrent: if no new tab can be created, return current tab
private Tab createNewTab(boolean incognito, boolean setActive,
boolean useCurrent) {
Tab tab = null;
if (mTabControl.canCreateNewTab()) {
tab = mTabControl.createNewTab(incognito);
addTab(tab);
if (setActive) {
setActiveTab(tab);
}
} else {
if (useCurrent) {
tab = mTabControl.getCurrentTab();
reuseTab(tab, null);
} else {
mUi.showMaxTabsWarning();
}
}
return tab;
}
@Override
public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
SnapshotTab tab = null;
if (mTabControl.canCreateNewTab()) {
tab = mTabControl.createSnapshotTab(snapshotId);
addTab(tab);
if (setActive) {
setActiveTab(tab);
}
} else {
mUi.showMaxTabsWarning();
}
return tab;
}
/**
* @param tab the tab to switch to
* @return boolean True if we successfully switched to a different tab. If
* the indexth tab is null, or if that tab is the same as
* the current one, return false.
*/
@Override
public boolean switchToTab(Tab tab) {
Tab currentTab = mTabControl.getCurrentTab();
if (tab == null || tab == currentTab) {
return false;
}
setActiveTab(tab);
return true;
}
@Override
public void closeCurrentTab() {
closeCurrentTab(false);
}
protected void closeCurrentTab(boolean andQuit) {
if (mTabControl.getTabCount() == 1) {
mCrashRecoveryHandler.clearState();
mTabControl.removeTab(getCurrentTab());
mActivity.finish();
return;
}
final Tab current = mTabControl.getCurrentTab();
final int pos = mTabControl.getCurrentPosition();
Tab newTab = current.getParent();
if (newTab == null) {
newTab = mTabControl.getTab(pos + 1);
if (newTab == null) {
newTab = mTabControl.getTab(pos - 1);
}
}
if (andQuit) {
mTabControl.setCurrentTab(newTab);
closeTab(current);
} else if (switchToTab(newTab)) {
// Close window
closeTab(current);
}
}
/**
* Close the tab, remove its associated title bar, and adjust mTabControl's
* current tab to a valid value.
*/
@Override
public void closeTab(Tab tab) {
if (tab == mTabControl.getCurrentTab()) {
closeCurrentTab();
} else {
removeTab(tab);
}
}
// Called when loading from context menu or LOAD_URL message
protected void loadUrlFromContext(String url) {
Tab tab = getCurrentTab();
WebView view = tab != null ? tab.getWebView() : null;
// In case the user enters nothing.
if (url != null && url.length() != 0 && tab != null && view != null) {
url = UrlUtils.smartUrlFilter(url);
if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
loadUrl(tab, url);
}
}
}
/**
* Load the URL into the given WebView and update the title bar
* to reflect the new load. Call this instead of WebView.loadUrl
* directly.
* @param view The WebView used to load url.
* @param url The URL to load.
*/
@Override
public void loadUrl(Tab tab, String url) {
loadUrl(tab, url, null);
}
protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
if (tab != null) {
dismissSubWindow(tab);
tab.loadUrl(url, headers);
mUi.onProgressChanged(tab);
}
}
/**
* Load UrlData into a Tab and update the title bar to reflect the new
* load. Call this instead of UrlData.loadIn directly.
* @param t The Tab used to load.
* @param data The UrlData being loaded.
*/
protected void loadUrlDataIn(Tab t, UrlData data) {
if (data != null) {
if (data.mVoiceIntent != null) {
t.activateVoiceSearchMode(data.mVoiceIntent);
} else if (data.isPreloaded()) {
// this isn't called for preloaded tabs
} else {
loadUrl(t, data.mUrl, data.mHeaders);
}
}
}
@Override
public void onUserCanceledSsl(Tab tab) {
// TODO: Figure out the "right" behavior
if (tab.canGoBack()) {
tab.goBack();
} else {
tab.loadUrl(mSettings.getHomePage(), null);
}
}
void goBackOnePageOrQuit() {
Tab current = mTabControl.getCurrentTab();
if (current == null) {
/*
* Instead of finishing the activity, simply push this to the back
* of the stack and let ActivityManager to choose the foreground
* activity. As BrowserActivity is singleTask, it will be always the
* root of the task. So we can use either true or false for
* moveTaskToBack().
*/
mActivity.moveTaskToBack(true);
return;
}
if (current.canGoBack()) {
current.goBack();
} else {
// Check to see if we are closing a window that was created by
// another window. If so, we switch back to that window.
Tab parent = current.getParent();
if (parent != null) {
switchToTab(parent);
// Now we close the other tab
closeTab(current);
} else {
if ((current.getAppId() != null) || current.closeOnBack()) {
closeCurrentTab(true);
}
/*
* Instead of finishing the activity, simply push this to the back
* of the stack and let ActivityManager to choose the foreground
* activity. As BrowserActivity is singleTask, it will be always the
* root of the task. So we can use either true or false for
* moveTaskToBack().
*/
mActivity.moveTaskToBack(true);
}
}
}
/**
* Feed the previously stored results strings to the BrowserProvider so that
* the SearchDialog will show them instead of the standard searches.
* @param result String to show on the editable line of the SearchDialog.
*/
@Override
public void showVoiceSearchResults(String result) {
ContentProviderClient client = mActivity.getContentResolver()
.acquireContentProviderClient(Browser.BOOKMARKS_URI);
ContentProvider prov = client.getLocalContentProvider();
BrowserProvider bp = (BrowserProvider) prov;
bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
client.release();
Bundle bundle = createGoogleSearchSourceBundle(
GOOGLE_SEARCH_SOURCE_SEARCHKEY);
bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
startSearch(result, false, bundle, false);
}
private void startSearch(String initialQuery, boolean selectInitialQuery,
Bundle appSearchData, boolean globalSearch) {
if (appSearchData == null) {
appSearchData = createGoogleSearchSourceBundle(
GOOGLE_SEARCH_SOURCE_TYPE);
}
SearchEngine searchEngine = mSettings.getSearchEngine();
if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
}
mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
globalSearch);
}
private Bundle createGoogleSearchSourceBundle(String source) {
Bundle bundle = new Bundle();
bundle.putString(Search.SOURCE, source);
return bundle;
}
/**
* helper method for key handler
* returns the current tab if it can't advance
*/
private Tab getNextTab() {
return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
mTabControl.getCurrentPosition() + 1));
}
/**
* helper method for key handler
* returns the current tab if it can't advance
*/
private Tab getPrevTab() {
return mTabControl.getTab(Math.max(0,
mTabControl.getCurrentPosition() - 1));
}
/**
* handle key events in browser
*
* @param keyCode
* @param event
* @return true if handled, false to pass to super
*/
boolean onKeyDown(int keyCode, KeyEvent event) {
boolean noModifiers = event.hasNoModifiers();
// Even if MENU is already held down, we need to call to super to open
// the IME on long press.
if (!noModifiers
&& ((KeyEvent.KEYCODE_MENU == keyCode)
|| (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
|| (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
mMenuIsDown = true;
return false;
}
WebView webView = getCurrentTopWebView();
Tab tab = getCurrentTab();
if (webView == null || tab == null) return false;
boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
switch(keyCode) {
case KeyEvent.KEYCODE_TAB:
if (event.isCtrlPressed()) {
if (event.isShiftPressed()) {
// prev tab
switchToTab(getPrevTab());
} else {
// next tab
switchToTab(getNextTab());
}
return true;
}
break;
case KeyEvent.KEYCODE_SPACE:
// WebView/WebTextView handle the keys in the KeyDown. As
// the Activity's shortcut keys are only handled when WebView
// doesn't, have to do it in onKeyDown instead of onKeyUp.
if (shift) {
pageUp();
} else if (noModifiers) {
pageDown();
}
return true;
case KeyEvent.KEYCODE_BACK:
if (!noModifiers) break;
event.startTracking();
return true;
case KeyEvent.KEYCODE_FORWARD:
if (!noModifiers) break;
tab.goForward();
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (ctrl) {
tab.goBack();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (ctrl) {
tab.goForward();
return true;
}
break;
case KeyEvent.KEYCODE_A:
if (ctrl) {
webView.selectAll();
return true;
}
break;
// case KeyEvent.KEYCODE_B: // menu
case KeyEvent.KEYCODE_C:
if (ctrl) {
webView.copySelection();
return true;
}
break;
// case KeyEvent.KEYCODE_D: // menu
// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
// case KeyEvent.KEYCODE_F: // menu
// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
// case KeyEvent.KEYCODE_H: // menu
// case KeyEvent.KEYCODE_I: // unused
// case KeyEvent.KEYCODE_J: // menu
// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
// case KeyEvent.KEYCODE_L: // menu
// case KeyEvent.KEYCODE_M: // unused
// case KeyEvent.KEYCODE_N: // in Chrome: new window
// case KeyEvent.KEYCODE_O: // in Chrome: open file
// case KeyEvent.KEYCODE_P: // in Chrome: print page
// case KeyEvent.KEYCODE_Q: // unused
// case KeyEvent.KEYCODE_R:
// case KeyEvent.KEYCODE_S: // in Chrome: saves page
case KeyEvent.KEYCODE_T:
// we can't use the ctrl/shift flags, they check for
// exclusive use of a modifier
if (event.isCtrlPressed()) {
if (event.isShiftPressed()) {
openIncognitoTab();
} else {
openTabToHomePage();
}
return true;
}
break;
// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
// case KeyEvent.KEYCODE_V: // text view intercepts to paste
// case KeyEvent.KEYCODE_W: // menu
// case KeyEvent.KEYCODE_X: // text view intercepts to cut
// case KeyEvent.KEYCODE_Y: // unused
// case KeyEvent.KEYCODE_Z: // unused
}
// it is a regular key and webview is not null
return mUi.dispatchKey(keyCode, event);
}
boolean onKeyLongPress(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mUi.isWebShowing()) {
bookmarksOrHistoryPicker(ComboViews.History);
return true;
}
break;
}
return false;
}
boolean onKeyUp(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_MENU == keyCode) {
mMenuIsDown = false;
if (event.isTracking() && !event.isCanceled()) {
return onMenuKey();
}
}
if (!event.hasNoModifiers()) return false;
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.isTracking() && !event.isCanceled()) {
onBackKey();
return true;
}
break;
}
return false;
}
public boolean isMenuDown() {
return mMenuIsDown;
}
public void setupAutoFill(Message message) {
// Open the settings activity at the AutoFill profile fragment so that
// the user can create a new profile. When they return, we will dispatch
// the message so that we can autofill the form using their new profile.
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
AutoFillSettingsFragment.class.getName());
mAutoFillSetupMessage = message;
mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
}
@Override
public void registerDropdownChangeListener(DropdownChangeListener d) {
mUi.registerDropdownChangeListener(d);
}
public boolean onSearchRequested() {
mUi.editUrl(false);
return true;
}
@Override
public boolean shouldCaptureThumbnails() {
return mUi.shouldCaptureThumbnails();
}
@Override
public void setBlockEvents(boolean block) {
mBlockEvents = block;
}
public boolean dispatchKeyEvent(KeyEvent event) {
return mBlockEvents;
}
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
return mBlockEvents;
}
public boolean dispatchTouchEvent(MotionEvent ev) {
return mBlockEvents;
}
public boolean dispatchTrackballEvent(MotionEvent ev) {
return mBlockEvents;
}
public boolean dispatchGenericMotionEvent(MotionEvent ev) {
return mBlockEvents;
}
}
| false | true | public boolean onOptionsItemSelected(MenuItem item) {
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
if (mUi.onOptionsItemSelected(item)) {
// ui callback handled it
return true;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
break;
case R.id.history_menu_id:
bookmarksOrHistoryPicker(ComboViews.History);
break;
case R.id.snapshots_menu_id:
bookmarksOrHistoryPicker(ComboViews.Snapshots);
break;
case R.id.add_bookmark_menu_id:
Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
if (bookmarkIntent != null) {
mActivity.startActivity(bookmarkIntent);
}
break;
case R.id.stop_reload_menu_id:
if (mInLoad) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTab().goBack();
break;
case R.id.forward_menu_id:
getCurrentTab().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
loadUrl(current, mSettings.getHomePage());
break;
case R.id.preferences_menu_id:
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
getCurrentTopWebView().getUrl());
mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
break;
case R.id.find_menu_id:
getCurrentTopWebView().showFindDialog(null, true);
break;
case R.id.save_snapshot_menu_id:
final Tab source = getTabControl().getCurrentTab();
if (source == null) break;
final ContentResolver cr = mActivity.getContentResolver();
final ContentValues values = source.createSnapshotValues();
if (values != null) {
new AsyncTask<Tab, Void, Long>() {
@Override
protected Long doInBackground(Tab... params) {
Uri result = cr.insert(Snapshots.CONTENT_URI, values);
long id = ContentUris.parseId(result);
return id;
}
@Override
protected void onPostExecute(Long id) {
Bundle b = new Bundle();
b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
mUi.showComboView(ComboViews.Snapshots, b);
};
}.execute(source);
} else {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
}
break;
case R.id.page_info_menu_id:
showPageInfo();
break;
case R.id.snapshot_go_live:
goLive();
return true;
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.dump_counters_menu_id:
getCurrentTopWebView().dumpV8Counters();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.ua_desktop_menu_id:
WebView web = getCurrentWebView();
mSettings.toggleDesktopUseragent(web);
web.loadUrl(web.getOriginalUrl());
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(desiredTab);
}
break;
}
}
}
break;
default:
return false;
}
return true;
}
| public boolean onOptionsItemSelected(MenuItem item) {
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
if (mUi.onOptionsItemSelected(item)) {
// ui callback handled it
return true;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(ComboViews.Bookmarks);
break;
case R.id.history_menu_id:
bookmarksOrHistoryPicker(ComboViews.History);
break;
case R.id.snapshots_menu_id:
bookmarksOrHistoryPicker(ComboViews.Snapshots);
break;
case R.id.add_bookmark_menu_id:
Intent bookmarkIntent = createBookmarkCurrentPageIntent(false);
if (bookmarkIntent != null) {
mActivity.startActivity(bookmarkIntent);
}
break;
case R.id.stop_reload_menu_id:
if (mInLoad) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTab().goBack();
break;
case R.id.forward_menu_id:
getCurrentTab().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
loadUrl(current, mSettings.getHomePage());
break;
case R.id.preferences_menu_id:
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
getCurrentTopWebView().getUrl());
mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
break;
case R.id.find_menu_id:
getCurrentTopWebView().showFindDialog(null, true);
break;
case R.id.save_snapshot_menu_id:
final Tab source = getTabControl().getCurrentTab();
if (source == null) break;
final ContentResolver cr = mActivity.getContentResolver();
final ContentValues values = source.createSnapshotValues();
if (values != null) {
new AsyncTask<Tab, Void, Long>() {
@Override
protected Long doInBackground(Tab... params) {
Uri result = cr.insert(Snapshots.CONTENT_URI, values);
if (result == null) {
return null;
}
long id = ContentUris.parseId(result);
return id;
}
@Override
protected void onPostExecute(Long id) {
if (id == null) {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
return;
}
Bundle b = new Bundle();
b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
mUi.showComboView(ComboViews.Snapshots, b);
};
}.execute(source);
} else {
Toast.makeText(mActivity, R.string.snapshot_failed,
Toast.LENGTH_SHORT).show();
}
break;
case R.id.page_info_menu_id:
showPageInfo();
break;
case R.id.snapshot_go_live:
goLive();
return true;
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.dump_counters_menu_id:
getCurrentTopWebView().dumpV8Counters();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.ua_desktop_menu_id:
WebView web = getCurrentWebView();
mSettings.toggleDesktopUseragent(web);
web.loadUrl(web.getOriginalUrl());
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(desiredTab);
}
break;
}
}
}
break;
default:
return false;
}
return true;
}
|
diff --git a/MolGenExp/src/biochem/Protex.java b/MolGenExp/src/biochem/Protex.java
index 7c7fc8f5..81345f60 100644
--- a/MolGenExp/src/biochem/Protex.java
+++ b/MolGenExp/src/biochem/Protex.java
@@ -1,155 +1,157 @@
package biochem;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import molGenExp.ColorModel;
import molGenExp.CombinedColorPanel;
import molGenExp.MolGenExp;
import molGenExp.Organism;
public class Protex extends JPanel {
private FoldingWindow upperFoldingWindow;
private FoldingWindow lowerFoldingWindow;
private ProteinHistoryList proteinHistoryList;
private JScrollPane histListScrollPane;
private ProteinHistListControlPanel proteinHistListControlPanel;
private CombinedColorPanel combinedColorPanel;
ColorModel colorModel;
ProteinPrinter printer;
File outFile;
private MolGenExp mge;
public Protex(MolGenExp mge) {
super();
this.mge = mge;
colorModel = mge.getOverallColorModel();
printer = new ProteinPrinter();
outFile = null;
setupUI();
}
class ApplicationCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
private void setupUI() {
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
leftPanel.add(Box.createRigidArea(new Dimension(200,1)));
JPanel aapPanel = new JPanel();
+ aapPanel.setLayout(new BoxLayout(aapPanel, BoxLayout.X_AXIS));
aapPanel.setBorder(BorderFactory.createTitledBorder("Amino acids"));
AminoAcidPalette aaPalette
= new AminoAcidPalette(180, 225, 5, 4, colorModel);
aapPanel.setMaximumSize(new Dimension(200, 250));
+ aapPanel.add(Box.createRigidArea(new Dimension(1,225)));
aapPanel.add(aaPalette);
JPanel histListPanel = new JPanel();
histListPanel.setBorder(
BorderFactory.createTitledBorder("History List"));
histListPanel.setLayout(new BoxLayout(histListPanel, BoxLayout.Y_AXIS));
proteinHistListControlPanel = new ProteinHistListControlPanel(this);
histListPanel.add(proteinHistListControlPanel);
proteinHistoryList = new ProteinHistoryList(
new DefaultListModel(), mge);
histListScrollPane = new JScrollPane(proteinHistoryList);
// histListScrollPane.setPreferredSize(new Dimension(200,1000));
histListPanel.add(histListScrollPane);
leftPanel.add(aapPanel);
leftPanel.add(histListPanel);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
upperFoldingWindow = new FoldingWindow("Upper Folding Window", this, colorModel);
lowerFoldingWindow = new FoldingWindow("Lower Folding Window", this, colorModel);
rightPanel.add(upperFoldingWindow);
combinedColorPanel = new CombinedColorPanel();
rightPanel.add(combinedColorPanel);
rightPanel.add(lowerFoldingWindow);
setButtonsEnabled(false);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(
new BoxLayout(mainPanel, BoxLayout.X_AXIS));
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
setLayout(new BorderLayout());
add(mainPanel, BorderLayout.CENTER);
}
public FoldingWindow getUpperFoldingWindow() {
return upperFoldingWindow;
}
public FoldingWindow getLowerFoldingWindow() {
return lowerFoldingWindow;
}
public void addFoldedToHistList(FoldedPolypeptide fp) {
proteinHistoryList.add(fp);
histListScrollPane.revalidate();
histListScrollPane.repaint();
updateCombinedColor();
}
public void updateCombinedColor() {
Color u = upperFoldingWindow.getColor();
Color l = lowerFoldingWindow.getColor();
Color combined = colorModel.mixTwoColors(u, l);
combinedColorPanel.setCombinedColor(combined);
}
public void sendSelectedFPtoUP() {
if (proteinHistoryList.getSelectedValue() != null) {
FoldedPolypeptide fp =
(FoldedPolypeptide) proteinHistoryList.getSelectedValue();
upperFoldingWindow.setFoldedPolypeptide(fp);
}
}
public void sendSelectedFPtoLP() {
if (proteinHistoryList.getSelectedValue() != null){
FoldedPolypeptide fp =
(FoldedPolypeptide) proteinHistoryList.getSelectedValue();
lowerFoldingWindow.setFoldedPolypeptide(fp);
}
}
public void loadOrganism(Organism o) {
upperFoldingWindow.setFoldedPolypeptide(
o.getGene1().getFoldedPolypeptide());
lowerFoldingWindow.setFoldedPolypeptide(
o.getGene2().getFoldedPolypeptide());
}
public void setButtonsEnabled(boolean b) {
proteinHistListControlPanel.setButtonsEnabled(b);
}
}
| false | true | private void setupUI() {
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
leftPanel.add(Box.createRigidArea(new Dimension(200,1)));
JPanel aapPanel = new JPanel();
aapPanel.setBorder(BorderFactory.createTitledBorder("Amino acids"));
AminoAcidPalette aaPalette
= new AminoAcidPalette(180, 225, 5, 4, colorModel);
aapPanel.setMaximumSize(new Dimension(200, 250));
aapPanel.add(aaPalette);
JPanel histListPanel = new JPanel();
histListPanel.setBorder(
BorderFactory.createTitledBorder("History List"));
histListPanel.setLayout(new BoxLayout(histListPanel, BoxLayout.Y_AXIS));
proteinHistListControlPanel = new ProteinHistListControlPanel(this);
histListPanel.add(proteinHistListControlPanel);
proteinHistoryList = new ProteinHistoryList(
new DefaultListModel(), mge);
histListScrollPane = new JScrollPane(proteinHistoryList);
// histListScrollPane.setPreferredSize(new Dimension(200,1000));
histListPanel.add(histListScrollPane);
leftPanel.add(aapPanel);
leftPanel.add(histListPanel);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
upperFoldingWindow = new FoldingWindow("Upper Folding Window", this, colorModel);
lowerFoldingWindow = new FoldingWindow("Lower Folding Window", this, colorModel);
rightPanel.add(upperFoldingWindow);
combinedColorPanel = new CombinedColorPanel();
rightPanel.add(combinedColorPanel);
rightPanel.add(lowerFoldingWindow);
setButtonsEnabled(false);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(
new BoxLayout(mainPanel, BoxLayout.X_AXIS));
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
setLayout(new BorderLayout());
add(mainPanel, BorderLayout.CENTER);
}
| private void setupUI() {
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
leftPanel.add(Box.createRigidArea(new Dimension(200,1)));
JPanel aapPanel = new JPanel();
aapPanel.setLayout(new BoxLayout(aapPanel, BoxLayout.X_AXIS));
aapPanel.setBorder(BorderFactory.createTitledBorder("Amino acids"));
AminoAcidPalette aaPalette
= new AminoAcidPalette(180, 225, 5, 4, colorModel);
aapPanel.setMaximumSize(new Dimension(200, 250));
aapPanel.add(Box.createRigidArea(new Dimension(1,225)));
aapPanel.add(aaPalette);
JPanel histListPanel = new JPanel();
histListPanel.setBorder(
BorderFactory.createTitledBorder("History List"));
histListPanel.setLayout(new BoxLayout(histListPanel, BoxLayout.Y_AXIS));
proteinHistListControlPanel = new ProteinHistListControlPanel(this);
histListPanel.add(proteinHistListControlPanel);
proteinHistoryList = new ProteinHistoryList(
new DefaultListModel(), mge);
histListScrollPane = new JScrollPane(proteinHistoryList);
// histListScrollPane.setPreferredSize(new Dimension(200,1000));
histListPanel.add(histListScrollPane);
leftPanel.add(aapPanel);
leftPanel.add(histListPanel);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
upperFoldingWindow = new FoldingWindow("Upper Folding Window", this, colorModel);
lowerFoldingWindow = new FoldingWindow("Lower Folding Window", this, colorModel);
rightPanel.add(upperFoldingWindow);
combinedColorPanel = new CombinedColorPanel();
rightPanel.add(combinedColorPanel);
rightPanel.add(lowerFoldingWindow);
setButtonsEnabled(false);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(
new BoxLayout(mainPanel, BoxLayout.X_AXIS));
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
setLayout(new BorderLayout());
add(mainPanel, BorderLayout.CENTER);
}
|
diff --git a/src/org/apache/ws/security/components/crypto/AbstractCrypto.java b/src/org/apache/ws/security/components/crypto/AbstractCrypto.java
index 99da06790..22e56dd3c 100644
--- a/src/org/apache/ws/security/components/crypto/AbstractCrypto.java
+++ b/src/org/apache/ws/security/components/crypto/AbstractCrypto.java
@@ -1,173 +1,176 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.ws.security.components.crypto;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.util.Loader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
* User: dims
* Date: Sep 15, 2005
* Time: 9:50:40 AM
* To change this template use File | Settings | File Templates.
*/
public abstract class AbstractCrypto extends CryptoBase {
private static Log log = LogFactory.getLog(AbstractCrypto.class);
protected static CertificateFactory certFact;
protected Properties properties = null;
/**
* Constructor
*
* @param properties
*/
public AbstractCrypto(Properties properties) throws CredentialException, IOException {
this(properties,AbstractCrypto.class.getClassLoader());
}
/**
* This allows providing a custom class loader to load the resources, etc
* @param properties
* @param loader
* @throws CredentialException
* @throws IOException
*/
public AbstractCrypto(Properties properties, ClassLoader loader) throws CredentialException, IOException {
this.properties = properties;
+ if (this.properties == null) {
+ return;
+ }
String location = this.properties.getProperty("org.apache.ws.security.crypto.merlin.file");
InputStream is = null;
java.net.URL url = Loader.getResource(loader, location);
if(url != null) {
is = url.openStream();
} else {
is = new java.io.FileInputStream(location);
}
/**
* If we don't find it, then look on the file system.
*/
if (is == null) {
try {
is = new FileInputStream(location);
} catch (Exception e) {
throw new CredentialException(3, "proxyNotFound", new Object[]{location});
}
}
/**
* Load the keystore
*/
try {
String provider = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.provider");
String passwd = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.password","security");
String type = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.type", KeyStore.getDefaultType());
this.keystore = load(is, passwd, provider, type);
} finally {
is.close();
}
/**
* Load cacerts
*/
String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
InputStream cacertsIs = new FileInputStream(cacertsPath);
try {
String cacertsPasswd = properties.getProperty("org.apache.ws.security.crypto.merlin.cacerts.password", "changeit");
this.cacerts = load(cacertsIs, cacertsPasswd, null, KeyStore.getDefaultType());
} finally {
cacertsIs.close();
}
}
/**
* Loads the the keystore from an <code>InputStream </code>.
* <p/>
*
* @param input <code>InputStream</code> to read from
* @throws CredentialException
*/
public KeyStore load(InputStream input, String storepass, String provider, String type) throws CredentialException {
if (input == null) {
throw new IllegalArgumentException("input stream cannot be null");
}
KeyStore ks = null;
try {
if (provider == null || provider.length() == 0) {
ks = KeyStore.getInstance(type);
} else {
ks = KeyStore.getInstance(type, provider);
}
ks.load(input, (storepass == null || storepass.length() == 0) ? new char[0] : storepass.toCharArray());
} catch (IOException e) {
e.printStackTrace();
throw new CredentialException(3, "ioError00", e);
} catch (GeneralSecurityException e) {
e.printStackTrace();
throw new CredentialException(3, "secError00", e);
} catch (Exception e) {
e.printStackTrace();
throw new CredentialException(-1, "error00", e);
}
return ks;
}
protected String
getCryptoProvider() {
return properties.getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
}
/**
* Retrieves the alias name of the default certificate which has been
* specified as a property. This should be the certificate that is used for
* signature and encryption. This alias corresponds to the certificate that
* should be used whenever KeyInfo is not present in a signed or
* an encrypted message. May return null.
*
* @return alias name of the default X509 certificate
*/
public String getDefaultX509Alias() {
if (properties == null) {
return null;
}
return properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.alias");
}
}
| true | true | public AbstractCrypto(Properties properties, ClassLoader loader) throws CredentialException, IOException {
this.properties = properties;
String location = this.properties.getProperty("org.apache.ws.security.crypto.merlin.file");
InputStream is = null;
java.net.URL url = Loader.getResource(loader, location);
if(url != null) {
is = url.openStream();
} else {
is = new java.io.FileInputStream(location);
}
/**
* If we don't find it, then look on the file system.
*/
if (is == null) {
try {
is = new FileInputStream(location);
} catch (Exception e) {
throw new CredentialException(3, "proxyNotFound", new Object[]{location});
}
}
/**
* Load the keystore
*/
try {
String provider = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.provider");
String passwd = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.password","security");
String type = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.type", KeyStore.getDefaultType());
this.keystore = load(is, passwd, provider, type);
} finally {
is.close();
}
/**
* Load cacerts
*/
String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
InputStream cacertsIs = new FileInputStream(cacertsPath);
try {
String cacertsPasswd = properties.getProperty("org.apache.ws.security.crypto.merlin.cacerts.password", "changeit");
this.cacerts = load(cacertsIs, cacertsPasswd, null, KeyStore.getDefaultType());
} finally {
cacertsIs.close();
}
}
| public AbstractCrypto(Properties properties, ClassLoader loader) throws CredentialException, IOException {
this.properties = properties;
if (this.properties == null) {
return;
}
String location = this.properties.getProperty("org.apache.ws.security.crypto.merlin.file");
InputStream is = null;
java.net.URL url = Loader.getResource(loader, location);
if(url != null) {
is = url.openStream();
} else {
is = new java.io.FileInputStream(location);
}
/**
* If we don't find it, then look on the file system.
*/
if (is == null) {
try {
is = new FileInputStream(location);
} catch (Exception e) {
throw new CredentialException(3, "proxyNotFound", new Object[]{location});
}
}
/**
* Load the keystore
*/
try {
String provider = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.provider");
String passwd = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.password","security");
String type = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.type", KeyStore.getDefaultType());
this.keystore = load(is, passwd, provider, type);
} finally {
is.close();
}
/**
* Load cacerts
*/
String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
InputStream cacertsIs = new FileInputStream(cacertsPath);
try {
String cacertsPasswd = properties.getProperty("org.apache.ws.security.crypto.merlin.cacerts.password", "changeit");
this.cacerts = load(cacertsIs, cacertsPasswd, null, KeyStore.getDefaultType());
} finally {
cacertsIs.close();
}
}
|
diff --git a/src/main/java/net/glxn/jmsutility/JMSUtility.java b/src/main/java/net/glxn/jmsutility/JMSUtility.java
index 441f733..c091ac7 100644
--- a/src/main/java/net/glxn/jmsutility/JMSUtility.java
+++ b/src/main/java/net/glxn/jmsutility/JMSUtility.java
@@ -1,168 +1,168 @@
package net.glxn.jmsutility;
import net.glxn.jmsutility.dispatch.JMSMessageDispatcher;
import net.glxn.jmsutility.dispatch.JMSMessageDispatcherFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JMSUtility extends Component {
private JPanel panel1;
protected JTextField jmsServerUrl;
protected JTextField queueDestinationTextField;
protected JTextField messagesTextField;
protected JTextPane messageTextPane;
protected JTextPane parameterListTextPane;
private JButton sendMessageSButton;
private JButton helpButton;
private int parameters;
private String[] parameterValues;
private Integer numberOfMessagesToSend;
private JMSMessageDispatcher jmsMessageDispatcher;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("JMSUtilForm");
frame.setContentPane(new JMSUtility().panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public JMSUtility() {
helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
showHelpDialog();
} catch (Exception ex) {
showErrorPane(ex.getMessage(), ExceptionUtils.getFullStackTrace(ex));
}
}
});
sendMessageSButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
validateInputFields();
allocateJMSMessageDispatcher();
sendMessage();
} catch (Exception ex) {
showErrorPane(ex.getMessage(), ExceptionUtils.getFullStackTrace(ex));
}
}
});
}
private void allocateJMSMessageDispatcher() {
jmsMessageDispatcher = JMSMessageDispatcherFactory.getJMSMessageDispatcher(jmsServerUrl.getText());
}
protected void validateInputFields() {
- if (!jmsServerUrl.getText().matches("\\w{2,5}://\\[a-zA-Z0-9]*:\\d{2,6}")) {
+ if (!jmsServerUrl.getText().matches("\\w{2,5}://.*:\\d{2,6}")) {
showErrorPane("input validation error", "JMS Server URL is not a valid URL. " +
"\n\n should be: [protocol]://[host]:[port]" +
"\n example: tcp://localhost:61616");
}
if (StringUtils.isBlank(queueDestinationTextField.getText())) {
showErrorPane("input validation error", "You must supply a Queue destination");
}
if (!StringUtils.isNumeric(messagesTextField.getText())) {
showErrorPane("input validation error", "Number of messages must be a number");
}
if (StringUtils.isBlank(messageTextPane.getText())) {
showErrorPane("input validation error", "Message can not be blank");
}
parameters = numberOfParametersInText(messageTextPane.getText());
parameterValues = StringUtils.split(parameterListTextPane.getText(), "\n");
if (parameters > 0 && parameterValues.length == 0) {
showErrorPane("input validation error", "You have supplied a parameterized message but no parameters. " +
"\n\nPlease see the Help! dialog.");
}
if (parameters == 0 && parameterValues.length > 0) {
showErrorPane("input validation error", "You have supplied parameters to a message that has no placeholders." +
"\n\nPlease see the Help! dialog.");
}
if (parameters > 1) {
boolean parameterNumberOfFieldsMismatch = false;
for (String parameterValue : parameterValues) {
int numberOfFieldsInParameterValue = StringUtils.countMatches(parameterValue, "|");
if (numberOfFieldsInParameterValue != (parameters - 1)) {
parameterNumberOfFieldsMismatch = true;
}
}
if (parameterNumberOfFieldsMismatch) {
showErrorPane("input validation error", "Your parameter list contains at least one entry that does not " +
"satisfy the parameterized message." +
"\n\nPlease see the Help! dialog.");
}
}
}
int numberOfParametersInText(String text) {
return StringUtils.countMatches(text, "%s");
}
private void sendMessage() {
LogWindow logWindow = new LogWindow(panel1.getX() + panel1.getWidth() + 25, panel1.getY());
if (parameterValues.length > 0) {
logWindow.log("Sending messages for parameters in list. \nTotal number of messages to send=" + parameterValues.length);
//TODO, iterate list of parameters and create message merging in the value in the message and send message
} else {
numberOfMessagesToSend = Integer.valueOf(messagesTextField.getText());
logWindow.log("Sending " + numberOfMessagesToSend + " message(s)");
//TODO, send numberOfMessagesToSend number of messages using only the message field
}
}
private void showHelpDialog() {
String message = "This tool let's you send a JMS messsage to a queue. " +
"\nSupply the input fields with correct values and click send button." +
"\n\nThere is a special feature for the message and parameter list input fields." +
"\nThese fields work together, so if you supply the message with a placeholder, namely %s, " +
"\nthen the tool will attempt to fill the placeholder with values from the parameter list. If you have one %s in you message, " +
"\nthen you can send several messages with each message being given a new value for %s with the next value in the list. " +
"\nThe parameter list entries need to be separated by a carriage return/new line feed. " +
"\n------" +
"\nExample parameter list for input with one %s:" +
"\nparam1" +
"\nparam2" +
"\nparam3" +
"\n------" +
"\nIf you have more than one placeholder, then the values should be separated by a pipe (|) in the parameter list. " +
"\nSo message 'hello %s %s' could be given the parameter list 'mr|duke' and the resulting message would be 'hello mr duke'." +
"\n------" +
"\nExample parameter list for input with two %s:" +
"\nmr|duke" +
"\nms|daisy" +
"\nmrs|robinson" +
"\n------" +
"\nIf you have given the number of messages when using parameter list, the number of messages to send will be ignored " +
"\nand messages will be sent for entire parameter list";
JOptionPane pane = new JOptionPane(message, JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(this, "Help!");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
protected void showErrorPane(String title, String msg) {
JOptionPane pane = new JOptionPane(msg, JOptionPane.ERROR_MESSAGE);
JDialog dialog = pane.createDialog("Application says: " + title);
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
}
| true | true | protected void validateInputFields() {
if (!jmsServerUrl.getText().matches("\\w{2,5}://\\[a-zA-Z0-9]*:\\d{2,6}")) {
showErrorPane("input validation error", "JMS Server URL is not a valid URL. " +
"\n\n should be: [protocol]://[host]:[port]" +
"\n example: tcp://localhost:61616");
}
if (StringUtils.isBlank(queueDestinationTextField.getText())) {
showErrorPane("input validation error", "You must supply a Queue destination");
}
if (!StringUtils.isNumeric(messagesTextField.getText())) {
showErrorPane("input validation error", "Number of messages must be a number");
}
if (StringUtils.isBlank(messageTextPane.getText())) {
showErrorPane("input validation error", "Message can not be blank");
}
parameters = numberOfParametersInText(messageTextPane.getText());
parameterValues = StringUtils.split(parameterListTextPane.getText(), "\n");
if (parameters > 0 && parameterValues.length == 0) {
showErrorPane("input validation error", "You have supplied a parameterized message but no parameters. " +
"\n\nPlease see the Help! dialog.");
}
if (parameters == 0 && parameterValues.length > 0) {
showErrorPane("input validation error", "You have supplied parameters to a message that has no placeholders." +
"\n\nPlease see the Help! dialog.");
}
if (parameters > 1) {
boolean parameterNumberOfFieldsMismatch = false;
for (String parameterValue : parameterValues) {
int numberOfFieldsInParameterValue = StringUtils.countMatches(parameterValue, "|");
if (numberOfFieldsInParameterValue != (parameters - 1)) {
parameterNumberOfFieldsMismatch = true;
}
}
if (parameterNumberOfFieldsMismatch) {
showErrorPane("input validation error", "Your parameter list contains at least one entry that does not " +
"satisfy the parameterized message." +
"\n\nPlease see the Help! dialog.");
}
}
}
| protected void validateInputFields() {
if (!jmsServerUrl.getText().matches("\\w{2,5}://.*:\\d{2,6}")) {
showErrorPane("input validation error", "JMS Server URL is not a valid URL. " +
"\n\n should be: [protocol]://[host]:[port]" +
"\n example: tcp://localhost:61616");
}
if (StringUtils.isBlank(queueDestinationTextField.getText())) {
showErrorPane("input validation error", "You must supply a Queue destination");
}
if (!StringUtils.isNumeric(messagesTextField.getText())) {
showErrorPane("input validation error", "Number of messages must be a number");
}
if (StringUtils.isBlank(messageTextPane.getText())) {
showErrorPane("input validation error", "Message can not be blank");
}
parameters = numberOfParametersInText(messageTextPane.getText());
parameterValues = StringUtils.split(parameterListTextPane.getText(), "\n");
if (parameters > 0 && parameterValues.length == 0) {
showErrorPane("input validation error", "You have supplied a parameterized message but no parameters. " +
"\n\nPlease see the Help! dialog.");
}
if (parameters == 0 && parameterValues.length > 0) {
showErrorPane("input validation error", "You have supplied parameters to a message that has no placeholders." +
"\n\nPlease see the Help! dialog.");
}
if (parameters > 1) {
boolean parameterNumberOfFieldsMismatch = false;
for (String parameterValue : parameterValues) {
int numberOfFieldsInParameterValue = StringUtils.countMatches(parameterValue, "|");
if (numberOfFieldsInParameterValue != (parameters - 1)) {
parameterNumberOfFieldsMismatch = true;
}
}
if (parameterNumberOfFieldsMismatch) {
showErrorPane("input validation error", "Your parameter list contains at least one entry that does not " +
"satisfy the parameterized message." +
"\n\nPlease see the Help! dialog.");
}
}
}
|
diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/endtoendtest/MenuItemsTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/endtoendtest/MenuItemsTest.java
index 634ff193..948cff50 100644
--- a/MyTracksTest/src/com/google/android/apps/mytracks/endtoendtest/MenuItemsTest.java
+++ b/MyTracksTest/src/com/google/android/apps/mytracks/endtoendtest/MenuItemsTest.java
@@ -1,161 +1,161 @@
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.endtoendtest;
import com.google.android.apps.mytracks.TrackListActivity;
import com.google.android.maps.mytracks.R;
import android.annotation.TargetApi;
import android.app.Instrumentation;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.view.View;
import java.util.ArrayList;
/**
* Tests some menu items of MyTracks.
*
* @author Youtao Liu
*/
public class MenuItemsTest extends ActivityInstrumentationTestCase2<TrackListActivity> {
private Instrumentation instrumentation;
private TrackListActivity activityMyTracks;
@TargetApi(8)
public MenuItemsTest() {
super(TrackListActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
instrumentation = getInstrumentation();
activityMyTracks = getActivity();
EndToEndTestUtils.setupForAllTest(instrumentation, activityMyTracks);
}
/**
* Tests following items in More menu.
* <ul>
* <li>Tests the aggregated statistics activity.</li>
* <li>Tests the Sensor state activity.</li>
* <li>Tests the help menu.</li>
* </ul>
*/
public void testSomeMenuItems() {
// Menu in TrackListActivity.
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_aggregated_statistics),
true);
EndToEndTestUtils.SOLO.waitForText(activityMyTracks.getString(R.string.stats_total_distance));
EndToEndTestUtils.SOLO.goBack();
instrumentation.waitForIdleSync();
EndToEndTestUtils.createTrackIfEmpty(1, false);
instrumentation.waitForIdleSync();
// Menu in TrackDetailActivity.
// When there is no sensor connected this menu will be hidden.
if (EndToEndTestUtils
.findMenuItem(activityMyTracks.getString(R.string.menu_sensor_state), true)) {
EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.sensor_state_last_sensor_time));
}
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_help), true);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.help_about), true, true);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
}
/**
* Tests search menu item.
*/
public void testSearch() {
EndToEndTestUtils.createSimpleTrack(1);
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_search), true);
EndToEndTestUtils.enterTextAvoidSoftKeyBoard(0, EndToEndTestUtils.trackName);
sendKeys(KeyEvent.KEYCODE_ENTER);
instrumentation.waitForIdleSync();
assertEquals(1, EndToEndTestUtils.SOLO.getCurrentListViews().size());
}
/**
* Tests the share menu item. This test to check whether crash will happen during the share.
*/
public void testShareActivity() {
// Try all share item.
for (int i = 0;; i++) {
View oneItemView = findShareItem(i);
if (oneItemView == null) {
break;
}
EndToEndTestUtils.SOLO.clickOnView(oneItemView);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), false,
true);
if(!GoogleUtils.checkAccountStatusDialog()) {
break;
}
// Waiting the send is finish.
while (EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.generic_progress_title), 1,
EndToEndTestUtils.SHORT_WAIT_TIME)) {}
- // Check whether data is correct on Google Map and the delete it.
+ // Check whether data is correct on Google Map and then delete it.
assertTrue(GoogleUtils.deleteMap(EndToEndTestUtils.trackName, activityMyTracks));
// Display the MyTracks activity for the share item may startup other
// applications.
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(activityMyTracks.getApplicationContext(), TrackListActivity.class);
activityMyTracks.getApplicationContext().startActivity(intent);
EndToEndTestUtils.sleep(EndToEndTestUtils.NORMAL_WAIT_TIME);
}
}
/**
* Gets the view to click the share item by item index.
* @param index of a share item
* @return null when no such item
*/
private View findShareItem(int index) {
EndToEndTestUtils.createTrackIfEmpty(0, false);
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_share), true);
ArrayList<View> cc = EndToEndTestUtils.SOLO.getViews();
int i = 0;
for (View view : cc) {
String name = view.getParent().getClass().getName();
// Each share item is in one Linear layout which is the child view of
if (name.indexOf("RecycleListView") > 0) {
if (index == i) {
return view;
}
i++;
}
}
return null;
}
@Override
protected void tearDown() throws Exception {
EndToEndTestUtils.SOLO.finishOpenedActivities();
super.tearDown();
}
}
| true | true | public void testShareActivity() {
// Try all share item.
for (int i = 0;; i++) {
View oneItemView = findShareItem(i);
if (oneItemView == null) {
break;
}
EndToEndTestUtils.SOLO.clickOnView(oneItemView);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), false,
true);
if(!GoogleUtils.checkAccountStatusDialog()) {
break;
}
// Waiting the send is finish.
while (EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.generic_progress_title), 1,
EndToEndTestUtils.SHORT_WAIT_TIME)) {}
// Check whether data is correct on Google Map and the delete it.
assertTrue(GoogleUtils.deleteMap(EndToEndTestUtils.trackName, activityMyTracks));
// Display the MyTracks activity for the share item may startup other
// applications.
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(activityMyTracks.getApplicationContext(), TrackListActivity.class);
activityMyTracks.getApplicationContext().startActivity(intent);
EndToEndTestUtils.sleep(EndToEndTestUtils.NORMAL_WAIT_TIME);
}
}
| public void testShareActivity() {
// Try all share item.
for (int i = 0;; i++) {
View oneItemView = findShareItem(i);
if (oneItemView == null) {
break;
}
EndToEndTestUtils.SOLO.clickOnView(oneItemView);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), false,
true);
if(!GoogleUtils.checkAccountStatusDialog()) {
break;
}
// Waiting the send is finish.
while (EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.generic_progress_title), 1,
EndToEndTestUtils.SHORT_WAIT_TIME)) {}
// Check whether data is correct on Google Map and then delete it.
assertTrue(GoogleUtils.deleteMap(EndToEndTestUtils.trackName, activityMyTracks));
// Display the MyTracks activity for the share item may startup other
// applications.
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(activityMyTracks.getApplicationContext(), TrackListActivity.class);
activityMyTracks.getApplicationContext().startActivity(intent);
EndToEndTestUtils.sleep(EndToEndTestUtils.NORMAL_WAIT_TIME);
}
}
|
diff --git a/vlcj/src/test/java/uk/co/caprica/vlcj/test/factory/FilterTest.java b/vlcj/src/test/java/uk/co/caprica/vlcj/test/factory/FilterTest.java
index fcc68249..33107cfd 100644
--- a/vlcj/src/test/java/uk/co/caprica/vlcj/test/factory/FilterTest.java
+++ b/vlcj/src/test/java/uk/co/caprica/vlcj/test/factory/FilterTest.java
@@ -1,72 +1,72 @@
/*
* This file is part of VLCJ.
*
* VLCJ is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VLCJ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VLCJ. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2009, 2010, 2011 Caprica Software Limited.
*/
package uk.co.caprica.vlcj.test.factory;
import java.util.List;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.ModuleDescription;
/**
* Simple test to dump out audio/video filters.
* <p>
* Requires libvlc 1.2.x.
*/
public class FilterTest {
private static final String FORMAT_PATTERN = "%3s %-24s %-24s %-80s %s\n";
public static void main(String[] args) throws Exception {
String[] libvlcArgs = new String[] {};
MediaPlayerFactory factory = new MediaPlayerFactory(libvlcArgs, LibVlc.INSTANCE);
System.out.println("Audio Filters:");
System.out.println();
System.out.printf(FORMAT_PATTERN , "#", "Name", "Short Name", "Long Name", "Help");
System.out.printf(FORMAT_PATTERN , "=", "====", "==========", "=========", "====");
List<ModuleDescription> audioFilters = factory.getAudioFilters();
for(int i = 0; i < audioFilters.size(); i++) {
dump(i, audioFilters.get(i));
}
System.out.println();
- System.out.println("VideoFilters:");
+ System.out.println("Video Filters:");
System.out.println();
System.out.printf(FORMAT_PATTERN , "#", "Name", "Short Name", "Long Name", "Help");
System.out.printf(FORMAT_PATTERN , "=", "====", "==========", "=========", "====");
List<ModuleDescription> videoFilters = factory.getVideoFilters();
for(int i = 0; i < videoFilters.size(); i++) {
dump(i, videoFilters.get(i));
}
}
private static void dump(int i, ModuleDescription moduleDescription) {
System.out.printf(FORMAT_PATTERN , String.valueOf(i+1), moduleDescription.name(), moduleDescription.shortName(), moduleDescription.longName(), formatHelp(moduleDescription.help()));
}
private static String formatHelp(String help) {
return help != null ? help.replaceAll("\\n", " ") : "";
}
}
| true | true | public static void main(String[] args) throws Exception {
String[] libvlcArgs = new String[] {};
MediaPlayerFactory factory = new MediaPlayerFactory(libvlcArgs, LibVlc.INSTANCE);
System.out.println("Audio Filters:");
System.out.println();
System.out.printf(FORMAT_PATTERN , "#", "Name", "Short Name", "Long Name", "Help");
System.out.printf(FORMAT_PATTERN , "=", "====", "==========", "=========", "====");
List<ModuleDescription> audioFilters = factory.getAudioFilters();
for(int i = 0; i < audioFilters.size(); i++) {
dump(i, audioFilters.get(i));
}
System.out.println();
System.out.println("VideoFilters:");
System.out.println();
System.out.printf(FORMAT_PATTERN , "#", "Name", "Short Name", "Long Name", "Help");
System.out.printf(FORMAT_PATTERN , "=", "====", "==========", "=========", "====");
List<ModuleDescription> videoFilters = factory.getVideoFilters();
for(int i = 0; i < videoFilters.size(); i++) {
dump(i, videoFilters.get(i));
}
}
| public static void main(String[] args) throws Exception {
String[] libvlcArgs = new String[] {};
MediaPlayerFactory factory = new MediaPlayerFactory(libvlcArgs, LibVlc.INSTANCE);
System.out.println("Audio Filters:");
System.out.println();
System.out.printf(FORMAT_PATTERN , "#", "Name", "Short Name", "Long Name", "Help");
System.out.printf(FORMAT_PATTERN , "=", "====", "==========", "=========", "====");
List<ModuleDescription> audioFilters = factory.getAudioFilters();
for(int i = 0; i < audioFilters.size(); i++) {
dump(i, audioFilters.get(i));
}
System.out.println();
System.out.println("Video Filters:");
System.out.println();
System.out.printf(FORMAT_PATTERN , "#", "Name", "Short Name", "Long Name", "Help");
System.out.printf(FORMAT_PATTERN , "=", "====", "==========", "=========", "====");
List<ModuleDescription> videoFilters = factory.getVideoFilters();
for(int i = 0; i < videoFilters.size(); i++) {
dump(i, videoFilters.get(i));
}
}
|
diff --git a/Android/OpenMenu/src/com/net/rmopenmenu/MainActivity.java b/Android/OpenMenu/src/com/net/rmopenmenu/MainActivity.java
index bd9757a..3a018e1 100644
--- a/Android/OpenMenu/src/com/net/rmopenmenu/MainActivity.java
+++ b/Android/OpenMenu/src/com/net/rmopenmenu/MainActivity.java
@@ -1,154 +1,155 @@
/*
* Copyright 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.net.rmopenmenu;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TabHost;
import android.widget.Toast;
import com.net.rmopenmenu.SearchActivity.TabsAdapter;
public class MainActivity extends ActionBarActivity {
TabHost mTabHost;
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
LocationManager locationManager;
LocationListener locationListener;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.fragment_tabs_pager);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager)findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Bundle b1 = new Bundle();
b1.putBoolean("menu", true);
Bundle b2 = new Bundle();
b2.putBoolean("menu", false);
mTabsAdapter.addTab(mTabHost.newTabSpec("menu").setIndicator("Menu"),
MenuFragment.class, b1);
mTabsAdapter.addTab(mTabHost.newTabSpec("restaurant").setIndicator("Restaurant"),
MenuFragment.class, b2);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
// Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("lat", (int)(location.getLatitude()*1000000));
editor.putInt("lon", (int)(location.getLongitude()*1000000));
editor.commit();
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
+ locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
@Override
public void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
// Calling super after populating the menu is necessary here to ensure that the
// action bar helpers have a chance to handle this event.
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onSearchRequested() {
Bundle appData = new Bundle();
String tag = mTabHost.getCurrentTabTag();
boolean menu = tag.equals("menu")? true : false;
appData.putBoolean("menu", menu);
startSearch(null, false, appData, false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
break;
case R.id.menu_refresh:
getActionBarHelper().setRefreshActionItemState(true);
getWindow().getDecorView().postDelayed(
new Runnable() {
@Override
public void run() {
getActionBarHelper().setRefreshActionItemState(false);
}
}, 3000);
break;
case R.id.menu_search:
onSearchRequested();
break;
case R.id.menu_share:
Toast.makeText(this, "Tapped share", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.fragment_tabs_pager);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager)findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Bundle b1 = new Bundle();
b1.putBoolean("menu", true);
Bundle b2 = new Bundle();
b2.putBoolean("menu", false);
mTabsAdapter.addTab(mTabHost.newTabSpec("menu").setIndicator("Menu"),
MenuFragment.class, b1);
mTabsAdapter.addTab(mTabHost.newTabSpec("restaurant").setIndicator("Restaurant"),
MenuFragment.class, b2);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
// Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("lat", (int)(location.getLatitude()*1000000));
editor.putInt("lon", (int)(location.getLongitude()*1000000));
editor.commit();
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.fragment_tabs_pager);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager)findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Bundle b1 = new Bundle();
b1.putBoolean("menu", true);
Bundle b2 = new Bundle();
b2.putBoolean("menu", false);
mTabsAdapter.addTab(mTabHost.newTabSpec("menu").setIndicator("Menu"),
MenuFragment.class, b1);
mTabsAdapter.addTab(mTabHost.newTabSpec("restaurant").setIndicator("Restaurant"),
MenuFragment.class, b2);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
// Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("lat", (int)(location.getLatitude()*1000000));
editor.putInt("lon", (int)(location.getLongitude()*1000000));
editor.commit();
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
|
diff --git a/src/main/java/me/tehbeard/BeardAch/achievement/Achievement.java b/src/main/java/me/tehbeard/BeardAch/achievement/Achievement.java
index 2670733..e039b0e 100644
--- a/src/main/java/me/tehbeard/BeardAch/achievement/Achievement.java
+++ b/src/main/java/me/tehbeard/BeardAch/achievement/Achievement.java
@@ -1,109 +1,111 @@
package me.tehbeard.BeardAch.achievement;
import java.util.HashSet;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import me.tehbeard.BeardAch.BeardAch;
import me.tehbeard.BeardAch.achievement.rewards.IReward;
import me.tehbeard.BeardAch.achievement.triggers.ITrigger;
/**
* Represents an achievement.
* @author James
*
*/
public class Achievement {
private String slug;
private String name;
private String descrip;
private int id = 0;
private static int nextId = 1;
private HashSet<ITrigger> triggers = new HashSet<ITrigger>();
private HashSet<IReward> rewards = new HashSet<IReward>();
boolean broadcast;
public Achievement(String slug,String name,String descrip,boolean broadcast) {
this.slug = slug;
this.name = name;
this.descrip = descrip;
this.broadcast = broadcast;
this.id = nextId;
nextId ++;
}
public static void resetId(){
nextId = 1;
}
public int getId() {
return id;
}
public String getSlug() {
return slug;
}
public String getName(){
return name;
}
public String getDescrip(){
return descrip;
}
public void addTrigger(ITrigger trigger){
if(trigger==null){return;}
triggers.add(trigger);
}
public void addReward(IReward reward){
if(reward==null){return;}
rewards.add(reward);
}
public boolean checkAchievement(Player player){
if(player==null){
return false;
}
for(AchievementPlayerLink link : BeardAch.self.getAchievementManager().playerHasCache.get(player.getName())){
if(link.getSlug().equals(slug)){
return false;
}
}
for(ITrigger trigger:triggers){
if(!trigger.checkAchievement(player)){
return false;
}
}
- for(IReward reward:rewards){
- reward.giveReward(player);
+ if(!player.hasPermission("ach.exempt.*") && !player.hasPermission("ach.exempt." + slug)){
+ for(IReward reward:rewards){
+ reward.giveReward(player);
+ }
}
if(broadcast || (BeardAch.self.getConfig().getBoolean("ach.msg.send.broadcast", false) && !BeardAch.self.getConfig().getBoolean("ach.msg.send.person", true))){
Bukkit.broadcastMessage(BeardAch.colorise(
BeardAch.self.getConfig().getString("ach.msg.broadcast",
(ChatColor.AQUA + "<PLAYER> " + ChatColor.WHITE + "Unlocked: " + ChatColor.GOLD + "<ACH>")).replace("<ACH>", name ).replace("<PLAYER>",player.getName()
)
)
);
}
if(BeardAch.self.getConfig().getBoolean("ach.msg.send.person", true)){
player.sendMessage(BeardAch.colorise(BeardAch.self.getConfig().getString("ach.msg.person", "Achievement Get! " + ChatColor.GOLD + "<ACH>").replace("<ACH>", name).replace("<PLAYER>",player.getName())));
player.sendMessage(ChatColor.BLUE + descrip);
}
return true;
}
public HashSet<ITrigger> getTrigs(){
return triggers;
}
}
| true | true | public boolean checkAchievement(Player player){
if(player==null){
return false;
}
for(AchievementPlayerLink link : BeardAch.self.getAchievementManager().playerHasCache.get(player.getName())){
if(link.getSlug().equals(slug)){
return false;
}
}
for(ITrigger trigger:triggers){
if(!trigger.checkAchievement(player)){
return false;
}
}
for(IReward reward:rewards){
reward.giveReward(player);
}
if(broadcast || (BeardAch.self.getConfig().getBoolean("ach.msg.send.broadcast", false) && !BeardAch.self.getConfig().getBoolean("ach.msg.send.person", true))){
Bukkit.broadcastMessage(BeardAch.colorise(
BeardAch.self.getConfig().getString("ach.msg.broadcast",
(ChatColor.AQUA + "<PLAYER> " + ChatColor.WHITE + "Unlocked: " + ChatColor.GOLD + "<ACH>")).replace("<ACH>", name ).replace("<PLAYER>",player.getName()
)
)
);
}
if(BeardAch.self.getConfig().getBoolean("ach.msg.send.person", true)){
player.sendMessage(BeardAch.colorise(BeardAch.self.getConfig().getString("ach.msg.person", "Achievement Get! " + ChatColor.GOLD + "<ACH>").replace("<ACH>", name).replace("<PLAYER>",player.getName())));
player.sendMessage(ChatColor.BLUE + descrip);
}
return true;
}
| public boolean checkAchievement(Player player){
if(player==null){
return false;
}
for(AchievementPlayerLink link : BeardAch.self.getAchievementManager().playerHasCache.get(player.getName())){
if(link.getSlug().equals(slug)){
return false;
}
}
for(ITrigger trigger:triggers){
if(!trigger.checkAchievement(player)){
return false;
}
}
if(!player.hasPermission("ach.exempt.*") && !player.hasPermission("ach.exempt." + slug)){
for(IReward reward:rewards){
reward.giveReward(player);
}
}
if(broadcast || (BeardAch.self.getConfig().getBoolean("ach.msg.send.broadcast", false) && !BeardAch.self.getConfig().getBoolean("ach.msg.send.person", true))){
Bukkit.broadcastMessage(BeardAch.colorise(
BeardAch.self.getConfig().getString("ach.msg.broadcast",
(ChatColor.AQUA + "<PLAYER> " + ChatColor.WHITE + "Unlocked: " + ChatColor.GOLD + "<ACH>")).replace("<ACH>", name ).replace("<PLAYER>",player.getName()
)
)
);
}
if(BeardAch.self.getConfig().getBoolean("ach.msg.send.person", true)){
player.sendMessage(BeardAch.colorise(BeardAch.self.getConfig().getString("ach.msg.person", "Achievement Get! " + ChatColor.GOLD + "<ACH>").replace("<ACH>", name).replace("<PLAYER>",player.getName())));
player.sendMessage(ChatColor.BLUE + descrip);
}
return true;
}
|
diff --git a/src/main/java/org/basex/gui/view/info/InfoView.java b/src/main/java/org/basex/gui/view/info/InfoView.java
index 2eb9fcd2d..0ab7db5a1 100644
--- a/src/main/java/org/basex/gui/view/info/InfoView.java
+++ b/src/main/java/org/basex/gui/view/info/InfoView.java
@@ -1,294 +1,294 @@
package org.basex.gui.view.info;
import static org.basex.core.Text.*;
import static org.basex.gui.GUIConstants.*;
import java.awt.*;
import java.awt.event.*;
import org.basex.core.*;
import org.basex.core.cmd.*;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.*;
import org.basex.gui.layout.*;
import org.basex.gui.view.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* This view displays query information.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public final class InfoView extends View {
/** Old text. */
private final TokenBuilder text = new TokenBuilder();
/** Header label. */
private final BaseXLabel header;
/** Timer label. */
private final BaseXLabel timer;
/** North label. */
private final BaseXBack north;
/** Text Area. */
private final BaseXEditor area;
/** Query statistics. */
private IntList stat = new IntList();
/** Query statistics strings. */
private StringList strings;
/** Focused bar. */
private int focus = -1;
/** Panel Width. */
private int w;
/** Panel Height. */
private int h;
/** Bar widths. */
private int bw;
/** Bar size. */
private int bs;
/**
* Default constructor.
* @param man view manager
*/
public InfoView(final ViewNotifier man) {
super(INFOVIEW, man);
border(6, 6, 6, 6).layout(new BorderLayout());
north = new BaseXBack(Fill.NONE).layout(new BorderLayout());
header = new BaseXLabel(QUERY_INFO);
north.add(header, BorderLayout.NORTH);
north.add(header, BorderLayout.NORTH);
timer = new BaseXLabel(" ", true, false);
north.add(timer, BorderLayout.SOUTH);
add(north, BorderLayout.NORTH);
area = new BaseXEditor(false, gui);
add(area, BorderLayout.CENTER);
refreshLayout();
}
@Override
public void refreshInit() { }
@Override
public void refreshFocus() { }
@Override
public void refreshMark() { }
@Override
public void refreshContext(final boolean more, final boolean quick) { }
@Override
public void refreshUpdate() { }
@Override
public void refreshLayout() {
header.setFont(lfont);
timer.setFont(font);
area.setFont(font);
}
@Override
public boolean visible() {
return gui.gprop.is(GUIProp.SHOWINFO);
}
@Override
public void visible(final boolean v) {
gui.gprop.set(GUIProp.SHOWINFO, v);
}
@Override
protected boolean db() {
return false;
}
/**
* Displays the specified information.
* @param info info string
* @param cmd command
* @param time time required
* @param ok flag indicating if command execution was successful
*/
public void setInfo(final String info, final Command cmd, final String time,
final boolean ok) {
final StringList eval = new StringList();
final StringList comp = new StringList();
final StringList plan = new StringList();
final StringList sl = new StringList();
final StringList stats = new StringList();
final IntList il = new IntList();
String err = "";
String qu = "";
String res = "";
final String[] split = info.split(NL);
for(int i = 0; i < split.length; ++i) {
final String line = split[i];
final int s = line.indexOf(':');
if(line.startsWith(PARSING_CC) || line.startsWith(COMPILING_CC) ||
line.startsWith(EVALUATING_CC) || line.startsWith(PRINTING_CC) ||
line.startsWith(TOTAL_TIME_CC)) {
final int t = line.indexOf(" ms");
sl.add(line.substring(0, s).trim());
il.add((int) (Double.parseDouble(line.substring(s + 1, t)) * 100));
} else if(line.startsWith(QUERY_C)) {
qu = line.substring(s + 1).trim();
} else if(line.startsWith(QUERY_PLAN_C)) {
while(++i < split.length && !split[i].isEmpty()) plan.add(split[i]);
--i;
} else if(line.startsWith(COMPILING_C)) {
while(++i < split.length && !split[i].isEmpty()) comp.add(split[i]);
} else if(line.startsWith(RESULT_C)) {
res = line.substring(s + 1).trim();
} else if(line.startsWith(EVALUATING_C)) {
while(++i < split.length && split[i].startsWith(QUERYSEP)) eval.add(split[i]);
--i;
} else if(!ok) {
err += line + NL;
} else if(line.startsWith(HITS_X_CC) || line.startsWith(UPDATED_CC) ||
line.startsWith(PRINTED_CC)) {
stats.add("- " + line);
}
}
stat = il;
strings = sl;
String total = time;
- if(ok && cmd instanceof XQuery) {
+ if(ok && cmd instanceof XQuery && !il.isEmpty()) {
text.reset();
add(EVALUATING_C, eval);
add(QUERY_C + ' ', qu);
add(COMPILING_C, comp);
if(!comp.isEmpty()) add(RESULT_C, res);
add(TIMING_C, sl);
add(RESULT_C, stats);
add(QUERY_PLAN_C, plan);
final int runs = Math.max(1, gui.context.prop.num(Prop.RUNS));
total = Performance.getTime(il.get(il.size() - 1) * 10000L * runs, runs);
} else {
if(ok) {
add(cmd);
text.add(info).nline();
} else {
add(ERROR_C, err);
add(cmd);
add(COMPILING_C, comp);
add(QUERY_PLAN_C, plan);
}
}
area.setText(text.finish());
if(total != null) timer.setText(TOTAL_TIME_CC + total);
repaint();
}
/**
* Adds the command representation.
* @param cmd command
*/
private void add(final Command cmd) {
if(cmd instanceof XQuery) {
add(QUERY_C + ' ', cmd.args[0].trim());
} else if(cmd != null) {
text.bold().add(COMMAND + COLS).norm().addExt(cmd).nline();
}
}
/**
* Resets the info string without repainting the view.
*/
public void reset() {
text.reset();
}
/**
* Adds the specified strings.
* @param head string header
* @param list list reference
*/
private void add(final String head, final StringList list) {
final int runs = Math.max(1, gui.context.prop.num(Prop.RUNS));
if(list.isEmpty()) return;
text.bold().add(head).norm().nline();
final int is = list.size();
for(int i = 0; i < is; ++i) {
String line = list.get(i);
if(list == strings) line = ' ' + QUERYSEP + line + ": " +
Performance.getTime(stat.get(i) * 10000L * runs, runs);
text.add(line).nline();
}
text.hline();
}
/**
* Adds a string.
* @param head string header
* @param txt text
*/
private void add(final String head, final String txt) {
if(!txt.isEmpty()) text.bold().add(head).norm().add(txt).nline().hline();
}
@Override
public void mouseMoved(final MouseEvent e) {
final int l = stat.size();
if(l == 0) return;
focus = -1;
if(e.getY() < h) {
for(int i = 0; i < l; ++i) {
final int bx = w - bw + bs * i;
if(e.getX() >= bx && e.getX() < bx + bs) focus = i;
}
}
final int runs = Math.max(1, gui.context.prop.num(Prop.RUNS));
final int f = focus == -1 ? l - 1 : focus;
timer.setText(strings.get(f) + COLS +
Performance.getTime(stat.get(f) * 10000L * runs, runs));
repaint();
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
final int l = stat.size();
if(l == 0) return;
h = north.getHeight();
w = getWidth() - 8;
bw = gui.gprop.num(GUIProp.FONTSIZE) * 2 + w / 10;
bs = bw / (l - 1);
// find maximum value
int m = 0;
for(int i = 0; i < l - 1; ++i) m = Math.max(m, stat.get(i));
// draw focused bar
final int by = 10;
final int bh = h - by;
for(int i = 0; i < l - 1; ++i) {
if(i != focus) continue;
final int bx = w - bw + bs * i;
g.setColor(color3);
g.fillRect(bx, by, bs + 1, bh);
}
// draw all bars
for(int i = 0; i < l - 1; ++i) {
final int bx = w - bw + bs * i;
g.setColor(color((i == focus ? 3 : 2) + i * 2));
final int p = Math.max(1, stat.get(i) * bh / m);
g.fillRect(bx, by + bh - p, bs, p);
g.setColor(color(8));
g.drawRect(bx, by + bh - p, bs, p - 1);
}
}
}
| true | true | public void setInfo(final String info, final Command cmd, final String time,
final boolean ok) {
final StringList eval = new StringList();
final StringList comp = new StringList();
final StringList plan = new StringList();
final StringList sl = new StringList();
final StringList stats = new StringList();
final IntList il = new IntList();
String err = "";
String qu = "";
String res = "";
final String[] split = info.split(NL);
for(int i = 0; i < split.length; ++i) {
final String line = split[i];
final int s = line.indexOf(':');
if(line.startsWith(PARSING_CC) || line.startsWith(COMPILING_CC) ||
line.startsWith(EVALUATING_CC) || line.startsWith(PRINTING_CC) ||
line.startsWith(TOTAL_TIME_CC)) {
final int t = line.indexOf(" ms");
sl.add(line.substring(0, s).trim());
il.add((int) (Double.parseDouble(line.substring(s + 1, t)) * 100));
} else if(line.startsWith(QUERY_C)) {
qu = line.substring(s + 1).trim();
} else if(line.startsWith(QUERY_PLAN_C)) {
while(++i < split.length && !split[i].isEmpty()) plan.add(split[i]);
--i;
} else if(line.startsWith(COMPILING_C)) {
while(++i < split.length && !split[i].isEmpty()) comp.add(split[i]);
} else if(line.startsWith(RESULT_C)) {
res = line.substring(s + 1).trim();
} else if(line.startsWith(EVALUATING_C)) {
while(++i < split.length && split[i].startsWith(QUERYSEP)) eval.add(split[i]);
--i;
} else if(!ok) {
err += line + NL;
} else if(line.startsWith(HITS_X_CC) || line.startsWith(UPDATED_CC) ||
line.startsWith(PRINTED_CC)) {
stats.add("- " + line);
}
}
stat = il;
strings = sl;
String total = time;
if(ok && cmd instanceof XQuery) {
text.reset();
add(EVALUATING_C, eval);
add(QUERY_C + ' ', qu);
add(COMPILING_C, comp);
if(!comp.isEmpty()) add(RESULT_C, res);
add(TIMING_C, sl);
add(RESULT_C, stats);
add(QUERY_PLAN_C, plan);
final int runs = Math.max(1, gui.context.prop.num(Prop.RUNS));
total = Performance.getTime(il.get(il.size() - 1) * 10000L * runs, runs);
} else {
if(ok) {
add(cmd);
text.add(info).nline();
} else {
add(ERROR_C, err);
add(cmd);
add(COMPILING_C, comp);
add(QUERY_PLAN_C, plan);
}
}
area.setText(text.finish());
if(total != null) timer.setText(TOTAL_TIME_CC + total);
repaint();
}
| public void setInfo(final String info, final Command cmd, final String time,
final boolean ok) {
final StringList eval = new StringList();
final StringList comp = new StringList();
final StringList plan = new StringList();
final StringList sl = new StringList();
final StringList stats = new StringList();
final IntList il = new IntList();
String err = "";
String qu = "";
String res = "";
final String[] split = info.split(NL);
for(int i = 0; i < split.length; ++i) {
final String line = split[i];
final int s = line.indexOf(':');
if(line.startsWith(PARSING_CC) || line.startsWith(COMPILING_CC) ||
line.startsWith(EVALUATING_CC) || line.startsWith(PRINTING_CC) ||
line.startsWith(TOTAL_TIME_CC)) {
final int t = line.indexOf(" ms");
sl.add(line.substring(0, s).trim());
il.add((int) (Double.parseDouble(line.substring(s + 1, t)) * 100));
} else if(line.startsWith(QUERY_C)) {
qu = line.substring(s + 1).trim();
} else if(line.startsWith(QUERY_PLAN_C)) {
while(++i < split.length && !split[i].isEmpty()) plan.add(split[i]);
--i;
} else if(line.startsWith(COMPILING_C)) {
while(++i < split.length && !split[i].isEmpty()) comp.add(split[i]);
} else if(line.startsWith(RESULT_C)) {
res = line.substring(s + 1).trim();
} else if(line.startsWith(EVALUATING_C)) {
while(++i < split.length && split[i].startsWith(QUERYSEP)) eval.add(split[i]);
--i;
} else if(!ok) {
err += line + NL;
} else if(line.startsWith(HITS_X_CC) || line.startsWith(UPDATED_CC) ||
line.startsWith(PRINTED_CC)) {
stats.add("- " + line);
}
}
stat = il;
strings = sl;
String total = time;
if(ok && cmd instanceof XQuery && !il.isEmpty()) {
text.reset();
add(EVALUATING_C, eval);
add(QUERY_C + ' ', qu);
add(COMPILING_C, comp);
if(!comp.isEmpty()) add(RESULT_C, res);
add(TIMING_C, sl);
add(RESULT_C, stats);
add(QUERY_PLAN_C, plan);
final int runs = Math.max(1, gui.context.prop.num(Prop.RUNS));
total = Performance.getTime(il.get(il.size() - 1) * 10000L * runs, runs);
} else {
if(ok) {
add(cmd);
text.add(info).nline();
} else {
add(ERROR_C, err);
add(cmd);
add(COMPILING_C, comp);
add(QUERY_PLAN_C, plan);
}
}
area.setText(text.finish());
if(total != null) timer.setText(TOTAL_TIME_CC + total);
repaint();
}
|
diff --git a/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/states/ProductionRecordStateService.java b/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/states/ProductionRecordStateService.java
index eb9962c380..44e9d00341 100644
--- a/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/states/ProductionRecordStateService.java
+++ b/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/states/ProductionRecordStateService.java
@@ -1,60 +1,57 @@
package com.qcadoo.mes.productionCounting.internal.states;
import java.util.Arrays;
import org.springframework.stereotype.Service;
import com.qcadoo.model.api.Entity;
import com.qcadoo.view.api.ComponentState;
import com.qcadoo.view.api.ViewDefinitionState;
import com.qcadoo.view.api.components.FieldComponent;
import com.qcadoo.view.api.components.FormComponent;
import com.qcadoo.view.api.components.GridComponent;
@Service
public class ProductionRecordStateService {
public void changeRecordStateToAccepted(final ViewDefinitionState view, final ComponentState state, final String[] args) {
changeRecordState(view, ProductionCountingStates.ACCEPTED.getStringValue());
state.performEvent(view, "save", new String[0]);
}
public void changeRecordStateToDeclined(final ViewDefinitionState view, final ComponentState state, final String[] args) {
changeRecordState(view, ProductionCountingStates.DECLINED.getStringValue());
state.performEvent(view, "save", new String[0]);
}
private void changeRecordState(final ViewDefinitionState view, final String state) {
FormComponent form = (FormComponent) view.getComponentByReference("form");
Entity productionCounting = form.getEntity();
productionCounting.setField("state", state);
FieldComponent stateField = (FieldComponent) view.getComponentByReference("state");
stateField.setFieldValue(state);
}
public void disabledFieldWhenStateNotDraft(final ViewDefinitionState view) {
- if (!(view instanceof ViewDefinitionState)) {
- return;
- }
FormComponent form = (FormComponent) view.getComponentByReference("form");
if (form.getEntity() == null) {
return;
}
Entity productionRecord = form.getEntity();
String states = productionRecord.getStringField("state");
if (!states.equals(ProductionCountingStates.DRAFT.getStringValue())) {
for (String reference : Arrays.asList("lastRecord", "number", "order", "orderOperationComponent", "shift",
"machineTime", "laborTime")) {
FieldComponent field = (FieldComponent) view.getComponentByReference(reference);
field.setEnabled(false);
field.requestComponentUpdateState();
}
GridComponent gridProductInComponent = (GridComponent) view
.getComponentByReference("recordOperationProductInComponent");
gridProductInComponent.setEditable(false);
GridComponent gridProductOutComponent = (GridComponent) view
.getComponentByReference("recordOperationProductOutComponent");
gridProductOutComponent.setEditable(false);
}
}
}
| true | true | public void disabledFieldWhenStateNotDraft(final ViewDefinitionState view) {
if (!(view instanceof ViewDefinitionState)) {
return;
}
FormComponent form = (FormComponent) view.getComponentByReference("form");
if (form.getEntity() == null) {
return;
}
Entity productionRecord = form.getEntity();
String states = productionRecord.getStringField("state");
if (!states.equals(ProductionCountingStates.DRAFT.getStringValue())) {
for (String reference : Arrays.asList("lastRecord", "number", "order", "orderOperationComponent", "shift",
"machineTime", "laborTime")) {
FieldComponent field = (FieldComponent) view.getComponentByReference(reference);
field.setEnabled(false);
field.requestComponentUpdateState();
}
GridComponent gridProductInComponent = (GridComponent) view
.getComponentByReference("recordOperationProductInComponent");
gridProductInComponent.setEditable(false);
GridComponent gridProductOutComponent = (GridComponent) view
.getComponentByReference("recordOperationProductOutComponent");
gridProductOutComponent.setEditable(false);
}
}
| public void disabledFieldWhenStateNotDraft(final ViewDefinitionState view) {
FormComponent form = (FormComponent) view.getComponentByReference("form");
if (form.getEntity() == null) {
return;
}
Entity productionRecord = form.getEntity();
String states = productionRecord.getStringField("state");
if (!states.equals(ProductionCountingStates.DRAFT.getStringValue())) {
for (String reference : Arrays.asList("lastRecord", "number", "order", "orderOperationComponent", "shift",
"machineTime", "laborTime")) {
FieldComponent field = (FieldComponent) view.getComponentByReference(reference);
field.setEnabled(false);
field.requestComponentUpdateState();
}
GridComponent gridProductInComponent = (GridComponent) view
.getComponentByReference("recordOperationProductInComponent");
gridProductInComponent.setEditable(false);
GridComponent gridProductOutComponent = (GridComponent) view
.getComponentByReference("recordOperationProductOutComponent");
gridProductOutComponent.setEditable(false);
}
}
|
diff --git a/src/main/java/org/jboss/netty/channel/iostream/IOStreamChannelSink.java b/src/main/java/org/jboss/netty/channel/iostream/IOStreamChannelSink.java
index 7af4dfb..111376b 100644
--- a/src/main/java/org/jboss/netty/channel/iostream/IOStreamChannelSink.java
+++ b/src/main/java/org/jboss/netty/channel/iostream/IOStreamChannelSink.java
@@ -1,176 +1,177 @@
/*
* Copyright 2011 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.jboss.netty.channel.iostream;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.util.concurrent.ExecutorService;
import static org.jboss.netty.channel.Channels.*;
/**
* A {@link org.jboss.netty.channel.ChannelSink} implementation which reads from an {@link java.io.InputStream} and
* writes to an {@link java.io.OutputStream}.
*
* @author Daniel Bimschas
* @author Dennis Pfisterer
*/
public class IOStreamChannelSink extends AbstractChannelSink {
private static class ReadRunnable implements Runnable {
private final IOStreamChannelSink channelSink;
public ReadRunnable(final IOStreamChannelSink channelSink) {
this.channelSink = channelSink;
}
@Override
public void run() {
PushbackInputStream in = channelSink.inputStream;
while (channelSink.channel.isOpen()) {
byte[] buf;
int readBytes;
try {
int bytesToRead = in.available();
if (bytesToRead > 0) {
buf = new byte[bytesToRead];
readBytes = in.read(buf);
} else {
// peek into the stream if it was closed (value=-1)
int b = in.read();
if (b < 0) {
break;
}
// push back the byte which was read too much
in.unread(b);
continue;
}
} catch (Throwable t) {
if (!channelSink.channel.getCloseFuture().isDone()) {
fireExceptionCaught(channelSink.channel, t);
}
break;
}
fireMessageReceived(channelSink.channel, ChannelBuffers.wrappedBuffer(buf, 0, readBytes));
}
// Clean up.
close(channelSink.channel);
}
}
private final ExecutorService executorService;
private IOStreamChannel channel;
public IOStreamChannelSink(final ExecutorService executorService) {
this.executorService = executorService;
}
public boolean isConnected() {
return inputStream != null && outputStream != null;
}
public IOStreamAddress getRemoteAddress() {
return remoteAddress;
}
public boolean isBound() {
return false;
}
public ChannelConfig getConfig() {
return config;
}
public void setChannel(final IOStreamChannel channel) {
this.channel = channel;
}
private IOStreamAddress remoteAddress;
private OutputStream outputStream;
private PushbackInputStream inputStream;
private ChannelConfig config = new DefaultChannelConfig();
@Override
public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e) throws Exception {
final ChannelFuture future = e.getFuture();
if (e instanceof ChannelStateEvent) {
final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
final ChannelState state = stateEvent.getState();
final Object value = stateEvent.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
outputStream = null;
inputStream = null;
channel.getCloseFuture().setSuccess();
}
break;
case BOUND:
throw new UnsupportedOperationException();
case CONNECTED:
if (value != null) {
remoteAddress = (IOStreamAddress) value;
outputStream = remoteAddress.getOutputStream();
inputStream = new PushbackInputStream(remoteAddress.getInputStream());
executorService.execute(new ReadRunnable(this));
future.setSuccess();
}
break;
case INTEREST_OPS:
// TODO implement
throw new UnsupportedOperationException();
}
} else if (e instanceof MessageEvent) {
final MessageEvent event = (MessageEvent) e;
if (event.getMessage() instanceof ChannelBuffer) {
final ChannelBuffer buffer = (ChannelBuffer) event.getMessage();
buffer.readBytes(outputStream, buffer.readableBytes());
+ e.getFuture().setSuccess();
} else {
throw new IllegalArgumentException(
"Only ChannelBuffer objects are supported to be written onto the IOStreamChannelSink! "
+ "Please check if the encoder pipeline is configured correctly."
);
}
}
}
}
| true | true | public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e) throws Exception {
final ChannelFuture future = e.getFuture();
if (e instanceof ChannelStateEvent) {
final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
final ChannelState state = stateEvent.getState();
final Object value = stateEvent.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
outputStream = null;
inputStream = null;
channel.getCloseFuture().setSuccess();
}
break;
case BOUND:
throw new UnsupportedOperationException();
case CONNECTED:
if (value != null) {
remoteAddress = (IOStreamAddress) value;
outputStream = remoteAddress.getOutputStream();
inputStream = new PushbackInputStream(remoteAddress.getInputStream());
executorService.execute(new ReadRunnable(this));
future.setSuccess();
}
break;
case INTEREST_OPS:
// TODO implement
throw new UnsupportedOperationException();
}
} else if (e instanceof MessageEvent) {
final MessageEvent event = (MessageEvent) e;
if (event.getMessage() instanceof ChannelBuffer) {
final ChannelBuffer buffer = (ChannelBuffer) event.getMessage();
buffer.readBytes(outputStream, buffer.readableBytes());
} else {
throw new IllegalArgumentException(
"Only ChannelBuffer objects are supported to be written onto the IOStreamChannelSink! "
+ "Please check if the encoder pipeline is configured correctly."
);
}
}
}
| public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e) throws Exception {
final ChannelFuture future = e.getFuture();
if (e instanceof ChannelStateEvent) {
final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
final ChannelState state = stateEvent.getState();
final Object value = stateEvent.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
outputStream = null;
inputStream = null;
channel.getCloseFuture().setSuccess();
}
break;
case BOUND:
throw new UnsupportedOperationException();
case CONNECTED:
if (value != null) {
remoteAddress = (IOStreamAddress) value;
outputStream = remoteAddress.getOutputStream();
inputStream = new PushbackInputStream(remoteAddress.getInputStream());
executorService.execute(new ReadRunnable(this));
future.setSuccess();
}
break;
case INTEREST_OPS:
// TODO implement
throw new UnsupportedOperationException();
}
} else if (e instanceof MessageEvent) {
final MessageEvent event = (MessageEvent) e;
if (event.getMessage() instanceof ChannelBuffer) {
final ChannelBuffer buffer = (ChannelBuffer) event.getMessage();
buffer.readBytes(outputStream, buffer.readableBytes());
e.getFuture().setSuccess();
} else {
throw new IllegalArgumentException(
"Only ChannelBuffer objects are supported to be written onto the IOStreamChannelSink! "
+ "Please check if the encoder pipeline is configured correctly."
);
}
}
}
|
diff --git a/src/com/tactfactory/harmony/utils/LibraryUtils.java b/src/com/tactfactory/harmony/utils/LibraryUtils.java
index 9aa5fb1b..ddee73a1 100644
--- a/src/com/tactfactory/harmony/utils/LibraryUtils.java
+++ b/src/com/tactfactory/harmony/utils/LibraryUtils.java
@@ -1,43 +1,42 @@
/**
* This file is part of the Harmony package.
*
* (c) Mickael Gaillard <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.tactfactory.harmony.utils;
import java.io.File;
import com.tactfactory.harmony.Harmony;
import com.tactfactory.harmony.plateforme.BaseAdapter;
/**
* Utility class for libraries.
*/
public abstract class LibraryUtils {
/**
* Update TestLibs.
* @param adapter The adapter.
* @param libName The library name.
*/
public static void addLibraryToTestProject(
final BaseAdapter adapter,
final String libName) {
final File dest = new File(String.format("%s/%s",
adapter.getTestLibsPath(),
libName));
if (!dest.exists()) {
+ final File src = Harmony.getLibrary(libName);
TactFileUtils.copyfile(
- new File(String.format("%s/%s",
- Harmony.getLibsPath(),
- libName)),
+ src,
dest);
}
}
}
| false | true | public static void addLibraryToTestProject(
final BaseAdapter adapter,
final String libName) {
final File dest = new File(String.format("%s/%s",
adapter.getTestLibsPath(),
libName));
if (!dest.exists()) {
TactFileUtils.copyfile(
new File(String.format("%s/%s",
Harmony.getLibsPath(),
libName)),
dest);
}
}
| public static void addLibraryToTestProject(
final BaseAdapter adapter,
final String libName) {
final File dest = new File(String.format("%s/%s",
adapter.getTestLibsPath(),
libName));
if (!dest.exists()) {
final File src = Harmony.getLibrary(libName);
TactFileUtils.copyfile(
src,
dest);
}
}
|
diff --git a/src/main/java/com/redhat/automationportal/scripts/FlagSearch.java b/src/main/java/com/redhat/automationportal/scripts/FlagSearch.java
index 4b1d279..d24ef2e 100644
--- a/src/main/java/com/redhat/automationportal/scripts/FlagSearch.java
+++ b/src/main/java/com/redhat/automationportal/scripts/FlagSearch.java
@@ -1,167 +1,167 @@
package com.redhat.automationportal.scripts;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.redhat.automationportal.base.AutomationBase;
import com.redhat.automationportal.base.Constants;
import com.redhat.ecs.commonutils.CollectionUtilities;
import com.redhat.ecs.commonutils.ExecUtilities;
import com.redhat.ecs.commonutils.PropertyUtils;
public class FlagSearch extends AutomationBase
{
private static String BUILD = "20120514-1344";
private static final String TEMPLATE_DIR = "/opt/automation-interface/Flag_search";
private static final String SAVE_DATA_FOLDER = "FlagSearch";
private static final String PERSIST_FILENAME = "saved_searches.txt";
private String bugzillaUsername;
private String bugzillaPassword;
private String productName;
private String component;
public String getBugzillaPassword()
{
return bugzillaPassword;
}
public void setBugzillaPassword(String bugzillaPassword)
{
this.bugzillaPassword = bugzillaPassword;
}
public String getBugzillaUsername()
{
return bugzillaUsername;
}
public void setBugzillaUsername(final String bugzillaUsername)
{
this.bugzillaUsername = bugzillaUsername;
}
public String getProductName()
{
return productName;
}
public void setProductName(String productName)
{
this.productName = productName;
}
public String getComponent()
{
return component;
}
public void setComponent(String component)
{
this.component = component;
}
@Override
public String getBuild()
{
return BUILD;
}
public List<String> getSavedSearches()
{
Process process = null;
try
{
final String catCommand = "/bin/su " + (this.username == null ? "automation-user" : this.username) + " -c \"if [ -f ~/" + AutomationBase.SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/" + PERSIST_FILENAME + " ]; then cat ~/" + AutomationBase.SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/" + PERSIST_FILENAME + "; fi; \"";
final String[] command = new String[] { "/bin/bash", "-c", catCommand };
process = Runtime.getRuntime().exec(command, ExecUtilities.getEnvironmentVars());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
this.success = ExecUtilities.runCommand(process, outputStream);
final String output = outputStream.toString();
return CollectionUtilities.toArrayList(output.split("\n"));
}
catch (final Exception ex)
{
return new ArrayList<String>();
}
finally
{
process.destroy();
}
}
public boolean run()
{
if (this.bugzillaUsername != null && this.bugzillaPassword != null &&
this.bugzillaUsername.trim().length() != 0 && this.bugzillaPassword.trim().length() != 0 &&
this.productName != null && this.productName != null &&
this.component != null && this.component != null)
{
final Integer randomInt = this.generateRandomInt();
final String randomString = this.generateRandomString(10);
if (randomInt == null)
{
this.message = "BugzillaReportGenerator.run() " + PropertyUtils.getProperty(Constants.ERROR_FPROPERTY_FILENAME, "AMPT0001", this.getClass());
return false;
}
if (randomString == null)
{
this.message = "BugzillaReportGenerator.run() " + PropertyUtils.getProperty(Constants.ERROR_FPROPERTY_FILENAME, "AMPT0002", this.getClass());
return false;
}
this.message = "";
final String[] environment = new String[] { randomString + "=" + this.bugzillaPassword };
final String script =
// copy the template files
"cp -R \\\"" + TEMPLATE_DIR + "/\\\"* \\\"" + this.getTmpDirectory(randomInt) + "\\\" " +
// make sure the data folder exists
"&& if [ ! -d ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + " ]; then " +
// create it if it doesn't
"mkdir -p ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "; " +
/* exit the statement */
"fi " +
// If the saved file exists
"&& if [ -f ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/" + PERSIST_FILENAME + " ]; then " +
/* copy the saved file */
"cp ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/" + PERSIST_FILENAME + " \\\"" + this.getTmpDirectory(randomInt) + "/\\\"; " +
/* exit the statement */
"fi " +
// enter the scripts directory
"&& cd \\\"" + this.getTmpDirectory(randomInt) + "\\\" " +
// run the python script
"&& perl flag_search7.pl --login=" + bugzillaUsername + " --password=${" + randomString + "} --product_name=\\\"" + this.productName + "\\\" --component=\\\"" + this.component + "\\\" " +
// copy the save_searches.txt to the data folder
- "&& cp \\\"" + this.getTmpDirectory(randomInt) + "/" + PERSIST_FILENAME + " ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/ ";
+ "&& cp \\\"" + this.getTmpDirectory(randomInt) + "/" + PERSIST_FILENAME + "\\\" ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/ ";
runScript(script, randomInt, true, true, true, null, environment);
// cleanup the temp dir
cleanup(randomInt);
return true;
}
else
{
this.message = "Please enter a username, password, product name and component";
return false;
}
}
}
| true | true | public boolean run()
{
if (this.bugzillaUsername != null && this.bugzillaPassword != null &&
this.bugzillaUsername.trim().length() != 0 && this.bugzillaPassword.trim().length() != 0 &&
this.productName != null && this.productName != null &&
this.component != null && this.component != null)
{
final Integer randomInt = this.generateRandomInt();
final String randomString = this.generateRandomString(10);
if (randomInt == null)
{
this.message = "BugzillaReportGenerator.run() " + PropertyUtils.getProperty(Constants.ERROR_FPROPERTY_FILENAME, "AMPT0001", this.getClass());
return false;
}
if (randomString == null)
{
this.message = "BugzillaReportGenerator.run() " + PropertyUtils.getProperty(Constants.ERROR_FPROPERTY_FILENAME, "AMPT0002", this.getClass());
return false;
}
this.message = "";
final String[] environment = new String[] { randomString + "=" + this.bugzillaPassword };
final String script =
// copy the template files
"cp -R \\\"" + TEMPLATE_DIR + "/\\\"* \\\"" + this.getTmpDirectory(randomInt) + "\\\" " +
// make sure the data folder exists
"&& if [ ! -d ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + " ]; then " +
// create it if it doesn't
"mkdir -p ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "; " +
/* exit the statement */
"fi " +
// If the saved file exists
"&& if [ -f ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/" + PERSIST_FILENAME + " ]; then " +
/* copy the saved file */
"cp ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/" + PERSIST_FILENAME + " \\\"" + this.getTmpDirectory(randomInt) + "/\\\"; " +
/* exit the statement */
"fi " +
// enter the scripts directory
"&& cd \\\"" + this.getTmpDirectory(randomInt) + "\\\" " +
// run the python script
"&& perl flag_search7.pl --login=" + bugzillaUsername + " --password=${" + randomString + "} --product_name=\\\"" + this.productName + "\\\" --component=\\\"" + this.component + "\\\" " +
// copy the save_searches.txt to the data folder
"&& cp \\\"" + this.getTmpDirectory(randomInt) + "/" + PERSIST_FILENAME + " ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/ ";
runScript(script, randomInt, true, true, true, null, environment);
// cleanup the temp dir
cleanup(randomInt);
return true;
}
else
{
this.message = "Please enter a username, password, product name and component";
return false;
}
}
| public boolean run()
{
if (this.bugzillaUsername != null && this.bugzillaPassword != null &&
this.bugzillaUsername.trim().length() != 0 && this.bugzillaPassword.trim().length() != 0 &&
this.productName != null && this.productName != null &&
this.component != null && this.component != null)
{
final Integer randomInt = this.generateRandomInt();
final String randomString = this.generateRandomString(10);
if (randomInt == null)
{
this.message = "BugzillaReportGenerator.run() " + PropertyUtils.getProperty(Constants.ERROR_FPROPERTY_FILENAME, "AMPT0001", this.getClass());
return false;
}
if (randomString == null)
{
this.message = "BugzillaReportGenerator.run() " + PropertyUtils.getProperty(Constants.ERROR_FPROPERTY_FILENAME, "AMPT0002", this.getClass());
return false;
}
this.message = "";
final String[] environment = new String[] { randomString + "=" + this.bugzillaPassword };
final String script =
// copy the template files
"cp -R \\\"" + TEMPLATE_DIR + "/\\\"* \\\"" + this.getTmpDirectory(randomInt) + "\\\" " +
// make sure the data folder exists
"&& if [ ! -d ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + " ]; then " +
// create it if it doesn't
"mkdir -p ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "; " +
/* exit the statement */
"fi " +
// If the saved file exists
"&& if [ -f ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/" + PERSIST_FILENAME + " ]; then " +
/* copy the saved file */
"cp ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/" + PERSIST_FILENAME + " \\\"" + this.getTmpDirectory(randomInt) + "/\\\"; " +
/* exit the statement */
"fi " +
// enter the scripts directory
"&& cd \\\"" + this.getTmpDirectory(randomInt) + "\\\" " +
// run the python script
"&& perl flag_search7.pl --login=" + bugzillaUsername + " --password=${" + randomString + "} --product_name=\\\"" + this.productName + "\\\" --component=\\\"" + this.component + "\\\" " +
// copy the save_searches.txt to the data folder
"&& cp \\\"" + this.getTmpDirectory(randomInt) + "/" + PERSIST_FILENAME + "\\\" ~" + (this.username == null ? "automation-user" : this.username) + "/" + SAVE_HOME_FOLDER + "/" + SAVE_DATA_FOLDER + "/ ";
runScript(script, randomInt, true, true, true, null, environment);
// cleanup the temp dir
cleanup(randomInt);
return true;
}
else
{
this.message = "Please enter a username, password, product name and component";
return false;
}
}
|
diff --git a/src/java/com/idega/development/presentation/SQLQueryer.java b/src/java/com/idega/development/presentation/SQLQueryer.java
index 4450ca2..6c554d0 100644
--- a/src/java/com/idega/development/presentation/SQLQueryer.java
+++ b/src/java/com/idega/development/presentation/SQLQueryer.java
@@ -1,341 +1,341 @@
//idega 2001 - Tryggvi Larusson
/*
*Copyright 2001 idega.is All Rights Reserved.
*/
package com.idega.development.presentation;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.Table;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.FramePane;
import com.idega.presentation.ui.SubmitButton;
import com.idega.presentation.ui.TextArea;
/**
*@author <a href="mailto:[email protected]">Tryggvi Larusson</a>
*@version 1.0
*/
public class SQLQueryer extends Block {
public final static String IW_BUNDLE_IDENTIFIER = "com.idega.developer";
private static String queryParameter = "SQLQUERYSTRING";
private FramePane queryPane;
private FramePane resultsPane;
private String query;
private boolean displayForm = true;
private String resultName = "Result";
public SQLQueryer() {
}
public void add(PresentationObject obj) {
resultsPane.add(obj);
}
public void setWidth(int width) {
if (queryPane != null)
queryPane.setWidth(width);
if (resultsPane != null)
resultsPane.setWidth(width);
}
public void setSQLQuery(String query) {
this.query = query;
this.displayForm = false;
}
public void setResultName(String resultName) {
this.resultName = resultName;
}
public void main(IWContext iwc) throws Exception {
resultsPane = new FramePane(resultName);
String queryString = iwc.getParameter(queryParameter);
if (displayForm) {
queryPane = new FramePane("Query");
super.add(queryPane);
Form form = new Form();
form.setTarget(IWDeveloper.frameName);
queryPane.add(form);
TextArea input = new TextArea(queryParameter);
- input.setWidth("100%");
+ input.setColumns(60);
input.setRows(5);
if (queryString != null) {
input.setContent(queryString);
}
Table innertTable = new Table(1, 2);
form.add(innertTable);
innertTable.add(input, 1, 1);
innertTable.add(new SubmitButton("Execute"), 1, 2);
}
Connection conn = getConnection();
if (queryString == null)
queryString = query;
try {
if (queryString != null) {
super.add(resultsPane);
if (displayForm) {
add("Your query was:");
add(Text.getBreak());
Text text = new Text(queryString);
text.setBold();
add(text);
addBreak();
}
Table table = new Table();
table.setColor("white");
add(table);
Statement stmt = conn.createStatement();
if (queryString.toLowerCase().indexOf("select") == -1) {
int i = stmt.executeUpdate(queryString);
//if (i>0){
add(i + " rows altered");
//}
//else{
//}
}
else {
ResultSet rs = stmt.executeQuery(queryString);
ResultSetMetaData rsMeta = rs.getMetaData();
// Get the N of Cols in the ResultSet
int noCols = rsMeta.getColumnCount();
//out.println("<tr>");
int y = 1;
int x = 1;
for (int c = 1; c <= noCols; c++) {
String el = rsMeta.getColumnLabel(c);
//out.println("<th> " + el + " </th>");
table.add(el, x, y);
x++;
}
//out.println("</tr>");
y++;
table.setRowColor(1, "#D0D0D0");
while (rs.next()) {
//out.println("<tr>");
x = 1;
for (int c = 1; c <= noCols; c++) {
String el = rs.getString(c);
table.add(el, x, y);
x++;
//out.println("<td> " + el + " </td>");
}
y++;
//out.println("</tr>");
}
}
//out.println("</table>");
} //end if querystring
} //end of try
catch (SQLException ex) {
//out.println ( "<P><PRE>" );
while (ex != null) {
add("Message: " + ex.getMessage());
this.addBreak();
add("SQLState: " + ex.getSQLState());
this.addBreak();
add("ErrorCode: " + ex.getErrorCode());
this.addBreak();
ex = ex.getNextException();
//out.println("");
}
//out.println ( "</PRE><P>" );
}
finally {
this.freeConnection(conn);
}
//out.println ("<hr>You can now try to retrieve something.");
//out.println("<FORM METHOD=POST ACTION=\"/servlet/CoffeeBreakServlet\">");
//out.println("<FORM METHOD=POST ACTION=\""+req.getRequestURI()+"\">");
//out.println("Query: <INPUT TYPE=TEXT SIZE=50 NAME=\"QUERYSTRING\"> ");
//out.println("<INPUT TYPE=SUBMIT VALUE=\"GO!\">");
//out.println("</FORM>");
//out.println("<hr><pre>e.g.:");
//out.println("SELECT * FROM COFFEES");
//out.println("SELECT * FROM COFFEES WHERE PRICE > 9");
//out.println("SELECT PRICE, COF_NAME FROM COFFEES");
//out.println("<pre>");
//out.println ("<hr><a href=\""+req.getRequestURI()+"\">Query again ?</a>");// | Source: <A HREF=\"/develop/servlets-ex/coffee-break/CoffeeBreakServlet.java\">CoffeeBreakServlet.java</A>");
//out.println ( "</body></html>" );
}
public synchronized Object clone() {
SQLQueryer obj = null;
try {
obj = (SQLQueryer) super.clone();
obj.queryParameter = this.queryParameter;
obj.queryPane = this.queryPane;
obj.resultsPane = this.resultsPane;
obj.query = this.query;
obj.displayForm = this.displayForm;
obj.resultName = this.resultName;
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
return obj;
}
public String getBundleIdentifier() {
return IW_BUNDLE_IDENTIFIER;
}
}
| true | true | public void main(IWContext iwc) throws Exception {
resultsPane = new FramePane(resultName);
String queryString = iwc.getParameter(queryParameter);
if (displayForm) {
queryPane = new FramePane("Query");
super.add(queryPane);
Form form = new Form();
form.setTarget(IWDeveloper.frameName);
queryPane.add(form);
TextArea input = new TextArea(queryParameter);
input.setWidth("100%");
input.setRows(5);
if (queryString != null) {
input.setContent(queryString);
}
Table innertTable = new Table(1, 2);
form.add(innertTable);
innertTable.add(input, 1, 1);
innertTable.add(new SubmitButton("Execute"), 1, 2);
}
Connection conn = getConnection();
if (queryString == null)
queryString = query;
try {
if (queryString != null) {
super.add(resultsPane);
if (displayForm) {
add("Your query was:");
add(Text.getBreak());
Text text = new Text(queryString);
text.setBold();
add(text);
addBreak();
}
Table table = new Table();
table.setColor("white");
add(table);
Statement stmt = conn.createStatement();
if (queryString.toLowerCase().indexOf("select") == -1) {
int i = stmt.executeUpdate(queryString);
//if (i>0){
add(i + " rows altered");
//}
//else{
//}
}
else {
ResultSet rs = stmt.executeQuery(queryString);
ResultSetMetaData rsMeta = rs.getMetaData();
// Get the N of Cols in the ResultSet
int noCols = rsMeta.getColumnCount();
//out.println("<tr>");
int y = 1;
int x = 1;
for (int c = 1; c <= noCols; c++) {
String el = rsMeta.getColumnLabel(c);
//out.println("<th> " + el + " </th>");
table.add(el, x, y);
x++;
}
//out.println("</tr>");
y++;
table.setRowColor(1, "#D0D0D0");
while (rs.next()) {
//out.println("<tr>");
x = 1;
for (int c = 1; c <= noCols; c++) {
String el = rs.getString(c);
table.add(el, x, y);
x++;
//out.println("<td> " + el + " </td>");
}
y++;
//out.println("</tr>");
}
}
//out.println("</table>");
} //end if querystring
} //end of try
catch (SQLException ex) {
//out.println ( "<P><PRE>" );
while (ex != null) {
add("Message: " + ex.getMessage());
this.addBreak();
add("SQLState: " + ex.getSQLState());
this.addBreak();
add("ErrorCode: " + ex.getErrorCode());
this.addBreak();
ex = ex.getNextException();
//out.println("");
}
//out.println ( "</PRE><P>" );
}
finally {
this.freeConnection(conn);
}
//out.println ("<hr>You can now try to retrieve something.");
//out.println("<FORM METHOD=POST ACTION=\"/servlet/CoffeeBreakServlet\">");
//out.println("<FORM METHOD=POST ACTION=\""+req.getRequestURI()+"\">");
//out.println("Query: <INPUT TYPE=TEXT SIZE=50 NAME=\"QUERYSTRING\"> ");
//out.println("<INPUT TYPE=SUBMIT VALUE=\"GO!\">");
//out.println("</FORM>");
//out.println("<hr><pre>e.g.:");
//out.println("SELECT * FROM COFFEES");
//out.println("SELECT * FROM COFFEES WHERE PRICE > 9");
//out.println("SELECT PRICE, COF_NAME FROM COFFEES");
//out.println("<pre>");
//out.println ("<hr><a href=\""+req.getRequestURI()+"\">Query again ?</a>");// | Source: <A HREF=\"/develop/servlets-ex/coffee-break/CoffeeBreakServlet.java\">CoffeeBreakServlet.java</A>");
//out.println ( "</body></html>" );
}
| public void main(IWContext iwc) throws Exception {
resultsPane = new FramePane(resultName);
String queryString = iwc.getParameter(queryParameter);
if (displayForm) {
queryPane = new FramePane("Query");
super.add(queryPane);
Form form = new Form();
form.setTarget(IWDeveloper.frameName);
queryPane.add(form);
TextArea input = new TextArea(queryParameter);
input.setColumns(60);
input.setRows(5);
if (queryString != null) {
input.setContent(queryString);
}
Table innertTable = new Table(1, 2);
form.add(innertTable);
innertTable.add(input, 1, 1);
innertTable.add(new SubmitButton("Execute"), 1, 2);
}
Connection conn = getConnection();
if (queryString == null)
queryString = query;
try {
if (queryString != null) {
super.add(resultsPane);
if (displayForm) {
add("Your query was:");
add(Text.getBreak());
Text text = new Text(queryString);
text.setBold();
add(text);
addBreak();
}
Table table = new Table();
table.setColor("white");
add(table);
Statement stmt = conn.createStatement();
if (queryString.toLowerCase().indexOf("select") == -1) {
int i = stmt.executeUpdate(queryString);
//if (i>0){
add(i + " rows altered");
//}
//else{
//}
}
else {
ResultSet rs = stmt.executeQuery(queryString);
ResultSetMetaData rsMeta = rs.getMetaData();
// Get the N of Cols in the ResultSet
int noCols = rsMeta.getColumnCount();
//out.println("<tr>");
int y = 1;
int x = 1;
for (int c = 1; c <= noCols; c++) {
String el = rsMeta.getColumnLabel(c);
//out.println("<th> " + el + " </th>");
table.add(el, x, y);
x++;
}
//out.println("</tr>");
y++;
table.setRowColor(1, "#D0D0D0");
while (rs.next()) {
//out.println("<tr>");
x = 1;
for (int c = 1; c <= noCols; c++) {
String el = rs.getString(c);
table.add(el, x, y);
x++;
//out.println("<td> " + el + " </td>");
}
y++;
//out.println("</tr>");
}
}
//out.println("</table>");
} //end if querystring
} //end of try
catch (SQLException ex) {
//out.println ( "<P><PRE>" );
while (ex != null) {
add("Message: " + ex.getMessage());
this.addBreak();
add("SQLState: " + ex.getSQLState());
this.addBreak();
add("ErrorCode: " + ex.getErrorCode());
this.addBreak();
ex = ex.getNextException();
//out.println("");
}
//out.println ( "</PRE><P>" );
}
finally {
this.freeConnection(conn);
}
//out.println ("<hr>You can now try to retrieve something.");
//out.println("<FORM METHOD=POST ACTION=\"/servlet/CoffeeBreakServlet\">");
//out.println("<FORM METHOD=POST ACTION=\""+req.getRequestURI()+"\">");
//out.println("Query: <INPUT TYPE=TEXT SIZE=50 NAME=\"QUERYSTRING\"> ");
//out.println("<INPUT TYPE=SUBMIT VALUE=\"GO!\">");
//out.println("</FORM>");
//out.println("<hr><pre>e.g.:");
//out.println("SELECT * FROM COFFEES");
//out.println("SELECT * FROM COFFEES WHERE PRICE > 9");
//out.println("SELECT PRICE, COF_NAME FROM COFFEES");
//out.println("<pre>");
//out.println ("<hr><a href=\""+req.getRequestURI()+"\">Query again ?</a>");// | Source: <A HREF=\"/develop/servlets-ex/coffee-break/CoffeeBreakServlet.java\">CoffeeBreakServlet.java</A>");
//out.println ( "</body></html>" );
}
|
diff --git a/src/main/java/cc/kune/core/client/state/SiteTokenListeners.java b/src/main/java/cc/kune/core/client/state/SiteTokenListeners.java
index fc31fe354..9a30f0c84 100644
--- a/src/main/java/cc/kune/core/client/state/SiteTokenListeners.java
+++ b/src/main/java/cc/kune/core/client/state/SiteTokenListeners.java
@@ -1,118 +1,117 @@
/*
*
* Copyright (C) 2007-2011 The kune development team (see CREDITS for details)
* This file is part of kune.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.kune.core.client.state;
import java.util.HashMap;
import cc.kune.core.client.auth.Register;
import cc.kune.core.client.auth.SignIn;
import cc.kune.core.client.groups.newgroup.NewGroup;
import cc.kune.core.client.sitebar.AboutKuneDialog;
import cc.kune.core.client.sitebar.spaces.Space;
import cc.kune.core.client.sitebar.spaces.SpaceSelectEvent;
import cc.kune.core.client.sub.SubtitlesManager;
import cc.kune.gspace.client.i18n.I18nTranslator;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.inject.Provider;
@SuppressWarnings("serial")
public class SiteTokenListeners extends HashMap<String, HistoryTokenCallback> {
private final Provider<AboutKuneDialog> aboutKuneDialog;
private final EventBus eventBus;
private final Provider<NewGroup> newGroup;
private final Provider<Register> register;
private final Session session;
private final Provider<SignIn> signIn;
private final Provider<SubtitlesManager> subProvider;
private final Provider<I18nTranslator> translator;
@Inject
public SiteTokenListeners(final Session session, final EventBus eventBus,
final Provider<SignIn> signIn, final Provider<Register> register,
final Provider<NewGroup> newGroup, final Provider<AboutKuneDialog> aboutKuneDialog,
final Provider<I18nTranslator> translator, final Provider<SubtitlesManager> subProvider) {
this.session = session;
this.eventBus = eventBus;
this.signIn = signIn;
this.register = register;
this.newGroup = newGroup;
this.aboutKuneDialog = aboutKuneDialog;
this.translator = translator;
this.subProvider = subProvider;
putValues();
}
private void putValues() {
put(SiteTokens.HOME, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.homeSpace);
}
});
put(SiteTokens.WAVEINBOX, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.userSpace);
}
});
put(SiteTokens.SIGNIN, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
signIn.get().showSignInDialog();
}
});
put(SiteTokens.REGISTER, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
register.get().doRegister();
}
});
put(SiteTokens.NEWGROUP, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
newGroup.get().doNewGroup();
}
});
put(SiteTokens.ABOUTKUNE, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
// FIXME, something to come back
aboutKuneDialog.get().showCentered();
}
});
put(SiteTokens.TRANSLATE, new HistoryTokenCallback() {
- // FIXME, something to come back
@Override
public void onHistoryToken(final String token) {
- if (session.getInitData().isTranslatorEnabled()) {
+ if (session.isLogged() && session.getInitData().isTranslatorEnabled()) {
translator.get().show();
}
}
});
put(SiteTokens.SUBTITLES, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
subProvider.get().show(token);
}
});
}
}
| false | true | private void putValues() {
put(SiteTokens.HOME, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.homeSpace);
}
});
put(SiteTokens.WAVEINBOX, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.userSpace);
}
});
put(SiteTokens.SIGNIN, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
signIn.get().showSignInDialog();
}
});
put(SiteTokens.REGISTER, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
register.get().doRegister();
}
});
put(SiteTokens.NEWGROUP, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
newGroup.get().doNewGroup();
}
});
put(SiteTokens.ABOUTKUNE, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
// FIXME, something to come back
aboutKuneDialog.get().showCentered();
}
});
put(SiteTokens.TRANSLATE, new HistoryTokenCallback() {
// FIXME, something to come back
@Override
public void onHistoryToken(final String token) {
if (session.getInitData().isTranslatorEnabled()) {
translator.get().show();
}
}
});
put(SiteTokens.SUBTITLES, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
subProvider.get().show(token);
}
});
}
| private void putValues() {
put(SiteTokens.HOME, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.homeSpace);
}
});
put(SiteTokens.WAVEINBOX, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
SpaceSelectEvent.fire(eventBus, Space.userSpace);
}
});
put(SiteTokens.SIGNIN, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
signIn.get().showSignInDialog();
}
});
put(SiteTokens.REGISTER, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
register.get().doRegister();
}
});
put(SiteTokens.NEWGROUP, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
newGroup.get().doNewGroup();
}
});
put(SiteTokens.ABOUTKUNE, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
// FIXME, something to come back
aboutKuneDialog.get().showCentered();
}
});
put(SiteTokens.TRANSLATE, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
if (session.isLogged() && session.getInitData().isTranslatorEnabled()) {
translator.get().show();
}
}
});
put(SiteTokens.SUBTITLES, new HistoryTokenCallback() {
@Override
public void onHistoryToken(final String token) {
subProvider.get().show(token);
}
});
}
|
diff --git a/src/net/slipcor/pvparena/loadables/ArenaGoalManager.java b/src/net/slipcor/pvparena/loadables/ArenaGoalManager.java
index 72bb9ecd..916e5cb6 100644
--- a/src/net/slipcor/pvparena/loadables/ArenaGoalManager.java
+++ b/src/net/slipcor/pvparena/loadables/ArenaGoalManager.java
@@ -1,403 +1,405 @@
package net.slipcor.pvparena.loadables;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import net.slipcor.pvparena.PVPArena;
import net.slipcor.pvparena.arena.Arena;
import net.slipcor.pvparena.arena.ArenaPlayer;
import net.slipcor.pvparena.arena.ArenaTeam;
import net.slipcor.pvparena.arena.ArenaPlayer.Status;
import net.slipcor.pvparena.core.Config.CFG;
import net.slipcor.pvparena.core.Debug;
import net.slipcor.pvparena.core.Language;
import net.slipcor.pvparena.core.Language.MSG;
import net.slipcor.pvparena.goals.GoalBlockDestroy;
import net.slipcor.pvparena.goals.GoalDomination;
import net.slipcor.pvparena.goals.GoalFlags;
import net.slipcor.pvparena.goals.GoalPhysicalFlags;
import net.slipcor.pvparena.goals.GoalPlayerDeathMatch;
import net.slipcor.pvparena.goals.GoalPlayerKillReward;
import net.slipcor.pvparena.goals.GoalPlayerLives;
import net.slipcor.pvparena.goals.GoalSabotage;
import net.slipcor.pvparena.goals.GoalTank;
import net.slipcor.pvparena.goals.GoalTeamDeathMatch;
import net.slipcor.pvparena.goals.GoalTeamLives;
import net.slipcor.pvparena.goals.GoalTime;
import net.slipcor.pvparena.ncloader.NCBLoader;
import net.slipcor.pvparena.runnables.EndRunnable;
/**
* <pre>Arena Goal Manager class</pre>
*
* Loads and manages arena goals
*
* @author slipcor
*
* @version v0.10.2
*/
public class ArenaGoalManager {
private List<ArenaGoal> types;
private final NCBLoader<ArenaGoal> loader;
protected static final Debug DEBUG = new Debug(31);
/**
* create an arena type instance
*
* @param plugin
* the plugin instance
*/
public ArenaGoalManager(final PVPArena plugin) {
final File path = new File(plugin.getDataFolder().toString() + "/goals");
if (!path.exists()) {
path.mkdir();
}
loader = new NCBLoader<ArenaGoal>(plugin, path, new Object[] {});
types = loader.load();
fill();
}
private void fill() {
types.add(new GoalBlockDestroy());
types.add(new GoalDomination());
types.add(new GoalFlags());
types.add(new GoalPhysicalFlags());
types.add(new GoalPlayerDeathMatch());
types.add(new GoalPlayerKillReward());
types.add(new GoalPlayerLives());
types.add(new GoalSabotage());
types.add(new GoalTank());
types.add(new GoalTeamDeathMatch());
types.add(new GoalTeamLives());
types.add(new GoalTime());
for (ArenaGoal type : types) {
type.onThisLoad();
DEBUG.i("module ArenaType loaded: " + type.getName() + " (version "
+ type.version() + ")");
}
}
public boolean allowsJoinInBattle(final Arena arena) {
for (ArenaGoal type : arena.getGoals()) {
if (!type.allowsJoinInBattle()) {
return false;
}
}
return true;
}
public String checkForMissingSpawns(final Arena arena, final Set<String> list) {
for (ArenaGoal type : arena.getGoals()) {
final String error = type.checkForMissingSpawns(list);
if (error != null) {
return error;
}
}
return null;
}
public void configParse(final Arena arena, final YamlConfiguration config) {
for (ArenaGoal type : arena.getGoals()) {
type.configParse(config);
}
}
public Set<String> getAllGoalNames() {
final Set<String> result = new HashSet<String>();
for (ArenaGoal goal : types) {
result.add(goal.getName());
}
return result;
}
public List<ArenaGoal> getAllGoals() {
return types;
}
/**
* find an arena type by arena type name
*
* @param tName
* the type name to find
* @return the arena type if found, null otherwise
*/
public ArenaGoal getGoalByName(final String tName) {
for (ArenaGoal type : types) {
if (type.getName().equalsIgnoreCase(tName)) {
return type;
}
}
return null;
}
public String guessSpawn(final Arena arena, final String place) {
for (ArenaGoal type : arena.getGoals()) {
final String result = type.guessSpawn(place);
if (result != null) {
return result;
}
}
return null;
}
public void initiate(final Arena arena, final Player player) {
DEBUG.i("initiating " + player.getName(), player);
for (ArenaGoal type : arena.getGoals()) {
type.initate(player);
}
}
public String ready(final Arena arena) {
DEBUG.i("AGM ready!?!");
String error = null;
for (ArenaGoal type : arena.getGoals()) {
error = type.ready();
if (error != null) {
DEBUG.i("type error:" + type.getName());
return error;
}
}
return null;
}
public void reload() {
types = loader.reload();
fill();
}
public void reset(final Arena arena, final boolean force) {
for (ArenaGoal type : arena.getGoals()) {
type.reset(force);
}
}
public void setDefaults(final Arena arena, final YamlConfiguration config) {
for (ArenaGoal type : arena.getGoals()) {
type.setDefaults(config);
}
}
public void setPlayerLives(final Arena arena, final int value) {
for (ArenaGoal type : arena.getGoals()) {
type.setPlayerLives(value);
}
}
public void setPlayerLives(final Arena arena, final ArenaPlayer player, final int value) {
for (ArenaGoal type : arena.getGoals()) {
type.setPlayerLives(player, value);
}
}
public void timedEnd(final Arena arena) {
/**
* name/team => score points
*
* handed over to each module
*/
DEBUG.i("timed end!");
Map<String, Double> scores = new HashMap<String, Double>();
for (ArenaGoal type : arena.getGoals()) {
DEBUG.i("scores: " + type.getName());
scores = type.timedEnd(scores);
}
final Set<String> winners = new HashSet<String>();
if (arena.isFreeForAll()) {
winners.add("free");
DEBUG.i("adding FREE");
} else if (arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER).equals("none")) {
// check all teams
double maxScore = 0;
for (String team : arena.getTeamNames()) {
if (scores.containsKey(team)) {
final double teamScore = scores.get(team);
if (teamScore > maxScore) {
maxScore = teamScore;
winners.clear();
winners.add(team);
DEBUG.i("clear and add team " + team);
} else if (teamScore == maxScore) {
winners.add(team);
DEBUG.i("add team "+team);
}
}
}
} else {
winners.add(arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER));
DEBUG.i("added winner!");
}
if (winners.size() > 1) {
DEBUG.i("more than 1");
final Set<String> preciseWinners = new HashSet<String>();
// several teams have max score!!
double maxSum = 0;
double sum = 0;
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
sum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
if (scores.containsKey(ap.getName())) {
sum += scores.get(ap.getName());
}
}
if (sum == maxSum) {
preciseWinners.add(team.getName());
DEBUG.i("adddding " + team.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(team.getName());
DEBUG.i("clearing and adddding + " + team.getName());
}
}
if (!preciseWinners.isEmpty()) {
winners.clear();
winners.addAll(preciseWinners);
}
}
if (arena.isFreeForAll()) {
DEBUG.i("FFAAA");
final Set<String> preciseWinners = new HashSet<String>();
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
double maxSum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
double sum = 0;
if (scores.containsKey(ap.getName())) {
sum = scores.get(ap.getName());
}
if (sum == maxSum) {
preciseWinners.add(ap.getName());
DEBUG.i("ffa adding " + ap.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(ap.getName());
DEBUG.i("ffa clr & adding " + ap.getName());
}
}
}
winners.clear();
if (preciseWinners.size() != arena.getPlayedPlayers().size()) {
winners.addAll(preciseWinners);
}
}
ArenaModuleManager.timedEnd(arena, winners);
if (arena.isFreeForAll()) {
for (ArenaTeam team : arena.getTeams()) {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (winners.isEmpty()) {
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
} else {
if (winners.contains(p.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.PLAYER_HAS_WON, p.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.PLAYER_HAS_WON, p.getName()));
} else {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (winners.isEmpty()) {
ArenaModuleManager.announce(arena, Language.parse(MSG.FIGHT_DRAW), "WINNER");
arena.broadcast(Language.parse(MSG.FIGHT_DRAW));
}
} else {
boolean hasBroadcasted = false;
for (ArenaTeam team : arena.getTeams()) {
if (winners.contains(team.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.TEAM_HAS_WON, "Team " + team.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
hasBroadcasted = true;
} else {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
if (!hasBroadcasted) {
- arena.msg(p.get(), Language.parse(MSG.TEAM_HAS_WON, team.getColor()
- + "Team " + team.getName()));
+ for (String winTeam : winners) {
+ arena.msg(p.get(), Language.parse(MSG.TEAM_HAS_WON, arena.getTeam(winTeam).getColor()
+ + "Team " + winTeam));
+ }
}
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (arena.realEndRunner == null) {
new EndRunnable(arena, arena.getArenaConfig().getInt(
CFG.TIME_ENDCOUNTDOWN));
}
}
public void unload(final Arena arena, final Player player) {
for (ArenaGoal type : arena.getGoals()) {
type.unload(player);
}
}
public void disconnect(final Arena arena, final ArenaPlayer player) {
if (arena == null) {
return;
}
for (ArenaGoal type : arena.getGoals()) {
type.disconnect(player);
}
}
}
| true | true | public void timedEnd(final Arena arena) {
/**
* name/team => score points
*
* handed over to each module
*/
DEBUG.i("timed end!");
Map<String, Double> scores = new HashMap<String, Double>();
for (ArenaGoal type : arena.getGoals()) {
DEBUG.i("scores: " + type.getName());
scores = type.timedEnd(scores);
}
final Set<String> winners = new HashSet<String>();
if (arena.isFreeForAll()) {
winners.add("free");
DEBUG.i("adding FREE");
} else if (arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER).equals("none")) {
// check all teams
double maxScore = 0;
for (String team : arena.getTeamNames()) {
if (scores.containsKey(team)) {
final double teamScore = scores.get(team);
if (teamScore > maxScore) {
maxScore = teamScore;
winners.clear();
winners.add(team);
DEBUG.i("clear and add team " + team);
} else if (teamScore == maxScore) {
winners.add(team);
DEBUG.i("add team "+team);
}
}
}
} else {
winners.add(arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER));
DEBUG.i("added winner!");
}
if (winners.size() > 1) {
DEBUG.i("more than 1");
final Set<String> preciseWinners = new HashSet<String>();
// several teams have max score!!
double maxSum = 0;
double sum = 0;
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
sum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
if (scores.containsKey(ap.getName())) {
sum += scores.get(ap.getName());
}
}
if (sum == maxSum) {
preciseWinners.add(team.getName());
DEBUG.i("adddding " + team.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(team.getName());
DEBUG.i("clearing and adddding + " + team.getName());
}
}
if (!preciseWinners.isEmpty()) {
winners.clear();
winners.addAll(preciseWinners);
}
}
if (arena.isFreeForAll()) {
DEBUG.i("FFAAA");
final Set<String> preciseWinners = new HashSet<String>();
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
double maxSum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
double sum = 0;
if (scores.containsKey(ap.getName())) {
sum = scores.get(ap.getName());
}
if (sum == maxSum) {
preciseWinners.add(ap.getName());
DEBUG.i("ffa adding " + ap.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(ap.getName());
DEBUG.i("ffa clr & adding " + ap.getName());
}
}
}
winners.clear();
if (preciseWinners.size() != arena.getPlayedPlayers().size()) {
winners.addAll(preciseWinners);
}
}
ArenaModuleManager.timedEnd(arena, winners);
if (arena.isFreeForAll()) {
for (ArenaTeam team : arena.getTeams()) {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (winners.isEmpty()) {
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
} else {
if (winners.contains(p.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.PLAYER_HAS_WON, p.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.PLAYER_HAS_WON, p.getName()));
} else {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (winners.isEmpty()) {
ArenaModuleManager.announce(arena, Language.parse(MSG.FIGHT_DRAW), "WINNER");
arena.broadcast(Language.parse(MSG.FIGHT_DRAW));
}
} else {
boolean hasBroadcasted = false;
for (ArenaTeam team : arena.getTeams()) {
if (winners.contains(team.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.TEAM_HAS_WON, "Team " + team.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
hasBroadcasted = true;
} else {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
if (!hasBroadcasted) {
arena.msg(p.get(), Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
}
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (arena.realEndRunner == null) {
new EndRunnable(arena, arena.getArenaConfig().getInt(
CFG.TIME_ENDCOUNTDOWN));
}
}
| public void timedEnd(final Arena arena) {
/**
* name/team => score points
*
* handed over to each module
*/
DEBUG.i("timed end!");
Map<String, Double> scores = new HashMap<String, Double>();
for (ArenaGoal type : arena.getGoals()) {
DEBUG.i("scores: " + type.getName());
scores = type.timedEnd(scores);
}
final Set<String> winners = new HashSet<String>();
if (arena.isFreeForAll()) {
winners.add("free");
DEBUG.i("adding FREE");
} else if (arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER).equals("none")) {
// check all teams
double maxScore = 0;
for (String team : arena.getTeamNames()) {
if (scores.containsKey(team)) {
final double teamScore = scores.get(team);
if (teamScore > maxScore) {
maxScore = teamScore;
winners.clear();
winners.add(team);
DEBUG.i("clear and add team " + team);
} else if (teamScore == maxScore) {
winners.add(team);
DEBUG.i("add team "+team);
}
}
}
} else {
winners.add(arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER));
DEBUG.i("added winner!");
}
if (winners.size() > 1) {
DEBUG.i("more than 1");
final Set<String> preciseWinners = new HashSet<String>();
// several teams have max score!!
double maxSum = 0;
double sum = 0;
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
sum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
if (scores.containsKey(ap.getName())) {
sum += scores.get(ap.getName());
}
}
if (sum == maxSum) {
preciseWinners.add(team.getName());
DEBUG.i("adddding " + team.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(team.getName());
DEBUG.i("clearing and adddding + " + team.getName());
}
}
if (!preciseWinners.isEmpty()) {
winners.clear();
winners.addAll(preciseWinners);
}
}
if (arena.isFreeForAll()) {
DEBUG.i("FFAAA");
final Set<String> preciseWinners = new HashSet<String>();
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
double maxSum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
double sum = 0;
if (scores.containsKey(ap.getName())) {
sum = scores.get(ap.getName());
}
if (sum == maxSum) {
preciseWinners.add(ap.getName());
DEBUG.i("ffa adding " + ap.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(ap.getName());
DEBUG.i("ffa clr & adding " + ap.getName());
}
}
}
winners.clear();
if (preciseWinners.size() != arena.getPlayedPlayers().size()) {
winners.addAll(preciseWinners);
}
}
ArenaModuleManager.timedEnd(arena, winners);
if (arena.isFreeForAll()) {
for (ArenaTeam team : arena.getTeams()) {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (winners.isEmpty()) {
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
} else {
if (winners.contains(p.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.PLAYER_HAS_WON, p.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.PLAYER_HAS_WON, p.getName()));
} else {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (winners.isEmpty()) {
ArenaModuleManager.announce(arena, Language.parse(MSG.FIGHT_DRAW), "WINNER");
arena.broadcast(Language.parse(MSG.FIGHT_DRAW));
}
} else {
boolean hasBroadcasted = false;
for (ArenaTeam team : arena.getTeams()) {
if (winners.contains(team.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.TEAM_HAS_WON, "Team " + team.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
hasBroadcasted = true;
} else {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
if (!hasBroadcasted) {
for (String winTeam : winners) {
arena.msg(p.get(), Language.parse(MSG.TEAM_HAS_WON, arena.getTeam(winTeam).getColor()
+ "Team " + winTeam));
}
}
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (arena.realEndRunner == null) {
new EndRunnable(arena, arena.getArenaConfig().getInt(
CFG.TIME_ENDCOUNTDOWN));
}
}
|
diff --git a/KitsuneChat/src/com/cyberkitsune/prefixchat/KitsuneChatCommand.java b/KitsuneChat/src/com/cyberkitsune/prefixchat/KitsuneChatCommand.java
index 1867517..67fa7d3 100644
--- a/KitsuneChat/src/com/cyberkitsune/prefixchat/KitsuneChatCommand.java
+++ b/KitsuneChat/src/com/cyberkitsune/prefixchat/KitsuneChatCommand.java
@@ -1,33 +1,35 @@
package com.cyberkitsune.prefixchat;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class KitsuneChatCommand implements CommandExecutor {
private KitsuneChat plugin;
public KitsuneChatCommand(KitsuneChat plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (sender instanceof Player) {
- if (command.getName().equalsIgnoreCase("ch")) {
+ if (command.getName().equalsIgnoreCase("kc")) {
if (args.length > 0) {
- plugin.chans.changeChannel((Player) sender, args[0]);
+ if(args[0] == "chan" && args.length > 1) {
+ plugin.chans.changeChannel((Player) sender, args[1]);
+ }
} else {
- sender.sendMessage(ChatColor.RED+"Usage: /ch [channel]");
+ sender.sendMessage(ChatColor.RED+"[KitsuneChat] Unknown or missing command. See /kc ? for help.");
}
}
return true;
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (sender instanceof Player) {
if (command.getName().equalsIgnoreCase("ch")) {
if (args.length > 0) {
plugin.chans.changeChannel((Player) sender, args[0]);
} else {
sender.sendMessage(ChatColor.RED+"Usage: /ch [channel]");
}
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (sender instanceof Player) {
if (command.getName().equalsIgnoreCase("kc")) {
if (args.length > 0) {
if(args[0] == "chan" && args.length > 1) {
plugin.chans.changeChannel((Player) sender, args[1]);
}
} else {
sender.sendMessage(ChatColor.RED+"[KitsuneChat] Unknown or missing command. See /kc ? for help.");
}
}
return true;
}
return false;
}
|
diff --git a/src/org/ohmage/cache/KeyValueCache.java b/src/org/ohmage/cache/KeyValueCache.java
index e4a23ab0..e7121618 100644
--- a/src/org/ohmage/cache/KeyValueCache.java
+++ b/src/org/ohmage/cache/KeyValueCache.java
@@ -1,216 +1,219 @@
/*******************************************************************************
* Copyright 2012 The Regents of the University of California
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
******************************************************************************/
package org.ohmage.cache;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.ohmage.exception.CacheMissException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/**
* The abstract cache class for key-Value pairs.
*
* @author John Jenkins
*/
public abstract class KeyValueCache extends Cache {
private static final Logger LOGGER = Logger.getLogger(KeyValueCache.class);
/**
* Inner class for handling the results of a query for the String keys and
* their respective String values.
*
* @author John Jenkins
*/
private final class KeyAndValue {
private final String key;
private final String value;
/**
* Creates a new object with the specified key and value. This is done
* instead of having a default constructor and directly setting the
* values as a convenience to make creating a new object a one-liner
* and to provide a thin veil of encapsulation.
*
* @param key
* The key for this key-value pair.
*
* @param value
* The value for this key-value pair.
*/
private KeyAndValue(String key, String value) {
this.key = key;
this.value = value;
}
}
// The map of all the keys to their values.
private Map<String, String> keyValueMap;
// The SQL to use to get the values which must return two String values as
// dictated by the private class KeyAndValue.
private final String sqlForRetrievingValues;
// The column names for the key and value columns to be used with the SQL.
private final String keyColumn;
private final String valueColumn;
/**
* Default constructor that calls its parent and is protected to maintain
* the Singleton-ness.
*/
protected KeyValueCache(
DataSource dataSource,
long updateFrequency,
String sqlForRetrievingValues,
String keyKey,
String valueKey) {
super(dataSource, updateFrequency);
keyValueMap = new HashMap<String, String>();
this.sqlForRetrievingValues = sqlForRetrievingValues;
keyColumn = keyKey;
valueColumn = valueKey;
}
/**
* Compares the current timestamp with the last time we did an update plus
* the amount of time between updates. If our cache has become stale, we
* attempt to update it.
*
* Then, we check to see if such a key exists in our cache. If not, we
* throw an exception because, if someone is querying for a key that
* doesn't exist, we need to bring it to their immediate attention rather
* than returning an "error" value. Otherwise, the corresponding integer
* value is returned.
*
* It is recommended, but not required, to use the constants declared in
* the concrete cache class as the parameter.
*
* The complexity is O(n) if a refresh is required; otherwise, the
* complexity of a Java Map object to lookup a key and return its value.
*
* @param key
* The key whose corresponding value is being requested.
*
* @return The corresponding value.
*
* @throws CacheMissException
* Thrown if no such key exists.
*/
public String lookup(String key) throws CacheMissException {
// If the lookup table is out-of-date, refresh it.
if((getLastUpdateTimestamp() + getUpdateFrequency()) <= System
.currentTimeMillis()) {
refreshMap();
}
// If the key exists in the lookup table, return its value.
if(keyValueMap.containsKey(key)) {
return keyValueMap.get(key);
}
// Otherwise, throw an exception that it is an unknown state.
else {
throw new CacheMissException("Unknown key: " + key);
}
}
/**
* Returns all the known keys.
*
* @return All known keys.
*/
@Override
public Set<String> getKeys() {
// If the lookup table is out-of-date, refresh it.
if((getLastUpdateTimestamp() + getUpdateFrequency()) <= System
.currentTimeMillis()) {
refreshMap();
}
return keyValueMap.keySet();
}
/**
* Gets a human-readable name for this cache.
*
* @return Returns a human-readable name for their cache.
*/
@Override
public abstract String getName();
/**
* Reads the database for the information in the lookup table and populates
* its map with the gathered information. If there is an issue reading the
* database, it will just remain with the current lookup table it has.
*
* @complexity O(n) where n is the number of keys in the database.
*/
protected synchronized void refreshMap() {
// Only one thread should be updating this information at a time. Once
// other threads enter, they should check to see if an update was just
// done and, if so, should abort a second update.
if((getLastUpdateTimestamp() + getUpdateFrequency()) > System
.currentTimeMillis()) {
return;
}
// This is the JdbcTemplate we will use for our query. If there is an
// issue report it and abort the update.
JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
// Get all the keys and their corresponding values.
List<KeyAndValue> keyAndValue;
try {
keyAndValue =
jdbcTemplate.query(
sqlForRetrievingValues,
new RowMapper<KeyAndValue>() {
@Override
public KeyAndValue mapRow(ResultSet rs, int row)
throws SQLException {
return new KeyAndValue(rs.getString(keyColumn), rs
.getString(valueColumn));
}
});
}
catch(org.springframework.dao.DataAccessException e) {
- LOGGER.error("Error executing SQL '" +
- sqlForRetrievingValues +
- "'. Aborting cache refresh.");
+ LOGGER
+ .error(
+ "Error executing SQL '" +
+ sqlForRetrievingValues +
+ "'. Aborting cache refresh.",
+ e);
return;
}
// Create a new Map, populate it, and replace the old one. This allows
// for concurrent readying while the new Map is being created.
Map<String, String> keyValueMap = new HashMap<String, String>();
for(KeyAndValue currStateAndId : keyAndValue) {
keyValueMap.put(currStateAndId.key, currStateAndId.value);
}
this.keyValueMap = keyValueMap;
setLastUpdateTimestamp(System.currentTimeMillis());
}
}
| true | true | protected synchronized void refreshMap() {
// Only one thread should be updating this information at a time. Once
// other threads enter, they should check to see if an update was just
// done and, if so, should abort a second update.
if((getLastUpdateTimestamp() + getUpdateFrequency()) > System
.currentTimeMillis()) {
return;
}
// This is the JdbcTemplate we will use for our query. If there is an
// issue report it and abort the update.
JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
// Get all the keys and their corresponding values.
List<KeyAndValue> keyAndValue;
try {
keyAndValue =
jdbcTemplate.query(
sqlForRetrievingValues,
new RowMapper<KeyAndValue>() {
@Override
public KeyAndValue mapRow(ResultSet rs, int row)
throws SQLException {
return new KeyAndValue(rs.getString(keyColumn), rs
.getString(valueColumn));
}
});
}
catch(org.springframework.dao.DataAccessException e) {
LOGGER.error("Error executing SQL '" +
sqlForRetrievingValues +
"'. Aborting cache refresh.");
return;
}
// Create a new Map, populate it, and replace the old one. This allows
// for concurrent readying while the new Map is being created.
Map<String, String> keyValueMap = new HashMap<String, String>();
for(KeyAndValue currStateAndId : keyAndValue) {
keyValueMap.put(currStateAndId.key, currStateAndId.value);
}
this.keyValueMap = keyValueMap;
setLastUpdateTimestamp(System.currentTimeMillis());
}
| protected synchronized void refreshMap() {
// Only one thread should be updating this information at a time. Once
// other threads enter, they should check to see if an update was just
// done and, if so, should abort a second update.
if((getLastUpdateTimestamp() + getUpdateFrequency()) > System
.currentTimeMillis()) {
return;
}
// This is the JdbcTemplate we will use for our query. If there is an
// issue report it and abort the update.
JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
// Get all the keys and their corresponding values.
List<KeyAndValue> keyAndValue;
try {
keyAndValue =
jdbcTemplate.query(
sqlForRetrievingValues,
new RowMapper<KeyAndValue>() {
@Override
public KeyAndValue mapRow(ResultSet rs, int row)
throws SQLException {
return new KeyAndValue(rs.getString(keyColumn), rs
.getString(valueColumn));
}
});
}
catch(org.springframework.dao.DataAccessException e) {
LOGGER
.error(
"Error executing SQL '" +
sqlForRetrievingValues +
"'. Aborting cache refresh.",
e);
return;
}
// Create a new Map, populate it, and replace the old one. This allows
// for concurrent readying while the new Map is being created.
Map<String, String> keyValueMap = new HashMap<String, String>();
for(KeyAndValue currStateAndId : keyAndValue) {
keyValueMap.put(currStateAndId.key, currStateAndId.value);
}
this.keyValueMap = keyValueMap;
setLastUpdateTimestamp(System.currentTimeMillis());
}
|
diff --git a/Client/src/main/java/slideShow/Slideshow.java b/Client/src/main/java/slideShow/Slideshow.java
index 1af96ac..8663844 100644
--- a/Client/src/main/java/slideShow/Slideshow.java
+++ b/Client/src/main/java/slideShow/Slideshow.java
@@ -1,264 +1,264 @@
package slideShow;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.FadeTransition;
import javafx.animation.KeyFrame;
import javafx.animation.SequentialTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
import login.LoginWindow;
/**
*
* @author Morten
*/
public class Slideshow extends Application {
private StackPane root;
private SequentialTransition slideshow;
private ImageTransition imageTrans;
private ArrayList<ImageView> imageList;
private ListOfImages imageViewSetter;
private CheckNewDelay checkNewDelay;
private Task retrieveImages, checkDelay;
private Thread retrieveImagesThread, checkDelayThread;
private boolean startup = true;
private Button quit, menu;
private HBox box;
private double delayDiffFactor = 1.0;
private int delay;
private Stage stage;
private double yPos, xPos;
private Timeline timeline = null;
private FadeTransition fadeOut = null;
@Override
public void start(Stage stage1) throws Exception {
this.stage = stage1;
root = new StackPane();
slideshow = new SequentialTransition();
imageTrans = new ImageTransition();
imageList = new ArrayList();
checkNewDelay = new CheckNewDelay(imageTrans.getFadeTime() / 1000);
checkDelay = checkNewDelay.checkNewDelay();
delay = imageTrans.getDelay();
initiateRetrieveImagesThread();
initiateCheckDelayThread();
menu = new Button();
menu.setText("Admin Menu");
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
LoginWindow login = new LoginWindow(getSlideshowObject());
login.generateStage();
}
});
quit = new Button();
quit.setText("Quit Slideshow");
quit.setLayoutX(500);
quit.setLayoutY(500);
quit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Platform.exit();
}
});
box = new HBox(20);
box.setAlignment(Pos.BOTTOM_RIGHT);
box.setOpacity(0.0);
box.getChildren().add(quit);
box.getChildren().add(menu);
box.setStyle("../stylesheets/Menu.css");
/*
* Listener on mouse movement for buttons
*/
root.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
root.setCursor(Cursor.DEFAULT);
FadeTransition fadeIn = new FadeTransition(Duration.millis(1), box);
fadeIn.setFromValue(0.0);
fadeIn.setToValue(1.0);
- if (box.getOpacity() <= 0.1) {
+ if (box.getOpacity() <= 0.8) {
fadeIn.play();
} else {
//Do nothing
}
if (timeline != null || fadeOut != null) {
timeline.stop();
fadeOut.stop();
}
timeline = new Timeline(
new KeyFrame(Duration.seconds(3),
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
root.setCursor(Cursor.NONE);
- fadeOut = new FadeTransition(Duration.millis(1000), box);
+ fadeOut = new FadeTransition(Duration.millis(500), box);
fadeOut.setFromValue(1.0);
fadeOut.setToValue(0.0);
fadeOut.play();
}
}));
timeline.play();
}
});
root.getChildren().add(box);
/*
* Initiates stage and sets it visible
*/
stage = SlideShowWindow.getSlideShowWindow();
stage.setScene(new Scene(root, 800, 600, Color.BLACK));
stage.getScene().getStylesheets().add(this.getClass().getResource("/stylesheets/Slideshow.css").toExternalForm());
//Toggle Fullscreen
root.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2 && !event.isConsumed()) {
event.consume();
stage.setFullScreen(!stage.isFullScreen());
}
}
});
//Moving the window
root.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
xPos = event.getX();
yPos = event.getY();
}
});
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (!stage.isFullScreen()) {
stage.getScene().getWindow().setX(event.getScreenX() - xPos);
stage.getScene().getWindow().setY(event.getScreenY() - yPos);
}
}
});
stage.show();
startup = false;
}
/*
* Creates a new slideshow with updated preferrences
*/
public void initiateNewSlideshow() {
Duration timestamp = slideshow.getCurrentTime();
imageTrans.setNewDelay();
slideshow.stop();
root.getChildren().clear();
slideshow.getChildren().clear();
root.getChildren().add(box);
for (int i = 0; i < imageList.size(); i++) {
imageList.get(i).setOpacity(0);
root.getChildren().add(imageList.get(i));
slideshow.getChildren().add(imageTrans.getFullTransition(imageList.get(i)));
}
slideshow.setCycleCount(Timeline.INDEFINITE);
double tempDuration = (timestamp.toMillis() * delayDiffFactor);
slideshow.playFrom(new Duration(tempDuration));
delay = imageTrans.getDelay();
delayDiffFactor = 1.0;
System.out.println("initated new slideshow with " + imageList.size() + " images");
}
public void initiateCheckDelayThread() {
checkDelayThread = new Thread(checkDelay);
checkDelayThread.setDaemon(true);
checkDelayThread.start();
/*
* Listening on ready signal from Task: checkDelay
*/
checkDelay.messageProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
System.out.println(newValue);
delayDiffFactor = Double.parseDouble(checkDelay.messageProperty().getValue().split(" ")[4]);
initiateNewSlideshow();
}
});
}
public void initiateRetrieveImagesThread() {
System.out.println("Initiating new retreiveImagesThread");
if (!startup) {
imageViewSetter.setIsRunning(false);
try {
retrieveImagesThread.join();
} catch (InterruptedException ex) {
Logger.getLogger(Slideshow.class.getName()).log(Level.SEVERE, null, ex);
}
}
imageList.clear();
imageViewSetter = new ListOfImages(imageList);
retrieveImages = imageViewSetter.getImageViewList();
retrieveImagesThread = new Thread(retrieveImages);
retrieveImagesThread.setDaemon(true);
retrieveImagesThread.start();
/*
* Listening on ready signal from Task: retrieveImages
*/
retrieveImages.messageProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
initiateNewSlideshow();
}
});
}
public Slideshow getSlideshowObject() {
return this;
}
/*
* Main function
*/
public static void main(String[] args) {
launch(args);
}
}
| false | true | public void start(Stage stage1) throws Exception {
this.stage = stage1;
root = new StackPane();
slideshow = new SequentialTransition();
imageTrans = new ImageTransition();
imageList = new ArrayList();
checkNewDelay = new CheckNewDelay(imageTrans.getFadeTime() / 1000);
checkDelay = checkNewDelay.checkNewDelay();
delay = imageTrans.getDelay();
initiateRetrieveImagesThread();
initiateCheckDelayThread();
menu = new Button();
menu.setText("Admin Menu");
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
LoginWindow login = new LoginWindow(getSlideshowObject());
login.generateStage();
}
});
quit = new Button();
quit.setText("Quit Slideshow");
quit.setLayoutX(500);
quit.setLayoutY(500);
quit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Platform.exit();
}
});
box = new HBox(20);
box.setAlignment(Pos.BOTTOM_RIGHT);
box.setOpacity(0.0);
box.getChildren().add(quit);
box.getChildren().add(menu);
box.setStyle("../stylesheets/Menu.css");
/*
* Listener on mouse movement for buttons
*/
root.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
root.setCursor(Cursor.DEFAULT);
FadeTransition fadeIn = new FadeTransition(Duration.millis(1), box);
fadeIn.setFromValue(0.0);
fadeIn.setToValue(1.0);
if (box.getOpacity() <= 0.1) {
fadeIn.play();
} else {
//Do nothing
}
if (timeline != null || fadeOut != null) {
timeline.stop();
fadeOut.stop();
}
timeline = new Timeline(
new KeyFrame(Duration.seconds(3),
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
root.setCursor(Cursor.NONE);
fadeOut = new FadeTransition(Duration.millis(1000), box);
fadeOut.setFromValue(1.0);
fadeOut.setToValue(0.0);
fadeOut.play();
}
}));
timeline.play();
}
});
root.getChildren().add(box);
/*
* Initiates stage and sets it visible
*/
stage = SlideShowWindow.getSlideShowWindow();
stage.setScene(new Scene(root, 800, 600, Color.BLACK));
stage.getScene().getStylesheets().add(this.getClass().getResource("/stylesheets/Slideshow.css").toExternalForm());
//Toggle Fullscreen
root.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2 && !event.isConsumed()) {
event.consume();
stage.setFullScreen(!stage.isFullScreen());
}
}
});
//Moving the window
root.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
xPos = event.getX();
yPos = event.getY();
}
});
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (!stage.isFullScreen()) {
stage.getScene().getWindow().setX(event.getScreenX() - xPos);
stage.getScene().getWindow().setY(event.getScreenY() - yPos);
}
}
});
stage.show();
startup = false;
}
| public void start(Stage stage1) throws Exception {
this.stage = stage1;
root = new StackPane();
slideshow = new SequentialTransition();
imageTrans = new ImageTransition();
imageList = new ArrayList();
checkNewDelay = new CheckNewDelay(imageTrans.getFadeTime() / 1000);
checkDelay = checkNewDelay.checkNewDelay();
delay = imageTrans.getDelay();
initiateRetrieveImagesThread();
initiateCheckDelayThread();
menu = new Button();
menu.setText("Admin Menu");
menu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
LoginWindow login = new LoginWindow(getSlideshowObject());
login.generateStage();
}
});
quit = new Button();
quit.setText("Quit Slideshow");
quit.setLayoutX(500);
quit.setLayoutY(500);
quit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Platform.exit();
}
});
box = new HBox(20);
box.setAlignment(Pos.BOTTOM_RIGHT);
box.setOpacity(0.0);
box.getChildren().add(quit);
box.getChildren().add(menu);
box.setStyle("../stylesheets/Menu.css");
/*
* Listener on mouse movement for buttons
*/
root.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
root.setCursor(Cursor.DEFAULT);
FadeTransition fadeIn = new FadeTransition(Duration.millis(1), box);
fadeIn.setFromValue(0.0);
fadeIn.setToValue(1.0);
if (box.getOpacity() <= 0.8) {
fadeIn.play();
} else {
//Do nothing
}
if (timeline != null || fadeOut != null) {
timeline.stop();
fadeOut.stop();
}
timeline = new Timeline(
new KeyFrame(Duration.seconds(3),
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
root.setCursor(Cursor.NONE);
fadeOut = new FadeTransition(Duration.millis(500), box);
fadeOut.setFromValue(1.0);
fadeOut.setToValue(0.0);
fadeOut.play();
}
}));
timeline.play();
}
});
root.getChildren().add(box);
/*
* Initiates stage and sets it visible
*/
stage = SlideShowWindow.getSlideShowWindow();
stage.setScene(new Scene(root, 800, 600, Color.BLACK));
stage.getScene().getStylesheets().add(this.getClass().getResource("/stylesheets/Slideshow.css").toExternalForm());
//Toggle Fullscreen
root.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2 && !event.isConsumed()) {
event.consume();
stage.setFullScreen(!stage.isFullScreen());
}
}
});
//Moving the window
root.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
xPos = event.getX();
yPos = event.getY();
}
});
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (!stage.isFullScreen()) {
stage.getScene().getWindow().setX(event.getScreenX() - xPos);
stage.getScene().getWindow().setY(event.getScreenY() - yPos);
}
}
});
stage.show();
startup = false;
}
|
diff --git a/javasvn/src/org/tmatesoft/svn/core/wc/SVNDiffClient.java b/javasvn/src/org/tmatesoft/svn/core/wc/SVNDiffClient.java
index 5f057f0cb..586992f60 100644
--- a/javasvn/src/org/tmatesoft/svn/core/wc/SVNDiffClient.java
+++ b/javasvn/src/org/tmatesoft/svn/core/wc/SVNDiffClient.java
@@ -1,346 +1,346 @@
/*
* Created on 26.05.2005
*/
package org.tmatesoft.svn.core.wc;
import java.io.File;
import java.io.OutputStream;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.internal.wc.SVNDiffEditor;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.core.internal.wc.SVNRemoteDiffEditor;
import org.tmatesoft.svn.core.internal.wc.SVNReporter;
import org.tmatesoft.svn.core.internal.wc.SVNWCAccess;
import org.tmatesoft.svn.core.io.ISVNCredentialsProvider;
import org.tmatesoft.svn.core.io.ISVNReporter;
import org.tmatesoft.svn.core.io.ISVNReporterBaton;
import org.tmatesoft.svn.core.io.SVNException;
import org.tmatesoft.svn.core.io.SVNNodeKind;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepositoryLocation;
import org.tmatesoft.svn.util.DebugLog;
import org.tmatesoft.svn.util.PathUtil;
public class SVNDiffClient extends SVNBasicClient {
private ISVNDiffGenerator myDiffGenerator;
public SVNDiffClient(final ISVNCredentialsProvider credentials, ISVNEventListener eventDispatcher) {
super(new ISVNRepositoryFactory() {
public SVNRepository createRepository(String url) throws SVNException {
SVNRepository repos = SVNRepositoryFactory.create(SVNRepositoryLocation.parseURL(url));
repos.setCredentialsProvider(credentials);
return repos;
}
}, null, eventDispatcher);
}
public SVNDiffClient(ISVNRepositoryFactory repositoryFactory,
SVNOptions options, ISVNEventListener eventDispatcher) {
super(repositoryFactory, options, eventDispatcher);
}
public void setDiffGenerator(ISVNDiffGenerator diffGenerator) {
myDiffGenerator = diffGenerator;
}
public ISVNDiffGenerator getDiffGenerator() {
if (myDiffGenerator == null) {
myDiffGenerator = new DefaultSVNDiffGenerator();
}
return myDiffGenerator;
}
public void doDiff(File path, boolean recursive, final boolean useAncestry, final OutputStream result) throws SVNException {
doDiff(path, SVNRevision.BASE, SVNRevision.WORKING, recursive, useAncestry, result);
}
public void doDiff(String url, SVNRevision pegRevision, File path, SVNRevision rN, SVNRevision rM,
boolean recursive, final boolean useAncestry, final OutputStream result) throws SVNException {
SVNWCAccess wcAccess = SVNWCAccess.create(path);
String rootPath = wcAccess.getAnchor().getRoot().getAbsolutePath();
getDiffGenerator().init(rootPath, rootPath);
if (rM == SVNRevision.BASE || rM == SVNRevision.WORKING || !rM.isValid()) {
// URL->WC diff.
String wcURL = wcAccess.getAnchor().getEntries().getEntry("").getURL();
String target = "".equals(wcAccess.getTargetName()) ? null : wcAccess.getTargetName();
SVNRepository repos = createRepository(wcURL);
wcAccess.open(true, recursive);
SVNReporter reporter = new SVNReporter(wcAccess, recursive);
SVNDiffEditor editor = new SVNDiffEditor(wcAccess, getDiffGenerator(), useAncestry,
false /*reverse*/, rM == SVNRevision.BASE /*compare to base*/, result);
if (rN == null || !rN.isValid()) {
rN = SVNRevision.HEAD;
}
long revN = getRevisionNumber(url, rN);
try {
repos.diff(url, revN, target, !useAncestry, recursive, reporter, editor);
} finally {
wcAccess.close(true, recursive);
}
} else {
// URL:URL diff
String url2;
SVNRevision rev2;
try {
url2 = wcAccess.getTargetEntryProperty(SVNProperty.URL);
rev2 = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
} finally {
wcAccess.close(true, false);
}
getDiffGenerator().setBasePath(wcAccess.getAnchor().getRoot());
doDiff(url, pegRevision, url2, rev2, rN, rM, recursive, useAncestry, result);
}
}
public void doDiff(File path, String url, SVNRevision pegRevision, SVNRevision rN, SVNRevision rM,
boolean recursive, final boolean useAncestry, final OutputStream result) throws SVNException {
SVNWCAccess wcAccess = SVNWCAccess.create(path);
String rootPath = wcAccess.getAnchor().getRoot().getAbsolutePath();
getDiffGenerator().init(rootPath, rootPath);
if (rN == SVNRevision.BASE || rN == SVNRevision.WORKING || !rN.isValid()) {
// URL->WC diff.
String wcURL = wcAccess.getAnchor().getEntries().getEntry("").getURL();
String target = "".equals(wcAccess.getTargetName()) ? null : wcAccess.getTargetName();
SVNRepository repos = createRepository(wcURL);
wcAccess.open(true, recursive);
SVNReporter reporter = new SVNReporter(wcAccess, recursive);
SVNDiffEditor editor = new SVNDiffEditor(wcAccess, getDiffGenerator(), useAncestry,
true /*reverse*/, rM == SVNRevision.BASE /*compare to base*/, result);
if (rM == null || !rM.isValid()) {
rM = SVNRevision.HEAD;
}
long revM = getRevisionNumber(url, rM);
try {
repos.diff(url, revM, target, !useAncestry, recursive, reporter, editor);
} finally {
wcAccess.close(true, recursive);
}
} else {
String url1;
SVNRevision rev1;
try {
url1 = wcAccess.getTargetEntryProperty(SVNProperty.URL);
rev1 = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
} finally {
wcAccess.close(true, false);
}
getDiffGenerator().setBasePath(wcAccess.getAnchor().getRoot());
doDiff(url1, rev1, url, pegRevision, rN, rM, recursive, useAncestry, result);
}
}
public void doDiff(File path, File path2, SVNRevision rN, SVNRevision rM,
boolean recursive, final boolean useAncestry, final OutputStream result) throws SVNException {
rN = rN == null ? SVNRevision.UNDEFINED : rN;
rM = rM == null ? SVNRevision.UNDEFINED : rM;
if (path.equals(path2)) {
if (rN == SVNRevision.WORKING || rN == SVNRevision.BASE ||
rM == SVNRevision.WORKING || rM == SVNRevision.BASE ||
(!rM.isValid() && !rN.isValid())) {
doDiff(path, rN, rM, recursive, useAncestry, result);
} else {
// do not use pegs.
SVNWCAccess wcAccess = createWCAccess(path);
String url = wcAccess.getTargetEntryProperty(SVNProperty.URL);
long revN = getRevisionNumber(path, rN);
long revM = getRevisionNumber(path, rM);
getDiffGenerator().setBasePath(wcAccess.getAnchor().getRoot());
doDiff(url, SVNRevision.UNDEFINED, url, SVNRevision.UNDEFINED, SVNRevision.create(revN), SVNRevision.create(revM),
recursive, useAncestry, result);
}
return;
}
if (rN == SVNRevision.UNDEFINED) {
rN = SVNRevision.HEAD;
}
if (rM == SVNRevision.UNDEFINED) {
rM = SVNRevision.HEAD;
}
SVNWCAccess wcAccess = SVNWCAccess.create(path);
String url1;
SVNRevision peg1;
try {
url1 = wcAccess.getTargetEntryProperty(SVNProperty.URL);
} finally {
wcAccess.close(true, false);
}
SVNWCAccess wcAccess2 = SVNWCAccess.create(path2);
String rootPath = wcAccess2.getAnchor().getRoot().getAbsolutePath();
getDiffGenerator().init(rootPath, rootPath);
getDiffGenerator().setBasePath(wcAccess2.getAnchor().getRoot());
String url2;
try {
url2 = wcAccess2.getTargetEntryProperty(SVNProperty.URL);
} finally {
wcAccess.close(true, false);
}
long revN = getRevisionNumber(path, rN);
long revM = getRevisionNumber(path, rM);
doDiff(url1, SVNRevision.UNDEFINED, url2, SVNRevision.UNDEFINED, SVNRevision.create(revN), SVNRevision.create(revM),
recursive, useAncestry, result);
}
public void doDiff(String url1, SVNRevision pegRevision1, String url2, SVNRevision pegRevision2, SVNRevision rN, SVNRevision rM,
boolean recursive, final boolean useAncestry, final OutputStream result) throws SVNException {
DebugLog.log("diff: -r" + rN + ":" + rM + " " + url1 + "@" + pegRevision1 + " " + url2 + "@" + pegRevision2);
rN = rN == null || rN == SVNRevision.UNDEFINED ? SVNRevision.HEAD : rN;
rM = rM == null || rM == SVNRevision.UNDEFINED ? SVNRevision.HEAD : rM;
if (rN != SVNRevision.HEAD && rN.getNumber() < 0 && rN.getDate() == null) {
SVNErrorManager.error("svn: invalid revision: '" + rN + "'");
}
if (rM != SVNRevision.HEAD && rM.getNumber() < 0 && rM.getDate() == null) {
SVNErrorManager.error("svn: invalid revision: '" + rM + "'");
}
url1 = validateURL(url1);
url2 = validateURL(url2);
pegRevision1 = pegRevision1 == null ? SVNRevision.UNDEFINED : pegRevision1;
pegRevision2 = pegRevision2 == null ? SVNRevision.UNDEFINED : pegRevision2;
url1 = getURL(url1, pegRevision1, rN);
url2 = getURL(url2, pegRevision2, rM);
final long revN = getRevisionNumber(url1, rN);
final long revM = getRevisionNumber(url2, rM);
SVNRepository repos = createRepository(url1);
SVNNodeKind nodeKind = repos.checkPath("", revN);
if (nodeKind == SVNNodeKind.NONE) {
SVNErrorManager.error("svn: '" + url1 + "' was not found in the repository at revision " + revN);
}
SVNRepository repos2 = createRepository(url2);
SVNNodeKind nodeKind2 = repos2.checkPath("", revM);
if (nodeKind2 == SVNNodeKind.NONE) {
SVNErrorManager.error("svn: '" + url2 + "' was not found in the repository at revision " + revM);
}
String target = null;
if (nodeKind == SVNNodeKind.FILE || nodeKind2 == SVNNodeKind.FILE) {
target = PathUtil.tail(url1);
target = PathUtil.decode(target);
url1 = PathUtil.removeTail(url1);
repos = createRepository(url1);
}
File tmpFile = getDiffGenerator().createTempDirectory();
try {
SVNRemoteDiffEditor editor = new SVNRemoteDiffEditor(tmpFile,
getDiffGenerator(), repos, revN, result);
ISVNReporterBaton reporter = new ISVNReporterBaton() {
public void report(ISVNReporter reporter) throws SVNException {
reporter.setPath("", null, revN, false);
reporter.finishReport();
}
};
repos = createRepository(url1);
repos.diff(url2, revM, revN, target, !useAncestry, recursive, reporter, editor);
} finally {
if (tmpFile != null) {
SVNFileUtil.deleteAll(tmpFile);
}
}
}
public void doDiff(File path, SVNRevision rN, SVNRevision rM,
boolean recursive, final boolean useAncestry, final OutputStream result) throws SVNException {
if (rN == null || rN == SVNRevision.UNDEFINED) {
rN = SVNRevision.BASE;
}
if (rM == null || rM == SVNRevision.UNDEFINED) {
rM = SVNRevision.WORKING;
}
// cases:
// 1.1 wc-wc: BASE->WORKING
// 1.2 wc-wc: WORKING->BASE (reversed to 1.1)
// 2.1 wc-url: BASE:REV
// 2.2 wc-url: WORKING:REV
// 2.3 wc-url: REV:BASE (reversed to 2.1)
// 2.4 wc-url: REV:WORKING (reversed to 2.2)
// 3.1 url-url: REV:REV
// path should always point to valid wc dir or file.
// for 'REV' revisions there could be also 'peg revision' defined, used to get real WC url.
SVNWCAccess wcAccess = createWCAccess(path);
wcAccess.open(true, recursive);
try {
File originalPath = path;
path = wcAccess.getAnchor().getRoot().getAbsoluteFile();
getDiffGenerator().init(path.getAbsolutePath(), path.getAbsolutePath());
if (rN == SVNRevision.BASE && rM == SVNRevision.WORKING) {
// case 1.1
if (!"".equals(wcAccess.getTargetName())) {
if (wcAccess.getAnchor().getEntries().getEntry(wcAccess.getTargetName()) == null) {
SVNErrorManager.error("svn: path '" + originalPath.getAbsolutePath() + "' is not under version control");
}
}
SVNDiffEditor editor = new SVNDiffEditor(wcAccess, getDiffGenerator(), useAncestry, false, false, result);
editor.closeEdit();
- } else if (rN == SVNRevision.WORKING || rM == SVNRevision.BASE) {
+ } else if (rN == SVNRevision.WORKING && rM == SVNRevision.BASE) {
// case 1.2 (not supported)
SVNErrorManager.error("svn: not supported diff revisions range: '" + rN + ":" + rM + "'");
} else if (rN == SVNRevision.WORKING || rN == SVNRevision.BASE) {
// cases 2.1, 2.2
doWCReposDiff(wcAccess, rM, rN, true, recursive, useAncestry, result);
} else if (rM == SVNRevision.WORKING || rM == SVNRevision.BASE) {
// cases 2.3, 2.4
doWCReposDiff(wcAccess, rN, rM, false, recursive, useAncestry, result);
} else {
// rev:rev
long revN = getRevisionNumber(path, rN);
long revM = getRevisionNumber(path, rM);
SVNRevision wcRev = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
String url = wcAccess.getTargetEntryProperty(SVNProperty.URL);
if (wcAccess.getTargetEntryProperty(SVNProperty.COPYFROM_URL) != null) {
url = wcAccess.getTargetEntryProperty(SVNProperty.COPYFROM_URL);
}
String url1 = getURL(url, wcRev, SVNRevision.create(revN));
String url2 = getURL(url, wcRev, SVNRevision.create(revM));
SVNRevision pegRev = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
getDiffGenerator().setBasePath(wcAccess.getTarget().getRoot());
doDiff(url, pegRev, url, pegRev, SVNRevision.create(revN), SVNRevision.create(revM),
recursive, useAncestry, result);
}
} finally {
wcAccess.close(true, recursive);
}
}
private void doWCReposDiff(SVNWCAccess wcAccess, SVNRevision reposRev, SVNRevision localRev,
boolean reverse,
boolean recursive, boolean useAncestry, OutputStream result) throws SVNException {
String url = wcAccess.getTargetEntryProperty(SVNProperty.URL);
// get wc url and revision
url = wcAccess.getAnchor().getEntries().getEntry("").getURL();
String target = "".equals(wcAccess.getTargetName()) ? null : wcAccess.getTargetName();
SVNRevision wcRevNumber = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
SVNRepository repos = createRepository(url);
SVNReporter reporter = new SVNReporter(wcAccess, recursive);
SVNDiffEditor editor = new SVNDiffEditor(wcAccess, getDiffGenerator(), useAncestry,
reverse /*reverse*/, localRev == SVNRevision.BASE /*compare to base*/, result);
// get target url and revision, fetch target url location at desired target revision
long revNumber = getRevisionNumber(url, reposRev);
String targetURL = wcAccess.getTargetEntryProperty(SVNProperty.URL);
if (wcAccess.getTargetEntryProperty(SVNProperty.COPYFROM_URL) != null) {
targetURL = wcAccess.getTargetEntryProperty(SVNProperty.COPYFROM_URL);
}
targetURL = getURL(targetURL, wcRevNumber, SVNRevision.create(revNumber));
targetURL = PathUtil.decode(targetURL);
repos.diff(targetURL, revNumber, wcRevNumber.getNumber(), target, !useAncestry, recursive, reporter, editor);
}
}
| true | true | public void doDiff(File path, SVNRevision rN, SVNRevision rM,
boolean recursive, final boolean useAncestry, final OutputStream result) throws SVNException {
if (rN == null || rN == SVNRevision.UNDEFINED) {
rN = SVNRevision.BASE;
}
if (rM == null || rM == SVNRevision.UNDEFINED) {
rM = SVNRevision.WORKING;
}
// cases:
// 1.1 wc-wc: BASE->WORKING
// 1.2 wc-wc: WORKING->BASE (reversed to 1.1)
// 2.1 wc-url: BASE:REV
// 2.2 wc-url: WORKING:REV
// 2.3 wc-url: REV:BASE (reversed to 2.1)
// 2.4 wc-url: REV:WORKING (reversed to 2.2)
// 3.1 url-url: REV:REV
// path should always point to valid wc dir or file.
// for 'REV' revisions there could be also 'peg revision' defined, used to get real WC url.
SVNWCAccess wcAccess = createWCAccess(path);
wcAccess.open(true, recursive);
try {
File originalPath = path;
path = wcAccess.getAnchor().getRoot().getAbsoluteFile();
getDiffGenerator().init(path.getAbsolutePath(), path.getAbsolutePath());
if (rN == SVNRevision.BASE && rM == SVNRevision.WORKING) {
// case 1.1
if (!"".equals(wcAccess.getTargetName())) {
if (wcAccess.getAnchor().getEntries().getEntry(wcAccess.getTargetName()) == null) {
SVNErrorManager.error("svn: path '" + originalPath.getAbsolutePath() + "' is not under version control");
}
}
SVNDiffEditor editor = new SVNDiffEditor(wcAccess, getDiffGenerator(), useAncestry, false, false, result);
editor.closeEdit();
} else if (rN == SVNRevision.WORKING || rM == SVNRevision.BASE) {
// case 1.2 (not supported)
SVNErrorManager.error("svn: not supported diff revisions range: '" + rN + ":" + rM + "'");
} else if (rN == SVNRevision.WORKING || rN == SVNRevision.BASE) {
// cases 2.1, 2.2
doWCReposDiff(wcAccess, rM, rN, true, recursive, useAncestry, result);
} else if (rM == SVNRevision.WORKING || rM == SVNRevision.BASE) {
// cases 2.3, 2.4
doWCReposDiff(wcAccess, rN, rM, false, recursive, useAncestry, result);
} else {
// rev:rev
long revN = getRevisionNumber(path, rN);
long revM = getRevisionNumber(path, rM);
SVNRevision wcRev = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
String url = wcAccess.getTargetEntryProperty(SVNProperty.URL);
if (wcAccess.getTargetEntryProperty(SVNProperty.COPYFROM_URL) != null) {
url = wcAccess.getTargetEntryProperty(SVNProperty.COPYFROM_URL);
}
String url1 = getURL(url, wcRev, SVNRevision.create(revN));
String url2 = getURL(url, wcRev, SVNRevision.create(revM));
SVNRevision pegRev = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
getDiffGenerator().setBasePath(wcAccess.getTarget().getRoot());
doDiff(url, pegRev, url, pegRev, SVNRevision.create(revN), SVNRevision.create(revM),
recursive, useAncestry, result);
}
} finally {
wcAccess.close(true, recursive);
}
}
| public void doDiff(File path, SVNRevision rN, SVNRevision rM,
boolean recursive, final boolean useAncestry, final OutputStream result) throws SVNException {
if (rN == null || rN == SVNRevision.UNDEFINED) {
rN = SVNRevision.BASE;
}
if (rM == null || rM == SVNRevision.UNDEFINED) {
rM = SVNRevision.WORKING;
}
// cases:
// 1.1 wc-wc: BASE->WORKING
// 1.2 wc-wc: WORKING->BASE (reversed to 1.1)
// 2.1 wc-url: BASE:REV
// 2.2 wc-url: WORKING:REV
// 2.3 wc-url: REV:BASE (reversed to 2.1)
// 2.4 wc-url: REV:WORKING (reversed to 2.2)
// 3.1 url-url: REV:REV
// path should always point to valid wc dir or file.
// for 'REV' revisions there could be also 'peg revision' defined, used to get real WC url.
SVNWCAccess wcAccess = createWCAccess(path);
wcAccess.open(true, recursive);
try {
File originalPath = path;
path = wcAccess.getAnchor().getRoot().getAbsoluteFile();
getDiffGenerator().init(path.getAbsolutePath(), path.getAbsolutePath());
if (rN == SVNRevision.BASE && rM == SVNRevision.WORKING) {
// case 1.1
if (!"".equals(wcAccess.getTargetName())) {
if (wcAccess.getAnchor().getEntries().getEntry(wcAccess.getTargetName()) == null) {
SVNErrorManager.error("svn: path '" + originalPath.getAbsolutePath() + "' is not under version control");
}
}
SVNDiffEditor editor = new SVNDiffEditor(wcAccess, getDiffGenerator(), useAncestry, false, false, result);
editor.closeEdit();
} else if (rN == SVNRevision.WORKING && rM == SVNRevision.BASE) {
// case 1.2 (not supported)
SVNErrorManager.error("svn: not supported diff revisions range: '" + rN + ":" + rM + "'");
} else if (rN == SVNRevision.WORKING || rN == SVNRevision.BASE) {
// cases 2.1, 2.2
doWCReposDiff(wcAccess, rM, rN, true, recursive, useAncestry, result);
} else if (rM == SVNRevision.WORKING || rM == SVNRevision.BASE) {
// cases 2.3, 2.4
doWCReposDiff(wcAccess, rN, rM, false, recursive, useAncestry, result);
} else {
// rev:rev
long revN = getRevisionNumber(path, rN);
long revM = getRevisionNumber(path, rM);
SVNRevision wcRev = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
String url = wcAccess.getTargetEntryProperty(SVNProperty.URL);
if (wcAccess.getTargetEntryProperty(SVNProperty.COPYFROM_URL) != null) {
url = wcAccess.getTargetEntryProperty(SVNProperty.COPYFROM_URL);
}
String url1 = getURL(url, wcRev, SVNRevision.create(revN));
String url2 = getURL(url, wcRev, SVNRevision.create(revM));
SVNRevision pegRev = SVNRevision.parse(wcAccess.getTargetEntryProperty(SVNProperty.REVISION));
getDiffGenerator().setBasePath(wcAccess.getTarget().getRoot());
doDiff(url, pegRev, url, pegRev, SVNRevision.create(revN), SVNRevision.create(revM),
recursive, useAncestry, result);
}
} finally {
wcAccess.close(true, recursive);
}
}
|
diff --git a/MorePhysics/src/com/FriedTaco/taco/MorePhysics/MorePhysics.java b/MorePhysics/src/com/FriedTaco/taco/MorePhysics/MorePhysics.java
index 720808e..2c8c119 100644
--- a/MorePhysics/src/com/FriedTaco/taco/MorePhysics/MorePhysics.java
+++ b/MorePhysics/src/com/FriedTaco/taco/MorePhysics/MorePhysics.java
@@ -1,268 +1,268 @@
package com.FriedTaco.taco.MorePhysics;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.PluginManager;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
public class MorePhysics extends JavaPlugin {
public static final Logger log = Logger.getLogger("Minecraft");
private final HashMap<Player, Boolean> debugees = new HashMap<Player, Boolean>();
private final MorePhysicsPlayerListener playerListener = new MorePhysicsPlayerListener(this);
private final MorePhysicsVehicleListener VehicleListener = new MorePhysicsVehicleListener(this);
private final MorePhysicsBlockListener BlockListener = new MorePhysicsBlockListener(this);
public static ArrayList<Boat> sinking = new ArrayList<Boat>();
@SuppressWarnings("unused")
private static Yaml yaml = new Yaml(new SafeConstructor());
public static PermissionHandler Permissions;
public boolean movement,swimming,boats,pistons,exemptions,pistonsB;
public double lhat,lshirt,lpants,lboots,ihat,ishirt,ipants,iboots,ghat,gshirt,gpants,gboots,dhat,dshirt,dpants,dboots,chat,cshirt,cpants,cboots;
static String mainDirectory = "plugins/MorePhysics";
static File config = new File(mainDirectory + File.separator + "config.dat");
static Properties properties = new Properties();
private void setupPermissions() {
Plugin test = this.getServer().getPluginManager().getPlugin("Permissions");
if (MorePhysics.Permissions == null)
{
if (test != null) {
MorePhysics.Permissions = ((Permissions)test).getHandler();
System.out.println("[MorePhysics] Permissions detected. Now using permissions.");
} else {
System.out.println("[MorePhysics] Permissions NOT detected. Giving permission to ops.");
}
}
}
public void loadSettings() throws Exception
{
if (!this.getDataFolder().exists())
{
this.getDataFolder().mkdirs();
}
final String dir = "plugins/MorePhysics";
if (!new File(dir + File.separator + "MorePhysics.properties").exists()) {
FileWriter writer = null;
try {
writer = new FileWriter(dir + File.separator + "MorePhysics.properties");
- writer.write("MorePhysics v 1.3 configuration\r\n\n");
+ writer.write("MorePhysics v 1.4 configuration\r\n\n");
writer.write("#Allow boats to sink.\r\n");
writer.write("BoatsSink=true \r\n\n");
writer.write("#Allow armour to affect movement on land.\r\n");
writer.write("MovementAffected=true\r\n");
writer.write("#Allow armour to affect movement in water.\r\n");
writer.write("SwimmingAffected=true\r\n\n");
writer.write("#Allow pistons to launch players and other entities. (Mobs, dropped items, arrows, etc.)\r\n");
writer.write("PistonLaunch=true\r\n\n");
writer.write("#Allow pistons to launch blocks.\r\n");
writer.write("PistonLaunchBlocks=true\r\n\n");
writer.write("#Allow people to be exempt from physics (Requires permissions node)\r\n");
writer.write("AllowExemptions=true\r\n\n");
writer.write("#The following are the weights of armour.\r\n");
writer.write("#These are values out of 100 and are predefined by default.\r\n");
writer.write("#Tampering with these values may result in players becoming conscious of their weight.\r\n");
writer.write("Leather_Helm=2\r\n");
writer.write("Leather_Chest=10\r\n");
writer.write("Leather_Pants=8\r\n");
writer.write("Leather_Boots=2\r\n");
writer.write("Iron_Helm=20\r\n");
writer.write("Iron_Chest=60\r\n");
writer.write("Iron_Pants=40\r\n");
writer.write("Iron_Boots=20\r\n");
writer.write("Gold_Helm=40\r\n");
writer.write("Gold_Chest=80\r\n");
writer.write("Gold_Pants=70\r\n");
writer.write("Gold_Boots=40\r\n");
writer.write("Diamond_Helm=5\r\n");
writer.write("Diamond_Chest=30\r\n");
writer.write("Diamond_Pants=20\r\n");
writer.write("Diamond_Boots=5\r\n");
writer.write("Chain_Helm=10\r\n");
writer.write("Chain_Chest=50\r\n");
writer.write("Chain_Pants=30\r\n");
writer.write("Chain_Boots=10\r\n");
} catch (Exception e) {
log.log(Level.SEVERE,
"Exception while creating MorePhysics.properties", e);
try {
if (writer != null)
writer.close();
} catch (IOException ex) {
log
.log(
Level.SEVERE,
"Exception while closing writer for MorePhysics.properties",
ex);
}
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
log
.log(
Level.SEVERE,
"Exception while closing writer for MorePhysics.properties",
e);
}
}
}
PropertiesFile properties = new PropertiesFile(dir + File.separator + "MorePhysics.properties");
try {
boats = properties.getBoolean("BoatsSink", true);
swimming = properties.getBoolean("MovementAffected", true);
movement = properties.getBoolean("SwimmingAffected", true);
lhat = properties.getDouble("Leather_Helm",2)/1000;
lshirt = properties.getDouble("Leather_Chest",10)/1000;
lpants = properties.getDouble("Leather_Pants",8)/1000;
lboots = properties.getDouble("Leather_Boots",2)/1000;
ihat = properties.getDouble("Iron_Helm",20)/1000;
ishirt = properties.getDouble("Iron_Chest",60)/1000;
ipants = properties.getDouble("Iron_Pants",40)/1000;
iboots = properties.getDouble("Iron_Boots",20)/1000;
ghat = properties.getDouble("Gold_Helm",40)/1000;
gshirt = properties.getDouble("Gold_Chest",80)/1000;
gpants = properties.getDouble("Gold_Pants",70)/1000;
gboots = properties.getDouble("Gold_Boots",40)/1000;
dhat = properties.getDouble("Diamond_Helm",5)/1000;
dshirt = properties.getDouble("Diamond_Chest",30)/1000;
dpants = properties.getDouble("Diamond_Pants",20)/1000;
dboots = properties.getDouble("Diamond_Boots",5)/1000;
chat = properties.getDouble("Chain_Helm",10)/1000;
cshirt = properties.getDouble("Chain_Chest",50)/1000;
cpants = properties.getDouble("Chain_Pants",30)/1000;
cboots = properties.getDouble("Chain_Boots",10)/1000;
pistons = properties.getBoolean("PistonLaunch", true);
pistonsB = properties.getBoolean("PistonLaunchBlocks", true);
exemptions = properties.getBoolean("AllowExemptions", true);
} catch (Exception e) {
log.log(Level.SEVERE,
"Exception while reading from MorePhysics.properties", e);
}
}
public void onDisable() {
}
@Override
public void onEnable() {
try {
loadSettings();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.VEHICLE_DAMAGE, VehicleListener, Priority.Normal, this);
pm.registerEvent(Event.Type.VEHICLE_DESTROY, VehicleListener, Priority.Normal, this);
pm.registerEvent(Event.Type.VEHICLE_MOVE, VehicleListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, BlockListener, Priority.Normal, this);
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
setupPermissions();
}
public boolean isDebugging(final Player player) {
if (debugees.containsKey(player)) {
return debugees.get(player);
} else {
return false;
}
}
public void setDebugging(final Player player, final boolean value) {
debugees.put(player, value);
}
public void recordEvent(PlayerLoginEvent event) {
// TODO Auto-generated method stub
}
double weight(int id)
{
switch(id)
{
case 298:
return this.lhat;
case 299:
return this.lshirt;
case 300:
return this.lpants;
case 301:
return this.lboots;
case 302:
return this.chat;
case 303:
return this.cshirt;
case 304:
return this.cpants;
case 305:
return this.cboots;
case 306:
return this.ihat;
case 307:
return this.ishirt;
case 308:
return this.ipants;
case 309:
return this.iboots;
case 310:
return this.dhat;
case 311:
return this.dshirt;
case 312:
return this.dpants;
case 313:
return this.dboots;
case 314:
return this.ghat;
case 315:
return this.gshirt;
case 316:
return this.gpants;
case 317:
return this.gboots;
default:
return 0;
}
}
double getTotalWeight(Player player)
{
double modifier = 0;
for(ItemStack i : player.getInventory().getArmorContents())
{
if(i != null)
modifier += weight(i.getTypeId());
}
return modifier;
}
}
| true | true | public void loadSettings() throws Exception
{
if (!this.getDataFolder().exists())
{
this.getDataFolder().mkdirs();
}
final String dir = "plugins/MorePhysics";
if (!new File(dir + File.separator + "MorePhysics.properties").exists()) {
FileWriter writer = null;
try {
writer = new FileWriter(dir + File.separator + "MorePhysics.properties");
writer.write("MorePhysics v 1.3 configuration\r\n\n");
writer.write("#Allow boats to sink.\r\n");
writer.write("BoatsSink=true \r\n\n");
writer.write("#Allow armour to affect movement on land.\r\n");
writer.write("MovementAffected=true\r\n");
writer.write("#Allow armour to affect movement in water.\r\n");
writer.write("SwimmingAffected=true\r\n\n");
writer.write("#Allow pistons to launch players and other entities. (Mobs, dropped items, arrows, etc.)\r\n");
writer.write("PistonLaunch=true\r\n\n");
writer.write("#Allow pistons to launch blocks.\r\n");
writer.write("PistonLaunchBlocks=true\r\n\n");
writer.write("#Allow people to be exempt from physics (Requires permissions node)\r\n");
writer.write("AllowExemptions=true\r\n\n");
writer.write("#The following are the weights of armour.\r\n");
writer.write("#These are values out of 100 and are predefined by default.\r\n");
writer.write("#Tampering with these values may result in players becoming conscious of their weight.\r\n");
writer.write("Leather_Helm=2\r\n");
writer.write("Leather_Chest=10\r\n");
writer.write("Leather_Pants=8\r\n");
writer.write("Leather_Boots=2\r\n");
writer.write("Iron_Helm=20\r\n");
writer.write("Iron_Chest=60\r\n");
writer.write("Iron_Pants=40\r\n");
writer.write("Iron_Boots=20\r\n");
writer.write("Gold_Helm=40\r\n");
writer.write("Gold_Chest=80\r\n");
writer.write("Gold_Pants=70\r\n");
writer.write("Gold_Boots=40\r\n");
writer.write("Diamond_Helm=5\r\n");
writer.write("Diamond_Chest=30\r\n");
writer.write("Diamond_Pants=20\r\n");
writer.write("Diamond_Boots=5\r\n");
writer.write("Chain_Helm=10\r\n");
writer.write("Chain_Chest=50\r\n");
writer.write("Chain_Pants=30\r\n");
writer.write("Chain_Boots=10\r\n");
} catch (Exception e) {
log.log(Level.SEVERE,
"Exception while creating MorePhysics.properties", e);
try {
if (writer != null)
writer.close();
} catch (IOException ex) {
log
.log(
Level.SEVERE,
"Exception while closing writer for MorePhysics.properties",
ex);
}
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
log
.log(
Level.SEVERE,
"Exception while closing writer for MorePhysics.properties",
e);
}
}
}
PropertiesFile properties = new PropertiesFile(dir + File.separator + "MorePhysics.properties");
try {
boats = properties.getBoolean("BoatsSink", true);
swimming = properties.getBoolean("MovementAffected", true);
movement = properties.getBoolean("SwimmingAffected", true);
lhat = properties.getDouble("Leather_Helm",2)/1000;
lshirt = properties.getDouble("Leather_Chest",10)/1000;
lpants = properties.getDouble("Leather_Pants",8)/1000;
lboots = properties.getDouble("Leather_Boots",2)/1000;
ihat = properties.getDouble("Iron_Helm",20)/1000;
ishirt = properties.getDouble("Iron_Chest",60)/1000;
ipants = properties.getDouble("Iron_Pants",40)/1000;
iboots = properties.getDouble("Iron_Boots",20)/1000;
ghat = properties.getDouble("Gold_Helm",40)/1000;
gshirt = properties.getDouble("Gold_Chest",80)/1000;
gpants = properties.getDouble("Gold_Pants",70)/1000;
gboots = properties.getDouble("Gold_Boots",40)/1000;
dhat = properties.getDouble("Diamond_Helm",5)/1000;
dshirt = properties.getDouble("Diamond_Chest",30)/1000;
dpants = properties.getDouble("Diamond_Pants",20)/1000;
dboots = properties.getDouble("Diamond_Boots",5)/1000;
chat = properties.getDouble("Chain_Helm",10)/1000;
cshirt = properties.getDouble("Chain_Chest",50)/1000;
cpants = properties.getDouble("Chain_Pants",30)/1000;
cboots = properties.getDouble("Chain_Boots",10)/1000;
pistons = properties.getBoolean("PistonLaunch", true);
pistonsB = properties.getBoolean("PistonLaunchBlocks", true);
exemptions = properties.getBoolean("AllowExemptions", true);
} catch (Exception e) {
log.log(Level.SEVERE,
"Exception while reading from MorePhysics.properties", e);
}
}
| public void loadSettings() throws Exception
{
if (!this.getDataFolder().exists())
{
this.getDataFolder().mkdirs();
}
final String dir = "plugins/MorePhysics";
if (!new File(dir + File.separator + "MorePhysics.properties").exists()) {
FileWriter writer = null;
try {
writer = new FileWriter(dir + File.separator + "MorePhysics.properties");
writer.write("MorePhysics v 1.4 configuration\r\n\n");
writer.write("#Allow boats to sink.\r\n");
writer.write("BoatsSink=true \r\n\n");
writer.write("#Allow armour to affect movement on land.\r\n");
writer.write("MovementAffected=true\r\n");
writer.write("#Allow armour to affect movement in water.\r\n");
writer.write("SwimmingAffected=true\r\n\n");
writer.write("#Allow pistons to launch players and other entities. (Mobs, dropped items, arrows, etc.)\r\n");
writer.write("PistonLaunch=true\r\n\n");
writer.write("#Allow pistons to launch blocks.\r\n");
writer.write("PistonLaunchBlocks=true\r\n\n");
writer.write("#Allow people to be exempt from physics (Requires permissions node)\r\n");
writer.write("AllowExemptions=true\r\n\n");
writer.write("#The following are the weights of armour.\r\n");
writer.write("#These are values out of 100 and are predefined by default.\r\n");
writer.write("#Tampering with these values may result in players becoming conscious of their weight.\r\n");
writer.write("Leather_Helm=2\r\n");
writer.write("Leather_Chest=10\r\n");
writer.write("Leather_Pants=8\r\n");
writer.write("Leather_Boots=2\r\n");
writer.write("Iron_Helm=20\r\n");
writer.write("Iron_Chest=60\r\n");
writer.write("Iron_Pants=40\r\n");
writer.write("Iron_Boots=20\r\n");
writer.write("Gold_Helm=40\r\n");
writer.write("Gold_Chest=80\r\n");
writer.write("Gold_Pants=70\r\n");
writer.write("Gold_Boots=40\r\n");
writer.write("Diamond_Helm=5\r\n");
writer.write("Diamond_Chest=30\r\n");
writer.write("Diamond_Pants=20\r\n");
writer.write("Diamond_Boots=5\r\n");
writer.write("Chain_Helm=10\r\n");
writer.write("Chain_Chest=50\r\n");
writer.write("Chain_Pants=30\r\n");
writer.write("Chain_Boots=10\r\n");
} catch (Exception e) {
log.log(Level.SEVERE,
"Exception while creating MorePhysics.properties", e);
try {
if (writer != null)
writer.close();
} catch (IOException ex) {
log
.log(
Level.SEVERE,
"Exception while closing writer for MorePhysics.properties",
ex);
}
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
log
.log(
Level.SEVERE,
"Exception while closing writer for MorePhysics.properties",
e);
}
}
}
PropertiesFile properties = new PropertiesFile(dir + File.separator + "MorePhysics.properties");
try {
boats = properties.getBoolean("BoatsSink", true);
swimming = properties.getBoolean("MovementAffected", true);
movement = properties.getBoolean("SwimmingAffected", true);
lhat = properties.getDouble("Leather_Helm",2)/1000;
lshirt = properties.getDouble("Leather_Chest",10)/1000;
lpants = properties.getDouble("Leather_Pants",8)/1000;
lboots = properties.getDouble("Leather_Boots",2)/1000;
ihat = properties.getDouble("Iron_Helm",20)/1000;
ishirt = properties.getDouble("Iron_Chest",60)/1000;
ipants = properties.getDouble("Iron_Pants",40)/1000;
iboots = properties.getDouble("Iron_Boots",20)/1000;
ghat = properties.getDouble("Gold_Helm",40)/1000;
gshirt = properties.getDouble("Gold_Chest",80)/1000;
gpants = properties.getDouble("Gold_Pants",70)/1000;
gboots = properties.getDouble("Gold_Boots",40)/1000;
dhat = properties.getDouble("Diamond_Helm",5)/1000;
dshirt = properties.getDouble("Diamond_Chest",30)/1000;
dpants = properties.getDouble("Diamond_Pants",20)/1000;
dboots = properties.getDouble("Diamond_Boots",5)/1000;
chat = properties.getDouble("Chain_Helm",10)/1000;
cshirt = properties.getDouble("Chain_Chest",50)/1000;
cpants = properties.getDouble("Chain_Pants",30)/1000;
cboots = properties.getDouble("Chain_Boots",10)/1000;
pistons = properties.getBoolean("PistonLaunch", true);
pistonsB = properties.getBoolean("PistonLaunchBlocks", true);
exemptions = properties.getBoolean("AllowExemptions", true);
} catch (Exception e) {
log.log(Level.SEVERE,
"Exception while reading from MorePhysics.properties", e);
}
}
|
diff --git a/copenhagenabm/src/repastcity3/environment/NetworkEdgeCreator.java b/copenhagenabm/src/repastcity3/environment/NetworkEdgeCreator.java
index b9a4a6e..1f815b2 100644
--- a/copenhagenabm/src/repastcity3/environment/NetworkEdgeCreator.java
+++ b/copenhagenabm/src/repastcity3/environment/NetworkEdgeCreator.java
@@ -1,50 +1,50 @@
/*
�Copyright 2012 Nick Malleson
This file is part of RepastCity.
RepastCity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RepastCity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RepastCity. If not, see <http://www.gnu.org/licenses/>.
*/
package repastcity3.environment;
import java.util.Arrays;
import repast.simphony.space.graph.EdgeCreator;
public class NetworkEdgeCreator <T> implements EdgeCreator<NetworkEdge<T>, T> {
/**
* Creates an Edge with the specified source, target, direction and weight.
*
* @param source the edge source
* @param target the edge target
* @param isDirected whether or not the edge is directed
* @param weight the weight of the edge
* @return the created edge.
*/
public NetworkEdge<T> createEdge(T source, T target, boolean isDirected, double weight) {
- return new NetworkEdge<T>(source, target, isDirected, weight, Arrays.asList(new String[] {"testingEdgeCreator"}));
+ return new NetworkEdge<T>(source, target, isDirected, weight);
}
/**
* Gets the edge type produced by this EdgeCreator.
*
* @return the edge type produced by this EdgeCreator.
*/
@SuppressWarnings("rawtypes")
public Class<NetworkEdge> getEdgeType() {
return NetworkEdge.class;
}
}
| true | true | public NetworkEdge<T> createEdge(T source, T target, boolean isDirected, double weight) {
return new NetworkEdge<T>(source, target, isDirected, weight, Arrays.asList(new String[] {"testingEdgeCreator"}));
}
| public NetworkEdge<T> createEdge(T source, T target, boolean isDirected, double weight) {
return new NetworkEdge<T>(source, target, isDirected, weight);
}
|
diff --git a/ui/web/IdentityEditor.java b/ui/web/IdentityEditor.java
index 3ea018d3..153b3181 100644
--- a/ui/web/IdentityEditor.java
+++ b/ui/web/IdentityEditor.java
@@ -1,307 +1,307 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.Freetalk.ui.web;
import java.util.Iterator;
import plugins.Freetalk.FTIdentity;
import plugins.Freetalk.FTOwnIdentity;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
/**
*
* @author xor, saces
*/
public final class IdentityEditor extends WebPageImpl {
public IdentityEditor(WebInterface myWebInterface, FTOwnIdentity viewer, HTTPRequest request) {
super(myWebInterface, viewer, request);
// TODO Auto-generated constructor stub
}
public final void make() {
makeOwnIdentitiesBox();
makeKnownIdentitiesBox();
}
private final void makeOwnIdentitiesBox() {
- HTMLNode box = getContentBox("Own Identities");
+ HTMLNode box = addContentBox("Own Identities");
Iterator<FTOwnIdentity> ownIdentities = mFreetalk.getIdentityManager().ownIdentityIterator();
if (ownIdentities.hasNext() == false) {
box.addChild("p", "No own identities received from the WoT plugin yet. Please create one there and wait for 15 minutes until it appears here.");
} else {
HTMLNode identitiesTable = box.addChild("table");
HTMLNode row = identitiesTable.addChild("tr");
row.addChild("th", "Name");
row.addChild("th", "Freetalk address");
while (ownIdentities.hasNext()) {
FTOwnIdentity id = ownIdentities.next();
row = identitiesTable.addChild("tr");
row.addChild("td", id.getNickname());
row.addChild("td", id.getFreetalkAddress());
/*
HTMLNode lastUpdateCell = row.addChild("td");
if (id.getLastInsert() == null) {
lastUpdateCell.addChild("p", "Insert in progress...");
} else if (id.getLastInsert().equals(new Date(0))) {
lastUpdateCell.addChild("p", "Never");
} else {
lastUpdateCell.addChild(new HTMLNode("a", "href", "/" + id.getRequestURI().toString(), id.getLastInsert().toString()));
}
*/
/* FIXME: repair, i.e. make it use the WoT plugin */
/*
HTMLNode deleteCell = row.addChild("td");
HTMLNode deleteForm = ft.mPluginRespirator.addFormChild(deleteCell, Freetalk.PLUGIN_URI + "/deleteOwnIdentity", "deleteForm");
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "identity", id.getRequestURI().toACIIString()});
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "delete", "Delete" });
*/
}
}
/* FIXME: repair, i.e. make it use the WoT plugin */
/* contentNode.addChild(createNewOwnIdentityBox(ft)); */
}
private final void makeKnownIdentitiesBox() {
HTMLNode box = getContentBox("Known Identities");
HTMLNode identitiesTable = box.addChild("table", "border", "0");
HTMLNode row = identitiesTable.addChild("tr");
row.addChild("th", "Name");
row.addChild("th", "Freetalk address");
//row.addChild("th");
for(FTIdentity id : mFreetalk.getIdentityManager().getAllIdentities()) {
if (id instanceof FTOwnIdentity)
continue;
row = identitiesTable.addChild("tr");
row.addChild("td", id.getNickname());
row.addChild("td", id.getFreetalkAddress());
//HTMLNode deleteCell = row.addChild("td");
/* FIXME: repair, i.e. make it use the WoT plugin */
/*
HTMLNode deleteForm = ft.mPluginRespirator.addFormChild(deleteCell, Freetalk.PLUGIN_URI + "/deleteIdentity", "deleteForm");
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "identity", id.getRequestURI().toACIIString()});
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "delete", "Delete" });
*/
}
/* FIXME: repair, i.e. make it use the WoT plugin */
/* contentNode.addChild(createNewKnownIdentityBox(ft)); */
}
/* === new own identity ================== */
/*
public static final String makeNewOwnIdentityPage(Freetalk ft, String nick, String requestUri, String insertUri, boolean publish, List<String> errors) {
HTMLNode pageNode = ft.getPageNode();
HTMLNode contentNode = ft.mPageMaker.getContentNode(pageNode);
contentNode.addChild(createNewOwnIdentityBox(ft, nick, requestUri, insertUri, publish, errors));
return pageNode.generate();
}
private static final HTMLNode createNewOwnIdentityBox(Freetalk ft) {
return createNewOwnIdentityBox(ft, "", "", "", true, null);
}
private static final HTMLNode createNewOwnIdentityBox(Freetalk ft, String nick, String requestUri, String insertUri, boolean publish, List<String> errors) {
HTMLNode addBox = ft.mPageMaker.getInfobox("New Identity");
HTMLNode addContent = ft.mPageMaker.getContentNode(addBox);
if (errors != null) {
HTMLNode errorBox = ft.mPageMaker.getInfobox("infobox-alert", "Typo");
HTMLNode errorContent = ft.mPageMaker.getContentNode(errorBox);
for (String s : errors) {
errorContent.addChild("#", s);
errorContent.addChild("br");
}
addContent.addChild(errorBox);
}
HTMLNode addForm = ft.mPluginRespirator.addFormChild(addContent, Freetalk.PLUGIN_URI + "/createownidentity", "addForm");
HTMLNode table = addForm.addChild("table", "class", "column");
HTMLNode tr1 = table.addChild("tr");
tr1.addChild("td", "width", "10%", "Nick:\u00a0");
HTMLNode cell12 = tr1.addChild("td", "width", "90%");
cell12.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "nick", "70", nick });
HTMLNode tr2 = table.addChild("tr");
tr2.addChild("td", "Request\u00a0URI:\u00a0");
HTMLNode cell22= tr2.addChild("td");
cell22.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "requestURI", "70", requestUri });
HTMLNode tr3 = table.addChild("tr");
tr3.addChild("td", "Insert\u00a0URI:\u00a0");
HTMLNode cell32= tr3.addChild("td");
cell32.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "insertURI", "70", insertUri });
HTMLNode tr4 = table.addChild("tr");
tr4.addChild("td", "Publish\u00a0trust\u00a0list:\u00a0");
HTMLNode cell42= tr4.addChild("td");
if (publish)
cell42.addChild("input", new String[] { "type", "name", "value", "checked" }, new String[] { "checkbox", "publishTrustList", "true", "checked" });
else
cell42.addChild("input", new String[] { "type", "name", "value" }, new String[] { "checkbox", "publishTrustList", "false" });
addForm.addChild("br");
addForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "create", "Create a new identity !" });
return addBox;
}
*/
/* === delete own identity =============== */
/*
public static String makeDeleteOwnIdentityPage(Freetalk ft, String requestUri, List<String> err) {
HTMLNode pageNode = ft.getPageNode();
HTMLNode contentNode = ft.mPageMaker.getContentNode(pageNode);
contentNode.addChild(deleteOwnIdentityBox(ft, "nick", requestUri, "insertUri", false, err));
return pageNode.generate();
}
private static final HTMLNode deleteOwnIdentityBox(Freetalk ft, String nick, String requestUri, String insertUri, boolean publish, List<String> errors) {
HTMLNode deleteBox = ft.mPageMaker.getInfobox("Delete Identity");
HTMLNode deleteContent = ft.mPageMaker.getContentNode(deleteBox);
if (errors != null) {
HTMLNode errorBox = ft.mPageMaker.getInfobox("infobox-alert", "Typo");
HTMLNode errorContent = ft.mPageMaker.getContentNode(errorBox);
for (String s : errors) {
errorContent.addChild("#", s);
errorContent.addChild("br");
}
deleteContent.addChild(errorBox);
}
HTMLNode deleteForm = ft.mPluginRespirator.addFormChild(deleteContent, Freetalk.PLUGIN_URI + "/deleteOwnIdentity", "deleteForm");
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "confirmed", "true"});
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "identity", requestUri});
deleteForm.addChild("#", "Nick:\u00a0"+nick);
deleteForm.addChild("br");
deleteForm.addChild("#", "Request URI:\u00a0"+requestUri);
deleteForm.addChild("br");
deleteForm.addChild("#", "Insert URI:\u00a0"+insertUri);
deleteForm.addChild("br");
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "delete", "Delete identity" });
return deleteBox;
}
*/
/* === new others identities ============= */
/*
public static final String makeNewKnownIdentityPage(Freetalk ft, String requestUri, List<String> errors) {
HTMLNode pageNode = ft.getPageNode();
HTMLNode contentNode = ft.mPageMaker.getContentNode(pageNode);
contentNode.addChild(createNewKnownIdentityBox(ft, requestUri, errors));
contentNode.addChild("#", "makeNewIdentitiesPagecc");
return pageNode.generate();
}
private static final HTMLNode createNewKnownIdentityBox(Freetalk ft) {
return createNewKnownIdentityBox(ft, "", null);
}
private static final HTMLNode createNewKnownIdentityBox(Freetalk ft, String requestUri, List<String> errors) {
HTMLNode addBox = ft.mPageMaker.getInfobox("Add Identity");
HTMLNode addContent = ft.mPageMaker.getContentNode(addBox);
if (errors != null) {
HTMLNode errorBox = ft.mPageMaker.getInfobox("infobox-alert", "Typo");
HTMLNode errorContent = ft.mPageMaker.getContentNode(errorBox);
for (String s : errors) {
errorContent.addChild("#", s);
errorContent.addChild("br");
}
addContent.addChild(errorBox);
}
HTMLNode addForm = ft.mPluginRespirator.addFormChild(addContent, Freetalk.PLUGIN_URI + "/addknownidentity", "addForm");
addForm.addChild("#", "Request URI : ");
addForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "requestURI", "70", requestUri });
addForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "create", "Add identity !" });
return addBox;
}
*/
/* delete */
/*
public static String makeDeleteKnownIdentityPage(Freetalk ft, String requestUri, List<String> err) {
HTMLNode pageNode = ft.getPageNode();
HTMLNode contentNode = ft.mPageMaker.getContentNode(pageNode);
contentNode.addChild(deleteKnownIdentityBox(ft, "nick", requestUri, "insertUri", false, err));
return pageNode.generate();
}
private static final HTMLNode deleteKnownIdentityBox(Freetalk ft, String nick, String requestUri, String insertUri, boolean publish, List<String> errors) {
HTMLNode deleteBox = ft.mPageMaker.getInfobox("Delete Identity");
HTMLNode deleteContent = ft.mPageMaker.getContentNode(deleteBox);
if (errors != null) {
HTMLNode errorBox = ft.mPageMaker.getInfobox("infobox-alert", "Typo");
HTMLNode errorContent = ft.mPageMaker.getContentNode(errorBox);
for (String s : errors) {
errorContent.addChild("#", s);
errorContent.addChild("br");
}
deleteContent.addChild(errorBox);
}
HTMLNode deleteForm = ft.mPluginRespirator.addFormChild(deleteContent, Freetalk.PLUGIN_URI + "/deleteIdentity", "deleteForm");
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "confirmed", "true"});
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "identity", requestUri});
deleteForm.addChild("#", "Nick:\u00a0"+nick);
deleteForm.addChild("br");
deleteForm.addChild("#", "Request URI:\u00a0"+requestUri);
deleteForm.addChild("br");
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "delete", "Delete identity" });
return deleteBox;
}
public static final void checkInsertURI(List<String> err, String insertUri) {
if (insertUri.length() == 0) {
err.add("Insert URI is missing");
return;
}
}
public static final void checkRequestURI(List<String> err, String requestUri) {
if (requestUri.length() == 0) {
err.add("Request URI is missing");
return;
}
}
public static final void addNewOwnIdentity(Freetalk ft, FTOwnIdentity identity, List<String> err) {
try {
ft.getIdentityManager().addNewOwnIdentity(identity);
} catch (Throwable t) {
Logger.error(IdentityEditor.class, "Error while adding Identity: " + t.getMessage(), t);
err.add("Error while adding Identity: " + t.getMessage());
}
}
public static final void addNewKnownIdentity(Freetalk ft, FTIdentity identity, List<String> err) {
try {
ft.getIdentityManager().addNewIdentity(identity);
} catch (Throwable t) {
Logger.error(IdentityEditor.class, "Error while adding Identity: " + t.getMessage(), t);
err.add("Error while adding Identity: " + t.getMessage());
}
}
*/
}
| true | true | private final void makeOwnIdentitiesBox() {
HTMLNode box = getContentBox("Own Identities");
Iterator<FTOwnIdentity> ownIdentities = mFreetalk.getIdentityManager().ownIdentityIterator();
if (ownIdentities.hasNext() == false) {
box.addChild("p", "No own identities received from the WoT plugin yet. Please create one there and wait for 15 minutes until it appears here.");
} else {
HTMLNode identitiesTable = box.addChild("table");
HTMLNode row = identitiesTable.addChild("tr");
row.addChild("th", "Name");
row.addChild("th", "Freetalk address");
while (ownIdentities.hasNext()) {
FTOwnIdentity id = ownIdentities.next();
row = identitiesTable.addChild("tr");
row.addChild("td", id.getNickname());
row.addChild("td", id.getFreetalkAddress());
/*
HTMLNode lastUpdateCell = row.addChild("td");
if (id.getLastInsert() == null) {
lastUpdateCell.addChild("p", "Insert in progress...");
} else if (id.getLastInsert().equals(new Date(0))) {
lastUpdateCell.addChild("p", "Never");
} else {
lastUpdateCell.addChild(new HTMLNode("a", "href", "/" + id.getRequestURI().toString(), id.getLastInsert().toString()));
}
*/
/* FIXME: repair, i.e. make it use the WoT plugin */
/*
HTMLNode deleteCell = row.addChild("td");
HTMLNode deleteForm = ft.mPluginRespirator.addFormChild(deleteCell, Freetalk.PLUGIN_URI + "/deleteOwnIdentity", "deleteForm");
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "identity", id.getRequestURI().toACIIString()});
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "delete", "Delete" });
*/
}
| private final void makeOwnIdentitiesBox() {
HTMLNode box = addContentBox("Own Identities");
Iterator<FTOwnIdentity> ownIdentities = mFreetalk.getIdentityManager().ownIdentityIterator();
if (ownIdentities.hasNext() == false) {
box.addChild("p", "No own identities received from the WoT plugin yet. Please create one there and wait for 15 minutes until it appears here.");
} else {
HTMLNode identitiesTable = box.addChild("table");
HTMLNode row = identitiesTable.addChild("tr");
row.addChild("th", "Name");
row.addChild("th", "Freetalk address");
while (ownIdentities.hasNext()) {
FTOwnIdentity id = ownIdentities.next();
row = identitiesTable.addChild("tr");
row.addChild("td", id.getNickname());
row.addChild("td", id.getFreetalkAddress());
/*
HTMLNode lastUpdateCell = row.addChild("td");
if (id.getLastInsert() == null) {
lastUpdateCell.addChild("p", "Insert in progress...");
} else if (id.getLastInsert().equals(new Date(0))) {
lastUpdateCell.addChild("p", "Never");
} else {
lastUpdateCell.addChild(new HTMLNode("a", "href", "/" + id.getRequestURI().toString(), id.getLastInsert().toString()));
}
*/
/* FIXME: repair, i.e. make it use the WoT plugin */
/*
HTMLNode deleteCell = row.addChild("td");
HTMLNode deleteForm = ft.mPluginRespirator.addFormChild(deleteCell, Freetalk.PLUGIN_URI + "/deleteOwnIdentity", "deleteForm");
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "identity", id.getRequestURI().toACIIString()});
deleteForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "delete", "Delete" });
*/
}
|
diff --git a/org.amanzi.neo.loader.ui/src/org/amanzi/neo/loader/ui/preferences/DataLoadPreferenceInitializer.java b/org.amanzi.neo.loader.ui/src/org/amanzi/neo/loader/ui/preferences/DataLoadPreferenceInitializer.java
index 9ab346a5c..c99422287 100644
--- a/org.amanzi.neo.loader.ui/src/org/amanzi/neo/loader/ui/preferences/DataLoadPreferenceInitializer.java
+++ b/org.amanzi.neo.loader.ui/src/org/amanzi/neo/loader/ui/preferences/DataLoadPreferenceInitializer.java
@@ -1,233 +1,233 @@
/* AWE - Amanzi Wireless Explorer
* http://awe.amanzi.org
* (C) 2008-2009, AmanziTel AB
*
* This library is provided under the terms of the Eclipse Public License
* as described at http://www.eclipse.org/legal/epl-v10.html. Any use,
* reproduction or distribution of the library constitutes recipient's
* acceptance of this agreement.
*
* This library is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.amanzi.neo.loader.ui.preferences;
import java.nio.charset.Charset;
import org.amanzi.neo.loader.core.preferences.DataLoadPreferences;
import org.amanzi.neo.loader.core.preferences.PreferenceStore;
import org.amanzi.neo.loader.ui.NeoLoaderPlugin;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import org.geotools.referencing.CRS;
/**
* <p>
* Preference initializer
* </p>
*
* @author Cinkel_A
* @since 1.0.0
*/
public class DataLoadPreferenceInitializer extends AbstractPreferenceInitializer {
private static class StoreWrapper{
IPreferenceStore pref = NeoLoaderPlugin.getDefault().getPreferenceStore();
PreferenceStore store = PreferenceStore.getPreferenceStore();
/**
* Sets the default value for the double-valued preference with the
* given name.
* <p>
* Note that the current value of the preference is affected if
* the preference's current value was its old default value, in which
* case it changes to the new default value. If the preference's current
* is different from its old default value, its current value is
* unaffected. No property change events are reported by changing default
* values.
* </p>
*
* @param name the name of the preference
* @param value the new default value for the preference
*/
public void setDefault(String name, double value){
pref.setDefault(name, value);
store.setProperty(name,value);
}
/**
* Sets the default value for the float-valued preference with the
* given name.
* <p>
* Note that the current value of the preference is affected if
* the preference's current value was its old default value, in which
* case it changes to the new default value. If the preference's current
* is different from its old default value, its current value is
* unaffected. No property change events are reported by changing default
* values.
* </p>
*
* @param name the name of the preference
* @param value the new default value for the preference
*/
public void setDefault(String name, float value){
pref.setDefault(name, value);
store.setProperty(name,value);
}
/**
* Sets the default value for the integer-valued preference with the
* given name.
* <p>
* Note that the current value of the preference is affected if
* the preference's current value was its old default value, in which
* case it changes to the new default value. If the preference's current
* is different from its old default value, its current value is
* unaffected. No property change events are reported by changing default
* values.
* </p>
*
* @param name the name of the preference
* @param value the new default value for the preference
*/
public void setDefault(String name, int value){
pref.setDefault(name, value);
store.setProperty(name,value);
}
/**
* Sets the default value for the long-valued preference with the
* given name.
* <p>
* Note that the current value of the preference is affected if
* the preference's current value was its old default value, in which
* case it changes to the new default value. If the preference's current
* is different from its old default value, its current value is
* unaffected. No property change events are reported by changing default
* values.
* </p>
*
* @param name the name of the preference
* @param value the new default value for the preference
*/
public void setDefault(String name, long value){
pref.setDefault(name, value);
store.setProperty(name,value);
}
/**
* Sets the default value for the string-valued preference with the
* given name.
* <p>
* Note that the current value of the preference is affected if
* the preference's current value was its old default value, in which
* case it changes to the new default value. If the preference's current
* is different from its old default value, its current value is
* unaffected. No property change events are reported by changing default
* values.
* </p>
*
* @param name the name of the preference
* @param defaultObject the new default value for the preference
*/
public void setDefault(String name, String defaultObject){
pref.setDefault(name, defaultObject);
store.setProperty(name,defaultObject);
}
/**
* Sets the default value for the boolean-valued preference with the
* given name.
* <p>
* Note that the current value of the preference is affected if
* the preference's current value was its old default value, in which
* case it changes to the new default value. If the preference's current
* is different from its old default value, its current value is
* unaffected. No property change events are reported by changing default
* values.
* </p>
*
* @param name the name of the preference
* @param value the new default value for the preference
*/
public void setDefault(String name, boolean value){
pref.setDefault(name, value);
store.setProperty(name,value);
}
}
/**
* constructor
*/
public DataLoadPreferenceInitializer() {
super();
}
@Override
public void initializeDefaultPreferences() {
StoreWrapper pref = new StoreWrapper();
pref.setDefault(DataLoadPreferences.REMOVE_SITE_NAME, true);
pref.setDefault(DataLoadPreferences.NETWORK_COMBINED_CALCULATION, true);
pref.setDefault(DataLoadPreferences.ZOOM_TO_LAYER, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_PROBES_TO_MAP, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_CALLS_TO_MAP, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_EVENTS_TO_MAP, true);
pref.setDefault(DataLoadPreferences.NH_CITY, "City, Town, Ort, SIT_City");
pref.setDefault(DataLoadPreferences.NH_MSC, "MSC, MSC_NAME, MSC Name");
pref.setDefault(DataLoadPreferences.NH_BSC, "BSC, BSC_NAME, RNC, BSC Name");
pref.setDefault(DataLoadPreferences.NH_SITE, "Site, Name, Site Name, SiteName, SITE_ID, SiteID");
pref.setDefault(DataLoadPreferences.NH_SECTOR, "Sector, SectorName, Cell, BTS_Name, CELL_NAME, GSM Sector ID,CellIdentity, cell name, Cell Name,sector_id, BS_NO");
pref.setDefault(DataLoadPreferences.NH_SECTOR_CI, "CI,CI_s,CellId,CellIdentity");
pref.setDefault(DataLoadPreferences.NH_SECTOR_LAC, "LAC,LAC_s,La_lacId");
pref.setDefault(DataLoadPreferences.NH_LATITUDE, "latitude, y_wert.*, SIT.*Y, northing, lat.*");
pref.setDefault(DataLoadPreferences.NH_LONGITUDE, "longitude, x_wert.*, SIT.*X, easting, lon.*");
- pref.setDefault(DataLoadPreferences.DR_LATITUDE, "latitude");
- pref.setDefault(DataLoadPreferences.DR_LONGITUDE, "longitude");
+ pref.setDefault(DataLoadPreferences.DR_LATITUDE, ".*latitude");
+ pref.setDefault(DataLoadPreferences.DR_LONGITUDE, ".*longitude");
pref.setDefault(DataLoadPreferences.DR_BCCH, "bcch");
pref.setDefault(DataLoadPreferences.DR_CI, "ci");
pref.setDefault(DataLoadPreferences.DR_EcIo, "ecio");
pref.setDefault(DataLoadPreferences.DR_PN, "pn");
pref.setDefault(DataLoadPreferences.DR_RSSI, "rssi");
pref.setDefault(DataLoadPreferences.DR_SC, "sc");
pref.setDefault(DataLoadPreferences.DR_TCH, "tch");
pref.setDefault(DataLoadPreferences.PR_NAME, "Probe");
pref.setDefault(DataLoadPreferences.PR_TYPE, "Type");
pref.setDefault(DataLoadPreferences.PR_LATITUDE, "lat.*, .*latitude.*");
pref.setDefault(DataLoadPreferences.PR_LONGITUDE, "long.*, .*longitude.*");
pref.setDefault(DataLoadPreferences.NH_AZIMUTH, ".*azimuth.*, bearing");
pref.setDefault(DataLoadPreferences.NH_BEAMWIDTH, ".*beamwidth.*, beam, hbw");
pref.setDefault(DataLoadPreferences.NE_CI, "CI,CI_s");
pref.setDefault(DataLoadPreferences.NE_BTS, "BTS_NAME,BTS_Name_s");
pref.setDefault(DataLoadPreferences.NE_LAC, "LAC,LAC_s");
pref.setDefault(DataLoadPreferences.NE_ADJ_CI, "ADJ_CI,CI_t");
pref.setDefault(DataLoadPreferences.NE_ADJ_BTS, "ADJ_BTS_NAME,BTS_Name_t");
pref.setDefault(DataLoadPreferences.NE_ADJ_LAC, "ADJ_LAC,LAC_t");
pref.setDefault(DataLoadPreferences.TR_SITE_ID_SERV, "Site ID, Near end Name");
pref.setDefault(DataLoadPreferences.TR_SITE_NO_SERV, "Site No, Near End Site No");
pref.setDefault(DataLoadPreferences.TR_ITEM_NAME_SERV, "ITEM_Name");
pref.setDefault(DataLoadPreferences.TR_SITE_ID_NEIB, "Site ID, Far end Name");
pref.setDefault(DataLoadPreferences.TR_SITE_NO_NEIB, "Site No, Far End Site No");
pref.setDefault(DataLoadPreferences.TR_ITEM_NAME_NEIB, "ITEM_Name");
// pref.setDefault(DataLoadPreferences.PROPERY_LISTS, "dbm--DELIMETER--dbm--DELIMETER--dbm+mw--DELIMETER--dbm,mw");
pref.setDefault(DataLoadPreferences.DEFAULT_CHARSET, Charset.defaultCharset().name());
StringBuilder def;
try {
def = new StringBuilder(CRS.decode("EPSG:4326").toWKT()).append(DataLoadPreferences.CRS_DELIMETERS).append(CRS.decode("EPSG:31467").toWKT()).append(
DataLoadPreferences.CRS_DELIMETERS).append(CRS.decode("EPSG:3021").toWKT());
} catch (Exception e) {
NeoLoaderPlugin.exception(e);
def = null;
}
pref.setDefault(DataLoadPreferences.COMMON_CRS_LIST, def.toString());
pref.setDefault(DataLoadPreferences.SELECTED_DATA, "");
pref.setDefault(DataLoadPreferences.REMOTE_SERVER_URL, "http://explorer.amanzitel.com/geoptima");
}
}
| true | true | public void initializeDefaultPreferences() {
StoreWrapper pref = new StoreWrapper();
pref.setDefault(DataLoadPreferences.REMOVE_SITE_NAME, true);
pref.setDefault(DataLoadPreferences.NETWORK_COMBINED_CALCULATION, true);
pref.setDefault(DataLoadPreferences.ZOOM_TO_LAYER, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_PROBES_TO_MAP, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_CALLS_TO_MAP, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_EVENTS_TO_MAP, true);
pref.setDefault(DataLoadPreferences.NH_CITY, "City, Town, Ort, SIT_City");
pref.setDefault(DataLoadPreferences.NH_MSC, "MSC, MSC_NAME, MSC Name");
pref.setDefault(DataLoadPreferences.NH_BSC, "BSC, BSC_NAME, RNC, BSC Name");
pref.setDefault(DataLoadPreferences.NH_SITE, "Site, Name, Site Name, SiteName, SITE_ID, SiteID");
pref.setDefault(DataLoadPreferences.NH_SECTOR, "Sector, SectorName, Cell, BTS_Name, CELL_NAME, GSM Sector ID,CellIdentity, cell name, Cell Name,sector_id, BS_NO");
pref.setDefault(DataLoadPreferences.NH_SECTOR_CI, "CI,CI_s,CellId,CellIdentity");
pref.setDefault(DataLoadPreferences.NH_SECTOR_LAC, "LAC,LAC_s,La_lacId");
pref.setDefault(DataLoadPreferences.NH_LATITUDE, "latitude, y_wert.*, SIT.*Y, northing, lat.*");
pref.setDefault(DataLoadPreferences.NH_LONGITUDE, "longitude, x_wert.*, SIT.*X, easting, lon.*");
pref.setDefault(DataLoadPreferences.DR_LATITUDE, "latitude");
pref.setDefault(DataLoadPreferences.DR_LONGITUDE, "longitude");
pref.setDefault(DataLoadPreferences.DR_BCCH, "bcch");
pref.setDefault(DataLoadPreferences.DR_CI, "ci");
pref.setDefault(DataLoadPreferences.DR_EcIo, "ecio");
pref.setDefault(DataLoadPreferences.DR_PN, "pn");
pref.setDefault(DataLoadPreferences.DR_RSSI, "rssi");
pref.setDefault(DataLoadPreferences.DR_SC, "sc");
pref.setDefault(DataLoadPreferences.DR_TCH, "tch");
pref.setDefault(DataLoadPreferences.PR_NAME, "Probe");
pref.setDefault(DataLoadPreferences.PR_TYPE, "Type");
pref.setDefault(DataLoadPreferences.PR_LATITUDE, "lat.*, .*latitude.*");
pref.setDefault(DataLoadPreferences.PR_LONGITUDE, "long.*, .*longitude.*");
pref.setDefault(DataLoadPreferences.NH_AZIMUTH, ".*azimuth.*, bearing");
pref.setDefault(DataLoadPreferences.NH_BEAMWIDTH, ".*beamwidth.*, beam, hbw");
pref.setDefault(DataLoadPreferences.NE_CI, "CI,CI_s");
pref.setDefault(DataLoadPreferences.NE_BTS, "BTS_NAME,BTS_Name_s");
pref.setDefault(DataLoadPreferences.NE_LAC, "LAC,LAC_s");
pref.setDefault(DataLoadPreferences.NE_ADJ_CI, "ADJ_CI,CI_t");
pref.setDefault(DataLoadPreferences.NE_ADJ_BTS, "ADJ_BTS_NAME,BTS_Name_t");
pref.setDefault(DataLoadPreferences.NE_ADJ_LAC, "ADJ_LAC,LAC_t");
pref.setDefault(DataLoadPreferences.TR_SITE_ID_SERV, "Site ID, Near end Name");
pref.setDefault(DataLoadPreferences.TR_SITE_NO_SERV, "Site No, Near End Site No");
pref.setDefault(DataLoadPreferences.TR_ITEM_NAME_SERV, "ITEM_Name");
pref.setDefault(DataLoadPreferences.TR_SITE_ID_NEIB, "Site ID, Far end Name");
pref.setDefault(DataLoadPreferences.TR_SITE_NO_NEIB, "Site No, Far End Site No");
pref.setDefault(DataLoadPreferences.TR_ITEM_NAME_NEIB, "ITEM_Name");
// pref.setDefault(DataLoadPreferences.PROPERY_LISTS, "dbm--DELIMETER--dbm--DELIMETER--dbm+mw--DELIMETER--dbm,mw");
pref.setDefault(DataLoadPreferences.DEFAULT_CHARSET, Charset.defaultCharset().name());
StringBuilder def;
try {
def = new StringBuilder(CRS.decode("EPSG:4326").toWKT()).append(DataLoadPreferences.CRS_DELIMETERS).append(CRS.decode("EPSG:31467").toWKT()).append(
DataLoadPreferences.CRS_DELIMETERS).append(CRS.decode("EPSG:3021").toWKT());
} catch (Exception e) {
NeoLoaderPlugin.exception(e);
def = null;
}
pref.setDefault(DataLoadPreferences.COMMON_CRS_LIST, def.toString());
pref.setDefault(DataLoadPreferences.SELECTED_DATA, "");
pref.setDefault(DataLoadPreferences.REMOTE_SERVER_URL, "http://explorer.amanzitel.com/geoptima");
}
| public void initializeDefaultPreferences() {
StoreWrapper pref = new StoreWrapper();
pref.setDefault(DataLoadPreferences.REMOVE_SITE_NAME, true);
pref.setDefault(DataLoadPreferences.NETWORK_COMBINED_CALCULATION, true);
pref.setDefault(DataLoadPreferences.ZOOM_TO_LAYER, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_PROBES_TO_MAP, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_CALLS_TO_MAP, true);
pref.setDefault(DataLoadPreferences.ADD_AMS_EVENTS_TO_MAP, true);
pref.setDefault(DataLoadPreferences.NH_CITY, "City, Town, Ort, SIT_City");
pref.setDefault(DataLoadPreferences.NH_MSC, "MSC, MSC_NAME, MSC Name");
pref.setDefault(DataLoadPreferences.NH_BSC, "BSC, BSC_NAME, RNC, BSC Name");
pref.setDefault(DataLoadPreferences.NH_SITE, "Site, Name, Site Name, SiteName, SITE_ID, SiteID");
pref.setDefault(DataLoadPreferences.NH_SECTOR, "Sector, SectorName, Cell, BTS_Name, CELL_NAME, GSM Sector ID,CellIdentity, cell name, Cell Name,sector_id, BS_NO");
pref.setDefault(DataLoadPreferences.NH_SECTOR_CI, "CI,CI_s,CellId,CellIdentity");
pref.setDefault(DataLoadPreferences.NH_SECTOR_LAC, "LAC,LAC_s,La_lacId");
pref.setDefault(DataLoadPreferences.NH_LATITUDE, "latitude, y_wert.*, SIT.*Y, northing, lat.*");
pref.setDefault(DataLoadPreferences.NH_LONGITUDE, "longitude, x_wert.*, SIT.*X, easting, lon.*");
pref.setDefault(DataLoadPreferences.DR_LATITUDE, ".*latitude");
pref.setDefault(DataLoadPreferences.DR_LONGITUDE, ".*longitude");
pref.setDefault(DataLoadPreferences.DR_BCCH, "bcch");
pref.setDefault(DataLoadPreferences.DR_CI, "ci");
pref.setDefault(DataLoadPreferences.DR_EcIo, "ecio");
pref.setDefault(DataLoadPreferences.DR_PN, "pn");
pref.setDefault(DataLoadPreferences.DR_RSSI, "rssi");
pref.setDefault(DataLoadPreferences.DR_SC, "sc");
pref.setDefault(DataLoadPreferences.DR_TCH, "tch");
pref.setDefault(DataLoadPreferences.PR_NAME, "Probe");
pref.setDefault(DataLoadPreferences.PR_TYPE, "Type");
pref.setDefault(DataLoadPreferences.PR_LATITUDE, "lat.*, .*latitude.*");
pref.setDefault(DataLoadPreferences.PR_LONGITUDE, "long.*, .*longitude.*");
pref.setDefault(DataLoadPreferences.NH_AZIMUTH, ".*azimuth.*, bearing");
pref.setDefault(DataLoadPreferences.NH_BEAMWIDTH, ".*beamwidth.*, beam, hbw");
pref.setDefault(DataLoadPreferences.NE_CI, "CI,CI_s");
pref.setDefault(DataLoadPreferences.NE_BTS, "BTS_NAME,BTS_Name_s");
pref.setDefault(DataLoadPreferences.NE_LAC, "LAC,LAC_s");
pref.setDefault(DataLoadPreferences.NE_ADJ_CI, "ADJ_CI,CI_t");
pref.setDefault(DataLoadPreferences.NE_ADJ_BTS, "ADJ_BTS_NAME,BTS_Name_t");
pref.setDefault(DataLoadPreferences.NE_ADJ_LAC, "ADJ_LAC,LAC_t");
pref.setDefault(DataLoadPreferences.TR_SITE_ID_SERV, "Site ID, Near end Name");
pref.setDefault(DataLoadPreferences.TR_SITE_NO_SERV, "Site No, Near End Site No");
pref.setDefault(DataLoadPreferences.TR_ITEM_NAME_SERV, "ITEM_Name");
pref.setDefault(DataLoadPreferences.TR_SITE_ID_NEIB, "Site ID, Far end Name");
pref.setDefault(DataLoadPreferences.TR_SITE_NO_NEIB, "Site No, Far End Site No");
pref.setDefault(DataLoadPreferences.TR_ITEM_NAME_NEIB, "ITEM_Name");
// pref.setDefault(DataLoadPreferences.PROPERY_LISTS, "dbm--DELIMETER--dbm--DELIMETER--dbm+mw--DELIMETER--dbm,mw");
pref.setDefault(DataLoadPreferences.DEFAULT_CHARSET, Charset.defaultCharset().name());
StringBuilder def;
try {
def = new StringBuilder(CRS.decode("EPSG:4326").toWKT()).append(DataLoadPreferences.CRS_DELIMETERS).append(CRS.decode("EPSG:31467").toWKT()).append(
DataLoadPreferences.CRS_DELIMETERS).append(CRS.decode("EPSG:3021").toWKT());
} catch (Exception e) {
NeoLoaderPlugin.exception(e);
def = null;
}
pref.setDefault(DataLoadPreferences.COMMON_CRS_LIST, def.toString());
pref.setDefault(DataLoadPreferences.SELECTED_DATA, "");
pref.setDefault(DataLoadPreferences.REMOTE_SERVER_URL, "http://explorer.amanzitel.com/geoptima");
}
|
diff --git a/org.cloudsmith.geppetto.pp.dsl.ui/src/org/cloudsmith/geppetto/pp/dsl/ui/editor/actions/SaveActions.java b/org.cloudsmith.geppetto.pp.dsl.ui/src/org/cloudsmith/geppetto/pp/dsl/ui/editor/actions/SaveActions.java
index 0dbfe672..1043092e 100644
--- a/org.cloudsmith.geppetto.pp.dsl.ui/src/org/cloudsmith/geppetto/pp/dsl/ui/editor/actions/SaveActions.java
+++ b/org.cloudsmith.geppetto.pp.dsl.ui/src/org/cloudsmith/geppetto/pp/dsl/ui/editor/actions/SaveActions.java
@@ -1,126 +1,129 @@
/**
* Copyright (c) 2011 Cloudsmith Inc. and other contributors, as listed below.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Cloudsmith
*
*/
package org.cloudsmith.geppetto.pp.dsl.ui.editor.actions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.cloudsmith.geppetto.pp.dsl.ui.linked.ISaveActions;
import org.cloudsmith.geppetto.pp.dsl.ui.preferences.PPPreferencesHelper;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import com.google.inject.Inject;
/**
* Implementation of save actions
*
*/
public class SaveActions implements ISaveActions {
// case '\u00A0': // NBSP
// case '\u1680': // OGHAM SPACE MARK");
// case '\u2000': // EN QUAD");
// case '\u2001': // EM QUAD");
// case '\u2002': // EN SPACE");
// case '\u2003': // EM SPACE");
// case '\u2004': // THREE-PER-EM SPACE");
// case '\u2005': // FOUR-PER-EM SPACE");
// case '\u2006': // SIX-PER-EM SPACE");
// case '\u2007': // FIGURE SPACE");
// case '\u2008': // PUNCTUATION SPACE");
// case '\u2009': // THIN SPACE");
// case '\u200A': // HAIR SPACE");
// case '\u200B': // ZERO WIDTH SPACE");
// case '\u202F': // NARROW NO-BREAK SPACE");
// case '\u3000': // IDEOGRAPHIC SPACE");
public static String funkySpaces = "\\u00A0\\u1680\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u200B\\u202F\\u3000";
private static Pattern trimPattern = Pattern.compile("[ \\t\\f\\x0B" + funkySpaces + "]+(\\r\\n|\\n)");
private static Pattern funkySpacePattern = Pattern.compile("[\\f\\x0B" + funkySpaces + "]");
@Inject
private PPPreferencesHelper preferenceHelper;
/*
* (non-Javadoc)
*
* @see org.cloudsmith.geppetto.pp.dsl.ui.linked.ISaveActions#perform(org.eclipse.core.resources.IResource,
* org.eclipse.xtext.ui.editor.model.IXtextDocument)
*/
@Override
public void perform(IResource r, IXtextDocument document) {
boolean ensureNl = preferenceHelper.getSaveActionEnsureEndsWithNewLine(r);
boolean replaceFunkySpace = preferenceHelper.getSaveActionReplaceFunkySpaces(r);
boolean trimLines = preferenceHelper.getSaveActionTrimLines(r);
if(ensureNl || replaceFunkySpace || trimLines) {
String content = document.get();
if(ensureNl)
if(!content.endsWith("\n")) {
content = content + "\n";
try {
document.replace(content.length() - 1, 0, "\n");
content = document.get();
}
catch(BadLocationException e) {
// ignore
}
}
if(trimLines) {
Matcher matcher = trimPattern.matcher(content);
boolean mustRefetch = false;
;
+ int lengthAdjustment = 0;
while(matcher.find()) {
int offset = matcher.start();
int length = matcher.end() - offset;
try {
- document.replace(offset, length, matcher.group(1));
+ String replacement = matcher.group(1);
+ document.replace(offset - lengthAdjustment, length, replacement);
+ lengthAdjustment += (length - replacement.length());
mustRefetch = true;
}
catch(BadLocationException e) {
// ignore
}
}
- // content = trimPattern.matcher(content).replaceAll("$1");
if(mustRefetch)
content = document.get();
}
if(replaceFunkySpace) {
Matcher matcher = funkySpacePattern.matcher(content);
+ int lengthAdjustment = 0;
while(matcher.find()) {
int offset = matcher.start();
int length = matcher.end() - offset;
try {
- document.replace(offset, length, " ");
+ document.replace(offset - lengthAdjustment, length, " ");
+ lengthAdjustment += length - 1;
}
catch(BadLocationException e) {
// ignore
}
}
- content = funkySpacePattern.matcher(content).replaceAll(" ");
}
}
// // USE THIS IF SEMANTIC CHANGES ARE NEEDED LATER
// document.modify(new IUnitOfWork.Void<XtextResource>() {
//
// @Override
// public void process(XtextResource state) throws Exception {
// // Do any semantic changes here
// }
// });
}
}
| false | true | public void perform(IResource r, IXtextDocument document) {
boolean ensureNl = preferenceHelper.getSaveActionEnsureEndsWithNewLine(r);
boolean replaceFunkySpace = preferenceHelper.getSaveActionReplaceFunkySpaces(r);
boolean trimLines = preferenceHelper.getSaveActionTrimLines(r);
if(ensureNl || replaceFunkySpace || trimLines) {
String content = document.get();
if(ensureNl)
if(!content.endsWith("\n")) {
content = content + "\n";
try {
document.replace(content.length() - 1, 0, "\n");
content = document.get();
}
catch(BadLocationException e) {
// ignore
}
}
if(trimLines) {
Matcher matcher = trimPattern.matcher(content);
boolean mustRefetch = false;
;
while(matcher.find()) {
int offset = matcher.start();
int length = matcher.end() - offset;
try {
document.replace(offset, length, matcher.group(1));
mustRefetch = true;
}
catch(BadLocationException e) {
// ignore
}
}
// content = trimPattern.matcher(content).replaceAll("$1");
if(mustRefetch)
content = document.get();
}
if(replaceFunkySpace) {
Matcher matcher = funkySpacePattern.matcher(content);
while(matcher.find()) {
int offset = matcher.start();
int length = matcher.end() - offset;
try {
document.replace(offset, length, " ");
}
catch(BadLocationException e) {
// ignore
}
}
content = funkySpacePattern.matcher(content).replaceAll(" ");
}
}
// // USE THIS IF SEMANTIC CHANGES ARE NEEDED LATER
// document.modify(new IUnitOfWork.Void<XtextResource>() {
//
// @Override
// public void process(XtextResource state) throws Exception {
// // Do any semantic changes here
// }
// });
}
| public void perform(IResource r, IXtextDocument document) {
boolean ensureNl = preferenceHelper.getSaveActionEnsureEndsWithNewLine(r);
boolean replaceFunkySpace = preferenceHelper.getSaveActionReplaceFunkySpaces(r);
boolean trimLines = preferenceHelper.getSaveActionTrimLines(r);
if(ensureNl || replaceFunkySpace || trimLines) {
String content = document.get();
if(ensureNl)
if(!content.endsWith("\n")) {
content = content + "\n";
try {
document.replace(content.length() - 1, 0, "\n");
content = document.get();
}
catch(BadLocationException e) {
// ignore
}
}
if(trimLines) {
Matcher matcher = trimPattern.matcher(content);
boolean mustRefetch = false;
;
int lengthAdjustment = 0;
while(matcher.find()) {
int offset = matcher.start();
int length = matcher.end() - offset;
try {
String replacement = matcher.group(1);
document.replace(offset - lengthAdjustment, length, replacement);
lengthAdjustment += (length - replacement.length());
mustRefetch = true;
}
catch(BadLocationException e) {
// ignore
}
}
if(mustRefetch)
content = document.get();
}
if(replaceFunkySpace) {
Matcher matcher = funkySpacePattern.matcher(content);
int lengthAdjustment = 0;
while(matcher.find()) {
int offset = matcher.start();
int length = matcher.end() - offset;
try {
document.replace(offset - lengthAdjustment, length, " ");
lengthAdjustment += length - 1;
}
catch(BadLocationException e) {
// ignore
}
}
}
}
// // USE THIS IF SEMANTIC CHANGES ARE NEEDED LATER
// document.modify(new IUnitOfWork.Void<XtextResource>() {
//
// @Override
// public void process(XtextResource state) throws Exception {
// // Do any semantic changes here
// }
// });
}
|
diff --git a/core/impl-base/src/main/java/org/jboss/arquillian/core/impl/loadable/ServiceRegistryLoader.java b/core/impl-base/src/main/java/org/jboss/arquillian/core/impl/loadable/ServiceRegistryLoader.java
index 6422b919..0027dbfd 100644
--- a/core/impl-base/src/main/java/org/jboss/arquillian/core/impl/loadable/ServiceRegistryLoader.java
+++ b/core/impl-base/src/main/java/org/jboss/arquillian/core/impl/loadable/ServiceRegistryLoader.java
@@ -1,131 +1,132 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.core.impl.loadable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jboss.arquillian.core.api.Injector;
import org.jboss.arquillian.core.spi.ServiceLoader;
/**
* MixedServiceLoader
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
public class ServiceRegistryLoader implements ServiceLoader
{
private Injector injector;
private ServiceRegistry registry;
private ConcurrentMap<Class<?>, Collection<Object>> serviceInstanceRegistry;
public ServiceRegistryLoader(Injector injector, ServiceRegistry registry)
{
this.injector = injector;
this.registry = registry;
this.serviceInstanceRegistry = new ConcurrentHashMap<Class<?>, Collection<Object>>();
}
/* (non-Javadoc)
* @see org.jboss.arquillian.core.spi.ServiceLoader#all(java.lang.Class)
*/
@SuppressWarnings("unchecked")
@Override
public <T> Collection<T> all(Class<T> serviceClass)
{
if(serviceInstanceRegistry.containsKey(serviceClass))
{
return (Collection<T>)serviceInstanceRegistry.get(serviceClass);
}
List<T> serviceImpls = new ArrayList<T>();
Set<Class<? extends T>> serviceImplClasses = registry.getServiceImpls(serviceClass);
for(Class<? extends T> serviceImplClass : serviceImplClasses)
{
T serviceImpl = createServiceInstance(serviceImplClass);
injector.inject(serviceImpl);
serviceImpls.add(serviceImpl);
}
- Collection<T> previouslyRegistrered = (Collection<T>)serviceInstanceRegistry.putIfAbsent(serviceClass, (Collection<Object>)serviceImpls);
- return previouslyRegistrered != null ? previouslyRegistrered:serviceImpls;
+ //Collection<T> previouslyRegistrered = (Collection<T>)serviceInstanceRegistry.putIfAbsent(serviceClass, (Collection<Object>)serviceImpls);
+ //return previouslyRegistrered != null ? previouslyRegistrered:serviceImpls;
+ return serviceImpls;
}
/* (non-Javadoc)
* @see org.jboss.arquillian.core.spi.ServiceLoader#onlyOne(java.lang.Class)
*/
@Override
public <T> T onlyOne(Class<T> serviceClass)
{
Collection<T> all = all(serviceClass);
if(all.size() == 1)
{
return all.iterator().next();
}
if(all.size() > 1)
{
throw new RuntimeException("Multiple service implementations found for " + serviceClass + ". " + toClassString(all));
}
return null;
}
/* (non-Javadoc)
* @see org.jboss.arquillian.core.spi.ServiceLoader#onlyOne(java.lang.Class, java.lang.Class)
*/
@Override
public <T> T onlyOne(Class<T> serviceClass, Class<? extends T> defaultServiceClass)
{
T one = null;
try
{
one = onlyOne(serviceClass);
}
catch (Exception e) { }
if(one == null)
{
one = createServiceInstance(defaultServiceClass);
}
return one;
}
private <T> T createServiceInstance(Class<T> service)
{
return SecurityActions.newInstance(
service,
new Class<?>[]{},
new Object[]{});
}
private <T> String toClassString(Collection<T> providers)
{
StringBuilder sb = new StringBuilder();
for(Object provider : providers)
{
sb.append(provider.getClass().getName()).append(", ");
}
return sb.subSequence(0, sb.length()-2).toString();
}
}
| true | true | public <T> Collection<T> all(Class<T> serviceClass)
{
if(serviceInstanceRegistry.containsKey(serviceClass))
{
return (Collection<T>)serviceInstanceRegistry.get(serviceClass);
}
List<T> serviceImpls = new ArrayList<T>();
Set<Class<? extends T>> serviceImplClasses = registry.getServiceImpls(serviceClass);
for(Class<? extends T> serviceImplClass : serviceImplClasses)
{
T serviceImpl = createServiceInstance(serviceImplClass);
injector.inject(serviceImpl);
serviceImpls.add(serviceImpl);
}
Collection<T> previouslyRegistrered = (Collection<T>)serviceInstanceRegistry.putIfAbsent(serviceClass, (Collection<Object>)serviceImpls);
return previouslyRegistrered != null ? previouslyRegistrered:serviceImpls;
}
| public <T> Collection<T> all(Class<T> serviceClass)
{
if(serviceInstanceRegistry.containsKey(serviceClass))
{
return (Collection<T>)serviceInstanceRegistry.get(serviceClass);
}
List<T> serviceImpls = new ArrayList<T>();
Set<Class<? extends T>> serviceImplClasses = registry.getServiceImpls(serviceClass);
for(Class<? extends T> serviceImplClass : serviceImplClasses)
{
T serviceImpl = createServiceInstance(serviceImplClass);
injector.inject(serviceImpl);
serviceImpls.add(serviceImpl);
}
//Collection<T> previouslyRegistrered = (Collection<T>)serviceInstanceRegistry.putIfAbsent(serviceClass, (Collection<Object>)serviceImpls);
//return previouslyRegistrered != null ? previouslyRegistrered:serviceImpls;
return serviceImpls;
}
|
diff --git a/geoserver/main/src/main/java/org/vfny/geoserver/global/GeoserverDataDirectory.java b/geoserver/main/src/main/java/org/vfny/geoserver/global/GeoserverDataDirectory.java
index 1deb9038c2..7b62b5fccb 100644
--- a/geoserver/main/src/main/java/org/vfny/geoserver/global/GeoserverDataDirectory.java
+++ b/geoserver/main/src/main/java/org/vfny/geoserver/global/GeoserverDataDirectory.java
@@ -1,228 +1,230 @@
/* Copyright (c) 2001, 2003 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.vfny.geoserver.global;
import org.geoserver.platform.GeoServerResourceLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/* Copyright (c) 2001, 2003 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
/**
* This class allows for abstracting the location of the Geoserver Data directory. Some people call this "GEOSERVER_HOME".
*
* Inside this directory should be two more directories: a. "WEB-INF/" Inside this is a catalog.xml b. "data/" Inside this is a set of other
* directories.
*
* For the exact content of these directories, see any existing geoserver install's server/geoserver directory.
*
* In order to find the geoserver data directory the following steps take place:
*
* 1. search for the "GEOSERVER_DATA_DIR" system property. this will most likely have come from "java -DGEOSERVER_DATA_DIR=..." or from you
* web container 2. search for a "GEOSERVER_DATA_DIR" in the web.xml document <context-param> <param-name>GEOSERVER_DATA_DIR</param-name>
* <param-value>...</param-value> </context-param> 3. It defaults to the old behavior - ie. the application root - usually
* "server/geoserver" in your .WAR.
*
*
* NOTE: a set method is currently undefined because you should either modify you web.xml or set the environment variable and re-start
* geoserver.
*
* @author dblasby
*
*/
public class GeoserverDataDirectory {
// caches the dataDir
private static GeoServerResourceLoader loader;
private static final Logger LOGGER = Logger.getLogger("org.vfny.geoserver.global");
private static boolean isTrueDataDir = false;
/**
* See the class documentation for more details. 1. search for the "GEOSERVER_DATA_DIR" system property. 2. search for a
* "GEOSERVER_DATA_DIR" in the web.xml document 3. It defaults to the old behavior - ie. the application root - usually
* "server/geoserver" in your .WAR.
*
* @return location of the geoserver data dir
*/
static public File getGeoserverDataDirectory() {
return loader.getBaseDirectory();
}
/**
* Returns whether GeoServer is using a true data directory, loaded from outside the webapp, or if its defaulting to the webapp embedded
* dataDir. We're in the process of moving away from storing anything in the webapp but are keeping this to ease the transition.
*
* @return <tt>true</tt> if the directory being used for loading is not embedded in the webapp.
*/
static public boolean isTrueDataDir() {
return isTrueDataDir;
}
/**
* Utility method to find the approriate sub-data dir config. This is a helper for the fact that we're transitioning away from the
* WEB-INF type of hacky storage, but during the transition things can be in both places. So this method takes the root file, the
* dataDir, and a name of a directory that is stored in the data dir, and checks for it in the data/ dir (the old way), and directly in
* the dir (the new way)
*
* @param root
* Generally the Data Directory, the directory to try to find the config file in.
* @param dirName
* The name of the directory to find in the data Dir.
* @return The proper config directory.
* @throws ConfigurationException
* if the directory could not be found at all.
*/
public static File findConfigDir(File root, String dirName)
throws ConfigurationException {
File configDir;
try {
configDir = loader.find(dirName);
} catch (IOException e) {
throw new ConfigurationException(e);
}
return configDir;
}
/**
* Given a url, tries to interpret it as a file into the data directory, or as an absolute
* location, and returns the actual absolute location of the File
* @param path
* @return
*/
public static File findDataFile(URL url) {
return findDataFile(url.getFile());
}
/**
* Given a path, tries to interpret it as a file into the data directory, or as an absolute
* location, and returns the actual absolute location of the File
* @param path
* @return
*/
public static File findDataFile(String path) {
File baseDir = GeoserverDataDirectory.getGeoserverDataDirectory();
// do we ever have something that is not a file system reference?
if (path.startsWith("file:")) {
path = path.substring(5); // remove 'file:' prefix
File f = new File(path);
if (f.exists()) {
return f;
} else {
return new File(baseDir, path);
}
} else {
return new File(path);
}
}
/**
* Utility method fofinding a config file under the data directory.
*
* @param file
* Path to file, absolute or relative to data dir.
*
* @return The file handle, or null.
*/
public static File findConfigFile(String file) throws ConfigurationException {
try {
return loader.find(file);
} catch (IOException e) {
throw new ConfigurationException(e);
}
}
/**
* Initializes the data directory lookup service.
* @param servContext
*/
public static void init(WebApplicationContext context) {
ServletContext servContext = context.getServletContext();
// This was once in the GetGeoserverDataDirectory method, I've moved
// here so that servlet
// context is not needed as a parameter anymore.
// caching this, so we're not looking up everytime, and more
// importantly, so we can actually look up this stuff without
// having to pass in a ServletContext. This should be fine, since we
// don't allow a set method, as we recommend restarting GeoServer,
// so it should always get a ServletContext in the startup routine.
// If this assumption can't be made, then we can't allow data_dir
// _and_ webapp options with relative data/ links -ch
if (loader == null) {
//get the loader from the context
loader = (GeoServerResourceLoader) context.getBean( "resourceLoader" );
File dataDir = null;
// see if there's a system property
try {
String prop = System.getProperty("GEOSERVER_DATA_DIR");
if ((prop != null) && !prop.equals("")) {
// its defined!!
isTrueDataDir = true;
dataDir = new File(prop);
loader = new GeoServerResourceLoader(dataDir);
loader.addSearchLocation(new File(dataDir, "data"));
+ loader.addSearchLocation(new File(dataDir, "WEB-INF"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
return;
}
} catch (SecurityException e) {
// gobble exception
LOGGER.fine("Security exception occurred. This is usually not a big deal.\n"
+ e.getMessage());
}
// try the webxml
String loc = servContext.getInitParameter("GEOSERVER_DATA_DIR");
if (loc != null) {
// its defined!!
isTrueDataDir = true;
dataDir = new File(loc);
loader = new GeoServerResourceLoader(dataDir);
loader.addSearchLocation(new File(dataDir, "data"));
+ loader.addSearchLocation(new File(dataDir, "WEB-INF"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
return;
}
// return default
isTrueDataDir = false;
String rootDir = servContext.getRealPath("/data");
dataDir = new File(rootDir);
//set the base directory of hte loader
loader.setBaseDirectory( dataDir );
loader.addSearchLocation(new File(dataDir, "data"));
+ loader.addSearchLocation(new File(dataDir, "WEB-INF"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
- // support old in-war data dirs as well
loader.addSearchLocation(new File(servContext.getRealPath("WEB-INF")));
loader.addSearchLocation(new File(servContext.getRealPath("data")));
}
}
}
| false | true | public static void init(WebApplicationContext context) {
ServletContext servContext = context.getServletContext();
// This was once in the GetGeoserverDataDirectory method, I've moved
// here so that servlet
// context is not needed as a parameter anymore.
// caching this, so we're not looking up everytime, and more
// importantly, so we can actually look up this stuff without
// having to pass in a ServletContext. This should be fine, since we
// don't allow a set method, as we recommend restarting GeoServer,
// so it should always get a ServletContext in the startup routine.
// If this assumption can't be made, then we can't allow data_dir
// _and_ webapp options with relative data/ links -ch
if (loader == null) {
//get the loader from the context
loader = (GeoServerResourceLoader) context.getBean( "resourceLoader" );
File dataDir = null;
// see if there's a system property
try {
String prop = System.getProperty("GEOSERVER_DATA_DIR");
if ((prop != null) && !prop.equals("")) {
// its defined!!
isTrueDataDir = true;
dataDir = new File(prop);
loader = new GeoServerResourceLoader(dataDir);
loader.addSearchLocation(new File(dataDir, "data"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
return;
}
} catch (SecurityException e) {
// gobble exception
LOGGER.fine("Security exception occurred. This is usually not a big deal.\n"
+ e.getMessage());
}
// try the webxml
String loc = servContext.getInitParameter("GEOSERVER_DATA_DIR");
if (loc != null) {
// its defined!!
isTrueDataDir = true;
dataDir = new File(loc);
loader = new GeoServerResourceLoader(dataDir);
loader.addSearchLocation(new File(dataDir, "data"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
return;
}
// return default
isTrueDataDir = false;
String rootDir = servContext.getRealPath("/data");
dataDir = new File(rootDir);
//set the base directory of hte loader
loader.setBaseDirectory( dataDir );
loader.addSearchLocation(new File(dataDir, "data"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
// support old in-war data dirs as well
loader.addSearchLocation(new File(servContext.getRealPath("WEB-INF")));
loader.addSearchLocation(new File(servContext.getRealPath("data")));
}
}
| public static void init(WebApplicationContext context) {
ServletContext servContext = context.getServletContext();
// This was once in the GetGeoserverDataDirectory method, I've moved
// here so that servlet
// context is not needed as a parameter anymore.
// caching this, so we're not looking up everytime, and more
// importantly, so we can actually look up this stuff without
// having to pass in a ServletContext. This should be fine, since we
// don't allow a set method, as we recommend restarting GeoServer,
// so it should always get a ServletContext in the startup routine.
// If this assumption can't be made, then we can't allow data_dir
// _and_ webapp options with relative data/ links -ch
if (loader == null) {
//get the loader from the context
loader = (GeoServerResourceLoader) context.getBean( "resourceLoader" );
File dataDir = null;
// see if there's a system property
try {
String prop = System.getProperty("GEOSERVER_DATA_DIR");
if ((prop != null) && !prop.equals("")) {
// its defined!!
isTrueDataDir = true;
dataDir = new File(prop);
loader = new GeoServerResourceLoader(dataDir);
loader.addSearchLocation(new File(dataDir, "data"));
loader.addSearchLocation(new File(dataDir, "WEB-INF"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
return;
}
} catch (SecurityException e) {
// gobble exception
LOGGER.fine("Security exception occurred. This is usually not a big deal.\n"
+ e.getMessage());
}
// try the webxml
String loc = servContext.getInitParameter("GEOSERVER_DATA_DIR");
if (loc != null) {
// its defined!!
isTrueDataDir = true;
dataDir = new File(loc);
loader = new GeoServerResourceLoader(dataDir);
loader.addSearchLocation(new File(dataDir, "data"));
loader.addSearchLocation(new File(dataDir, "WEB-INF"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
return;
}
// return default
isTrueDataDir = false;
String rootDir = servContext.getRealPath("/data");
dataDir = new File(rootDir);
//set the base directory of hte loader
loader.setBaseDirectory( dataDir );
loader.addSearchLocation(new File(dataDir, "data"));
loader.addSearchLocation(new File(dataDir, "WEB-INF"));
System.out.println("----------------------------------");
System.out.println("- GEOSERVER_DATA_DIR: " + dataDir.getAbsolutePath());
System.out.println("----------------------------------");
loader.addSearchLocation(new File(servContext.getRealPath("WEB-INF")));
loader.addSearchLocation(new File(servContext.getRealPath("data")));
}
}
|
diff --git a/src/uk/co/uwcs/choob/support/GetContentsCached.java b/src/uk/co/uwcs/choob/support/GetContentsCached.java
index 7a3c4ea..cdfaa6c 100644
--- a/src/uk/co/uwcs/choob/support/GetContentsCached.java
+++ b/src/uk/co/uwcs/choob/support/GetContentsCached.java
@@ -1,80 +1,82 @@
package uk.co.uwcs.choob.support;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public final class GetContentsCached
{
public static int DEFAULT_TIMEOUT=5*60*1000; // <-- 5 mins in ms.
public GetContentsCached(URL url) { this.url=url; }
public GetContentsCached(URL url, long mintime) { this.url=url; setTimeout(mintime); }
URL url;
long lastaccess;
long mintime=DEFAULT_TIMEOUT;
protected String contents=null;
public boolean expired()
{
return lastaccess+mintime<(new Date()).getTime();
}
public long getTimeout()
{
return mintime;
}
public void setTimeout(long timeout)
{
mintime=timeout;
updateNextCheck();
}
public void updateIfNeeded() throws IOException
{
long now=(new Date()).getTime();
if (contents != null && (now - lastaccess) < mintime)
return;
URLConnection site = url.openConnection();
+ site.setReadTimeout(15000);
+ site.setConnectTimeout(15000);
site.setRequestProperty("User-agent", "Opera/8.51 (X11; Linux x86_64; U; en)");
InputStream is = site.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String l;
StringBuilder ls=new StringBuilder();
while ((l=br.readLine())!=null)
ls.append(l).append("\n");
contents=ls.toString();
lastaccess=now;
}
public void updateNextCheck()
{
lastaccess=(new Date()).getTime()-mintime;
}
public String getContents() throws IOException
{
updateIfNeeded();
return contents;
}
public String getContentsNull()
{
try
{
return getContents();
}
catch (IOException e)
{
return null;
}
}
}
| true | true | public void updateIfNeeded() throws IOException
{
long now=(new Date()).getTime();
if (contents != null && (now - lastaccess) < mintime)
return;
URLConnection site = url.openConnection();
site.setRequestProperty("User-agent", "Opera/8.51 (X11; Linux x86_64; U; en)");
InputStream is = site.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String l;
StringBuilder ls=new StringBuilder();
while ((l=br.readLine())!=null)
ls.append(l).append("\n");
contents=ls.toString();
lastaccess=now;
}
| public void updateIfNeeded() throws IOException
{
long now=(new Date()).getTime();
if (contents != null && (now - lastaccess) < mintime)
return;
URLConnection site = url.openConnection();
site.setReadTimeout(15000);
site.setConnectTimeout(15000);
site.setRequestProperty("User-agent", "Opera/8.51 (X11; Linux x86_64; U; en)");
InputStream is = site.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String l;
StringBuilder ls=new StringBuilder();
while ((l=br.readLine())!=null)
ls.append(l).append("\n");
contents=ls.toString();
lastaccess=now;
}
|
diff --git a/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/clusters/ClusterModel.java b/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/clusters/ClusterModel.java
index 9c313840..c70409f5 100644
--- a/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/clusters/ClusterModel.java
+++ b/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/clusters/ClusterModel.java
@@ -1,812 +1,812 @@
package org.ovirt.engine.ui.uicommonweb.models.clusters;
import org.ovirt.engine.core.common.businessentities.MigrateOnErrorOptions;
import org.ovirt.engine.core.common.businessentities.ServerCpu;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.DataProvider;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.LengthValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NoSpacesValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
import org.ovirt.engine.ui.uicommonweb.validation.RegexValidation;
@SuppressWarnings("unused")
public class ClusterModel extends Model
{
private int privateServerOverCommit;
public int getServerOverCommit()
{
return privateServerOverCommit;
}
public void setServerOverCommit(int value)
{
privateServerOverCommit = value;
}
private int privateDesktopOverCommit;
public int getDesktopOverCommit()
{
return privateDesktopOverCommit;
}
public void setDesktopOverCommit(int value)
{
privateDesktopOverCommit = value;
}
private int privateDefaultOverCommit;
public int getDefaultOverCommit()
{
return privateDefaultOverCommit;
}
public void setDefaultOverCommit(int value)
{
privateDefaultOverCommit = value;
}
private VDSGroup privateEntity;
public VDSGroup getEntity()
{
return privateEntity;
}
public void setEntity(VDSGroup value)
{
privateEntity = value;
}
private boolean privateIsEdit;
public boolean getIsEdit()
{
return privateIsEdit;
}
public void setIsEdit(boolean value)
{
privateIsEdit = value;
}
private boolean isCPUinitialized = false;
private boolean privateIsNew;
public boolean getIsNew()
{
return privateIsNew;
}
public void setIsNew(boolean value)
{
privateIsNew = value;
}
private String privateOriginalName;
public String getOriginalName()
{
return privateOriginalName;
}
public void setOriginalName(String value)
{
privateOriginalName = value;
}
private NGuid privateClusterId;
public NGuid getClusterId()
{
return privateClusterId;
}
public void setClusterId(NGuid value)
{
privateClusterId = value;
}
private EntityModel privateName;
public EntityModel getName()
{
return privateName;
}
public void setName(EntityModel value)
{
privateName = value;
}
private EntityModel privateDescription;
public EntityModel getDescription()
{
return privateDescription;
}
public void setDescription(EntityModel value)
{
privateDescription = value;
}
private ListModel privateDataCenter;
public ListModel getDataCenter()
{
return privateDataCenter;
}
public void setDataCenter(ListModel value)
{
privateDataCenter = value;
}
private ListModel privateCPU;
public ListModel getCPU()
{
return privateCPU;
}
public void setCPU(ListModel value)
{
privateCPU = value;
}
private ListModel privateVersion;
public ListModel getVersion()
{
return privateVersion;
}
public void setVersion(ListModel value)
{
privateVersion = value;
}
private EntityModel privateOptimizationNone;
public EntityModel getOptimizationNone()
{
return privateOptimizationNone;
}
public void setOptimizationNone(EntityModel value)
{
privateOptimizationNone = value;
}
private EntityModel privateOptimizationForServer;
public EntityModel getOptimizationForServer()
{
return privateOptimizationForServer;
}
public void setOptimizationForServer(EntityModel value)
{
privateOptimizationForServer = value;
}
private EntityModel privateOptimizationForDesktop;
public EntityModel getOptimizationForDesktop()
{
return privateOptimizationForDesktop;
}
public void setOptimizationForDesktop(EntityModel value)
{
privateOptimizationForDesktop = value;
}
private EntityModel privateOptimizationCustom;
public EntityModel getOptimizationCustom()
{
return privateOptimizationCustom;
}
public void setOptimizationCustom(EntityModel value)
{
privateOptimizationCustom = value;
}
private EntityModel privateOptimizationNone_IsSelected;
public EntityModel getOptimizationNone_IsSelected()
{
return privateOptimizationNone_IsSelected;
}
public void setOptimizationNone_IsSelected(EntityModel value)
{
privateOptimizationNone_IsSelected = value;
}
private EntityModel privateOptimizationForServer_IsSelected;
public EntityModel getOptimizationForServer_IsSelected()
{
return privateOptimizationForServer_IsSelected;
}
public void setOptimizationForServer_IsSelected(EntityModel value)
{
privateOptimizationForServer_IsSelected = value;
}
private EntityModel privateOptimizationForDesktop_IsSelected;
public EntityModel getOptimizationForDesktop_IsSelected()
{
return privateOptimizationForDesktop_IsSelected;
}
public void setOptimizationForDesktop_IsSelected(EntityModel value)
{
privateOptimizationForDesktop_IsSelected = value;
}
private EntityModel privateOptimizationCustom_IsSelected;
public EntityModel getOptimizationCustom_IsSelected()
{
return privateOptimizationCustom_IsSelected;
}
public void setOptimizationCustom_IsSelected(EntityModel value)
{
privateOptimizationCustom_IsSelected = value;
}
private EntityModel privateMigrateOnErrorOption_NO;
public EntityModel getMigrateOnErrorOption_NO()
{
return privateMigrateOnErrorOption_NO;
}
public void setMigrateOnErrorOption_NO(EntityModel value)
{
privateMigrateOnErrorOption_NO = value;
}
private EntityModel privateMigrateOnErrorOption_YES;
public EntityModel getMigrateOnErrorOption_YES()
{
return privateMigrateOnErrorOption_YES;
}
public void setMigrateOnErrorOption_YES(EntityModel value)
{
privateMigrateOnErrorOption_YES = value;
}
private EntityModel privateMigrateOnErrorOption_HA_ONLY;
public EntityModel getMigrateOnErrorOption_HA_ONLY()
{
return privateMigrateOnErrorOption_HA_ONLY;
}
public void setMigrateOnErrorOption_HA_ONLY(EntityModel value)
{
privateMigrateOnErrorOption_HA_ONLY = value;
}
private boolean isGeneralTabValid;
public boolean getIsGeneralTabValid()
{
return isGeneralTabValid;
}
public void setIsGeneralTabValid(boolean value)
{
if (isGeneralTabValid != value)
{
isGeneralTabValid = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsGeneralTabValid"));
}
}
private MigrateOnErrorOptions migrateOnErrorOption = MigrateOnErrorOptions.values()[0];
public MigrateOnErrorOptions getMigrateOnErrorOption()
{
if ((Boolean) getMigrateOnErrorOption_NO().getEntity() == true)
{
return MigrateOnErrorOptions.NO;
}
else if ((Boolean) getMigrateOnErrorOption_YES().getEntity() == true)
{
return MigrateOnErrorOptions.YES;
}
else if ((Boolean) getMigrateOnErrorOption_HA_ONLY().getEntity() == true)
{
return MigrateOnErrorOptions.HA_ONLY;
}
return MigrateOnErrorOptions.YES;
}
public void setMigrateOnErrorOption(MigrateOnErrorOptions value)
{
if (migrateOnErrorOption != value)
{
migrateOnErrorOption = value;
// webadmin use.
switch (migrateOnErrorOption)
{
case NO:
getMigrateOnErrorOption_NO().setEntity(true);
getMigrateOnErrorOption_YES().setEntity(false);
getMigrateOnErrorOption_HA_ONLY().setEntity(false);
break;
case YES:
getMigrateOnErrorOption_NO().setEntity(false);
getMigrateOnErrorOption_YES().setEntity(true);
getMigrateOnErrorOption_HA_ONLY().setEntity(false);
break;
case HA_ONLY:
getMigrateOnErrorOption_NO().setEntity(false);
getMigrateOnErrorOption_YES().setEntity(false);
getMigrateOnErrorOption_HA_ONLY().setEntity(true);
break;
default:
break;
}
OnPropertyChanged(new PropertyChangedEventArgs("MigrateOnErrorOption"));
}
}
private boolean privateisResiliencePolicyTabAvailable;
public boolean getisResiliencePolicyTabAvailable()
{
return privateisResiliencePolicyTabAvailable;
}
public void setisResiliencePolicyTabAvailable(boolean value)
{
privateisResiliencePolicyTabAvailable = value;
}
public boolean getIsResiliencePolicyTabAvailable()
{
return getisResiliencePolicyTabAvailable();
}
public void setIsResiliencePolicyTabAvailable(boolean value)
{
if (getisResiliencePolicyTabAvailable() != value)
{
setisResiliencePolicyTabAvailable(value);
OnPropertyChanged(new PropertyChangedEventArgs("IsResiliencePolicyTabAvailable"));
}
}
public int getMemoryOverCommit()
{
if ((Boolean) getOptimizationNone_IsSelected().getEntity())
{
return (Integer) getOptimizationNone().getEntity();
}
if ((Boolean) getOptimizationForServer_IsSelected().getEntity())
{
return (Integer) getOptimizationForServer().getEntity();
}
if ((Boolean) getOptimizationForDesktop_IsSelected().getEntity())
{
return (Integer) getOptimizationForDesktop().getEntity();
}
if ((Boolean) getOptimizationCustom_IsSelected().getEntity())
{
return (Integer) getOptimizationCustom().getEntity();
}
return DataProvider.GetClusterDefaultMemoryOverCommit();
}
public void setMemoryOverCommit(int value)
{
getOptimizationNone_IsSelected().setEntity(value == (Integer) getOptimizationNone().getEntity());
getOptimizationForServer_IsSelected().setEntity(value == (Integer) getOptimizationForServer().getEntity());
getOptimizationForDesktop_IsSelected().setEntity(value == (Integer) getOptimizationForDesktop().getEntity());
if (!(Boolean) getOptimizationNone_IsSelected().getEntity()
&& !(Boolean) getOptimizationForServer_IsSelected().getEntity()
&& !(Boolean) getOptimizationForDesktop_IsSelected().getEntity())
{
getOptimizationCustom().setIsAvailable(true);
getOptimizationCustom().setEntity(value);
getOptimizationCustom_IsSelected().setIsAvailable(true);
getOptimizationCustom_IsSelected().setEntity(true);
}
}
public ClusterModel()
{
}
public void Init(boolean isEdit)
{
setIsEdit(isEdit);
setName(new EntityModel());
setDescription(new EntityModel());
setOptimizationNone(new EntityModel());
setOptimizationForServer(new EntityModel());
setOptimizationForDesktop(new EntityModel());
setOptimizationCustom(new EntityModel());
EntityModel tempVar = new EntityModel();
tempVar.setEntity(false);
setOptimizationNone_IsSelected(tempVar);
getOptimizationNone_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar2 = new EntityModel();
tempVar2.setEntity(false);
setOptimizationForServer_IsSelected(tempVar2);
getOptimizationForServer_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar3 = new EntityModel();
tempVar3.setEntity(false);
setOptimizationForDesktop_IsSelected(tempVar3);
getOptimizationForDesktop_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar4 = new EntityModel();
tempVar4.setEntity(false);
tempVar4.setIsAvailable(false);
setOptimizationCustom_IsSelected(tempVar4);
getOptimizationCustom_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar5 = new EntityModel();
tempVar5.setEntity(false);
setMigrateOnErrorOption_YES(tempVar5);
getMigrateOnErrorOption_YES().getEntityChangedEvent().addListener(this);
EntityModel tempVar6 = new EntityModel();
tempVar6.setEntity(false);
setMigrateOnErrorOption_NO(tempVar6);
getMigrateOnErrorOption_NO().getEntityChangedEvent().addListener(this);
EntityModel tempVar7 = new EntityModel();
tempVar7.setEntity(false);
setMigrateOnErrorOption_HA_ONLY(tempVar7);
getMigrateOnErrorOption_HA_ONLY().getEntityChangedEvent().addListener(this);
// Optimization methods:
// default value =100;
setDefaultOverCommit(DataProvider.GetClusterDefaultMemoryOverCommit());
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object result)
{
ClusterModel clusterModel = (ClusterModel) model;
- clusterModel.setServerOverCommit((Integer) result);
+ clusterModel.setDesktopOverCommit((Integer) result);
AsyncQuery _asyncQuery1 = new AsyncQuery();
_asyncQuery1.setModel(clusterModel);
_asyncQuery1.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result1)
{
ClusterModel clusterModel1 = (ClusterModel) model1;
- clusterModel1.setDesktopOverCommit((Integer) result1);
+ clusterModel1.setServerOverCommit((Integer) result1);
// temp is used for conversion purposes
EntityModel temp;
temp = clusterModel1.getOptimizationNone();
temp.setEntity(clusterModel1.getDefaultOverCommit());
// res1, res2 is used for conversion purposes.
boolean res1 = clusterModel1.getDesktopOverCommit() != clusterModel1.getDefaultOverCommit();
boolean res2 = clusterModel1.getServerOverCommit() != clusterModel1.getDefaultOverCommit();
temp = clusterModel1.getOptimizationNone_IsSelected();
setIsSelected(res1 && res2);
temp.setEntity(getIsSelected());
temp = clusterModel1.getOptimizationForServer();
temp.setEntity(clusterModel1.getServerOverCommit());
temp = clusterModel1.getOptimizationForServer_IsSelected();
temp.setEntity(clusterModel1.getServerOverCommit() == clusterModel1.getDefaultOverCommit());
temp = clusterModel1.getOptimizationForDesktop();
temp.setEntity(clusterModel1.getDesktopOverCommit());
temp = temp = clusterModel1.getOptimizationForDesktop_IsSelected();
temp.setEntity(clusterModel1.getDesktopOverCommit() == clusterModel1.getDefaultOverCommit());
temp = clusterModel1.getOptimizationCustom();
temp.setIsAvailable(false);
temp.setIsChangable(false);
if (clusterModel1.getIsEdit())
{
clusterModel1.postInit();
}
}
};
AsyncDataProvider.GetClusterServerMemoryOverCommit(_asyncQuery1);
}
};
AsyncDataProvider.GetClusterDesktopMemoryOverCommit(_asyncQuery);
setDataCenter(new ListModel());
getDataCenter().getSelectedItemChangedEvent().addListener(this);
setCPU(new ListModel());
setVersion(new ListModel());
getVersion().getSelectedItemChangedEvent().addListener(this);
setMigrateOnErrorOption(MigrateOnErrorOptions.YES);
setIsGeneralTabValid(true);
setIsResiliencePolicyTabAvailable(true);
}
private void postInit()
{
getDescription().setEntity(getEntity().getdescription());
setMemoryOverCommit(getEntity().getmax_vds_memory_over_commit());
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object result)
{
ClusterModel clusterModel = (ClusterModel) model;
java.util.ArrayList<storage_pool> dataCenters = (java.util.ArrayList<storage_pool>) result;
clusterModel.getDataCenter().setItems(dataCenters);
clusterModel.getDataCenter().setSelectedItem(null);
for (storage_pool a : dataCenters)
{
if (clusterModel.getEntity().getstorage_pool_id() != null
&& a.getId().equals(clusterModel.getEntity().getstorage_pool_id()))
{
clusterModel.getDataCenter().setSelectedItem(a);
break;
}
}
clusterModel.getDataCenter().setIsChangable(clusterModel.getDataCenter().getSelectedItem() == null);
clusterModel.setMigrateOnErrorOption(clusterModel.getEntity().getMigrateOnError());
}
};
AsyncDataProvider.GetDataCenterList(_asyncQuery);
}
@Override
public void eventRaised(Event ev, Object sender, EventArgs args)
{
super.eventRaised(ev, sender, args);
if (ev.equals(ListModel.SelectedItemChangedEventDefinition))
{
if (sender == getDataCenter())
{
StoragePool_SelectedItemChanged(args);
}
else if (sender == getVersion())
{
Version_SelectedItemChanged(args);
}
}
else if (ev.equals(EntityModel.EntityChangedEventDefinition))
{
EntityModel senderEntityModel = (EntityModel) sender;
if ((Boolean) senderEntityModel.getEntity())
{
if (senderEntityModel == getOptimizationNone_IsSelected())
{
getOptimizationForServer_IsSelected().setEntity(false);
getOptimizationForDesktop_IsSelected().setEntity(false);
getOptimizationCustom_IsSelected().setEntity(false);
}
else if (senderEntityModel == getOptimizationForServer_IsSelected())
{
getOptimizationNone_IsSelected().setEntity(false);
getOptimizationForDesktop_IsSelected().setEntity(false);
getOptimizationCustom_IsSelected().setEntity(false);
}
else if (senderEntityModel == getOptimizationForDesktop_IsSelected())
{
getOptimizationNone_IsSelected().setEntity(false);
getOptimizationForServer_IsSelected().setEntity(false);
getOptimizationCustom_IsSelected().setEntity(false);
}
else if (senderEntityModel == getOptimizationCustom_IsSelected())
{
getOptimizationNone_IsSelected().setEntity(false);
getOptimizationForServer_IsSelected().setEntity(false);
getOptimizationForDesktop_IsSelected().setEntity(false);
}
else if (senderEntityModel == getMigrateOnErrorOption_YES())
{
getMigrateOnErrorOption_NO().setEntity(false);
getMigrateOnErrorOption_HA_ONLY().setEntity(false);
}
else if (senderEntityModel == getMigrateOnErrorOption_NO())
{
getMigrateOnErrorOption_YES().setEntity(false);
getMigrateOnErrorOption_HA_ONLY().setEntity(false);
}
else if (senderEntityModel == getMigrateOnErrorOption_HA_ONLY())
{
getMigrateOnErrorOption_YES().setEntity(false);
getMigrateOnErrorOption_NO().setEntity(false);
}
}
}
}
private void Version_SelectedItemChanged(EventArgs e)
{
Version version;
if (getVersion().getSelectedItem() != null)
{
version = (Version) getVersion().getSelectedItem();
}
else
{
version = ((storage_pool) getDataCenter().getSelectedItem()).getcompatibility_version();
}
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object result)
{
ClusterModel clusterModel = (ClusterModel) model;
java.util.ArrayList<ServerCpu> cpus = (java.util.ArrayList<ServerCpu>) result;
ServerCpu oldSelectedCpu = (ServerCpu) clusterModel.getCPU().getSelectedItem();
clusterModel.getCPU().setItems(cpus);
if (oldSelectedCpu != null)
{
clusterModel.getCPU().setSelectedItem(Linq.FirstOrDefault(cpus,
new Linq.ServerCpuPredicate(oldSelectedCpu.getCpuName())));
}
if (clusterModel.getCPU().getSelectedItem() == null || !isCPUinitialized)
{
clusterModel.getCPU().setSelectedItem(Linq.FirstOrDefault(cpus));
InitCPU();
}
}
};
AsyncDataProvider.GetCPUList(_asyncQuery, version);
}
private void InitCPU()
{
if (!isCPUinitialized && getIsEdit())
{
isCPUinitialized = true;
getCPU().setSelectedItem(null);
for (ServerCpu a : (java.util.ArrayList<ServerCpu>) getCPU().getItems())
{
if (StringHelper.stringsEqual(a.getCpuName(), getEntity().getcpu_name()))
{
getCPU().setSelectedItem(a);
break;
}
}
}
}
private void StoragePool_SelectedItemChanged(EventArgs e)
{
// possible versions for new cluster (when editing cluster, this event won't occur)
// are actually the possible versions for the data-center that the cluster is going
// to be attached to.
storage_pool selectedDataCenter = (storage_pool) getDataCenter().getSelectedItem();
if (selectedDataCenter == null)
{
return;
}
if (selectedDataCenter.getstorage_pool_type() == StorageType.LOCALFS)
{
setIsResiliencePolicyTabAvailable(false);
}
else
{
setIsResiliencePolicyTabAvailable(true);
}
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object result)
{
ClusterModel clusterModel = (ClusterModel) model;
java.util.ArrayList<Version> versions = (java.util.ArrayList<Version>) result;
clusterModel.getVersion().setItems(versions);
if (!versions.contains(clusterModel.getVersion().getSelectedItem()))
{
if (versions.contains(((storage_pool) clusterModel.getDataCenter().getSelectedItem()).getcompatibility_version()))
{
clusterModel.getVersion().setSelectedItem(((storage_pool) clusterModel.getDataCenter()
.getSelectedItem()).getcompatibility_version());
}
else
{
clusterModel.getVersion().setSelectedItem(Linq.SelectHighestVersion(versions));
}
}
}
};
AsyncDataProvider.GetDataCenterVersions(_asyncQuery, selectedDataCenter == null ? null
: (NGuid) (selectedDataCenter.getId()));
}
public boolean Validate()
{
return Validate(true);
}
public boolean Validate(boolean validateStoragePool)
{
LengthValidation tempVar = new LengthValidation();
tempVar.setMaxLength(40);
RegexValidation tempVar2 = new RegexValidation();
tempVar2.setExpression("^[A-Za-z0-9_-]+$");
tempVar2.setMessage("Name can contain only 'A-Z', 'a-z', '0-9', '_' or '-' characters.");
getName().ValidateEntity(new IValidation[] { new NotEmptyValidation(), new NoSpacesValidation(), tempVar,
tempVar2 });
if (validateStoragePool)
{
getDataCenter().ValidateSelectedItem(new IValidation[] { new NotEmptyValidation() });
}
getCPU().ValidateSelectedItem(new IValidation[] { new NotEmptyValidation() });
getVersion().ValidateSelectedItem(new IValidation[] { new NotEmptyValidation() });
// TODO: async validation for webadmin
// string name = (string)Name.Entity;
// //Check name unicitate.
// if (String.Compare(name, OriginalName, true) != 0 && !DataProvider.IsClusterNameUnique(name))
// {
// Name.IsValid = false;
// Name.InvalidityReasons.Add("Name must be unique.");
// }
setIsGeneralTabValid(getName().getIsValid() && getDataCenter().getIsValid() && getCPU().getIsValid()
&& getVersion().getIsValid());
return getName().getIsValid() && getDataCenter().getIsValid() && getCPU().getIsValid()
&& getVersion().getIsValid();
}
}
| false | true | public void Init(boolean isEdit)
{
setIsEdit(isEdit);
setName(new EntityModel());
setDescription(new EntityModel());
setOptimizationNone(new EntityModel());
setOptimizationForServer(new EntityModel());
setOptimizationForDesktop(new EntityModel());
setOptimizationCustom(new EntityModel());
EntityModel tempVar = new EntityModel();
tempVar.setEntity(false);
setOptimizationNone_IsSelected(tempVar);
getOptimizationNone_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar2 = new EntityModel();
tempVar2.setEntity(false);
setOptimizationForServer_IsSelected(tempVar2);
getOptimizationForServer_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar3 = new EntityModel();
tempVar3.setEntity(false);
setOptimizationForDesktop_IsSelected(tempVar3);
getOptimizationForDesktop_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar4 = new EntityModel();
tempVar4.setEntity(false);
tempVar4.setIsAvailable(false);
setOptimizationCustom_IsSelected(tempVar4);
getOptimizationCustom_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar5 = new EntityModel();
tempVar5.setEntity(false);
setMigrateOnErrorOption_YES(tempVar5);
getMigrateOnErrorOption_YES().getEntityChangedEvent().addListener(this);
EntityModel tempVar6 = new EntityModel();
tempVar6.setEntity(false);
setMigrateOnErrorOption_NO(tempVar6);
getMigrateOnErrorOption_NO().getEntityChangedEvent().addListener(this);
EntityModel tempVar7 = new EntityModel();
tempVar7.setEntity(false);
setMigrateOnErrorOption_HA_ONLY(tempVar7);
getMigrateOnErrorOption_HA_ONLY().getEntityChangedEvent().addListener(this);
// Optimization methods:
// default value =100;
setDefaultOverCommit(DataProvider.GetClusterDefaultMemoryOverCommit());
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object result)
{
ClusterModel clusterModel = (ClusterModel) model;
clusterModel.setServerOverCommit((Integer) result);
AsyncQuery _asyncQuery1 = new AsyncQuery();
_asyncQuery1.setModel(clusterModel);
_asyncQuery1.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result1)
{
ClusterModel clusterModel1 = (ClusterModel) model1;
clusterModel1.setDesktopOverCommit((Integer) result1);
// temp is used for conversion purposes
EntityModel temp;
temp = clusterModel1.getOptimizationNone();
temp.setEntity(clusterModel1.getDefaultOverCommit());
// res1, res2 is used for conversion purposes.
boolean res1 = clusterModel1.getDesktopOverCommit() != clusterModel1.getDefaultOverCommit();
boolean res2 = clusterModel1.getServerOverCommit() != clusterModel1.getDefaultOverCommit();
temp = clusterModel1.getOptimizationNone_IsSelected();
setIsSelected(res1 && res2);
temp.setEntity(getIsSelected());
temp = clusterModel1.getOptimizationForServer();
temp.setEntity(clusterModel1.getServerOverCommit());
temp = clusterModel1.getOptimizationForServer_IsSelected();
temp.setEntity(clusterModel1.getServerOverCommit() == clusterModel1.getDefaultOverCommit());
temp = clusterModel1.getOptimizationForDesktop();
temp.setEntity(clusterModel1.getDesktopOverCommit());
temp = temp = clusterModel1.getOptimizationForDesktop_IsSelected();
temp.setEntity(clusterModel1.getDesktopOverCommit() == clusterModel1.getDefaultOverCommit());
temp = clusterModel1.getOptimizationCustom();
temp.setIsAvailable(false);
temp.setIsChangable(false);
if (clusterModel1.getIsEdit())
{
clusterModel1.postInit();
}
}
};
AsyncDataProvider.GetClusterServerMemoryOverCommit(_asyncQuery1);
}
};
AsyncDataProvider.GetClusterDesktopMemoryOverCommit(_asyncQuery);
setDataCenter(new ListModel());
getDataCenter().getSelectedItemChangedEvent().addListener(this);
setCPU(new ListModel());
setVersion(new ListModel());
getVersion().getSelectedItemChangedEvent().addListener(this);
setMigrateOnErrorOption(MigrateOnErrorOptions.YES);
setIsGeneralTabValid(true);
setIsResiliencePolicyTabAvailable(true);
}
| public void Init(boolean isEdit)
{
setIsEdit(isEdit);
setName(new EntityModel());
setDescription(new EntityModel());
setOptimizationNone(new EntityModel());
setOptimizationForServer(new EntityModel());
setOptimizationForDesktop(new EntityModel());
setOptimizationCustom(new EntityModel());
EntityModel tempVar = new EntityModel();
tempVar.setEntity(false);
setOptimizationNone_IsSelected(tempVar);
getOptimizationNone_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar2 = new EntityModel();
tempVar2.setEntity(false);
setOptimizationForServer_IsSelected(tempVar2);
getOptimizationForServer_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar3 = new EntityModel();
tempVar3.setEntity(false);
setOptimizationForDesktop_IsSelected(tempVar3);
getOptimizationForDesktop_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar4 = new EntityModel();
tempVar4.setEntity(false);
tempVar4.setIsAvailable(false);
setOptimizationCustom_IsSelected(tempVar4);
getOptimizationCustom_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel tempVar5 = new EntityModel();
tempVar5.setEntity(false);
setMigrateOnErrorOption_YES(tempVar5);
getMigrateOnErrorOption_YES().getEntityChangedEvent().addListener(this);
EntityModel tempVar6 = new EntityModel();
tempVar6.setEntity(false);
setMigrateOnErrorOption_NO(tempVar6);
getMigrateOnErrorOption_NO().getEntityChangedEvent().addListener(this);
EntityModel tempVar7 = new EntityModel();
tempVar7.setEntity(false);
setMigrateOnErrorOption_HA_ONLY(tempVar7);
getMigrateOnErrorOption_HA_ONLY().getEntityChangedEvent().addListener(this);
// Optimization methods:
// default value =100;
setDefaultOverCommit(DataProvider.GetClusterDefaultMemoryOverCommit());
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object result)
{
ClusterModel clusterModel = (ClusterModel) model;
clusterModel.setDesktopOverCommit((Integer) result);
AsyncQuery _asyncQuery1 = new AsyncQuery();
_asyncQuery1.setModel(clusterModel);
_asyncQuery1.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model1, Object result1)
{
ClusterModel clusterModel1 = (ClusterModel) model1;
clusterModel1.setServerOverCommit((Integer) result1);
// temp is used for conversion purposes
EntityModel temp;
temp = clusterModel1.getOptimizationNone();
temp.setEntity(clusterModel1.getDefaultOverCommit());
// res1, res2 is used for conversion purposes.
boolean res1 = clusterModel1.getDesktopOverCommit() != clusterModel1.getDefaultOverCommit();
boolean res2 = clusterModel1.getServerOverCommit() != clusterModel1.getDefaultOverCommit();
temp = clusterModel1.getOptimizationNone_IsSelected();
setIsSelected(res1 && res2);
temp.setEntity(getIsSelected());
temp = clusterModel1.getOptimizationForServer();
temp.setEntity(clusterModel1.getServerOverCommit());
temp = clusterModel1.getOptimizationForServer_IsSelected();
temp.setEntity(clusterModel1.getServerOverCommit() == clusterModel1.getDefaultOverCommit());
temp = clusterModel1.getOptimizationForDesktop();
temp.setEntity(clusterModel1.getDesktopOverCommit());
temp = temp = clusterModel1.getOptimizationForDesktop_IsSelected();
temp.setEntity(clusterModel1.getDesktopOverCommit() == clusterModel1.getDefaultOverCommit());
temp = clusterModel1.getOptimizationCustom();
temp.setIsAvailable(false);
temp.setIsChangable(false);
if (clusterModel1.getIsEdit())
{
clusterModel1.postInit();
}
}
};
AsyncDataProvider.GetClusterServerMemoryOverCommit(_asyncQuery1);
}
};
AsyncDataProvider.GetClusterDesktopMemoryOverCommit(_asyncQuery);
setDataCenter(new ListModel());
getDataCenter().getSelectedItemChangedEvent().addListener(this);
setCPU(new ListModel());
setVersion(new ListModel());
getVersion().getSelectedItemChangedEvent().addListener(this);
setMigrateOnErrorOption(MigrateOnErrorOptions.YES);
setIsGeneralTabValid(true);
setIsResiliencePolicyTabAvailable(true);
}
|
diff --git a/src/main/java/com/ryanmichela/giantcaves/GCChunkProviderGenerate.java b/src/main/java/com/ryanmichela/giantcaves/GCChunkProviderGenerate.java
index d588d15..b839afe 100644
--- a/src/main/java/com/ryanmichela/giantcaves/GCChunkProviderGenerate.java
+++ b/src/main/java/com/ryanmichela/giantcaves/GCChunkProviderGenerate.java
@@ -1,64 +1,68 @@
package com.ryanmichela.giantcaves;
import net.minecraft.server.v1_7_R1.*;
import java.util.Random;
/**
* Copyright 2013 Ryan Michela
*/
public class GCChunkProviderGenerate extends ChunkProviderGenerate {
public GCChunkProviderGenerate(World world, long l, boolean b) {
super(world, l, b);
}
@Override
public Chunk getChunkAt(int i, int j) {
throw new UnsupportedOperationException();
}
@Override
public Chunk getOrCreateChunk(int i, int j) {
throw new UnsupportedOperationException();
}
public byte[][] getChunkSectionsAt(int ii, int jj) {
Random i = ReflectionUtil.getProtectedValue(this, "i");
World n = ReflectionUtil.getProtectedValue(this, "n");
Boolean o = ReflectionUtil.getProtectedValue(this, "o");
WorldGenBase t = ReflectionUtil.getProtectedValue(this, "t");
WorldGenStronghold u = ReflectionUtil.getProtectedValue(this, "u");
WorldGenVillage v = ReflectionUtil.getProtectedValue(this, "v");
WorldGenMineshaft w = ReflectionUtil.getProtectedValue(this, "w");
WorldGenLargeFeature x = ReflectionUtil.getProtectedValue(this, "x");
WorldGenBase y = ReflectionUtil.getProtectedValue(this, "y");
BiomeBase[] z = ReflectionUtil.getProtectedValue(this, "z");
i.setSeed(ii * 341873128712L + jj * 132897987541L);
Block[] arrayOfBlock = new Block[65536];
byte[] arrayOfByte1 = new byte[65536];
a(ii, jj, arrayOfBlock);
z = n.getWorldChunkManager().getBiomeBlock(z, ii * 16, jj * 16, 16, 16);
a(ii, jj, arrayOfBlock, arrayOfByte1, z);
t.a(this, n, ii, jj, arrayOfBlock);
y.a(this, n, ii, jj, arrayOfBlock);
if (o) {
w.a(this, n, ii, jj, arrayOfBlock);
v.a(this, n, ii, jj, arrayOfBlock);
u.a(this, n, ii, jj, arrayOfBlock);
x.a(this, n, ii, jj, arrayOfBlock);
}
Chunk localChunk = new Chunk(n, arrayOfBlock, arrayOfByte1, ii, jj);
ChunkSection[] chunkSections = localChunk.i();
byte[][] chunkSectionBytes = new byte[chunkSections.length][];
for(int k = 0; k < chunkSectionBytes.length; k++) {
- chunkSectionBytes[k] = chunkSections[k].getIdArray();
+ if (chunkSections[k] != null) {
+ chunkSectionBytes[k] = chunkSections[k].getIdArray();
+ } else {
+ chunkSectionBytes[k] = null;
+ }
}
return chunkSectionBytes;
}
}
| true | true | public byte[][] getChunkSectionsAt(int ii, int jj) {
Random i = ReflectionUtil.getProtectedValue(this, "i");
World n = ReflectionUtil.getProtectedValue(this, "n");
Boolean o = ReflectionUtil.getProtectedValue(this, "o");
WorldGenBase t = ReflectionUtil.getProtectedValue(this, "t");
WorldGenStronghold u = ReflectionUtil.getProtectedValue(this, "u");
WorldGenVillage v = ReflectionUtil.getProtectedValue(this, "v");
WorldGenMineshaft w = ReflectionUtil.getProtectedValue(this, "w");
WorldGenLargeFeature x = ReflectionUtil.getProtectedValue(this, "x");
WorldGenBase y = ReflectionUtil.getProtectedValue(this, "y");
BiomeBase[] z = ReflectionUtil.getProtectedValue(this, "z");
i.setSeed(ii * 341873128712L + jj * 132897987541L);
Block[] arrayOfBlock = new Block[65536];
byte[] arrayOfByte1 = new byte[65536];
a(ii, jj, arrayOfBlock);
z = n.getWorldChunkManager().getBiomeBlock(z, ii * 16, jj * 16, 16, 16);
a(ii, jj, arrayOfBlock, arrayOfByte1, z);
t.a(this, n, ii, jj, arrayOfBlock);
y.a(this, n, ii, jj, arrayOfBlock);
if (o) {
w.a(this, n, ii, jj, arrayOfBlock);
v.a(this, n, ii, jj, arrayOfBlock);
u.a(this, n, ii, jj, arrayOfBlock);
x.a(this, n, ii, jj, arrayOfBlock);
}
Chunk localChunk = new Chunk(n, arrayOfBlock, arrayOfByte1, ii, jj);
ChunkSection[] chunkSections = localChunk.i();
byte[][] chunkSectionBytes = new byte[chunkSections.length][];
for(int k = 0; k < chunkSectionBytes.length; k++) {
chunkSectionBytes[k] = chunkSections[k].getIdArray();
}
return chunkSectionBytes;
}
| public byte[][] getChunkSectionsAt(int ii, int jj) {
Random i = ReflectionUtil.getProtectedValue(this, "i");
World n = ReflectionUtil.getProtectedValue(this, "n");
Boolean o = ReflectionUtil.getProtectedValue(this, "o");
WorldGenBase t = ReflectionUtil.getProtectedValue(this, "t");
WorldGenStronghold u = ReflectionUtil.getProtectedValue(this, "u");
WorldGenVillage v = ReflectionUtil.getProtectedValue(this, "v");
WorldGenMineshaft w = ReflectionUtil.getProtectedValue(this, "w");
WorldGenLargeFeature x = ReflectionUtil.getProtectedValue(this, "x");
WorldGenBase y = ReflectionUtil.getProtectedValue(this, "y");
BiomeBase[] z = ReflectionUtil.getProtectedValue(this, "z");
i.setSeed(ii * 341873128712L + jj * 132897987541L);
Block[] arrayOfBlock = new Block[65536];
byte[] arrayOfByte1 = new byte[65536];
a(ii, jj, arrayOfBlock);
z = n.getWorldChunkManager().getBiomeBlock(z, ii * 16, jj * 16, 16, 16);
a(ii, jj, arrayOfBlock, arrayOfByte1, z);
t.a(this, n, ii, jj, arrayOfBlock);
y.a(this, n, ii, jj, arrayOfBlock);
if (o) {
w.a(this, n, ii, jj, arrayOfBlock);
v.a(this, n, ii, jj, arrayOfBlock);
u.a(this, n, ii, jj, arrayOfBlock);
x.a(this, n, ii, jj, arrayOfBlock);
}
Chunk localChunk = new Chunk(n, arrayOfBlock, arrayOfByte1, ii, jj);
ChunkSection[] chunkSections = localChunk.i();
byte[][] chunkSectionBytes = new byte[chunkSections.length][];
for(int k = 0; k < chunkSectionBytes.length; k++) {
if (chunkSections[k] != null) {
chunkSectionBytes[k] = chunkSections[k].getIdArray();
} else {
chunkSectionBytes[k] = null;
}
}
return chunkSectionBytes;
}
|
diff --git a/src/org/trecena/modules/jira/JiraModule.java b/src/org/trecena/modules/jira/JiraModule.java
index 47e65bf..107ae75 100644
--- a/src/org/trecena/modules/jira/JiraModule.java
+++ b/src/org/trecena/modules/jira/JiraModule.java
@@ -1,828 +1,828 @@
package org.trecena.modules.jira;
import com.atlassian.jira.rpc.exception.RemoteAuthenticationException;
import com.atlassian.jira.rpc.exception.RemotePermissionException;
import com.atlassian.jira.rpc.soap.beans.*;
import com.atlassian.jira.rpc.soap.jirasoapservice_v2.JiraSoapService;
import com.atlassian.jira.rpc.soap.jirasoapservice_v2.JiraSoapServiceServiceLocator;
import org.apache.axis.AxisFault;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.trecena.ApplicationException;
import org.trecena.ModuleManager;
import org.trecena.UserManager;
import org.trecena.beans.*;
import org.trecena.dto.ResultDTO;
import org.trecena.dto.UserDTO;
import org.trecena.modules.jira.dto.*;
import javax.annotation.PostConstruct;
import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* Jira integration module.
*
* @author Ivan Latysh <[email protected]>
* @version 0.1
* @since 22/11/11 7:12 PM
*/
@Transactional(propagation = Propagation.REQUIRED)
@Component
public class JiraModule {
// Error prefix JIRA300032
/** Logger */
protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
/** JiraModule name */
public final static String MODULE_NAME = JiraModule.class.getName();
/** JiraModule name */
public final static String MODULE_TITLE = "Jira";
/** Number of errors to occur before server is auto-disabled */
public static final long ERROR_THRESHOLD = 3L;
/** JiraModule mappingBean */
protected ModuleBean moduleBean = new ModuleBean(null,
MODULE_NAME,
MODULE_TITLE,
"jira/settings.html",
"jira/userprofile.html",
new Date());
@Autowired
protected ModuleManager moduleManager;
/** User manager */
@Autowired
protected UserManager userManager;
@Autowired
protected SessionFactory sessionFactory;
@Autowired
protected XStreamMarshaller xstream;
/**
* Register jiraModule
*
* @throws ApplicationException when failed
*/
@PostConstruct
public void registerModule() throws ApplicationException {
moduleBean = moduleManager.registerModule(moduleBean);
// register annotated XStream DTO's
xstream.setAnnotatedClasses(new Class[]{
JiraServerDTO.class,
JiraServerInfoDTO.class,
JiraUserAccountMappingDTO.class,
JiraIssueTypeMappingDTO.class,
JiraIssueStatusMappingDTO.class,
JiraIssuePriorityMappingDTO.class,
JiraIssuePriorityDTO.class,
JiraIssueStatusDTO.class,
JiraIssueTypeDTO.class,
JiraFilterDTO.class
});
}
/**
* Create and return JIRA SOAP service endpoint
*
* @param jiraServer jira server to get the service for
* @return service endpoint
* @throws javax.xml.rpc.ServiceException
* @throws java.rmi.RemoteException
*/
public JiraSoapService getService(JiraServerBean jiraServer) throws ServiceException, java.rmi.RemoteException {
JiraSoapServiceServiceLocator jiraSoapServiceGetter = new JiraSoapServiceServiceLocator();
// set endpoint URL
jiraSoapServiceGetter.setEndpointAddress("JirasoapserviceV2", jiraServer.getUrl());
// return service
return jiraSoapServiceGetter.getJirasoapserviceV2();
}
/**
* Login to given server
* @param jiraServer server
* @param jiraSoapService soap service
* @throws ApplicationException when failed
*/
public String login(JiraServerBean jiraServer, JiraSoapService jiraSoapService) throws ApplicationException {
try {
return jiraSoapService.login(jiraServer.getLogin(), jiraServer.getPassword());
} catch (AxisFault axisex) {
throw new ApplicationException("JIRA300003", "["+axisex.getFaultCode()+"] "+axisex.getFaultString(), axisex);
} catch (RemoteException ex) {
throw new ApplicationException("JIRA300003", ex.getMessage(), ex);
}
}
/**
* Return all configured JIRA servers
*
* @return server list
* @throws ApplicationException when failed
*/
public List<JiraServerBean> getServers() throws ApplicationException{
try {
Session session = sessionFactory.getCurrentSession();
return session.createCriteria(JiraServerBean.class)
.add(Restrictions.eq("enabled", true))
.list();
} catch (Exception ex) {
logger.error( "[JIRA300003] Unable to load registered servers.", ex);
throw new ApplicationException("JIRA300003", "Unable to load registered servers.", ex);
}
}
/**
* Return server with given ID
*
* @param id serve id
* @return server or null
* @throws ApplicationException when failes
*/
public JiraServerBean getServer(Long id) throws ApplicationException {
try {
Session session = sessionFactory.getCurrentSession();
return (JiraServerBean) session.get(JiraServerBean.class, id);
} catch (Exception ex) {
logger.error( "[JIRA300004] Unable to load server with id {"+id+"}", ex);
throw new ApplicationException("JIRA300004", "Unable to load server with id {"+id+"}", ex);
}
}
/**
* Save given server
*
* @param serverBean server to save
* @return saved server
* @throws ApplicationException when failed
*/
public JiraServerBean saveServer(JiraServerBean serverBean) throws ApplicationException {
try {
Session session = sessionFactory.getCurrentSession();
// merge if required
if (null!=serverBean.getId()) {
serverBean = (JiraServerBean) session.merge(serverBean);
} else {
// set error threshold
serverBean.setErrorThreshold(ERROR_THRESHOLD);
}
// save changes
session.save(serverBean);
// return saved server
return serverBean;
} catch (Exception ex) {
logger.error( "[JIRA300005] Unable to save server {"+ serverBean +"}", ex);
throw new ApplicationException("JIRA300005", "Unable to save server {"+ serverBean +"}", ex);
}
}
/**
* Delete server with given ID
*
* @param serverBean server mappingBean to delete
* @throws ApplicationException when failed
*/
public void deleteServer(JiraServerBean serverBean) throws ApplicationException {
try {
Session session = sessionFactory.getCurrentSession();
session.delete(serverBean);
} catch (Exception ex) {
logger.error( "[JIRA300011] Unable to delete server {"+serverBean+"}.", ex);
throw new ApplicationException("JIRA300011", "Unable to delete server {"+serverBean+"}.", ex);
}
}
/**
* Return Trecena user for given JIRA username
*
* @param username JIRA username
* @param server server
* @return Trecena user or null when no user has been found
* @throws ApplicationException when failed
*/
public UserBean getTrecenaUserForJiraUser(String username, JiraServerBean server) throws ApplicationException {
try {
Session session = sessionFactory.getCurrentSession();
// check mappings
List mappings = session.createCriteria(JiraUserAccountMappingBean.class)
.add(Restrictions.eq("server", server))
.add(Restrictions.eq("jiraUsername", username))
.list();
if (mappings.size()>0) {
return ((JiraUserAccountMappingBean)mappings.get(0)).getUser();
}
// try direct mapping
try {
return userManager.getUserByLogin(username);
} catch (Exception e) {
logger.warn( "Unable to find Trecena user for JIRA user {"+username+"}.", e);
}
// unable to map the user
return null;
} catch (Exception ex) {
logger.error( "[JIRA300009] Unable to find Trecena user for JIRA user {"+username+"}.", ex);
throw new ApplicationException("JIRA300009", "Unable to find Trecena user for JIRA user {"+username+"}.", ex);
}
}
/**
* Return Trecena user bean for given username
*
* @param userName user name
* @return Trecena user bean or null, if user has not ben found.
* @throws ApplicationException when failed
*/
public UserBean getUserBean(String userName) throws ApplicationException {
return userManager.getUserByLogin(userName);
}
/**
* Return user mappings for given server
*
*
* @param server server
* @param userBean user bean to get mappings for, or null to get mappings for all users
* @return list of user mappings
* @throws ApplicationException when failed
*/
public Result<JiraUserAccountMappingBean> getUserMappings(JiraServerBean server, UserBean userBean, int firstResult, int maxResults) throws ApplicationException {
Result<JiraUserAccountMappingBean> reslt = new Result<JiraUserAccountMappingBean>();
try {
Session session = sessionFactory.getCurrentSession();
// count rows
Criteria rowCountCriteria = session.createCriteria(JiraUserAccountMappingBean.class)
.add(Restrictions.eq("server", server))
.setProjection(Projections.rowCount());
// set user restrictions if needed
if (null!=userBean && null!=userBean.getId()) {
rowCountCriteria.add(Restrictions.eq("user", userBean));
}
reslt.setAvailable(rowCountCriteria.uniqueResult());
if (reslt.getAvailable() == 0) return reslt;
// list records
Criteria listCriteria = session.createCriteria(JiraUserAccountMappingBean.class)
.add(Restrictions.eq("server", server))
.setFirstResult(firstResult)
.setMaxResults(maxResults);
// set user restrictions if needed
if (null!=userBean && null!=userBean.getId()) {
- rowCountCriteria.add(Restrictions.eq("user", userBean));
+ listCriteria.add(Restrictions.eq("user", userBean));
}
List<JiraUserAccountMappingBean> mappings = listCriteria.list();
for (JiraUserAccountMappingBean mappingBean : mappings) {
reslt.getEntities().add(mappingBean);
}
// set returned
reslt.setReturned(reslt.getEntities().size());
// return result
return reslt;
} catch (Exception ex) {
logger.error( "[JIRA300010] Unable to return user mappings.", ex);
throw new ApplicationException("JIRA300010", "Unable to return user mappings.", ex);
}
}
/**
* Return jira user account mapping with given id
* @param mappingId mapping id
* @return mapping bean or null
* @throws ApplicationException when failed
*/
public JiraUserAccountMappingBean getUserMapping(Long mappingId) throws ApplicationException {
try {
Session session = sessionFactory.getCurrentSession();
return (JiraUserAccountMappingBean) session.get(JiraUserAccountMappingBean.class, mappingId);
} catch (Exception ex) {
logger.error( "[JIRA300014] Unable to load user mapping with id {"+mappingId+"}", ex);
throw new ApplicationException("JIRA300014", "Unable to load user mapping", ex);
}
}
/**
* Save user account mapping
*
* @param mappingBean mapping to save
* @return saved mapping
* @throws ApplicationException when failed
*/
public JiraUserAccountMappingBean saveUserAccountMapping(JiraUserAccountMappingBean mappingBean) throws ApplicationException{
try {
// sanity check
if (null==mappingBean) return null;
Session session = sessionFactory.getCurrentSession();
if (null!= mappingBean.getId()) {
mappingBean = (JiraUserAccountMappingBean) session.merge(mappingBean);
}
session.saveOrUpdate(mappingBean);
return mappingBean;
} catch (Exception ex) {
logger.error( "[JIRA300012] Unable to save user account mapping {"+mappingBean+"}", ex);
throw new ApplicationException("JIRA300012", "Unable to save user account mapping.", ex);
}
}
/**
* Delete given mapping
*
* @param mappingBean mapping bean
* @throws ApplicationException when failed
*/
public void deleteUserAccountMapping(JiraUserAccountMappingBean mappingBean) throws ApplicationException {
try {
// sanity check
if (null==mappingBean || null==mappingBean.getId()) return;
Session session = sessionFactory.getCurrentSession();
session.delete(mappingBean);
} catch (Exception ex) {
logger.error( "[JIRA300013] Unable to delete user account mapping {"+mappingBean+"}", ex);
throw new ApplicationException("JIRA300013", "Unable to delete user account mapping", ex);
}
}
/**
* Return issue type mappings
*
* @param server server to get mappings for
* @return type mappings
* @throws ApplicationException when failed
*/
public Result<JiraIssueTypeMappingBean> getIssueTypeMappings(JiraServerBean server) throws ApplicationException{
Result<JiraIssueTypeMappingBean> reslt;
try {
Session session = sessionFactory.getCurrentSession();
List<JiraIssueTypeMappingBean> _mappings = session.createCriteria(JiraIssueTypeMappingBean.class)
.add(Restrictions.eq("server", server))
.list();
if (null==_mappings || _mappings.size()==0) return Result.EMPTY_RESULT;
reslt = new Result<JiraIssueTypeMappingBean>();
reslt.setIndex(0);
reslt.setAvailable(_mappings.size());
reslt.setReturned(_mappings.size());
for (JiraIssueTypeMappingBean bean: _mappings) {
reslt.getEntities().add(bean);
}
return reslt;
} catch (Exception ex) {
logger.error( "[JIRA300006] Unable to load issue type mappings for server {"+server+"}.", ex);
throw new ApplicationException("JIRA300006", "Unable to load issue type mappings.", ex);
}
}
/**
* Return issue type mapping
*
* @param mappingId id of the mapping to return
* @return type mapping
* @throws ApplicationException when failed
*/
public JiraIssueTypeMappingBean getIssueTypeMapping(Long mappingId) throws ApplicationException{
try {
Session session = sessionFactory.getCurrentSession();
return (JiraIssueTypeMappingBean) session.get(JiraIssueTypeMappingBean.class, mappingId);
} catch (Exception ex) {
logger.error( "[JIRA300017] Unable to load issue type mapping with id {"+mappingId+"}.", ex);
throw new ApplicationException("JIRA300017", "Unable to load issue type mapping.", ex);
}
}
/**
* Save given type mapping
*
* @param mappingBean mapping to save
* @return saved mapping bean
* @throws ApplicationException when failed
*/
public JiraIssueTypeMappingBean saveIssueTypeMapping(JiraIssueTypeMappingBean mappingBean) throws ApplicationException{
try {
// sanity check
if (null==mappingBean) return null;
Session session = sessionFactory.getCurrentSession();
if (null!=mappingBean.getId()) {
mappingBean = (JiraIssueTypeMappingBean) session.merge(mappingBean);
}
session.saveOrUpdate(mappingBean);
return mappingBean;
} catch (Exception ex) {
logger.error( "[JIRA300015] Unable to save issue type mapping bean {"+mappingBean+"}", ex);
throw new ApplicationException("JIRA300015", "Unable to save issue type mapping bean.", ex);
}
}
/**
* Delete given issue type mapping bean
*
* @param mappingBean mapping bean to delete
* @throws ApplicationException when failed
*/
public void deleteIssueTypeMapping(JiraIssueTypeMappingBean mappingBean) throws ApplicationException {
try {
// sanity check
if (null==mappingBean || null==mappingBean.getId()) return;
Session session = sessionFactory.getCurrentSession();
session.delete(mappingBean);
} catch (Exception ex) {
logger.error( "[JIRA300016] Unable to delete issue type mapping bean {"+mappingBean+"}", ex);
throw new ApplicationException("JIRA300016", "Unable to delete issue type mapping bean.", ex);
}
}
/**
* Return issue status mappings
*
* @param server server to get mappings for
* @return status mappings
* @throws ApplicationException when failed
*/
public Result<JiraIssueStatusMappingBean> getIssueStatusMappings(JiraServerBean server) throws ApplicationException{
Result<JiraIssueStatusMappingBean> reslt;
try {
// sanity check
if (null==server) return Result.EMPTY_RESULT;
Session session = sessionFactory.getCurrentSession();
List<JiraIssueStatusMappingBean> _mappings = session.createCriteria(JiraIssueStatusMappingBean.class)
.add(Restrictions.eq("server", server))
.list();
if (null==_mappings || _mappings.size()==0) return Result.EMPTY_RESULT;
reslt = new Result<JiraIssueStatusMappingBean>(null, 0, _mappings.size(), _mappings.size());
for (JiraIssueStatusMappingBean bean: _mappings) {
reslt.getEntities().add(bean);
}
return reslt;
} catch (Exception ex) {
logger.error( "[JIRA300007] Unable to load issue status mappings for server {"+server+"}.", ex);
throw new ApplicationException("JIRA300007", "Unable to load issue status mappings.", ex);
}
}
/**
* Return issue status mapping with given ID
*
* @param mappingId mapping id
* @return mapping with given id or null
* @throws ApplicationException when failed
*/
public JiraIssueStatusMappingBean getIssueStatusMapping(Long mappingId) throws ApplicationException{
try {
// sanity check
if (null==mappingId) return null;
Session session = sessionFactory.getCurrentSession();
return (JiraIssueStatusMappingBean) session.get(JiraIssueStatusMappingBean.class, mappingId);
} catch (Exception ex) {
logger.error( "[JIRA300018] Unable to return issue status mapping with id {"+mappingId+"}", ex);
throw new ApplicationException("JIRA300018", "Unable to return issue status mapping.", ex);
}
}
/**
* Save give issue status mapping
*
* @param mappingBean mapping to save
* @return saved mapping
* @throws ApplicationException when failed
*/
public JiraIssueStatusMappingBean saveIssueStatusMapping(JiraIssueStatusMappingBean mappingBean) throws ApplicationException{
try {
// sanity check
if (null==mappingBean) return null;
Session session = sessionFactory.getCurrentSession();
if (null!=mappingBean.getId()) {
mappingBean = (JiraIssueStatusMappingBean) session.merge(mappingBean);
}
session.saveOrUpdate(mappingBean);
return mappingBean;
} catch (Exception ex) {
logger.error( "[JIRA300019] Unable to save issue status mapping {"+mappingBean+"}", ex);
throw new ApplicationException("JIRA300019", "Unable to save issue status mapping.", ex);
}
}
/**
* Delete given status mapping bean
*
* @param mappingBean bean to delete
* @throws ApplicationException when failed
*/
public void deleteIssueStatusMapping(JiraIssueStatusMappingBean mappingBean) throws ApplicationException {
try {
// sanity check
if (null==mappingBean || null==mappingBean.getId()) return;
Session session = sessionFactory.getCurrentSession();
session.delete(mappingBean);
} catch (Exception ex) {
logger.error( "[JIRA300020] Unable to delete issue status mapping bean {"+mappingBean+"}", ex);
throw new ApplicationException("JIRA300020", "Unable to delete issue status mapping bean.", ex);
}
}
/**
* Return issue priority mappings
*
* @param server server to get mappings for
* @return priority mappings
* @throws ApplicationException when failed
*/
public Result<JiraIssuePriorityMappingBean> getIssuePriorityMappings(JiraServerBean server) throws ApplicationException{
Result<JiraIssuePriorityMappingBean> reslt = null;
try {
// sanity check
if (null==server) return Result.EMPTY_RESULT;
Session session = sessionFactory.getCurrentSession();
List<JiraIssuePriorityMappingBean> mappings = session.createCriteria(JiraIssuePriorityMappingBean.class)
.add(Restrictions.eq("server", server))
.list();
// create new result
reslt = new Result<JiraIssuePriorityMappingBean>(null, 0, mappings.size(), mappings.size());
// copy beans
for (JiraIssuePriorityMappingBean bean: mappings) {
reslt.getEntities().add(bean);
}
return reslt;
} catch (Exception ex) {
logger.error( "[JIRA300008] Unable to load issue priority mappings for server {"+server+"}.", ex);
throw new ApplicationException("JIRA300008", "Unable to load issue priority mappings.", ex);
}
}
/**
* Return issue priority mapping
*
* @param mappigId mapping id
* @return priority mapping
* @throws ApplicationException when failed
*/
public JiraIssuePriorityMappingBean getIssuePriorityMapping(Long mappigId) throws ApplicationException{
try {
// sanity check
if (null==mappigId) return null;
Session session = sessionFactory.getCurrentSession();
return (JiraIssuePriorityMappingBean) session.get(JiraIssuePriorityMappingBean.class, mappigId);
} catch (Exception ex) {
logger.error( "[JIRA300021] Unable to load issue priority mapping with id {"+mappigId+"}.", ex);
throw new ApplicationException("JIRA300021", "Unable to load issue priority mapping.", ex);
}
}
/**
* Save given issue priority mapping
*
* @param mappingBean mapping to save
* @return updated mapping
* @throws ApplicationException when failed
*/
public JiraIssuePriorityMappingBean saveIssuePriorityMapping(JiraIssuePriorityMappingBean mappingBean) throws ApplicationException {
try {
// sanity check
if (null==mappingBean) return null;
Session session = sessionFactory.getCurrentSession();
if (null!=mappingBean.getId()) {
mappingBean = (JiraIssuePriorityMappingBean) session.merge(mappingBean);
}
session.saveOrUpdate(mappingBean);
return mappingBean;
} catch (Exception ex) {
logger.error( "[JIRA300022] Unable to save issue priority mapping {"+mappingBean+"}", ex);
throw new ApplicationException("JIRA300022", "Unable to save issue priority mapping.", ex);
}
}
/**
* Delete issue priority mapping
*
* @param mappingBean mapping to delete
* @throws ApplicationException when failed
*/
public void deleteIssuePriorityMapping(JiraIssuePriorityMappingBean mappingBean) throws ApplicationException {
try {
// sanity check
if (null==mappingBean || null==mappingBean.getId()) return;
Session session = sessionFactory.getCurrentSession();
session.delete(mappingBean);
} catch (Exception ex) {
logger.error( "[JIRA300023] Unable to delete issue priority mapping {"+mappingBean+"}", ex);
throw new ApplicationException("JIRA300023", "Unable to delete issue priority mapping.", ex);
}
}
/**
* Return issue priorities from a remote JIRA server
*
* @param serverBean server to get priorities from
* @return priorities list
* @throws ApplicationException when failed
*/
public ResultDTO<JiraIssuePriorityDTO> getRemotePriorities(JiraServerBean serverBean) throws ApplicationException {
ResultDTO<JiraIssuePriorityDTO> reslt = null;
// sanity check
if (null==serverBean) return ResultDTO.EMPTY_RESULT;
try {
// get JIRA SOAP service
JiraSoapService service = getService(serverBean);
// login
String authToken = login(serverBean, service);
// get remote priorities
RemotePriority[] remotePriorities = service.getPriorities(authToken);
if (null==remotePriorities) return ResultDTO.EMPTY_RESULT;
// create new result
reslt = new ResultDTO<JiraIssuePriorityDTO>(null, 0, remotePriorities.length, remotePriorities.length);
// fill it up
for (RemotePriority rpr: remotePriorities) {
reslt.getEntities().add(new JiraIssuePriorityDTO(rpr.getId(), rpr.getName()));
}
// return result
return reslt;
} catch (ApplicationException appex) {
throw appex;
} catch (com.atlassian.jira.rpc.exception.RemoteException e) {
logger.error("[JIRA300024] Error while retrieving issue types from the server {"+serverBean+"}", e);
throw new ApplicationException("JIRA300024", "["+e.getFaultCode()+"] "+e.getFaultString(), e);
} catch (Exception e) {
logger.error( "[JIRA300024] Error while retrieving issue types from the server {"+serverBean+"}", e);
throw new ApplicationException("JIRA300024", "Error while retrieving issue types from the server {"+serverBean+"}", e);
}
}
/**
* Return issue statuses from a remote JIRA server
*
* @param serverBean server to get statuses from
* @return issue statuses
* @throws ApplicationException when failed
*/
public ResultDTO<JiraIssueStatusDTO> getRemoteStatuses(JiraServerBean serverBean) throws ApplicationException {
ResultDTO<JiraIssueStatusDTO> reslt = null;
// sanity check
if (null==serverBean) return ResultDTO.EMPTY_RESULT;
try {
// get JIRA SOAP service
JiraSoapService service = getService(serverBean);
// login
String authToken = login(serverBean, service);
// get remote priorities
RemoteStatus[] remoteStatuses = service.getStatuses(authToken);
if (null==remoteStatuses) return ResultDTO.EMPTY_RESULT;
// create new result
reslt = new ResultDTO<JiraIssueStatusDTO>(null, 0, remoteStatuses.length, remoteStatuses.length);
// fill it up
for (RemoteStatus rst: remoteStatuses) {
reslt.getEntities().add(new JiraIssueStatusDTO(rst.getId(), rst.getName()));
}
// return result
return reslt;
} catch (ApplicationException appex) {
throw appex;
} catch (com.atlassian.jira.rpc.exception.RemoteException e) {
logger.error("[JIRA300025] Error while retrieving issue statuses from the server {"+serverBean+"}", e);
throw new ApplicationException("JIRA300025", "["+e.getFaultCode()+"] "+e.getFaultString(), e);
} catch (Exception e) {
logger.error( "[JIRA300025] Error while retrieving issue statuses from the server {"+serverBean+"}", e);
throw new ApplicationException("JIRA300025", "Error while retrieving issue statuses from the server {"+serverBean+"}", e);
}
}
/**
* Return issue types from a remote JIRA server
* sc
* @param serverBean server to get types from
* @return issue types
* @throws ApplicationException when failed
*/
public ResultDTO<JiraIssueTypeDTO> getRemoteTypes(JiraServerBean serverBean) throws ApplicationException {
ResultDTO<JiraIssueTypeDTO> reslt = null;
// sanity check
if (null==serverBean) return ResultDTO.EMPTY_RESULT;
try {
// get JIRA SOAP service
JiraSoapService service = getService(serverBean);
// login
String authToken = login(serverBean, service);
// get remote priorities
RemoteIssueType[] remoteTypes = service.getIssueTypes(authToken);
if (null==remoteTypes) return ResultDTO.EMPTY_RESULT;
// create new result
reslt = new ResultDTO<JiraIssueTypeDTO>(null, 0, remoteTypes.length, remoteTypes.length);
// fill it up
for (RemoteIssueType rst: remoteTypes) {
reslt.getEntities().add(new JiraIssueTypeDTO(rst.getId(), rst.getName()));
}
// return result
return reslt;
} catch (ApplicationException appex) {
throw appex;
} catch (com.atlassian.jira.rpc.exception.RemoteException e) {
logger.error("[JIRA300026] Error while retrieving issue types from the server {"+serverBean+"}", e);
throw new ApplicationException("JIRA300026", "["+e.getFaultCode()+"] "+e.getFaultString(), e);
} catch (Exception e) {
logger.error("[JIRA300026] Error while retrieving issue types from the server {"+serverBean+"}", e);
throw new ApplicationException("JIRA300026", "Error while retrieving issue types from the server {"+serverBean+"}", e);
}
}
/**
* Return filers from a remote server
*
* @param serverBean server to get filters from
* @return filters
* @throws ApplicationException when failed
*/
public ResultDTO<JiraFilterDTO> getRemoteFilters(JiraServerBean serverBean) throws ApplicationException {
ResultDTO<JiraFilterDTO> reslt = null;
// sanity check
if (null==serverBean) return ResultDTO.EMPTY_RESULT;
try {
// get JIRA SOAP service
JiraSoapService service = getService(serverBean);
// login
String authToken = login(serverBean, service);
// get remote priorities
RemoteFilter[] remoteFilters = service.getFavouriteFilters(authToken);
if (null==remoteFilters) return ResultDTO.EMPTY_RESULT;
// create new result
reslt = new ResultDTO<JiraFilterDTO>(null, 0, remoteFilters.length, remoteFilters.length);
// fill it up
for (RemoteFilter rst: remoteFilters) {
reslt.getEntities().add(new JiraFilterDTO(rst.getId(), rst.getName()));
}
// return result
return reslt;
} catch (ApplicationException appex) {
throw appex;
} catch (com.atlassian.jira.rpc.exception.RemoteException e) {
logger.error("[JIRA300027] Error while retrieving filters from the server {"+serverBean+"}", e);
throw new ApplicationException("JIRA300027", "["+e.getFaultCode()+"] "+e.getFaultString(), e);
} catch (Exception e) {
logger.error( "[JIRA300027] Error while retrieving filters from the server {"+serverBean+"}", e);
throw new ApplicationException("JIRA300027", "Error while retrieving filters from the server {"+serverBean+"}", e);
}
}
/**
* Return remote server info
*
* @param serverBean server bean
* @return server info
* @throws ApplicationException when failed
*/
public JiraServerInfoDTO getRemoteServerInfo(JiraServerBean serverBean) throws ApplicationException {
JiraServerInfoDTO serverInfoDTO = new JiraServerInfoDTO();
try {
// get JIRA SOAP service
JiraSoapService service = getService(serverBean);
// login
String authToken = login(serverBean, service);
// get server info
RemoteServerInfo serverInfo = service.getServerInfo(authToken);
// prepare DTO
serverInfoDTO.setBaseUrl(serverInfo.getBaseUrl());
serverInfoDTO.setBuildDate(serverInfo.getBuildDate().getTime());
serverInfoDTO.setBuildNumber(serverInfo.getBuildNumber());
serverInfoDTO.setServerTime(serverInfo.getServerTime().getServerTime());
serverInfoDTO.setServerTimeZone(serverInfo.getServerTime().getTimeZoneId());
serverInfoDTO.setVersion(serverInfo.getVersion());
// return server info
return serverInfoDTO;
} catch (ApplicationException appex) {
throw appex;
} catch (com.atlassian.jira.rpc.exception.RemoteException e) {
logger.error("[JIRA300028] Error while retrieving server info {"+serverBean+"}", e);
throw new ApplicationException("JIRA300028", "["+e.getFaultCode()+"] "+e.getFaultString(), e);
} catch (Exception e) {
logger.error("[JIRA300028] Error while retrieving server info {"+serverBean+"}", e);
throw new ApplicationException("JIRA300028", "Error while retrieving server info. Cause:"+e.getMessage(), e);
}
}
}
| true | true | public Result<JiraUserAccountMappingBean> getUserMappings(JiraServerBean server, UserBean userBean, int firstResult, int maxResults) throws ApplicationException {
Result<JiraUserAccountMappingBean> reslt = new Result<JiraUserAccountMappingBean>();
try {
Session session = sessionFactory.getCurrentSession();
// count rows
Criteria rowCountCriteria = session.createCriteria(JiraUserAccountMappingBean.class)
.add(Restrictions.eq("server", server))
.setProjection(Projections.rowCount());
// set user restrictions if needed
if (null!=userBean && null!=userBean.getId()) {
rowCountCriteria.add(Restrictions.eq("user", userBean));
}
reslt.setAvailable(rowCountCriteria.uniqueResult());
if (reslt.getAvailable() == 0) return reslt;
// list records
Criteria listCriteria = session.createCriteria(JiraUserAccountMappingBean.class)
.add(Restrictions.eq("server", server))
.setFirstResult(firstResult)
.setMaxResults(maxResults);
// set user restrictions if needed
if (null!=userBean && null!=userBean.getId()) {
rowCountCriteria.add(Restrictions.eq("user", userBean));
}
List<JiraUserAccountMappingBean> mappings = listCriteria.list();
for (JiraUserAccountMappingBean mappingBean : mappings) {
reslt.getEntities().add(mappingBean);
}
// set returned
reslt.setReturned(reslt.getEntities().size());
// return result
return reslt;
} catch (Exception ex) {
logger.error( "[JIRA300010] Unable to return user mappings.", ex);
throw new ApplicationException("JIRA300010", "Unable to return user mappings.", ex);
}
}
| public Result<JiraUserAccountMappingBean> getUserMappings(JiraServerBean server, UserBean userBean, int firstResult, int maxResults) throws ApplicationException {
Result<JiraUserAccountMappingBean> reslt = new Result<JiraUserAccountMappingBean>();
try {
Session session = sessionFactory.getCurrentSession();
// count rows
Criteria rowCountCriteria = session.createCriteria(JiraUserAccountMappingBean.class)
.add(Restrictions.eq("server", server))
.setProjection(Projections.rowCount());
// set user restrictions if needed
if (null!=userBean && null!=userBean.getId()) {
rowCountCriteria.add(Restrictions.eq("user", userBean));
}
reslt.setAvailable(rowCountCriteria.uniqueResult());
if (reslt.getAvailable() == 0) return reslt;
// list records
Criteria listCriteria = session.createCriteria(JiraUserAccountMappingBean.class)
.add(Restrictions.eq("server", server))
.setFirstResult(firstResult)
.setMaxResults(maxResults);
// set user restrictions if needed
if (null!=userBean && null!=userBean.getId()) {
listCriteria.add(Restrictions.eq("user", userBean));
}
List<JiraUserAccountMappingBean> mappings = listCriteria.list();
for (JiraUserAccountMappingBean mappingBean : mappings) {
reslt.getEntities().add(mappingBean);
}
// set returned
reslt.setReturned(reslt.getEntities().size());
// return result
return reslt;
} catch (Exception ex) {
logger.error( "[JIRA300010] Unable to return user mappings.", ex);
throw new ApplicationException("JIRA300010", "Unable to return user mappings.", ex);
}
}
|
diff --git a/svn/org.cfeclipse.cfml/trunk/src/org/cfeclipse/cfml/preferences/BrowserPreferencePage.java b/svn/org.cfeclipse.cfml/trunk/src/org/cfeclipse/cfml/preferences/BrowserPreferencePage.java
index 9ce06112..155bdf7a 100644
--- a/svn/org.cfeclipse.cfml/trunk/src/org/cfeclipse/cfml/preferences/BrowserPreferencePage.java
+++ b/svn/org.cfeclipse.cfml/trunk/src/org/cfeclipse/cfml/preferences/BrowserPreferencePage.java
@@ -1,50 +1,50 @@
package org.cfeclipse.cfml.preferences;
import java.util.Map;
import java.util.Properties;
import org.cfeclipse.cfml.CFMLPlugin;
import org.eclipse.jface.preference.DirectoryFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
public class BrowserPreferencePage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage {
public BrowserPreferencePage() {
super(GRID);
setPreferenceStore(CFMLPlugin.getDefault().getPreferenceStore());
}
public void createFieldEditors() {
if(System.getProperty("os.name").equals("Mac OS X")){
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent()));
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent()));
}
else {
addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent()));
addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent()));
- addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
+ addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
public void init(IWorkbench workbench) {
// TODO Auto-generated method stub
}
}
| false | true | public void createFieldEditors() {
if(System.getProperty("os.name").equals("Mac OS X")){
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent()));
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent()));
}
else {
addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent()));
addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent()));
addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
}
| public void createFieldEditors() {
if(System.getProperty("os.name").equals("Mac OS X")){
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent()));
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent()));
}
else {
addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent()));
addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent()));
}
addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
|
diff --git a/generator/stax-mate/src/main/java/com/cedarsoft/serialization/generator/output/staxmate/serializer/DelegateGenerator.java b/generator/stax-mate/src/main/java/com/cedarsoft/serialization/generator/output/staxmate/serializer/DelegateGenerator.java
index 29b48cd0..0d18886f 100644
--- a/generator/stax-mate/src/main/java/com/cedarsoft/serialization/generator/output/staxmate/serializer/DelegateGenerator.java
+++ b/generator/stax-mate/src/main/java/com/cedarsoft/serialization/generator/output/staxmate/serializer/DelegateGenerator.java
@@ -1,91 +1,92 @@
/**
* Copyright (C) cedarsoft GmbH.
*
* Licensed under the GNU General Public License version 3 (the "License")
* with Classpath Exception; you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cedarsoft.org/gpl3ce
* (GPL 3 with Classpath Exception)
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3 only, as
* published by the Free Software Foundation. cedarsoft GmbH designates this
* particular file as subject to the "Classpath" exception as provided
* by cedarsoft GmbH in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 3 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 3 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
* or visit www.cedarsoft.com if you need additional information or
* have any questions.
*/
package com.cedarsoft.serialization.generator.output.staxmate.serializer;
import com.cedarsoft.serialization.generator.decision.XmlDecisionCallback;
import com.cedarsoft.serialization.generator.model.FieldDeclarationInfo;
import com.cedarsoft.serialization.generator.output.CodeGenerator;
import com.cedarsoft.serialization.generator.output.serializer.Expressions;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JInvocation;
import com.sun.codemodel.JStatement;
import com.sun.codemodel.JVar;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
/**
*
*/
public class DelegateGenerator extends AbstractDelegateGenerator {
@NonNls
public static final String METHOD_NAME_DESERIALIZE = "deserialize";
@NonNls
public static final String METHOD_NAME_SERIALIZE = "serialize";
public DelegateGenerator( @NotNull CodeGenerator<XmlDecisionCallback> codeGenerator ) {
super( codeGenerator );
}
@NotNull
@Override
public JStatement createAddToSerializeToExpression( @NotNull JDefinedClass serializerClass, @NotNull JExpression serializeTo, @NotNull FieldDeclarationInfo fieldInfo, @NotNull JVar object ) {
JFieldVar constant = getConstant( serializerClass, fieldInfo );
JExpression getterInvocation = codeGenerator.createGetterInvocation( object, fieldInfo );
return JExpr.invoke( METHOD_NAME_SERIALIZE )
.arg( getterInvocation )
+ .arg( JExpr.dotclass( codeGenerator.ref( fieldInfo.getType().toString() ) ) )
.arg( createAddElementExpression( serializeTo, constant )
);
}
@NotNull
@Override
public Expressions createReadFromDeserializeFromExpression( @NotNull JDefinedClass serializerClass, @NotNull JExpression deserializeFrom, @NotNull JVar formatVersion, @NotNull FieldDeclarationInfo fieldInfo ) {
JInvocation nextTagExpression = createNextTagInvocation( serializerClass, deserializeFrom, fieldInfo );
JInvocation closeTagExpression = createCloseTagInvocation( deserializeFrom );
JClass type = codeGenerator.ref( fieldInfo.getType().toString() );
JInvocation expression = JExpr.invoke( METHOD_NAME_DESERIALIZE ).arg( JExpr.dotclass( type ) ).arg( formatVersion ).arg( deserializeFrom );
return new Expressions( expression, nextTagExpression, closeTagExpression );
}
@NotNull
@Override
public JClass generateFieldType( @NotNull FieldDeclarationInfo fieldInfo ) {
return codeGenerator.ref( fieldInfo.getType().toString() );
}
}
| true | true | public JStatement createAddToSerializeToExpression( @NotNull JDefinedClass serializerClass, @NotNull JExpression serializeTo, @NotNull FieldDeclarationInfo fieldInfo, @NotNull JVar object ) {
JFieldVar constant = getConstant( serializerClass, fieldInfo );
JExpression getterInvocation = codeGenerator.createGetterInvocation( object, fieldInfo );
return JExpr.invoke( METHOD_NAME_SERIALIZE )
.arg( getterInvocation )
.arg( createAddElementExpression( serializeTo, constant )
);
}
| public JStatement createAddToSerializeToExpression( @NotNull JDefinedClass serializerClass, @NotNull JExpression serializeTo, @NotNull FieldDeclarationInfo fieldInfo, @NotNull JVar object ) {
JFieldVar constant = getConstant( serializerClass, fieldInfo );
JExpression getterInvocation = codeGenerator.createGetterInvocation( object, fieldInfo );
return JExpr.invoke( METHOD_NAME_SERIALIZE )
.arg( getterInvocation )
.arg( JExpr.dotclass( codeGenerator.ref( fieldInfo.getType().toString() ) ) )
.arg( createAddElementExpression( serializeTo, constant )
);
}
|
diff --git a/src/net/slipcor/pvparena/goals/GoalLiberation.java b/src/net/slipcor/pvparena/goals/GoalLiberation.java
index e95a67f2..61fdecf1 100644
--- a/src/net/slipcor/pvparena/goals/GoalLiberation.java
+++ b/src/net/slipcor/pvparena/goals/GoalLiberation.java
@@ -1,584 +1,584 @@
package net.slipcor.pvparena.goals;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.util.Vector;
import net.slipcor.pvparena.PVPArena;
import net.slipcor.pvparena.arena.ArenaClass;
import net.slipcor.pvparena.arena.ArenaPlayer;
import net.slipcor.pvparena.arena.ArenaPlayer.Status;
import net.slipcor.pvparena.arena.ArenaTeam;
import net.slipcor.pvparena.classes.PABlockLocation;
import net.slipcor.pvparena.classes.PACheck;
import net.slipcor.pvparena.commands.PAA_Region;
import net.slipcor.pvparena.core.Config.CFG;
import net.slipcor.pvparena.core.Debug;
import net.slipcor.pvparena.core.Language;
import net.slipcor.pvparena.core.Language.MSG;
import net.slipcor.pvparena.events.PAGoalEvent;
import net.slipcor.pvparena.loadables.ArenaGoal;
import net.slipcor.pvparena.loadables.ArenaModuleManager;
import net.slipcor.pvparena.managers.InventoryManager;
import net.slipcor.pvparena.managers.SpawnManager;
import net.slipcor.pvparena.managers.TeamManager;
import net.slipcor.pvparena.runnables.EndRunnable;
import net.slipcor.pvparena.runnables.InventoryRefillRunnable;
import net.slipcor.pvparena.runnables.RespawnRunnable;
/**
* <pre>
* Arena Goal class "Liberation"
* </pre>
*
* Players have lives. When every life is lost, the player is teleported
* to the killer's team's jail. Once every player of a team is jailed, the
* team is out.
*
* @author slipcor
*/
public class GoalLiberation extends ArenaGoal {
public GoalLiberation() {
super("Liberation");
debug = new Debug(102);
}
private EndRunnable endRunner = null;
private String flagName = "";
@Override
public String version() {
return PVPArena.instance.getDescription().getVersion();
}
private static final int PRIORITY = 10;
public PACheck checkCommand(final PACheck res, final String string) {
if (res.getPriority() > PRIORITY) {
return res;
}
for (ArenaTeam team : arena.getTeams()) {
final String sTeam = team.getName();
if (string.contains(sTeam + "button")) {
res.setPriority(this, PRIORITY);
}
}
return res;
}
@Override
public PACheck checkEnd(final PACheck res) {
arena.getDebugger().i("checkEnd - " + arena.getName());
if (res.getPriority() > PRIORITY) {
arena.getDebugger().i(res.getPriority() + ">" + PRIORITY);
return res;
}
if (!arena.isFreeForAll()) {
arena.getDebugger().i("TEAMS!");
final int count = TeamManager.countActiveTeams(arena);
arena.getDebugger().i("count: " + count);
if (count <= 1) {
res.setPriority(this, PRIORITY); // yep. only one team left. go!
}
return res;
}
PVPArena.instance.getLogger().warning("Liberation goal running in FFA mode: " + arena.getName());
return res;
}
@Override
public String checkForMissingSpawns(final Set<String> list) {
if (!arena.isFreeForAll()) {
String team = checkForMissingTeamSpawn(list);
if (team != null) {
return team;
}
return checkForMissingTeamCustom(list,"jail");
}
PVPArena.instance.getLogger().warning("Liberation goal running in FFA mode: " + arena.getName());
return null;
}
/**
* hook into an interacting player
*
* @param res
*
* @param player
* the interacting player
* @param clickedBlock
* the block being clicked
* @return
*/
@Override
public PACheck checkInteract(final PACheck res, final Player player, final Block block) {
if (block == null || res.getPriority() > PRIORITY) {
return res;
}
arena.getDebugger().i("checking interact", player);
if (block.getType() != Material.STONE_BUTTON) {
arena.getDebugger().i("block, but not button", player);
return res;
}
arena.getDebugger().i("button click!", player);
Vector vLoc;
Vector vFlag = null;
final ArenaPlayer aPlayer = ArenaPlayer.parsePlayer(player.getName());
final ArenaTeam pTeam = aPlayer.getArenaTeam();
if (pTeam == null) {
return res;
}
final Set<ArenaTeam> setTeam = new HashSet<ArenaTeam>();
for (ArenaTeam team : arena.getTeams()) {
setTeam.add(team);
}
for (ArenaTeam team : setTeam) {
final String aTeam = team.getName();
if (aTeam.equals(pTeam.getName())) {
arena.getDebugger().i("equals!OUT! ", player);
continue;
}
if (team.getTeamMembers().size() < 1) {
arena.getDebugger().i("size!OUT! ", player);
continue; // dont check for inactive teams
}
arena.getDebugger().i("checking for flag of team " + aTeam, player);
vLoc = block.getLocation().toVector();
arena.getDebugger().i("block: " + vLoc.toString(), player);
if (SpawnManager.getBlocksStartingWith(arena, aTeam + "button").size() > 0) {
vFlag = SpawnManager
.getBlockNearest(
SpawnManager.getBlocksStartingWith(arena, aTeam
+ "button"),
new PABlockLocation(player.getLocation()))
.toLocation().toVector();
}
if ((vFlag != null) && (vLoc.distance(vFlag) < 2)) {
arena.getDebugger().i("button found!", player);
arena.getDebugger().i("vFlag: " + vFlag.toString(), player);
arena.broadcast(Language
.parse(arena, MSG.GOAL_LIBERATION_LIBERATED,
pTeam.getColoredName()
+ ChatColor.YELLOW));
PAGoalEvent gEvent = new PAGoalEvent(arena, this, "trigger:"+player.getName());
Bukkit.getPluginManager().callEvent(gEvent);
for (ArenaPlayer jailedPlayer : pTeam.getTeamMembers()) {
if (jailedPlayer.getStatus() == Status.DEAD) {
SpawnManager.respawn(arena, jailedPlayer, null);
}
}
return res;
}
}
return res;
}
@Override
public PACheck checkJoin(final CommandSender sender, final PACheck res, final String[] args) {
if (res.getPriority() >= PRIORITY) {
return res;
}
final int maxPlayers = arena.getArenaConfig().getInt(CFG.READY_MAXPLAYERS);
final int maxTeamPlayers = arena.getArenaConfig().getInt(
CFG.READY_MAXTEAMPLAYERS);
if (maxPlayers > 0 && arena.getFighters().size() >= maxPlayers) {
res.setError(this, Language.parse(arena, MSG.ERROR_JOIN_ARENA_FULL));
return res;
}
if (args == null || args.length < 1) {
return res;
}
if (!arena.isFreeForAll()) {
final ArenaTeam team = arena.getTeam(args[0]);
if (team != null && maxTeamPlayers > 0
&& team.getTeamMembers().size() >= maxTeamPlayers) {
res.setError(this, Language.parse(arena, MSG.ERROR_JOIN_TEAM_FULL));
return res;
}
}
res.setPriority(this, PRIORITY);
return res;
}
@Override
public PACheck checkSetBlock(final PACheck res, final Player player, final Block block) {
if (res.getPriority() > PRIORITY
|| !PAA_Region.activeSelections.containsKey(player.getName())) {
return res;
}
if (block == null
|| block.getType() != Material.STONE_BUTTON) {
return res;
}
if (!PVPArena.hasAdminPerms(player)
&& !(PVPArena.hasCreatePerms(player, arena))) {
return res;
}
res.setPriority(this, PRIORITY); // success :)
return res;
}
@Override
public PACheck checkPlayerDeath(final PACheck res, final Player player) {
if (res.getPriority() <= PRIORITY) {
res.setPriority(this, PRIORITY);
}
return res;
}
@Override
public void commitCommand(final CommandSender sender, final String[] args) {
if (args[0].contains("button")) {
for (ArenaTeam team : arena.getTeams()) {
final String sTeam = team.getName();
if (args[0].contains(sTeam + "button")) {
flagName = args[0];
PAA_Region.activeSelections.put(sender.getName(), arena);
arena.msg(sender,
Language.parse(arena, MSG.GOAL_LIBERATION_TOSET, flagName));
}
}
}
}
@Override
public void commitEnd(final boolean force) {
if (endRunner != null) {
return;
}
PAGoalEvent gEvent = new PAGoalEvent(arena, this, "");
Bukkit.getPluginManager().callEvent(gEvent);
for (ArenaTeam team : arena.getTeams()) {
for (ArenaPlayer ap : team.getTeamMembers()) {
if (!ap.getStatus().equals(Status.FIGHT)) {
continue;
}
if (arena.isFreeForAll()) {
ArenaModuleManager.announce(arena,
Language.parse(arena, MSG.PLAYER_HAS_WON, ap.getName()),
"WINNER");
arena.broadcast(Language.parse(arena, MSG.PLAYER_HAS_WON,
ap.getName()));
} else {
ArenaModuleManager.announce(
arena,
Language.parse(arena, MSG.TEAM_HAS_WON,
team.getColoredName()), "WINNER");
arena.broadcast(Language.parse(arena, MSG.TEAM_HAS_WON,
team.getColoredName()));
break;
}
}
if (ArenaModuleManager.commitEnd(arena, team)) {
return;
}
}
endRunner = new EndRunnable(arena, arena.getArenaConfig().getInt(
CFG.TIME_ENDCOUNTDOWN));
}
@Override
public void commitPlayerDeath(final Player player, final boolean doesRespawn,
final String error, final PlayerDeathEvent event) {
if (!getLifeMap().containsKey(player.getName())) {
return;
}
PAGoalEvent gEvent = new PAGoalEvent(arena, this, "playerDeath:"+player.getName());
Bukkit.getPluginManager().callEvent(gEvent);
int pos = getLifeMap().get(player.getName());
arena.getDebugger().i("lives before death: " + pos, player);
if (pos <= 1) {
getLifeMap().put(player.getName(),1);
ArenaPlayer aPlayer = ArenaPlayer.parsePlayer(player.getName());
aPlayer.setStatus(Status.DEAD);
ArenaTeam team = aPlayer.getArenaTeam();
boolean someoneAlive = false;
for (ArenaPlayer temp : team.getTeamMembers()) {
if (temp.getStatus() == Status.FIGHT) {
someoneAlive = true;
break;
}
}
if (!someoneAlive) {
PACheck.handleEnd(arena, false);
} else {
final ArenaTeam respawnTeam = ArenaPlayer.parsePlayer(player.getName())
.getArenaTeam();
if (arena.getArenaConfig().getBoolean(CFG.USES_DEATHMESSAGES)) {
arena.broadcast(Language.parse(arena,
MSG.FIGHT_KILLED_BY,
respawnTeam.colorizePlayer(player) + ChatColor.YELLOW,
arena.parseDeathCause(player, event.getEntity()
.getLastDamageCause().getCause(),
player.getKiller()), String.valueOf(pos)));
}
if (arena.isCustomClassAlive()
|| arena.getArenaConfig().getBoolean(
CFG.PLAYER_DROPSINVENTORY)) {
InventoryManager.drop(player);
event.getDrops().clear();
}
new InventoryRefillRunnable(arena, aPlayer.get(), event.getDrops());
- String teamName = null;
+ String teamName = aPlayer.getArenaTeam().getName();
Bukkit.getScheduler().runTaskLater(PVPArena.instance, new RespawnRunnable(arena, aPlayer, teamName+"jail"), 1L);
arena.unKillPlayer(aPlayer.get(), aPlayer.get().getLastDamageCause()==null?null:aPlayer.get().getLastDamageCause().getCause(), aPlayer.get().getKiller());
}
} else {
pos--;
getLifeMap().put(player.getName(), pos);
final ArenaTeam respawnTeam = ArenaPlayer.parsePlayer(player.getName())
.getArenaTeam();
if (arena.getArenaConfig().getBoolean(CFG.USES_DEATHMESSAGES)) {
arena.broadcast(Language.parse(arena,
MSG.FIGHT_KILLED_BY_REMAINING,
respawnTeam.colorizePlayer(player) + ChatColor.YELLOW,
arena.parseDeathCause(player, event.getEntity()
.getLastDamageCause().getCause(),
player.getKiller()), String.valueOf(pos)));
}
if (arena.isCustomClassAlive()
|| arena.getArenaConfig().getBoolean(
CFG.PLAYER_DROPSINVENTORY)) {
InventoryManager.drop(player);
event.getDrops().clear();
}
PACheck.handleRespawn(arena,
ArenaPlayer.parsePlayer(player.getName()), event.getDrops());
}
}
@Override
public boolean commitSetFlag(final Player player, final Block block) {
arena.getDebugger().i("trying to set a button", player);
// command : /pa redbutton1
// location: redbutton1:
SpawnManager.setBlock(arena, new PABlockLocation(block.getLocation()),
flagName);
arena.msg(player, Language.parse(arena, MSG.GOAL_LIBERATION_SET, flagName));
PAA_Region.activeSelections.remove(player.getName());
flagName = "";
return true;
}
@Override
public void displayInfo(final CommandSender sender) {
sender.sendMessage("lives: "
+ arena.getArenaConfig().getInt(CFG.GOAL_LLIVES_LIVES));
}
@Override
public PACheck getLives(final PACheck res, final ArenaPlayer aPlayer) {
if (res.getPriority() <= PRIORITY+1000) {
res.setError(
this,
String.valueOf(getLifeMap().containsKey(aPlayer.getName()) ? getLifeMap().get(aPlayer
.getName()) : 0));
}
return res;
}
@Override
public boolean hasSpawn(final String string) {
if (arena.isFreeForAll()) {
PVPArena.instance.getLogger().warning("Liberation goal running in FFA mode! /pa " + arena.getName() + " !gm team");
return false;
}
for (String teamName : arena.getTeamNames()) {
if (string.toLowerCase().startsWith(
teamName.toLowerCase() + "spawn")) {
return true;
}
if (arena.getArenaConfig().getBoolean(CFG.GENERAL_CLASSSPAWN)) {
for (ArenaClass aClass : arena.getClasses()) {
if (string.toLowerCase().startsWith(teamName.toLowerCase() +
aClass.getName().toLowerCase() + "spawn")) {
return true;
}
}
}
if (string.toLowerCase().startsWith(
teamName.toLowerCase() + "jail")) {
return true;
}
}
return false;
}
@Override
public void initate(final Player player) {
getLifeMap().put(player.getName(),
arena.getArenaConfig().getInt(CFG.GOAL_LLIVES_LIVES));
}
@Override
public boolean isInternal() {
return true;
}
@Override
public void parseLeave(final Player player) {
if (player == null) {
PVPArena.instance.getLogger().warning(
this.getName() + ": player NULL");
return;
}
if (getLifeMap().containsKey(player.getName())) {
getLifeMap().remove(player.getName());
}
}
@Override
public void parseStart() {
for (ArenaTeam team : arena.getTeams()) {
for (ArenaPlayer ap : team.getTeamMembers()) {
this.getLifeMap().put(ap.getName(),
arena.getArenaConfig().getInt(CFG.GOAL_LLIVES_LIVES));
}
}
}
@Override
public void reset(final boolean force) {
endRunner = null;
getLifeMap().clear();
}
@Override
public void setDefaults(final YamlConfiguration config) {
if (arena.isFreeForAll()) {
return;
}
if (config.get("teams.free") != null) {
config.set("teams", null);
}
if (config.get("teams") == null) {
arena.getDebugger().i("no teams defined, adding custom red and blue!");
config.addDefault("teams.red", ChatColor.RED.name());
config.addDefault("teams.blue", ChatColor.BLUE.name());
}
}
@Override
public void setPlayerLives(final int value) {
final Set<String> plrs = new HashSet<String>();
for (String name : getLifeMap().keySet()) {
plrs.add(name);
}
for (String s : plrs) {
getLifeMap().put(s, value);
}
}
@Override
public void setPlayerLives(final ArenaPlayer aPlayer, final int value) {
getLifeMap().put(aPlayer.getName(), value);
}
@Override
public Map<String, Double> timedEnd(final Map<String, Double> scores) {
double score;
for (ArenaPlayer ap : arena.getFighters()) {
score = (getLifeMap().containsKey(ap.getName()) ? getLifeMap().get(ap.getName())
: 0);
if (arena.isFreeForAll()) {
if (scores.containsKey(ap.getName())) {
scores.put(ap.getName(), scores.get(ap.getName()) + score);
} else {
scores.put(ap.getName(), score);
}
} else {
if (ap.getArenaTeam() == null) {
continue;
}
if (scores.containsKey(ap.getArenaTeam().getName())) {
scores.put(ap.getArenaTeam().getName(),
scores.get(ap.getName()) + score);
} else {
scores.put(ap.getArenaTeam().getName(), score);
}
}
}
return scores;
}
@Override
public void unload(final Player player) {
getLifeMap().remove(player.getName());
}
}
| true | true | public void commitPlayerDeath(final Player player, final boolean doesRespawn,
final String error, final PlayerDeathEvent event) {
if (!getLifeMap().containsKey(player.getName())) {
return;
}
PAGoalEvent gEvent = new PAGoalEvent(arena, this, "playerDeath:"+player.getName());
Bukkit.getPluginManager().callEvent(gEvent);
int pos = getLifeMap().get(player.getName());
arena.getDebugger().i("lives before death: " + pos, player);
if (pos <= 1) {
getLifeMap().put(player.getName(),1);
ArenaPlayer aPlayer = ArenaPlayer.parsePlayer(player.getName());
aPlayer.setStatus(Status.DEAD);
ArenaTeam team = aPlayer.getArenaTeam();
boolean someoneAlive = false;
for (ArenaPlayer temp : team.getTeamMembers()) {
if (temp.getStatus() == Status.FIGHT) {
someoneAlive = true;
break;
}
}
if (!someoneAlive) {
PACheck.handleEnd(arena, false);
} else {
final ArenaTeam respawnTeam = ArenaPlayer.parsePlayer(player.getName())
.getArenaTeam();
if (arena.getArenaConfig().getBoolean(CFG.USES_DEATHMESSAGES)) {
arena.broadcast(Language.parse(arena,
MSG.FIGHT_KILLED_BY,
respawnTeam.colorizePlayer(player) + ChatColor.YELLOW,
arena.parseDeathCause(player, event.getEntity()
.getLastDamageCause().getCause(),
player.getKiller()), String.valueOf(pos)));
}
if (arena.isCustomClassAlive()
|| arena.getArenaConfig().getBoolean(
CFG.PLAYER_DROPSINVENTORY)) {
InventoryManager.drop(player);
event.getDrops().clear();
}
new InventoryRefillRunnable(arena, aPlayer.get(), event.getDrops());
String teamName = null;
Bukkit.getScheduler().runTaskLater(PVPArena.instance, new RespawnRunnable(arena, aPlayer, teamName+"jail"), 1L);
arena.unKillPlayer(aPlayer.get(), aPlayer.get().getLastDamageCause()==null?null:aPlayer.get().getLastDamageCause().getCause(), aPlayer.get().getKiller());
}
} else {
pos--;
getLifeMap().put(player.getName(), pos);
final ArenaTeam respawnTeam = ArenaPlayer.parsePlayer(player.getName())
.getArenaTeam();
if (arena.getArenaConfig().getBoolean(CFG.USES_DEATHMESSAGES)) {
arena.broadcast(Language.parse(arena,
MSG.FIGHT_KILLED_BY_REMAINING,
respawnTeam.colorizePlayer(player) + ChatColor.YELLOW,
arena.parseDeathCause(player, event.getEntity()
.getLastDamageCause().getCause(),
player.getKiller()), String.valueOf(pos)));
}
if (arena.isCustomClassAlive()
|| arena.getArenaConfig().getBoolean(
CFG.PLAYER_DROPSINVENTORY)) {
InventoryManager.drop(player);
event.getDrops().clear();
}
PACheck.handleRespawn(arena,
ArenaPlayer.parsePlayer(player.getName()), event.getDrops());
}
}
| public void commitPlayerDeath(final Player player, final boolean doesRespawn,
final String error, final PlayerDeathEvent event) {
if (!getLifeMap().containsKey(player.getName())) {
return;
}
PAGoalEvent gEvent = new PAGoalEvent(arena, this, "playerDeath:"+player.getName());
Bukkit.getPluginManager().callEvent(gEvent);
int pos = getLifeMap().get(player.getName());
arena.getDebugger().i("lives before death: " + pos, player);
if (pos <= 1) {
getLifeMap().put(player.getName(),1);
ArenaPlayer aPlayer = ArenaPlayer.parsePlayer(player.getName());
aPlayer.setStatus(Status.DEAD);
ArenaTeam team = aPlayer.getArenaTeam();
boolean someoneAlive = false;
for (ArenaPlayer temp : team.getTeamMembers()) {
if (temp.getStatus() == Status.FIGHT) {
someoneAlive = true;
break;
}
}
if (!someoneAlive) {
PACheck.handleEnd(arena, false);
} else {
final ArenaTeam respawnTeam = ArenaPlayer.parsePlayer(player.getName())
.getArenaTeam();
if (arena.getArenaConfig().getBoolean(CFG.USES_DEATHMESSAGES)) {
arena.broadcast(Language.parse(arena,
MSG.FIGHT_KILLED_BY,
respawnTeam.colorizePlayer(player) + ChatColor.YELLOW,
arena.parseDeathCause(player, event.getEntity()
.getLastDamageCause().getCause(),
player.getKiller()), String.valueOf(pos)));
}
if (arena.isCustomClassAlive()
|| arena.getArenaConfig().getBoolean(
CFG.PLAYER_DROPSINVENTORY)) {
InventoryManager.drop(player);
event.getDrops().clear();
}
new InventoryRefillRunnable(arena, aPlayer.get(), event.getDrops());
String teamName = aPlayer.getArenaTeam().getName();
Bukkit.getScheduler().runTaskLater(PVPArena.instance, new RespawnRunnable(arena, aPlayer, teamName+"jail"), 1L);
arena.unKillPlayer(aPlayer.get(), aPlayer.get().getLastDamageCause()==null?null:aPlayer.get().getLastDamageCause().getCause(), aPlayer.get().getKiller());
}
} else {
pos--;
getLifeMap().put(player.getName(), pos);
final ArenaTeam respawnTeam = ArenaPlayer.parsePlayer(player.getName())
.getArenaTeam();
if (arena.getArenaConfig().getBoolean(CFG.USES_DEATHMESSAGES)) {
arena.broadcast(Language.parse(arena,
MSG.FIGHT_KILLED_BY_REMAINING,
respawnTeam.colorizePlayer(player) + ChatColor.YELLOW,
arena.parseDeathCause(player, event.getEntity()
.getLastDamageCause().getCause(),
player.getKiller()), String.valueOf(pos)));
}
if (arena.isCustomClassAlive()
|| arena.getArenaConfig().getBoolean(
CFG.PLAYER_DROPSINVENTORY)) {
InventoryManager.drop(player);
event.getDrops().clear();
}
PACheck.handleRespawn(arena,
ArenaPlayer.parsePlayer(player.getName()), event.getDrops());
}
}
|
diff --git a/src/com/fsck/k9/activity/MessageList.java b/src/com/fsck/k9/activity/MessageList.java
index 0153d6eb..54d65d6f 100644
--- a/src/com/fsck/k9/activity/MessageList.java
+++ b/src/com/fsck/k9/activity/MessageList.java
@@ -1,724 +1,726 @@
package com.fsck.k9.activity;
import java.util.ArrayList;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.fsck.k9.Account;
import com.fsck.k9.Account.SortType;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.misc.SwipeGestureDetector.OnSwipeGestureListener;
import com.fsck.k9.activity.setup.AccountSettings;
import com.fsck.k9.activity.setup.FolderSettings;
import com.fsck.k9.activity.setup.Prefs;
import com.fsck.k9.fragment.MessageListFragment;
import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.store.StorageManager;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchAccount;
import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.Searchfield;
import com.fsck.k9.search.SearchSpecification.SearchCondition;
/**
* MessageList is the primary user interface for the program. This Activity
* shows a list of messages.
* From this Activity the user can perform all standard message operations.
*/
public class MessageList extends K9FragmentActivity implements MessageListFragmentListener,
OnBackStackChangedListener, OnSwipeGestureListener {
// for this activity
private static final String EXTRA_SEARCH = "search";
private static final String EXTRA_NO_THREADING = "no_threading";
private static final String ACTION_SHORTCUT = "shortcut";
private static final String EXTRA_SPECIAL_FOLDER = "special_folder";
// used for remote search
private static final String EXTRA_SEARCH_ACCOUNT = "com.fsck.k9.search_account";
private static final String EXTRA_SEARCH_FOLDER = "com.fsck.k9.search_folder";
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask) {
actionDisplaySearch(context, search, noThreading, newTask, true);
}
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
context.startActivity(
intentDisplaySearch(context, search, noThreading, newTask, clearTop));
}
public static Intent intentDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
Intent intent = new Intent(context, MessageList.class);
intent.putExtra(EXTRA_SEARCH, search);
intent.putExtra(EXTRA_NO_THREADING, noThreading);
if (clearTop) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
if (newTask) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
return intent;
}
public static Intent shortcutIntent(Context context, String specialFolder) {
Intent intent = new Intent(context, MessageList.class);
intent.setAction(ACTION_SHORTCUT);
intent.putExtra(EXTRA_SPECIAL_FOLDER, specialFolder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation();
private ActionBar mActionBar;
private TextView mActionBarTitle;
private TextView mActionBarSubTitle;
private TextView mActionBarUnread;
private Menu mMenu;
private MessageListFragment mMessageListFragment;
private Account mAccount;
private String mFolderName;
private LocalSearch mSearch;
private boolean mSingleFolderMode;
private boolean mSingleAccountMode;
/**
* {@code true} if the message list should be displayed as flat list (i.e. no threading)
* regardless whether or not message threading was enabled in the settings. This is used for
* filtered views, e.g. when only displaying the unread messages in a folder.
*/
private boolean mNoThreading;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message_list);
mActionBar = getSupportActionBar();
initializeActionBar();
// Enable gesture detection for MessageLists
setupGestureDetector(this);
decodeExtras(getIntent());
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
mMessageListFragment = (MessageListFragment) fragmentManager.findFragmentById(R.id.message_list_container);
if (mMessageListFragment == null) {
FragmentTransaction ft = fragmentManager.beginTransaction();
mMessageListFragment = MessageListFragment.newInstance(mSearch, false,
(K9.isThreadedViewEnabled() && !mNoThreading));
ft.add(R.id.message_list_container, mMessageListFragment);
ft.commit();
}
}
private void decodeExtras(Intent intent) {
if (ACTION_SHORTCUT.equals(intent.getAction())) {
// Handle shortcut intents
String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER);
if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) {
mSearch = SearchAccount.createUnifiedInboxAccount(this).getRelatedSearch();
} else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) {
mSearch = SearchAccount.createAllMessagesAccount(this).getRelatedSearch();
}
} else if (intent.getStringExtra(SearchManager.QUERY) != null) {
// check if this intent comes from the system search ( remote )
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
//Query was received from Search Dialog
String query = intent.getStringExtra(SearchManager.QUERY);
mSearch = new LocalSearch(getString(R.string.search_results));
mSearch.setManualSearch(true);
mNoThreading = true;
mSearch.or(new SearchCondition(Searchfield.SENDER, Attribute.CONTAINS, query));
mSearch.or(new SearchCondition(Searchfield.SUBJECT, Attribute.CONTAINS, query));
mSearch.or(new SearchCondition(Searchfield.MESSAGE_CONTENTS, Attribute.CONTAINS, query));
Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
mSearch.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT));
mSearch.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER));
} else {
mSearch.addAccountUuid(LocalSearch.ALL_ACCOUNTS);
}
}
} else {
// regular LocalSearch object was passed
mSearch = intent.getParcelableExtra(EXTRA_SEARCH);
mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false);
}
String[] accountUuids = mSearch.getAccountUuids();
mSingleAccountMode = (accountUuids.length == 1 && !mSearch.searchAllAccounts());
mSingleFolderMode = mSingleAccountMode && (mSearch.getFolderNames().size() == 1);
if (mSingleAccountMode) {
Preferences prefs = Preferences.getPreferences(getApplicationContext());
mAccount = prefs.getAccount(accountUuids[0]);
if (mAccount != null && !mAccount.isAvailable(this)) {
Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account");
onAccountUnavailable();
return;
}
}
if (mSingleFolderMode) {
mFolderName = mSearch.getFolderNames().get(0);
}
// now we know if we are in single account mode and need a subtitle
mActionBarSubTitle.setVisibility((!mSingleFolderMode) ? View.GONE : View.VISIBLE);
}
@Override
public void onPause() {
super.onPause();
StorageManager.getInstance(getApplication()).removeListener(mStorageListener);
}
@Override
public void onResume() {
super.onResume();
if (!(this instanceof Search)) {
//necessary b/c no guarantee Search.onStop will be called before MessageList.onResume
//when returning from search results
Search.setActive(false);
}
if (mAccount != null && !mAccount.isAvailable(this)) {
onAccountUnavailable();
return;
}
StorageManager.getInstance(getApplication()).addListener(mStorageListener);
}
private void initializeActionBar() {
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setCustomView(R.layout.actionbar_custom);
View customView = mActionBar.getCustomView();
mActionBarTitle = (TextView) customView.findViewById(R.id.actionbar_title_first);
mActionBarSubTitle = (TextView) customView.findViewById(R.id.actionbar_title_sub);
mActionBarUnread = (TextView) customView.findViewById(R.id.actionbar_unread_count);
mActionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Shortcuts that work no matter what is selected
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP: {
if (K9.useVolumeKeysForListNavigationEnabled()) {
mMessageListFragment.onMoveUp();
return true;
}
return false;
}
case KeyEvent.KEYCODE_VOLUME_DOWN: {
if (K9.useVolumeKeysForListNavigationEnabled()) {
mMessageListFragment.onMoveDown();
return true;
}
return false;
}
case KeyEvent.KEYCODE_C: {
mMessageListFragment.onCompose();
return true;
}
case KeyEvent.KEYCODE_Q: {
onShowFolderList();
return true;
}
case KeyEvent.KEYCODE_O: {
mMessageListFragment.onCycleSort();
return true;
}
case KeyEvent.KEYCODE_I: {
mMessageListFragment.onReverseSort();
return true;
}
case KeyEvent.KEYCODE_H: {
Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG);
toast.show();
return true;
}
}
boolean retval = true;
try {
switch (keyCode) {
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_D: {
mMessageListFragment.onDelete();
return true;
}
case KeyEvent.KEYCODE_S: {
mMessageListFragment.toggleMessageSelect();
return true;
}
case KeyEvent.KEYCODE_G: {
mMessageListFragment.onToggleFlagged();
return true;
}
case KeyEvent.KEYCODE_M: {
mMessageListFragment.onMove();
return true;
}
case KeyEvent.KEYCODE_V: {
mMessageListFragment.onArchive();
return true;
}
case KeyEvent.KEYCODE_Y: {
mMessageListFragment.onCopy();
return true;
}
case KeyEvent.KEYCODE_Z: {
mMessageListFragment.onToggleRead();
return true;
}
}
} finally {
retval = super.onKeyDown(keyCode, event);
}
return retval;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// Swallow these events too to avoid the audible notification of a volume change
if (K9.useVolumeKeysForListNavigationEnabled()) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Swallowed key up.");
return true;
}
}
return super.onKeyUp(keyCode, event);
}
private void onAccounts() {
Accounts.listAccounts(this);
finish();
}
private void onShowFolderList() {
FolderList.actionHandleAccount(this, mAccount);
finish();
}
private void onEditPrefs() {
Prefs.actionPrefs(this);
}
private void onEditAccount() {
AccountSettings.actionSettings(this, mAccount);
}
@Override
public boolean onSearchRequested() {
return mMessageListFragment.onSearchRequested();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home: {
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
- } else if (!mSingleFolderMode || mMessageListFragment.isManualSearch()) {
+ } else if (mMessageListFragment.isManualSearch()) {
onBackPressed();
+ } else if (!mSingleFolderMode) {
+ onAccounts();
} else {
onShowFolderList();
}
return true;
}
case R.id.compose: {
mMessageListFragment.onCompose();
return true;
}
case R.id.check_mail: {
mMessageListFragment.checkMail();
return true;
}
case R.id.set_sort_date: {
mMessageListFragment.changeSort(SortType.SORT_DATE);
return true;
}
case R.id.set_sort_arrival: {
mMessageListFragment.changeSort(SortType.SORT_ARRIVAL);
return true;
}
case R.id.set_sort_subject: {
mMessageListFragment.changeSort(SortType.SORT_SUBJECT);
return true;
}
// case R.id.set_sort_sender: {
// mMessageListFragment.changeSort(SortType.SORT_SENDER);
// return true;
// }
case R.id.set_sort_flag: {
mMessageListFragment.changeSort(SortType.SORT_FLAGGED);
return true;
}
case R.id.set_sort_unread: {
mMessageListFragment.changeSort(SortType.SORT_UNREAD);
return true;
}
case R.id.set_sort_attach: {
mMessageListFragment.changeSort(SortType.SORT_ATTACHMENT);
return true;
}
case R.id.select_all: {
mMessageListFragment.selectAll();
return true;
}
case R.id.app_settings: {
onEditPrefs();
return true;
}
case R.id.account_settings: {
onEditAccount();
return true;
}
case R.id.search: {
mMessageListFragment.onSearchRequested();
return true;
}
case R.id.search_remote: {
mMessageListFragment.onRemoteSearch();
return true;
}
}
if (!mSingleFolderMode) {
// None of the options after this point are "safe" for search results
//TODO: This is not true for "unread" and "starred" searches in regular folders
return false;
}
switch (itemId) {
case R.id.send_messages: {
mMessageListFragment.onSendPendingMessages();
return true;
}
case R.id.folder_settings: {
if (mFolderName != null) {
FolderSettings.actionSettings(this, mAccount, mFolderName);
}
return true;
}
case R.id.expunge: {
mMessageListFragment.onExpunge();
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.message_list_option, menu);
mMenu = menu;
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
configureMenu(menu);
return true;
}
private void configureMenu(Menu menu) {
if (menu == null) {
return;
}
menu.findItem(R.id.search).setVisible(false);
menu.findItem(R.id.search_remote).setVisible(false);
if (mMessageListFragment == null) {
// Hide everything (except "compose") if no MessageListFragment instance is available
menu.findItem(R.id.check_mail).setVisible(false);
menu.findItem(R.id.set_sort).setVisible(false);
menu.findItem(R.id.select_all).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.settings).setVisible(false);
} else {
menu.findItem(R.id.set_sort).setVisible(true);
menu.findItem(R.id.select_all).setVisible(true);
menu.findItem(R.id.settings).setVisible(true);
if (!mSingleAccountMode) {
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.check_mail).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.folder_settings).setVisible(false);
menu.findItem(R.id.account_settings).setVisible(false);
} else {
menu.findItem(R.id.folder_settings).setVisible(mSingleFolderMode);
menu.findItem(R.id.account_settings).setVisible(true);
if (mMessageListFragment.isOutbox()) {
menu.findItem(R.id.send_messages).setVisible(true);
} else {
menu.findItem(R.id.send_messages).setVisible(false);
}
if (mMessageListFragment.isRemoteFolder()) {
menu.findItem(R.id.check_mail).setVisible(true);
menu.findItem(R.id.expunge).setVisible(mMessageListFragment.isAccountExpungeCapable());
} else {
menu.findItem(R.id.check_mail).setVisible(false);
menu.findItem(R.id.expunge).setVisible(false);
}
}
// If this is an explicit local search, show the option to search the cloud.
if (!mMessageListFragment.isRemoteSearch() &&
mMessageListFragment.isRemoteSearchAllowed()) {
menu.findItem(R.id.search_remote).setVisible(true);
} else if (!mMessageListFragment.isManualSearch()) {
menu.findItem(R.id.search).setVisible(true);
}
}
}
protected void onAccountUnavailable() {
finish();
// TODO inform user about account unavailability using Toast
Accounts.listAccounts(this);
}
public void setActionBarTitle(String title) {
mActionBarTitle.setText(title);
}
public void setActionBarSubTitle(String subTitle) {
mActionBarSubTitle.setText(subTitle);
}
public void setActionBarUnread(int unread) {
if (unread == 0) {
mActionBarUnread.setVisibility(View.GONE);
} else {
mActionBarUnread.setVisibility(View.VISIBLE);
mActionBarUnread.setText(Integer.toString(unread));
}
}
@Override
public void setMessageListTitle(String title) {
setActionBarTitle(title);
}
@Override
public void setMessageListSubTitle(String subTitle) {
setActionBarSubTitle(subTitle);
}
@Override
public void setUnreadCount(int unread) {
setActionBarUnread(unread);
}
@Override
public void setMessageListProgress(int progress) {
setSupportProgress(progress);
}
@Override
public void openMessage(MessageReference messageReference) {
Preferences prefs = Preferences.getPreferences(getApplicationContext());
Account account = prefs.getAccount(messageReference.accountUuid);
String folderName = messageReference.folderName;
if (folderName.equals(account.getDraftsFolderName())) {
MessageCompose.actionEditDraft(this, messageReference);
} else {
ArrayList<MessageReference> messageRefs = mMessageListFragment.getMessageReferences();
Log.i(K9.LOG_TAG, "MessageList sending message " + messageReference);
MessageView.actionView(this, messageReference, messageRefs, getIntent().getExtras());
}
/*
* We set read=true here for UI performance reasons. The actual value
* will get picked up on the refresh when the Activity is resumed but
* that may take a second or so and we don't want this to show and
* then go away. I've gone back and forth on this, and this gives a
* better UI experience, so I am putting it back in.
*/
// if (!message.read) {
// message.read = true;
// }
}
@Override
public void onResendMessage(Message message) {
MessageCompose.actionEditDraft(this, message.makeMessageReference());
}
@Override
public void onForward(Message message) {
MessageCompose.actionForward(this, message.getFolder().getAccount(), message, null);
}
@Override
public void onReply(Message message) {
MessageCompose.actionReply(this, message.getFolder().getAccount(), message, false, null);
}
@Override
public void onReplyAll(Message message) {
MessageCompose.actionReply(this, message.getFolder().getAccount(), message, true, null);
}
@Override
public void onCompose(Account account) {
MessageCompose.actionCompose(this, account);
}
@Override
public void showMoreFromSameSender(String senderAddress) {
LocalSearch tmpSearch = new LocalSearch("From " + senderAddress);
tmpSearch.addAccountUuids(mSearch.getAccountUuids());
tmpSearch.and(Searchfield.SENDER, senderAddress, Attribute.CONTAINS);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, false, false);
addMessageListFragment(fragment, true);
}
@Override
public void onBackStackChanged() {
FragmentManager fragmentManager = getSupportFragmentManager();
mMessageListFragment = (MessageListFragment) fragmentManager.findFragmentById(
R.id.message_list_container);
configureMenu(mMenu);
}
@Override
public void onSwipeRightToLeft(MotionEvent e1, MotionEvent e2) {
if (mMessageListFragment != null) {
mMessageListFragment.onSwipeRightToLeft(e1, e2);
}
}
@Override
public void onSwipeLeftToRight(MotionEvent e1, MotionEvent e2) {
if (mMessageListFragment != null) {
mMessageListFragment.onSwipeLeftToRight(e1, e2);
}
}
private final class StorageListenerImplementation implements StorageManager.StorageListener {
@Override
public void onUnmount(String providerId) {
if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) {
runOnUiThread(new Runnable() {
@Override
public void run() {
onAccountUnavailable();
}
});
}
}
@Override
public void onMount(String providerId) {
// no-op
}
}
private void addMessageListFragment(MessageListFragment fragment, boolean addToBackStack) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.message_list_container, fragment);
if (addToBackStack)
ft.addToBackStack(null);
mMessageListFragment = fragment;
ft.commit();
}
@Override
public boolean startSearch(Account account, String folderName) {
// If this search was started from a MessageList of a single folder, pass along that folder info
// so that we can enable remote search.
if (account != null && folderName != null) {
final Bundle appData = new Bundle();
appData.putString(EXTRA_SEARCH_ACCOUNT, account.getUuid());
appData.putString(EXTRA_SEARCH_FOLDER, folderName);
startSearch(null, false, appData, false);
} else {
// TODO Handle the case where we're searching from within a search result.
startSearch(null, false, null, false);
}
return true;
}
@Override
public void showThread(Account account, String folderName, long threadRootId) {
LocalSearch tmpSearch = new LocalSearch();
tmpSearch.addAccountUuid(account.getUuid());
tmpSearch.and(Searchfield.THREAD_ROOT, String.valueOf(threadRootId), Attribute.EQUALS);
tmpSearch.or(new SearchCondition(Searchfield.ID, Attribute.EQUALS, String.valueOf(threadRootId)));
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, true, false);
addMessageListFragment(fragment, true);
}
@Override
public void remoteSearchStarted() {
// Remove action button for remote search
configureMenu(mMenu);
}
}
| false | true | public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home: {
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
} else if (!mSingleFolderMode || mMessageListFragment.isManualSearch()) {
onBackPressed();
} else {
onShowFolderList();
}
return true;
}
case R.id.compose: {
mMessageListFragment.onCompose();
return true;
}
case R.id.check_mail: {
mMessageListFragment.checkMail();
return true;
}
case R.id.set_sort_date: {
mMessageListFragment.changeSort(SortType.SORT_DATE);
return true;
}
case R.id.set_sort_arrival: {
mMessageListFragment.changeSort(SortType.SORT_ARRIVAL);
return true;
}
case R.id.set_sort_subject: {
mMessageListFragment.changeSort(SortType.SORT_SUBJECT);
return true;
}
// case R.id.set_sort_sender: {
// mMessageListFragment.changeSort(SortType.SORT_SENDER);
// return true;
// }
case R.id.set_sort_flag: {
mMessageListFragment.changeSort(SortType.SORT_FLAGGED);
return true;
}
case R.id.set_sort_unread: {
mMessageListFragment.changeSort(SortType.SORT_UNREAD);
return true;
}
case R.id.set_sort_attach: {
mMessageListFragment.changeSort(SortType.SORT_ATTACHMENT);
return true;
}
case R.id.select_all: {
mMessageListFragment.selectAll();
return true;
}
case R.id.app_settings: {
onEditPrefs();
return true;
}
case R.id.account_settings: {
onEditAccount();
return true;
}
case R.id.search: {
mMessageListFragment.onSearchRequested();
return true;
}
case R.id.search_remote: {
mMessageListFragment.onRemoteSearch();
return true;
}
}
if (!mSingleFolderMode) {
// None of the options after this point are "safe" for search results
//TODO: This is not true for "unread" and "starred" searches in regular folders
return false;
}
switch (itemId) {
case R.id.send_messages: {
mMessageListFragment.onSendPendingMessages();
return true;
}
case R.id.folder_settings: {
if (mFolderName != null) {
FolderSettings.actionSettings(this, mAccount, mFolderName);
}
return true;
}
case R.id.expunge: {
mMessageListFragment.onExpunge();
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
| public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home: {
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
} else if (mMessageListFragment.isManualSearch()) {
onBackPressed();
} else if (!mSingleFolderMode) {
onAccounts();
} else {
onShowFolderList();
}
return true;
}
case R.id.compose: {
mMessageListFragment.onCompose();
return true;
}
case R.id.check_mail: {
mMessageListFragment.checkMail();
return true;
}
case R.id.set_sort_date: {
mMessageListFragment.changeSort(SortType.SORT_DATE);
return true;
}
case R.id.set_sort_arrival: {
mMessageListFragment.changeSort(SortType.SORT_ARRIVAL);
return true;
}
case R.id.set_sort_subject: {
mMessageListFragment.changeSort(SortType.SORT_SUBJECT);
return true;
}
// case R.id.set_sort_sender: {
// mMessageListFragment.changeSort(SortType.SORT_SENDER);
// return true;
// }
case R.id.set_sort_flag: {
mMessageListFragment.changeSort(SortType.SORT_FLAGGED);
return true;
}
case R.id.set_sort_unread: {
mMessageListFragment.changeSort(SortType.SORT_UNREAD);
return true;
}
case R.id.set_sort_attach: {
mMessageListFragment.changeSort(SortType.SORT_ATTACHMENT);
return true;
}
case R.id.select_all: {
mMessageListFragment.selectAll();
return true;
}
case R.id.app_settings: {
onEditPrefs();
return true;
}
case R.id.account_settings: {
onEditAccount();
return true;
}
case R.id.search: {
mMessageListFragment.onSearchRequested();
return true;
}
case R.id.search_remote: {
mMessageListFragment.onRemoteSearch();
return true;
}
}
if (!mSingleFolderMode) {
// None of the options after this point are "safe" for search results
//TODO: This is not true for "unread" and "starred" searches in regular folders
return false;
}
switch (itemId) {
case R.id.send_messages: {
mMessageListFragment.onSendPendingMessages();
return true;
}
case R.id.folder_settings: {
if (mFolderName != null) {
FolderSettings.actionSettings(this, mAccount, mFolderName);
}
return true;
}
case R.id.expunge: {
mMessageListFragment.onExpunge();
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
|
diff --git a/src/se/kth/maandree/utilsay/unisay2ttyunisay.java b/src/se/kth/maandree/utilsay/unisay2ttyunisay.java
index d2c9038..b839e85 100644
--- a/src/se/kth/maandree/utilsay/unisay2ttyunisay.java
+++ b/src/se/kth/maandree/utilsay/unisay2ttyunisay.java
@@ -1,194 +1,194 @@
/**
* unisay2ttyunisay — TTY suitifying unisay pony tool
*
* Copyright © 2012 Mattias Andrée ([email protected])
*
* This prorgram is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package se.kth.maandree.utilsay;
import java.util.*;
import java.io.*;
/**
* The main class of the unisay2ttyunisay program
*
* @author Mattias Andrée, <a href="mailto:[email protected]">[email protected]</a>
*/
public class unisay2ttyunisay
{
/**
* Non-constructor
*/
private unisay2ttyunisay()
{
assert false : "This class [unisay2ttyunisay] is not meant to be instansiated.";
}
/**
* This is the main entry point of the program
*
* @param args Startup arguments, start the program with </code>--help</code> for details
*
* @throws IOException On I/O exception
*/
public static void main(final String... args) throws IOException
{
if ((args.length > 0) && args[0].equals("--help"))
{
System.out.println("TTY suitifying unisay pony tool");
System.out.println();
System.out.println("USAGE: unisay2ttyunisay [SOURCE... | < SOURCE > TARGET]");
System.out.println();
System.out.println("Source (STDIN): Regular unisay pony");
System.out.println("Target (STDOUT): New TTY unisay pony");
System.out.println();
System.out.println();
System.out.println("Copyright (C) 2012 Mattias Andrée <[email protected]>");
System.out.println();
System.out.println("This program is free software: you can redistribute it and/or modify");
System.out.println("it under the terms of the GNU General Public License as published by");
System.out.println("the Free Software Foundation, either version 3 of the License, or");
System.out.println("(at your option) any later version.");
System.out.println();
System.out.println("This program is distributed in the hope that it will be useful,");
System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the");
System.out.println("GNU General Public License for more details.");
System.out.println();
System.out.println("You should have received a copy of the GNU General Public License");
System.out.println("along with this program. If not, see <http://www.gnu.org/licenses/>.");
System.out.println();
System.out.println();
return;
}
if (args.length == 0)
convert(stdin, stdout);
else
for (final String arg : args)
{
String file = (new File(arg)).getAbsolutePath();
String outfile = file.substring(0, file.lastIndexOf("/"));
outfile = outfile.substring(0, outfile.lastIndexOf("/"));
outfile += "/ttypony";
outfile += file.substring(file.lastIndexOf("/"));
InputStream fin = new BufferedInputStream(new FileInputStream(new File(arg)));
PrintStream fout = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File(outfile))));
convert(fin, fout);
fin.close();
fout.close();
}
}
private static final InputStream stdin = System.in;
private static final PrintStream stdout = System.out;
private static void convert(final InputStream in, final PrintStream out) throws IOException
{
- out.println("\033c");
+ out.print("\033c");
boolean dollar = false;
for (int d; (d = in.read()) != -1;)
if (d == '$')
{
dollar ^= true;
out.write(d);
}
else if (dollar)
out.write(d);
else if (d == '\033')
{
d = in.read();
if (d == '[')
{
d = in.read();
if (d == 'm')
out.print("\033]P7aaaaaa\033]Pfffffff\033[0m");
int lastlast = 0;
int last = 0;
int item = 0;
for (;;)
{
if ((d == ';') || (d == 'm'))
{
item = -item;
if (item == 0) out.print("\033]P7aaaaaa\033]Pfffffff\033[0m");
else if (item == 39) out.print("\033[39m");
else if (item == 49) out.print("\033[49m");
else if ((last == 5) && (lastlast == 38))
{
Colour colour = new Colour(item);
out.print(getOSIPCode(colour.red, colour.green, colour.blue, false));
}
else if ((last == 5) && (lastlast == 48))
{
Colour colour = new Colour(item);
out.print(getOSIPCode(colour.red, colour.green, colour.blue, true));
}
else if ((item != 5) || ((last != 38) && (last != 48)))
if ((item != 38) && (item != 48))
{
System.err.println("Not a pretty pony. Stop.");
System.exit(-1);
}
lastlast = last;
last = item;
item = 0;
if (d == 'm')
break;
}
else
item = (item * 10) - (d & 15);
d = in.read();
}
}
else
{
System.err.println("Not a pretty pony. Stop.");
System.exit(-1);
}
}
else
out.write(d);
}
private static final String HEX = "0123456789abcdef";
private static String getOSIPCode(final int r, final int g, final int b, final boolean background)
{
String code = new String();
code += HEX.charAt((r >> 4) & 15);
code += HEX.charAt( r & 15);
code += HEX.charAt((g >> 4) & 15);
code += HEX.charAt( g & 15);
code += HEX.charAt((b >> 4) & 15);
code += HEX.charAt( b & 15);
return "\033]P" + (background ? '7' : 'f') + code + "\033[" + (background ? "4" : "1;3") + "7m";
}
}
| true | true | private static void convert(final InputStream in, final PrintStream out) throws IOException
{
out.println("\033c");
boolean dollar = false;
for (int d; (d = in.read()) != -1;)
if (d == '$')
{
dollar ^= true;
out.write(d);
}
else if (dollar)
out.write(d);
else if (d == '\033')
{
d = in.read();
if (d == '[')
{
d = in.read();
if (d == 'm')
out.print("\033]P7aaaaaa\033]Pfffffff\033[0m");
int lastlast = 0;
int last = 0;
int item = 0;
for (;;)
{
if ((d == ';') || (d == 'm'))
{
item = -item;
if (item == 0) out.print("\033]P7aaaaaa\033]Pfffffff\033[0m");
else if (item == 39) out.print("\033[39m");
else if (item == 49) out.print("\033[49m");
else if ((last == 5) && (lastlast == 38))
{
Colour colour = new Colour(item);
out.print(getOSIPCode(colour.red, colour.green, colour.blue, false));
}
else if ((last == 5) && (lastlast == 48))
{
Colour colour = new Colour(item);
out.print(getOSIPCode(colour.red, colour.green, colour.blue, true));
}
else if ((item != 5) || ((last != 38) && (last != 48)))
if ((item != 38) && (item != 48))
{
System.err.println("Not a pretty pony. Stop.");
System.exit(-1);
}
lastlast = last;
last = item;
item = 0;
if (d == 'm')
break;
}
else
item = (item * 10) - (d & 15);
d = in.read();
}
}
else
{
System.err.println("Not a pretty pony. Stop.");
System.exit(-1);
}
}
else
out.write(d);
}
| private static void convert(final InputStream in, final PrintStream out) throws IOException
{
out.print("\033c");
boolean dollar = false;
for (int d; (d = in.read()) != -1;)
if (d == '$')
{
dollar ^= true;
out.write(d);
}
else if (dollar)
out.write(d);
else if (d == '\033')
{
d = in.read();
if (d == '[')
{
d = in.read();
if (d == 'm')
out.print("\033]P7aaaaaa\033]Pfffffff\033[0m");
int lastlast = 0;
int last = 0;
int item = 0;
for (;;)
{
if ((d == ';') || (d == 'm'))
{
item = -item;
if (item == 0) out.print("\033]P7aaaaaa\033]Pfffffff\033[0m");
else if (item == 39) out.print("\033[39m");
else if (item == 49) out.print("\033[49m");
else if ((last == 5) && (lastlast == 38))
{
Colour colour = new Colour(item);
out.print(getOSIPCode(colour.red, colour.green, colour.blue, false));
}
else if ((last == 5) && (lastlast == 48))
{
Colour colour = new Colour(item);
out.print(getOSIPCode(colour.red, colour.green, colour.blue, true));
}
else if ((item != 5) || ((last != 38) && (last != 48)))
if ((item != 38) && (item != 48))
{
System.err.println("Not a pretty pony. Stop.");
System.exit(-1);
}
lastlast = last;
last = item;
item = 0;
if (d == 'm')
break;
}
else
item = (item * 10) - (d & 15);
d = in.read();
}
}
else
{
System.err.println("Not a pretty pony. Stop.");
System.exit(-1);
}
}
else
out.write(d);
}
|
diff --git a/org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/strategies/get_service_input_term_0_1.java b/org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/strategies/get_service_input_term_0_1.java
index 670dc49..c843996 100644
--- a/org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/strategies/get_service_input_term_0_1.java
+++ b/org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/strategies/get_service_input_term_0_1.java
@@ -1,33 +1,33 @@
package org.strategoxt.imp.testing.strategies;
import static org.spoofax.interpreter.core.Tools.isTermAppl;
import static org.spoofax.terms.Term.*;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.strategoxt.HybridInterpreter;
import org.strategoxt.imp.runtime.services.InputTermBuilder;
import org.strategoxt.imp.runtime.services.StrategoReferenceResolver;
import org.strategoxt.lang.Context;
import org.strategoxt.lang.Strategy;
/**
* @author Lennart Kats <lennart add lclnet.nl>
*/
public class get_service_input_term_0_1 extends Strategy {
public static get_service_input_term_0_1 instance = new get_service_input_term_0_1();
@Override
public IStrategoTerm invoke(Context context, IStrategoTerm current, IStrategoTerm analyzedAst) {
// TODO: adapt to latest strategy of StrategoReferenceResolver?
if (isTermAppl(analyzedAst) && ((IStrategoAppl) analyzedAst).getName().equals("None"))
analyzedAst = null;
- if ("COMPLETION" != tryGetName(current))
+ if (!"COMPLETION".equals(tryGetName(current)) && !"NOCONTEXT".equals(tryGetName(current)))
current = InputTermBuilder.getMatchingAncestor(current, StrategoReferenceResolver.ALLOW_MULTI_CHILD_PARENT);
HybridInterpreter runtime = HybridInterpreter.getInterpreter(context);
InputTermBuilder inputBuilder = new InputTermBuilder(runtime, analyzedAst);
- return inputBuilder.makeInputTerm(current, true);
+ return inputBuilder.makeInputTerm(current, true, false);
}
}
| false | true | public IStrategoTerm invoke(Context context, IStrategoTerm current, IStrategoTerm analyzedAst) {
// TODO: adapt to latest strategy of StrategoReferenceResolver?
if (isTermAppl(analyzedAst) && ((IStrategoAppl) analyzedAst).getName().equals("None"))
analyzedAst = null;
if ("COMPLETION" != tryGetName(current))
current = InputTermBuilder.getMatchingAncestor(current, StrategoReferenceResolver.ALLOW_MULTI_CHILD_PARENT);
HybridInterpreter runtime = HybridInterpreter.getInterpreter(context);
InputTermBuilder inputBuilder = new InputTermBuilder(runtime, analyzedAst);
return inputBuilder.makeInputTerm(current, true);
}
| public IStrategoTerm invoke(Context context, IStrategoTerm current, IStrategoTerm analyzedAst) {
// TODO: adapt to latest strategy of StrategoReferenceResolver?
if (isTermAppl(analyzedAst) && ((IStrategoAppl) analyzedAst).getName().equals("None"))
analyzedAst = null;
if (!"COMPLETION".equals(tryGetName(current)) && !"NOCONTEXT".equals(tryGetName(current)))
current = InputTermBuilder.getMatchingAncestor(current, StrategoReferenceResolver.ALLOW_MULTI_CHILD_PARENT);
HybridInterpreter runtime = HybridInterpreter.getInterpreter(context);
InputTermBuilder inputBuilder = new InputTermBuilder(runtime, analyzedAst);
return inputBuilder.makeInputTerm(current, true, false);
}
|
diff --git a/src/com/gwt/seminar/client/activity/ResourcesActivity.java b/src/com/gwt/seminar/client/activity/ResourcesActivity.java
index bad3b91..8c9dd50 100644
--- a/src/com/gwt/seminar/client/activity/ResourcesActivity.java
+++ b/src/com/gwt/seminar/client/activity/ResourcesActivity.java
@@ -1,68 +1,68 @@
package com.gwt.seminar.client.activity;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.StackLayoutPanel;
import com.google.gwt.user.client.ui.StackPanel;
import com.google.inject.Inject;
import com.gwt.seminar.client.view.ResourcesView;
import com.gwt.seminar.client.view.resources.GwtLinks;
import com.gwt.seminar.client.view.resources.OtherLinks;
import com.gwt.seminar.client.view.resources.SampleCode;
import com.gwt.seminar.client.view.resources.Videos;
public class ResourcesActivity extends AbstractActivity {
// ResourceView is our containing UiBinder widget
private ResourcesView view;
// Below are the UiBinder widgets that we are going
// to insert into the StackPanel
private SampleCode sampleCode;
private Videos videos;
private GwtLinks gwtLinks;
private OtherLinks otherLinks;
private StackLayoutPanel stackPanel;
@Inject
public ResourcesActivity(ResourcesView view, SampleCode sampleCode, Videos videos,
GwtLinks gwtLinks, OtherLinks otherLinks){
this.view = view;
this.sampleCode = sampleCode;
this.videos = videos;
this.gwtLinks = gwtLinks;
this.otherLinks = otherLinks;
/* I injected the views so we can take full advantage of DI
* And also so I don't have to worry about not creating the
* views twice. Now the view widgets are only created once
* and then they are reused.
*
* I Also go ahead and tie everything into the StackPanel
* (Which I'm not sure if I'm using correctly...)
* so the full StackPanel is just reused each time
* someone visits the Resources Place */
stackPanel = new StackLayoutPanel(Unit.EM);
stackPanel.add(sampleCode, "Sample Code", 2);
stackPanel.add(videos, "Videos", 2);
stackPanel.add(gwtLinks, "GWT Links", 2);
stackPanel.add(otherLinks, "Other Links", 2);
stackPanel.setWidth("100%");
stackPanel.setHeight("100%");
- view.getContent().add(new HTML("resources coming soon"));
+ //view.getContent().add(new HTML("resources coming soon"));
//view.getContent().add(stackPanel);
/* Abstracting everything out into a a new view package (client.view.resources)
* may be over kill for this but it shows one way of organizing
* you project. */
}
@Override
public void start(AcceptsOneWidget panel, EventBus eventBus) {
panel.setWidget(view.asWidget());
}
}
| true | true | public ResourcesActivity(ResourcesView view, SampleCode sampleCode, Videos videos,
GwtLinks gwtLinks, OtherLinks otherLinks){
this.view = view;
this.sampleCode = sampleCode;
this.videos = videos;
this.gwtLinks = gwtLinks;
this.otherLinks = otherLinks;
/* I injected the views so we can take full advantage of DI
* And also so I don't have to worry about not creating the
* views twice. Now the view widgets are only created once
* and then they are reused.
*
* I Also go ahead and tie everything into the StackPanel
* (Which I'm not sure if I'm using correctly...)
* so the full StackPanel is just reused each time
* someone visits the Resources Place */
stackPanel = new StackLayoutPanel(Unit.EM);
stackPanel.add(sampleCode, "Sample Code", 2);
stackPanel.add(videos, "Videos", 2);
stackPanel.add(gwtLinks, "GWT Links", 2);
stackPanel.add(otherLinks, "Other Links", 2);
stackPanel.setWidth("100%");
stackPanel.setHeight("100%");
view.getContent().add(new HTML("resources coming soon"));
//view.getContent().add(stackPanel);
/* Abstracting everything out into a a new view package (client.view.resources)
* may be over kill for this but it shows one way of organizing
* you project. */
}
| public ResourcesActivity(ResourcesView view, SampleCode sampleCode, Videos videos,
GwtLinks gwtLinks, OtherLinks otherLinks){
this.view = view;
this.sampleCode = sampleCode;
this.videos = videos;
this.gwtLinks = gwtLinks;
this.otherLinks = otherLinks;
/* I injected the views so we can take full advantage of DI
* And also so I don't have to worry about not creating the
* views twice. Now the view widgets are only created once
* and then they are reused.
*
* I Also go ahead and tie everything into the StackPanel
* (Which I'm not sure if I'm using correctly...)
* so the full StackPanel is just reused each time
* someone visits the Resources Place */
stackPanel = new StackLayoutPanel(Unit.EM);
stackPanel.add(sampleCode, "Sample Code", 2);
stackPanel.add(videos, "Videos", 2);
stackPanel.add(gwtLinks, "GWT Links", 2);
stackPanel.add(otherLinks, "Other Links", 2);
stackPanel.setWidth("100%");
stackPanel.setHeight("100%");
//view.getContent().add(new HTML("resources coming soon"));
//view.getContent().add(stackPanel);
/* Abstracting everything out into a a new view package (client.view.resources)
* may be over kill for this but it shows one way of organizing
* you project. */
}
|
diff --git a/src/com/jverrecchia/initializr/builder/zip/ZipContentPrinter.java b/src/com/jverrecchia/initializr/builder/zip/ZipContentPrinter.java
index c994ae6..895548e 100644
--- a/src/com/jverrecchia/initializr/builder/zip/ZipContentPrinter.java
+++ b/src/com/jverrecchia/initializr/builder/zip/ZipContentPrinter.java
@@ -1,37 +1,38 @@
package com.jverrecchia.initializr.builder.zip;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import com.jverrecchia.initializr.builder.files.ZipFile;
public class ZipContentPrinter {
private Zip zip;
private HttpServletResponse resp;
public ZipContentPrinter(HttpServletResponse resp, Zip zip){
this.resp = resp;
this.zip = zip;
}
public void printZip() throws IOException{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(zip.getFilename());
for (ZipFile currentFile : zip.getZipFiles()){
out.println("<h1>" + currentFile.getZipPath() + "</h1>");
+ System.err.println(currentFile.getZipPath());
if (currentFile.getContent() == null)
out.println("<xmp>" + new String(currentFile.getBytesData()) + "</xmp>");
else
out.println("<xmp>" + currentFile.getContent() + "</xmp>");
}
}
}
| true | true | public void printZip() throws IOException{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(zip.getFilename());
for (ZipFile currentFile : zip.getZipFiles()){
out.println("<h1>" + currentFile.getZipPath() + "</h1>");
if (currentFile.getContent() == null)
out.println("<xmp>" + new String(currentFile.getBytesData()) + "</xmp>");
else
out.println("<xmp>" + currentFile.getContent() + "</xmp>");
}
}
| public void printZip() throws IOException{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(zip.getFilename());
for (ZipFile currentFile : zip.getZipFiles()){
out.println("<h1>" + currentFile.getZipPath() + "</h1>");
System.err.println(currentFile.getZipPath());
if (currentFile.getContent() == null)
out.println("<xmp>" + new String(currentFile.getBytesData()) + "</xmp>");
else
out.println("<xmp>" + currentFile.getContent() + "</xmp>");
}
}
|
diff --git a/org.emftext.sdk.ant/src/org/emftext/sdk/ant/GenerateTextResourceTask.java b/org.emftext.sdk.ant/src/org/emftext/sdk/ant/GenerateTextResourceTask.java
index 4069cd7af..d0c6d53dc 100644
--- a/org.emftext.sdk.ant/src/org/emftext/sdk/ant/GenerateTextResourceTask.java
+++ b/org.emftext.sdk.ant/src/org/emftext/sdk/ant/GenerateTextResourceTask.java
@@ -1,279 +1,279 @@
/*******************************************************************************
* Copyright (c) 2006-2012
* Software Technology Group, Dresden University of Technology
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.ant;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.emftext.sdk.IPluginDescriptor;
import org.emftext.sdk.codegen.GenerationProblem;
import org.emftext.sdk.codegen.IFileSystemConnector;
import org.emftext.sdk.codegen.resource.ui.CreateResourcePluginsJob.Result;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
import org.emftext.sdk.concretesyntax.resource.cs.ICsTextResource;
import org.emftext.sdk.concretesyntax.resource.cs.mopp.CsResourceFactory;
import org.emftext.sdk.concretesyntax.resource.cs.util.CsResourceUtil;
import org.emftext.sdk.ui.jobs.UICreateResourcePluginsJob;
import org.emftext.sdk.ui.jobs.UIGenerationContext;
/**
* A custom task for the ANT build tool that generates a resource plug-in for a
* given syntax specification.
*/
public class GenerateTextResourceTask extends AbstractEMFTextAntTask {
private File rootFolder;
private File syntaxFile;
private String syntaxProjectName;
private List<GenModelElement> genModels = new ArrayList<GenModelElement>();
private List<GenPackageElement> genPackages = new ArrayList<GenPackageElement>();
private SyntaxProcessor preprocessor;
private boolean generateANTLRPlugin;
private boolean generateModelCode = true;
@Override
public void execute() throws BuildException {
checkParameters();
AntClassLoader taskloader = setClassLoader();
registerResourceFactories();
try {
log("loading syntax file...");
ICsTextResource csResource = CsResourceUtil.getResource(syntaxFile);
EList<EObject> contents = csResource.getContents();
if (contents.size() < 1) {
if (!csResource.getErrors().isEmpty()) {
log("Resource has the following errors:");
for (Resource.Diagnostic diagnostic : csResource.getErrors()) {
log(diagnostic.getMessage() + " (line " + diagnostic.getLine() + ", column " + diagnostic.getColumn() + ")");
}
}
throw new BuildException("Generation failed, because the syntax file could not be loaded. Probably it contains syntactical errors.");
}
ResourceSet resourceSet = csResource.getResourceSet();
EcoreUtil.resolveAll(resourceSet);
Set<EObject> unresolvedProxies = CsResourceUtil.findUnresolvedProxies(resourceSet);
for (EObject unresolvedProxy : unresolvedProxies) {
- log("Found unresolved proxy: " + unresolvedProxy);
+ log("Found unresolved proxy: " + unresolvedProxy, Project.MSG_ERR);
}
if (unresolvedProxies.size() > 0) {
throw new BuildException("Generation failed, because the syntax file contains unresolved proxy objects.");
}
ConcreteSyntax syntax = (ConcreteSyntax) contents.get(0);
performPreprocessing(syntax);
IFileSystemConnector folderConnector = new IFileSystemConnector() {
public File getProjectFolder(IPluginDescriptor plugin) {
return new File(rootFolder.getAbsolutePath() + File.separator + plugin.getName());
}
};
Result result = null;
boolean useUIJob = false;
if (Platform.isRunning()) {
File wsFolder = new File(ResourcesPlugin.getWorkspace().getRoot().getLocationURI());
if(rootFolder.equals(wsFolder))
useUIJob = true;
}
AntProblemCollector problemCollector = new AntProblemCollector(this);
if (useUIJob) {
UIGenerationContext context = new UIGenerationContext(folderConnector, problemCollector, syntax);
UICreateResourcePluginsJob job = new UICreateResourcePluginsJob();
result = job.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
} else {
AntGenerationContext context = new AntGenerationContext(folderConnector, problemCollector, syntax, rootFolder, syntaxProjectName, generateANTLRPlugin, generateModelCode);
AntResourcePluginGenerator generator = new AntResourcePluginGenerator();
result = generator.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
}
if (result != Result.SUCCESS) {
if (result == Result.ERROR_FOUND_UNRESOLVED_PROXIES) {
for (EObject unresolvedProxy : result.getUnresolvedProxies()) {
log("Found unresolved proxy \"" + ((InternalEObject) unresolvedProxy).eProxyURI() + "\" in " + unresolvedProxy.eResource());
}
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
} else {
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
}
}
Collection<GenerationProblem> errors = problemCollector.getErrors();
if (!errors.isEmpty()) {
for (GenerationProblem error : errors) {
log("Found problem: " + error.getMessage(), Project.MSG_ERR);
}
throw new BuildException("Generation failed. Found " + errors.size() + " problem(s) while generating text resource plug-ins.");
}
} catch (Exception e) {
resetClassLoader(taskloader);
log("Exception while generation text resource: " + e.getMessage(), Project.MSG_ERR);
e.printStackTrace();
throw new BuildException(e);
}
resetClassLoader(taskloader);
}
private void performPreprocessing(ConcreteSyntax syntax) {
if (preprocessor == null) {
return;
}
preprocessor.process(syntax);
}
public void setPreprocessor(SyntaxProcessor preprocessor) {
this.preprocessor = preprocessor;
}
private void checkParameters() {
if (syntaxFile == null) {
throw new BuildException("Parameter \"syntax\" is missing.");
}
if (rootFolder == null) {
throw new BuildException("Parameter \"rootFolder\" is missing.");
}
if (syntaxProjectName == null) {
throw new BuildException("Parameter \"syntaxProjectName\" is missing.");
}
}
public void setGenerateANTLRPlugin(boolean generateANTLRPlugin) {
this.generateANTLRPlugin = generateANTLRPlugin;
}
public void setSyntax(File syntaxFile) {
this.syntaxFile = syntaxFile;
}
public void setRootFolder(File rootFolder) {
this.rootFolder = rootFolder;
}
public void setSyntaxProjectName(String syntaxProjectName) {
this.syntaxProjectName = syntaxProjectName;
}
public void setGenerateModelCode(boolean generateModelCode) {
this.generateModelCode = generateModelCode;
}
public void addGenModel(GenModelElement factory) {
genModels.add(factory);
}
public void addGenPackage(GenPackageElement factory) {
genPackages.add(factory);
}
public void registerResourceFactories() {
//in case a old version from last run is registered here
EPackage.Registry.INSTANCE.remove("http://www.emftext.org/sdk/concretesyntax");
registerFactory("cs", new CsResourceFactory());
//TODO: the rest of this method is never used in our build scripts at the moment
for (GenModelElement genModelElement : genModels) {
String namespaceURI = genModelElement.getNamespaceURI();
String genModelURI = genModelElement.getGenModelURI();
try {
log("registering genmodel " + namespaceURI + " at " + genModelURI);
EcorePlugin.getEPackageNsURIToGenModelLocationMap().put(
namespaceURI,
URI.createURI(genModelURI)
);
//register a mapping for "resource:/plugin/..." URIs in case
//one genmodel imports another genmodel using this URI
String filesSystemURI = genModelURI;
int startIdx = filesSystemURI.indexOf("/plugins");
int versionStartIdx = filesSystemURI.indexOf("_",startIdx);
int filePathStartIdx = filesSystemURI.lastIndexOf("!/") + 1;
if(startIdx > -1 && versionStartIdx > startIdx && filePathStartIdx > versionStartIdx) {
String platformPluginURI = "platform:" + filesSystemURI.substring(startIdx, versionStartIdx);
platformPluginURI = platformPluginURI + filesSystemURI.substring(filePathStartIdx);
platformPluginURI = platformPluginURI.replace("/plugins/", "/plugin/");
//gen model
log("adding mapping from " + platformPluginURI + " to " + filesSystemURI);
URIConverter.URI_MAP.put(
URI.createURI(platformPluginURI),
URI.createURI(filesSystemURI));
//ecore model (this code assumes that both files are named equally)
filesSystemURI = filesSystemURI.replace(".genmodel", ".ecore");
platformPluginURI = platformPluginURI.replace(".genmodel", ".ecore");
log("adding mapping from " + platformPluginURI + " to " + filesSystemURI);
URIConverter.URI_MAP.put(
URI.createURI(platformPluginURI),
URI.createURI(filesSystemURI));
}
} catch (Exception e) {
throw new BuildException("Error while registering genmodel " + namespaceURI, e);
}
}
for (GenPackageElement genPackage : genPackages) {
String namespaceURI = genPackage.getNamespaceURI();
String ePackageClassName = genPackage.getEPackageClassName();
try {
log("registering ePackage " + namespaceURI + " at " + ePackageClassName);
Field factoryInstance = Class.forName(ePackageClassName).getField("eINSTANCE");
Object ePackageObject = factoryInstance.get(null);
EPackage.Registry.INSTANCE.put(namespaceURI, ePackageObject);
} catch (Exception e) {
e.printStackTrace();
throw new BuildException("Error while registering EPackage " + namespaceURI, e);
}
}
}
private void registerFactory(String extension, Object factory) {
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().remove(extension);
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
extension,
factory);
}
}
| true | true | public void execute() throws BuildException {
checkParameters();
AntClassLoader taskloader = setClassLoader();
registerResourceFactories();
try {
log("loading syntax file...");
ICsTextResource csResource = CsResourceUtil.getResource(syntaxFile);
EList<EObject> contents = csResource.getContents();
if (contents.size() < 1) {
if (!csResource.getErrors().isEmpty()) {
log("Resource has the following errors:");
for (Resource.Diagnostic diagnostic : csResource.getErrors()) {
log(diagnostic.getMessage() + " (line " + diagnostic.getLine() + ", column " + diagnostic.getColumn() + ")");
}
}
throw new BuildException("Generation failed, because the syntax file could not be loaded. Probably it contains syntactical errors.");
}
ResourceSet resourceSet = csResource.getResourceSet();
EcoreUtil.resolveAll(resourceSet);
Set<EObject> unresolvedProxies = CsResourceUtil.findUnresolvedProxies(resourceSet);
for (EObject unresolvedProxy : unresolvedProxies) {
log("Found unresolved proxy: " + unresolvedProxy);
}
if (unresolvedProxies.size() > 0) {
throw new BuildException("Generation failed, because the syntax file contains unresolved proxy objects.");
}
ConcreteSyntax syntax = (ConcreteSyntax) contents.get(0);
performPreprocessing(syntax);
IFileSystemConnector folderConnector = new IFileSystemConnector() {
public File getProjectFolder(IPluginDescriptor plugin) {
return new File(rootFolder.getAbsolutePath() + File.separator + plugin.getName());
}
};
Result result = null;
boolean useUIJob = false;
if (Platform.isRunning()) {
File wsFolder = new File(ResourcesPlugin.getWorkspace().getRoot().getLocationURI());
if(rootFolder.equals(wsFolder))
useUIJob = true;
}
AntProblemCollector problemCollector = new AntProblemCollector(this);
if (useUIJob) {
UIGenerationContext context = new UIGenerationContext(folderConnector, problemCollector, syntax);
UICreateResourcePluginsJob job = new UICreateResourcePluginsJob();
result = job.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
} else {
AntGenerationContext context = new AntGenerationContext(folderConnector, problemCollector, syntax, rootFolder, syntaxProjectName, generateANTLRPlugin, generateModelCode);
AntResourcePluginGenerator generator = new AntResourcePluginGenerator();
result = generator.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
}
if (result != Result.SUCCESS) {
if (result == Result.ERROR_FOUND_UNRESOLVED_PROXIES) {
for (EObject unresolvedProxy : result.getUnresolvedProxies()) {
log("Found unresolved proxy \"" + ((InternalEObject) unresolvedProxy).eProxyURI() + "\" in " + unresolvedProxy.eResource());
}
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
} else {
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
}
}
Collection<GenerationProblem> errors = problemCollector.getErrors();
if (!errors.isEmpty()) {
for (GenerationProblem error : errors) {
log("Found problem: " + error.getMessage(), Project.MSG_ERR);
}
throw new BuildException("Generation failed. Found " + errors.size() + " problem(s) while generating text resource plug-ins.");
}
} catch (Exception e) {
resetClassLoader(taskloader);
log("Exception while generation text resource: " + e.getMessage(), Project.MSG_ERR);
e.printStackTrace();
throw new BuildException(e);
}
resetClassLoader(taskloader);
}
| public void execute() throws BuildException {
checkParameters();
AntClassLoader taskloader = setClassLoader();
registerResourceFactories();
try {
log("loading syntax file...");
ICsTextResource csResource = CsResourceUtil.getResource(syntaxFile);
EList<EObject> contents = csResource.getContents();
if (contents.size() < 1) {
if (!csResource.getErrors().isEmpty()) {
log("Resource has the following errors:");
for (Resource.Diagnostic diagnostic : csResource.getErrors()) {
log(diagnostic.getMessage() + " (line " + diagnostic.getLine() + ", column " + diagnostic.getColumn() + ")");
}
}
throw new BuildException("Generation failed, because the syntax file could not be loaded. Probably it contains syntactical errors.");
}
ResourceSet resourceSet = csResource.getResourceSet();
EcoreUtil.resolveAll(resourceSet);
Set<EObject> unresolvedProxies = CsResourceUtil.findUnresolvedProxies(resourceSet);
for (EObject unresolvedProxy : unresolvedProxies) {
log("Found unresolved proxy: " + unresolvedProxy, Project.MSG_ERR);
}
if (unresolvedProxies.size() > 0) {
throw new BuildException("Generation failed, because the syntax file contains unresolved proxy objects.");
}
ConcreteSyntax syntax = (ConcreteSyntax) contents.get(0);
performPreprocessing(syntax);
IFileSystemConnector folderConnector = new IFileSystemConnector() {
public File getProjectFolder(IPluginDescriptor plugin) {
return new File(rootFolder.getAbsolutePath() + File.separator + plugin.getName());
}
};
Result result = null;
boolean useUIJob = false;
if (Platform.isRunning()) {
File wsFolder = new File(ResourcesPlugin.getWorkspace().getRoot().getLocationURI());
if(rootFolder.equals(wsFolder))
useUIJob = true;
}
AntProblemCollector problemCollector = new AntProblemCollector(this);
if (useUIJob) {
UIGenerationContext context = new UIGenerationContext(folderConnector, problemCollector, syntax);
UICreateResourcePluginsJob job = new UICreateResourcePluginsJob();
result = job.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
} else {
AntGenerationContext context = new AntGenerationContext(folderConnector, problemCollector, syntax, rootFolder, syntaxProjectName, generateANTLRPlugin, generateModelCode);
AntResourcePluginGenerator generator = new AntResourcePluginGenerator();
result = generator.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
}
if (result != Result.SUCCESS) {
if (result == Result.ERROR_FOUND_UNRESOLVED_PROXIES) {
for (EObject unresolvedProxy : result.getUnresolvedProxies()) {
log("Found unresolved proxy \"" + ((InternalEObject) unresolvedProxy).eProxyURI() + "\" in " + unresolvedProxy.eResource());
}
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
} else {
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
}
}
Collection<GenerationProblem> errors = problemCollector.getErrors();
if (!errors.isEmpty()) {
for (GenerationProblem error : errors) {
log("Found problem: " + error.getMessage(), Project.MSG_ERR);
}
throw new BuildException("Generation failed. Found " + errors.size() + " problem(s) while generating text resource plug-ins.");
}
} catch (Exception e) {
resetClassLoader(taskloader);
log("Exception while generation text resource: " + e.getMessage(), Project.MSG_ERR);
e.printStackTrace();
throw new BuildException(e);
}
resetClassLoader(taskloader);
}
|
diff --git a/common/cpw/mods/fml/common/modloader/BaseModTicker.java b/common/cpw/mods/fml/common/modloader/BaseModTicker.java
index 866b1393..3e915202 100644
--- a/common/cpw/mods/fml/common/modloader/BaseModTicker.java
+++ b/common/cpw/mods/fml/common/modloader/BaseModTicker.java
@@ -1,132 +1,132 @@
/*
* The FML Forge Mod Loader suite.
* Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package cpw.mods.fml.common.modloader;
import java.util.EnumSet;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
/**
* @author cpw
*
*/
public class BaseModTicker implements ITickHandler
{
private BaseMod mod;
private EnumSet<TickType> ticks;
private boolean clockTickTrigger;
private boolean sendGuiTicks;
BaseModTicker(BaseMod mod, boolean guiTicker)
{
this.mod = mod;
this.ticks = EnumSet.of(TickType.WORLDLOAD);
this.sendGuiTicks = guiTicker;
}
BaseModTicker(EnumSet<TickType> ticks, boolean guiTicker)
{
this.ticks = ticks;
this.sendGuiTicks = guiTicker;
}
@Override
public void tickStart(EnumSet<TickType> types, Object... tickData)
{
tickBaseMod(types, false, tickData);
}
@Override
public void tickEnd(EnumSet<TickType> types, Object... tickData)
{
tickBaseMod(types, true, tickData);
}
private void tickBaseMod(EnumSet<TickType> types, boolean end, Object... tickData)
{
- if (FMLCommonHandler.instance().getSide().isClient() && ( ticks.contains(TickType.GAME) || ticks.contains(TickType.WORLDLOAD)) || ticks.contains(TickType.RENDER))
+ if (FMLCommonHandler.instance().getSide().isClient() && ( ticks.contains(TickType.GAME) || ticks.contains(TickType.WORLDLOAD)))
{
EnumSet cTypes=EnumSet.copyOf(types);
if ( ( end && types.contains(TickType.GAME)) || types.contains(TickType.WORLDLOAD))
{
clockTickTrigger = true;
cTypes.remove(TickType.GAME);
cTypes.remove(TickType.WORLDLOAD);
}
if (end && clockTickTrigger && types.contains(TickType.RENDER))
{
clockTickTrigger = false;
cTypes.remove(TickType.RENDER);
cTypes.add(TickType.GAME);
}
sendTick(cTypes, end, tickData);
}
else
{
sendTick(types, end, tickData);
}
}
private void sendTick(EnumSet<TickType> types, boolean end, Object... tickData)
{
for (TickType type : types)
{
if (!ticks.contains(type))
{
continue;
}
boolean keepTicking=true;
if (sendGuiTicks)
{
keepTicking = mod.doTickInGUI(type, end, FMLCommonHandler.instance().getMinecraftInstance(), tickData);
}
else
{
keepTicking = mod.doTickInGame(type, end, FMLCommonHandler.instance().getMinecraftInstance(), tickData);
}
if (!keepTicking) {
ticks.remove(type);
ticks.removeAll(type.partnerTicks());
}
}
}
@Override
public EnumSet<TickType> ticks()
{
return (clockTickTrigger ? EnumSet.of(TickType.RENDER) : ticks);
}
@Override
public String getLabel()
{
return mod.getClass().getSimpleName();
}
/**
* @param mod2
*/
public void setMod(BaseMod mod)
{
this.mod = mod;
}
}
| true | true | private void tickBaseMod(EnumSet<TickType> types, boolean end, Object... tickData)
{
if (FMLCommonHandler.instance().getSide().isClient() && ( ticks.contains(TickType.GAME) || ticks.contains(TickType.WORLDLOAD)) || ticks.contains(TickType.RENDER))
{
EnumSet cTypes=EnumSet.copyOf(types);
if ( ( end && types.contains(TickType.GAME)) || types.contains(TickType.WORLDLOAD))
{
clockTickTrigger = true;
cTypes.remove(TickType.GAME);
cTypes.remove(TickType.WORLDLOAD);
}
if (end && clockTickTrigger && types.contains(TickType.RENDER))
{
clockTickTrigger = false;
cTypes.remove(TickType.RENDER);
cTypes.add(TickType.GAME);
}
sendTick(cTypes, end, tickData);
}
else
{
sendTick(types, end, tickData);
}
}
| private void tickBaseMod(EnumSet<TickType> types, boolean end, Object... tickData)
{
if (FMLCommonHandler.instance().getSide().isClient() && ( ticks.contains(TickType.GAME) || ticks.contains(TickType.WORLDLOAD)))
{
EnumSet cTypes=EnumSet.copyOf(types);
if ( ( end && types.contains(TickType.GAME)) || types.contains(TickType.WORLDLOAD))
{
clockTickTrigger = true;
cTypes.remove(TickType.GAME);
cTypes.remove(TickType.WORLDLOAD);
}
if (end && clockTickTrigger && types.contains(TickType.RENDER))
{
clockTickTrigger = false;
cTypes.remove(TickType.RENDER);
cTypes.add(TickType.GAME);
}
sendTick(cTypes, end, tickData);
}
else
{
sendTick(types, end, tickData);
}
}
|
diff --git a/app/Global.java b/app/Global.java
index d9101d8..e63c0fd 100644
--- a/app/Global.java
+++ b/app/Global.java
@@ -1,94 +1,94 @@
import java.util.Arrays;
import models.SecurityRole;
import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.PlayAuthenticate.Resolver;
import com.feth.play.module.pa.exceptions.AccessDeniedException;
import com.feth.play.module.pa.exceptions.AuthException;
import controllers.routes;
import play.Application;
import play.GlobalSettings;
import play.mvc.Call;
import java.net.UnknownHostException;
import play.Logger;
import com.google.code.morphia.Morphia;
import com.mongodb.Mongo;
import controllers.MorphiaObject;
public class Global extends GlobalSettings {
public void onStart(Application app) {
super.beforeStart(app);
Logger.debug("** Starting Application **");
try {
- //MorphiaObject.mongo = new Mongo("10.172.104.17", 27017);
- MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
+ MorphiaObject.mongo = new Mongo("10.172.104.17", 27017);
+ //MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "test");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
PlayAuthenticate.setResolver(new Resolver() {
@Override
public Call login() {
// Your login page
return routes.Application.index();//return routes.Templates.login();
}
@Override
public Call afterAuth() {
// The user will be redirected to this page after authentication
// if no original URL was saved
return routes.Application.index();
}
@Override
public Call afterLogout() {
return routes.Application.index();//routes.Templates.logout();
}
@Override
public Call auth(final String provider) {
// You can provide your own authentication implementation,
// however the default should be sufficient for most cases
return com.feth.play.module.pa.controllers.routes.Authenticate.authenticate(provider);
}
@Override
public Call askMerge() {
return routes.Account.askMerge();
}
@Override
public Call askLink() {
return routes.Account.askLink();
}
@Override
public Call onException(final AuthException e) {
if (e instanceof AccessDeniedException) {
return routes.Signup.oAuthDenied(((AccessDeniedException) e).getProviderKey());
}
// more custom problem handling here...
return super.onException(e);
}
});
initialData();
}
private void initialData() {
if (SecurityRole.all(SecurityRole.class).size() == 0) {
for (final String roleName : Arrays.asList(controllers.Application.USER_ROLE)) {
final SecurityRole role = new SecurityRole();
role.roleName = roleName;
role.save();
}
}
}
}
| true | true | public void onStart(Application app) {
super.beforeStart(app);
Logger.debug("** Starting Application **");
try {
//MorphiaObject.mongo = new Mongo("10.172.104.17", 27017);
MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "test");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
PlayAuthenticate.setResolver(new Resolver() {
@Override
public Call login() {
// Your login page
return routes.Application.index();//return routes.Templates.login();
}
@Override
public Call afterAuth() {
// The user will be redirected to this page after authentication
// if no original URL was saved
return routes.Application.index();
}
@Override
public Call afterLogout() {
return routes.Application.index();//routes.Templates.logout();
}
@Override
public Call auth(final String provider) {
// You can provide your own authentication implementation,
// however the default should be sufficient for most cases
return com.feth.play.module.pa.controllers.routes.Authenticate.authenticate(provider);
}
@Override
public Call askMerge() {
return routes.Account.askMerge();
}
@Override
public Call askLink() {
return routes.Account.askLink();
}
@Override
public Call onException(final AuthException e) {
if (e instanceof AccessDeniedException) {
return routes.Signup.oAuthDenied(((AccessDeniedException) e).getProviderKey());
}
// more custom problem handling here...
return super.onException(e);
}
});
initialData();
}
| public void onStart(Application app) {
super.beforeStart(app);
Logger.debug("** Starting Application **");
try {
MorphiaObject.mongo = new Mongo("10.172.104.17", 27017);
//MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "test");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
PlayAuthenticate.setResolver(new Resolver() {
@Override
public Call login() {
// Your login page
return routes.Application.index();//return routes.Templates.login();
}
@Override
public Call afterAuth() {
// The user will be redirected to this page after authentication
// if no original URL was saved
return routes.Application.index();
}
@Override
public Call afterLogout() {
return routes.Application.index();//routes.Templates.logout();
}
@Override
public Call auth(final String provider) {
// You can provide your own authentication implementation,
// however the default should be sufficient for most cases
return com.feth.play.module.pa.controllers.routes.Authenticate.authenticate(provider);
}
@Override
public Call askMerge() {
return routes.Account.askMerge();
}
@Override
public Call askLink() {
return routes.Account.askLink();
}
@Override
public Call onException(final AuthException e) {
if (e instanceof AccessDeniedException) {
return routes.Signup.oAuthDenied(((AccessDeniedException) e).getProviderKey());
}
// more custom problem handling here...
return super.onException(e);
}
});
initialData();
}
|
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
index 2cdbad399..a1ee2c059 100755
--- a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
@@ -1,277 +1,277 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.misc;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import javax.tools.JavaFileObject;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager;
import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl;
import com.redhat.ceylon.compiler.java.tools.CeyloncTool;
public class MiscTest extends CompilerTest {
@Test
public void testDefaultedModel() throws Exception{
compile("defaultedmodel/DefineDefaulted.ceylon");
compile("defaultedmodel/UseDefaulted.ceylon");
}
@Test
public void testHelloWorld(){
compareWithJavaSource("helloworld/helloworld");
}
@Test
public void runHelloWorld() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.helloworld.helloworld", "helloworld/helloworld.ceylon");
}
@Test
public void testCompileTwoDepdendantClasses() throws Exception{
compile("twoclasses/Two.ceylon");
compile("twoclasses/One.ceylon");
}
@Test
public void testCompileTwoClasses() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.twoclasses.main", "twoclasses/One.ceylon", "twoclasses/Two.ceylon", "twoclasses/main.ceylon");
}
@Test
public void testEqualsHashOverriding(){
compareWithJavaSource("equalshashoverriding/EqualsHashOverriding");
}
@Test
public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.metamodel"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
- "Array", "Boolean", "Callable", "Character", "className",
+ "Array", "ArraySequence", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
"parseFloat", "parseInteger", "string", "true", "integerRangeByIterable"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
private void addJavaSourceFile(String baseName, List<File> sourceFiles, File javaPkgDir) {
if (Character.isLowerCase(baseName.charAt(0))) {
sourceFiles.add(new File(javaPkgDir, baseName + "_.java"));
} else {
sourceFiles.add(new File(javaPkgDir, baseName + ".java"));
File impl = new File(javaPkgDir, baseName + "$impl.java");
if (impl.exists()) {
sourceFiles.add(impl);
}
}
}
@Test
public void compileSDK(){
String[] modules = {
"collection",
"dbc",
"file",
"interop.java",
"io",
"json",
"math",
"util",
"net",
"process",
};
String sourceDir = "../ceylon-sdk/source";
// don't run this if the SDK is not checked out
File sdkFile = new File(sourceDir);
if(!sdkFile.exists())
return;
java.util.List<String> moduleNames = new ArrayList<String>(modules.length);
for(String module : modules){
moduleNames.add("ceylon." + module);
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", sourceDir, "-d", "build/classes-sdk"),
moduleNames, null);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
//
// Java keyword avoidance
// Note class names and generic type arguments are not a problem because
// in Ceylon they must begin with an upper case latter, but the Java
// keywords are all lowercase
@Test
public void testKeywordVariable(){
compareWithJavaSource("keyword/Variable");
}
@Test
public void testKeywordAttribute(){
compareWithJavaSource("keyword/Attribute");
}
@Test
public void testKeywordMethod(){
compareWithJavaSource("keyword/Method");
}
@Test
public void testKeywordParameter(){
compareWithJavaSource("keyword/Parameter");
}
@Test
public void testJDKModules(){
Assert.assertTrue(JDKUtils.isJDKModule("java.base"));
Assert.assertTrue(JDKUtils.isJDKModule("java.desktop"));
Assert.assertTrue(JDKUtils.isJDKModule("java.compiler")); // last one
Assert.assertFalse(JDKUtils.isJDKModule("java.stef"));
}
@Test
public void testJDKPackages(){
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.awt"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.lang"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.util"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("javax.swing"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.w3c.dom"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.xml.sax.helpers"));// last one
Assert.assertFalse(JDKUtils.isJDKAnyPackage("fr.epardaud"));
}
@Test
public void testOracleJDKModules(){
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.base"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.desktop"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.httpserver"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.tools.base")); // last one
Assert.assertFalse(JDKUtils.isOracleJDKModule("oracle.jdk.stef"));
Assert.assertFalse(JDKUtils.isOracleJDKModule("jdk.base"));
}
@Test
public void testOracleJDKPackages(){
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.oracle.net"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.awt"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.imageio.plugins.bmp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.java.swing.plaf.gtk"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.nio.sctp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sun.nio"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sunw.util"));// last one
Assert.assertFalse(JDKUtils.isOracleJDKAnyPackage("fr.epardaud"));
}
}
| true | true | public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.metamodel"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
"Array", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
"parseFloat", "parseInteger", "string", "true", "integerRangeByIterable"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
| public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.metamodel"};
HashSet exceptions = new HashSet();
for (String ex : new String[] {
// Native files
"Array", "ArraySequence", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "unflatten",
}) {
exceptions.add(ex);
}
String[] extras = new String[]{
"array", "arrayOfSize", "copyArray", "false", "infinity",
"parseFloat", "parseInteger", "string", "true", "integerRangeByIterable"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.contains(baseName)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
|
diff --git a/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/StatusBar.java b/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/StatusBar.java
index e2553d6..d8a56d3 100644
--- a/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/StatusBar.java
+++ b/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/StatusBar.java
@@ -1,170 +1,170 @@
// ============================================================================
// Copyright 2006-2009 Daniel W. Dyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ============================================================================
package org.uncommons.watchmaker.swing.evolutionmonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import org.uncommons.watchmaker.framework.PopulationData;
import org.uncommons.watchmaker.framework.islands.IslandEvolutionObserver;
/**
* Status bar component for the evolution monitor. Can also be used separately to
* provide basic status information without having to use the full evolution monitor.
* @author Daniel Dyer
*/
public class StatusBar extends Box implements IslandEvolutionObserver<Object>
{
private final JLabel generationsLabel = new JLabel("N/A", JLabel.RIGHT);
private final JLabel timeLabel = new JLabel("N/A", JLabel.RIGHT);
private final JLabel populationLabel = new JLabel("N/A", JLabel.RIGHT);
private final JLabel elitismLabel = new JLabel("N/A", JLabel.RIGHT);
private final AtomicInteger islandPopulationSize = new AtomicInteger(-1);
private final AtomicLong startTime = new AtomicLong(-1);
public StatusBar()
{
this(false);
}
/**
* @param islands Whether the status bar should be configured for updates from
* {@link org.uncommons.watchmaker.framework.islands.IslandEvolution}. Set this
* parameter to false when using a standard {@link org.uncommons.watchmaker.framework.EvolutionEngine}
*/
public StatusBar(boolean islands)
{
super(BoxLayout.X_AXIS);
add(new JLabel("Population: "));
add(populationLabel);
add(createHorizontalStrut(15));
add(new JLabel("Elitism: "));
add(elitismLabel);
add(createHorizontalStrut(15));
add(new JLabel(islands ? "Epochs: " : "Generations: "));
add(generationsLabel);
add(createHorizontalStrut(15));
add(new JLabel("Elapsed Time: "));
add(timeLabel);
setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
// Set component names for easy look-up from tests.
populationLabel.setName("Population");
elitismLabel.setName("Elitism");
generationsLabel.setName("Generations");
timeLabel.setName("Time");
}
public void populationUpdate(final PopulationData<?> populationData)
{
configure(populationData);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if (populationData.getGenerationNumber() == 0)
{
int islandSize = islandPopulationSize.get();
- if (islandSize > 0)
+ int islandCount = populationData.getPopulationSize() / islandSize;
+ if (islandCount > 1)
{
- int islandCount = populationData.getPopulationSize() / islandSize;
populationLabel.setText(islandCount + "x" + islandSize);
elitismLabel.setText(islandCount + "x" + populationData.getEliteCount());
}
else
{
populationLabel.setText(String.valueOf(populationData.getPopulationSize()));
elitismLabel.setText(String.valueOf(populationData.getEliteCount()));
}
}
generationsLabel.setText(String.valueOf(populationData.getGenerationNumber() + 1));
}
});
}
public void islandPopulationUpdate(int islandIndex,
PopulationData<? extends Object> populationData)
{
configure(populationData);
}
/**
* Once we receive the first notification, we have a better idea of what the configuration is.
* We start the time elapsed timer and set the island population size.
*/
private void configure(PopulationData<? extends Object> populationData)
{
if (startTime.get() < 0) // Make sure the initialisation hasn't already been done.
{
boolean updated = startTime.compareAndSet(-1, System.currentTimeMillis() - populationData.getElapsedTime());
if (updated)
{
Timer timer = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
timeLabel.setText(formatTime(System.currentTimeMillis() - startTime.get()));
}
});
timer.setInitialDelay(0);
timer.start();
islandPopulationSize.set(populationData.getPopulationSize());
}
}
}
private String formatTime(long time)
{
long seconds = time / 1000;
long minutes = seconds / 60;
seconds %= 60;
long hours = minutes / 60;
minutes %= 60;
StringBuilder buffer = new StringBuilder();
if (hours < 10)
{
buffer.append('0');
}
buffer.append(hours);
buffer.append(':');
if (minutes < 10)
{
buffer.append('0');
}
buffer.append(minutes);
buffer.append(':');
if (seconds < 10)
{
buffer.append('0');
}
buffer.append(seconds);
return buffer.toString();
}
}
| false | true | public void populationUpdate(final PopulationData<?> populationData)
{
configure(populationData);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if (populationData.getGenerationNumber() == 0)
{
int islandSize = islandPopulationSize.get();
if (islandSize > 0)
{
int islandCount = populationData.getPopulationSize() / islandSize;
populationLabel.setText(islandCount + "x" + islandSize);
elitismLabel.setText(islandCount + "x" + populationData.getEliteCount());
}
else
{
populationLabel.setText(String.valueOf(populationData.getPopulationSize()));
elitismLabel.setText(String.valueOf(populationData.getEliteCount()));
}
}
generationsLabel.setText(String.valueOf(populationData.getGenerationNumber() + 1));
}
});
}
| public void populationUpdate(final PopulationData<?> populationData)
{
configure(populationData);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if (populationData.getGenerationNumber() == 0)
{
int islandSize = islandPopulationSize.get();
int islandCount = populationData.getPopulationSize() / islandSize;
if (islandCount > 1)
{
populationLabel.setText(islandCount + "x" + islandSize);
elitismLabel.setText(islandCount + "x" + populationData.getEliteCount());
}
else
{
populationLabel.setText(String.valueOf(populationData.getPopulationSize()));
elitismLabel.setText(String.valueOf(populationData.getEliteCount()));
}
}
generationsLabel.setText(String.valueOf(populationData.getGenerationNumber() + 1));
}
});
}
|
diff --git a/TFC_Shared/src/TFC/TileEntities/TECrucible.java b/TFC_Shared/src/TFC/TileEntities/TECrucible.java
index c3b80bb8d..f973487f7 100644
--- a/TFC_Shared/src/TFC/TileEntities/TECrucible.java
+++ b/TFC_Shared/src/TFC/TileEntities/TECrucible.java
@@ -1,489 +1,489 @@
package TFC.TileEntities;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.packet.Packet;
import TFC.TFCBlocks;
import TFC.TFCItems;
import TFC.TerraFirmaCraft;
import TFC.API.ISmeltable;
import TFC.API.Metal;
import TFC.API.Constant.Global;
import TFC.Core.TFC_Climate;
import TFC.Core.TFC_Core;
import TFC.Core.TFC_ItemHeat;
import TFC.Core.Metal.Alloy;
import TFC.Core.Metal.AlloyManager;
import TFC.Core.Metal.AlloyMetal;
import TFC.Core.Metal.MetalPair;
import TFC.Core.Metal.MetalRegistry;
import TFC.Handlers.PacketHandler;
import TFC.Items.ItemMeltedMetal;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class TECrucible extends NetworkTileEntity implements IInventory
{
public HashMap metals = new HashMap();
public Alloy currentAlloy;
public int temperature = 0;
public ItemStack[] storage;
public byte inputTick = 0;
public byte outputTick = 0;
public byte tempTick = 0;
public TECrucible()
{
storage = new ItemStack[2];
}
@Override
public void writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
nbt.setInteger("temp", temperature);
NBTTagList nbttaglist = new NBTTagList();
Iterator iter = metals.values().iterator();
while(iter.hasNext())
{
MetalPair m = (MetalPair) iter.next();
if(m != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setInteger("ID", m.type.IngotID);
nbttagcompound1.setShort("Amount", m.amount);
nbttaglist.appendTag(nbttagcompound1);
}
}
nbt.setTag("Metals", nbttaglist);
nbttaglist = new NBTTagList();
for(int i = 0; i < storage.length; i++)
{
if(storage[i] != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
storage[i].writeToNBT(nbttagcompound1);
nbttaglist.appendTag(nbttagcompound1);
}
}
nbt.setTag("Items", nbttaglist);
if(currentAlloy != null)
{
nbt.setInteger("outputAmount", currentAlloy.outputAmount);
}
else
{
nbt.setInteger("outputAmount", 0);
}
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
readFromItemNBT(nbt);
}
public void readFromItemNBT(NBTTagCompound nbt)
{
temperature = nbt.getInteger("temp");
NBTTagList nbttaglist = nbt.getTagList("Metals");
for(int i = 0; i < nbttaglist.tagCount(); i++)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i);
int id = nbttagcompound1.getInteger("ID");
short amount = nbttagcompound1.getShort("Amount");
Metal m = MetalRegistry.instance.getMetalFromItem(Item.itemsList[id]);
addMetal(MetalRegistry.instance.getMetalFromItem(Item.itemsList[id]), amount);
}
nbttaglist = nbt.getTagList("Items");
storage = new ItemStack[getSizeInventory()];
for(int i = 0; i < nbttaglist.tagCount(); i++)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i);
byte byte0 = nbttagcompound1.getByte("Slot");
if(byte0 >= 0 && byte0 < storage.length)
{
storage[byte0] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
}
}
if(currentAlloy != null)
{
currentAlloy.outputAmount = nbt.getInteger("outputAmount");
}
}
@Override
public void updateEntity()
{
if(!worldObj.isRemote)
{
inputTick++;
outputTick++;
tempTick++;
/*Heat the crucible based on the Forge beneath it*/
if(worldObj.getBlockId(xCoord,yCoord-1,zCoord) == TFCBlocks.Forge.blockID)
{
TileEntityForge te = (TileEntityForge) worldObj.getBlockTileEntity(xCoord, yCoord-1, zCoord);
if(te.fireTemperature > temperature) {
temperature++;
}
}
if(tempTick > 22)
{
tempTick = 0;
if(temperature > TFC_Climate.getHeightAdjustedTemp(xCoord, yCoord, zCoord)) {
temperature--;
}
}
ItemStack stackToSmelt = storage[0];
if(stackToSmelt != null)
{
Item itemToSmelt = stackToSmelt.getItem();
if(itemToSmelt instanceof ItemMeltedMetal && TFC_ItemHeat.getIsLiquid(storage[0]))
{
if(inputTick > 5)
{
if(currentAlloy != null && currentAlloy.outputType != null && itemToSmelt.itemID == currentAlloy.outputType.MeltedItemID)
{
this.addMetal(MetalRegistry.instance.getMetalFromItem(itemToSmelt), (short) 1);
- currentAlloy.outputAmount++;
if(stackToSmelt.getItemDamage()+1 >= storage[0].getMaxDamage()) {
storage[0] = new ItemStack(TFCItems.CeramicMold,1,1);
} else {
stackToSmelt.setItemDamage(stackToSmelt.getItemDamage() + 1);
}
}
else
{
this.addMetal(MetalRegistry.instance.getMetalFromItem(itemToSmelt), (short) 1);
if(stackToSmelt.getItemDamage()+1 >= stackToSmelt.getMaxDamage()) {
storage[0] = new ItemStack(TFCItems.CeramicMold,1,1);
} else {
stackToSmelt.setItemDamage(stackToSmelt.getItemDamage() + 1);
}
}
inputTick = 0;
updateGui((byte) 0);
}
}
else if(itemToSmelt instanceof ISmeltable && ((ISmeltable)itemToSmelt).isSmeltable(stackToSmelt) && !TFC_Core.isOreIron(stackToSmelt)
&& temperature >= TFC_ItemHeat.getMeltingPoint(stackToSmelt))
{
Metal mType =((ISmeltable)itemToSmelt).GetMetalType(stackToSmelt);
if(addMetal(mType, ((ISmeltable)itemToSmelt).GetMetalReturnAmount(stackToSmelt)))
{
temperature *= 0.9f;
if(stackToSmelt.stackSize <= 1) {
storage[0] = null;
}
updateGui((byte) 0);
}
}
}
//Metal Output handling
if(currentAlloy != null && storage[1] != null && currentAlloy.outputType != null && outputTick >= 3 && temperature >= TFC_ItemHeat.getMeltingPoint(currentAlloy.outputType))
{
if(storage[1].itemID == TFCItems.CeramicMold.itemID)
{
storage[1] = new ItemStack(Item.itemsList[currentAlloy.outputType.MeltedItemID], 1, 99);
TFC_ItemHeat.SetTemperature(storage[1], temperature);
currentAlloy.outputAmount--;
updateGui((byte) 1);
}
else if(storage[1].itemID == currentAlloy.outputType.MeltedItemID && storage[1].getItemDamage() > 0)
{
storage[1].setItemDamage(storage[1].getItemDamage()-1);
float inTemp =TFC_ItemHeat.GetTemperature(storage[1]);
float temp = Math.abs(temperature - inTemp) / 2;
TFC_ItemHeat.SetTemperature(storage[1], inTemp+temp);
currentAlloy.outputAmount--;
storage[1].stackSize = 1;
updateGui((byte) 1);
}
outputTick = 0;
}
if(currentAlloy != null && currentAlloy.outputAmount <= 0) {
metals = new HashMap();
updateCurrentAlloy();
this.updateGui((byte) 2);
+ currentAlloy = null;
}
if(storage[1] != null && storage[1].stackSize <= 0) {
storage[1].stackSize = 1;
}
if(inputTick > 5) {
inputTick = 0;
}
if(outputTick >= 3) {
outputTick = 0;
}
}
}
public boolean addMetal(Metal m, short amt)
{
if(getTotalMetal()+amt <= 3000 && m.Name != "Unknown")
{
if(metals.containsKey(m.Name)) {
((MetalPair)metals.get(m.Name)).amount += amt;
} else {
metals.put(m.Name, new MetalPair(m, amt));
}
updateCurrentAlloy();
return true;
}
return false;
}
public int getTotalMetal()
{
Iterator iter = metals.values().iterator();
int totalAmount = 0;
while(iter.hasNext())
{
MetalPair m = (MetalPair) iter.next();
if(m != null)
{
totalAmount += m.amount;
}
}
return totalAmount;
}
private void updateCurrentAlloy()
{
List<AlloyMetal> a = new ArrayList<AlloyMetal>();
Iterator iter = metals.values().iterator();
int totalAmount = getTotalMetal();
iter = metals.values().iterator();
while(iter.hasNext())
{
MetalPair m = (MetalPair) iter.next();
if(m != null)
{
a.add(new AlloyMetal(m.type, ((float)m.amount/totalAmount) * 100f));
}
}
Metal match = AlloyManager.instance.matchesAlloy(a, Alloy.EnumTier.TierV);
if(match != null)
{
currentAlloy = new Alloy(match, totalAmount);
currentAlloy.AlloyIngred = a;
}
else
{
currentAlloy = new Alloy(Global.UNKNOWN, totalAmount);
currentAlloy.AlloyIngred = a;
}
}
@Override
public void handleDataPacket(DataInputStream inStream) throws IOException
{
byte id = inStream.readByte();
if(id == 0 && inStream.available() > 0)
{
this.currentAlloy = new Alloy().fromPacket(inStream);
}
else if(id == 1)
{
currentAlloy.outputAmount = inStream.readInt();
}
else if(id == 2)
{
currentAlloy = null;
}
}
@Override
public void handleDataPacketServer(DataInputStream inStream)
throws IOException {
// TODO Auto-generated method stub
}
@Override
public void createInitPacket(DataOutputStream outStream) throws IOException {
// TODO Auto-generated method stub
}
@Override
@SideOnly(Side.CLIENT)
public void handleInitPacket(DataInputStream inStream) throws IOException {
// TODO Auto-generated method stub
}
@Override
public int getSizeInventory() {
return 2;
}
@Override
public ItemStack getStackInSlot(int i) {
return storage[i];
}
@Override
public ItemStack decrStackSize(int i, int j) {
if(storage[i] != null)
{
if(storage[i].stackSize <= j)
{
ItemStack itemstack = storage[i];
storage[i] = null;
return itemstack;
}
ItemStack itemstack1 = storage[i].splitStack(j);
if(storage[i].stackSize == 0)
{
storage[i] = null;
}
return itemstack1;
} else
{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
// TODO Auto-generated method stub
return storage[i];
}
@Override
public void setInventorySlotContents(int i, ItemStack itemstack)
{
storage[i] = itemstack;
}
@Override
public String getInvName() {
return "Crucible";
}
@Override
public boolean isInvNameLocalized() {
// TODO Auto-generated method stub
return false;
}
@Override
public int getInventoryStackLimit() {
// TODO Auto-generated method stub
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
// TODO Auto-generated method stub
return true;
}
@Override
public void openChest() {
// TODO Auto-generated method stub
}
@Override
public void closeChest() {
// TODO Auto-generated method stub
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
// TODO Auto-generated method stub
return true;
}
public Packet createUpdatePacket(byte id)
{
ByteArrayOutputStream bos=new ByteArrayOutputStream(140);
DataOutputStream dos=new DataOutputStream(bos);
try
{
dos.writeByte(PacketHandler.Packet_Data_Block_Client);
dos.writeInt(xCoord);
dos.writeInt(yCoord);
dos.writeInt(zCoord);
if(id == 0 && currentAlloy != null)
{
dos.writeByte(0);
currentAlloy.toPacket(dos);
}
else if(id == 1 && currentAlloy != null)
{
dos.writeByte(1);
dos.writeInt(currentAlloy.outputAmount);
}
else if(id == 2)
{
dos.writeByte(2);
}
}
catch (IOException e) {
}
return this.setupCustomPacketData(bos.toByteArray(), bos.size());
}
public int getOutCountScaled(int length)
{
if(currentAlloy != null) {
return (this.currentAlloy.outputAmount * length)/3000;
} else {
return 0;
}
}
public int getTemperatureScaled(int s)
{
return (temperature * s) / 2500;
}
public void updateGui(byte id)
{
if(!worldObj.isRemote) {
TerraFirmaCraft.proxy.sendCustomPacketToPlayersInRange(xCoord, yCoord, zCoord, createUpdatePacket(id), 5);
}
}
}
| false | true | public void updateEntity()
{
if(!worldObj.isRemote)
{
inputTick++;
outputTick++;
tempTick++;
/*Heat the crucible based on the Forge beneath it*/
if(worldObj.getBlockId(xCoord,yCoord-1,zCoord) == TFCBlocks.Forge.blockID)
{
TileEntityForge te = (TileEntityForge) worldObj.getBlockTileEntity(xCoord, yCoord-1, zCoord);
if(te.fireTemperature > temperature) {
temperature++;
}
}
if(tempTick > 22)
{
tempTick = 0;
if(temperature > TFC_Climate.getHeightAdjustedTemp(xCoord, yCoord, zCoord)) {
temperature--;
}
}
ItemStack stackToSmelt = storage[0];
if(stackToSmelt != null)
{
Item itemToSmelt = stackToSmelt.getItem();
if(itemToSmelt instanceof ItemMeltedMetal && TFC_ItemHeat.getIsLiquid(storage[0]))
{
if(inputTick > 5)
{
if(currentAlloy != null && currentAlloy.outputType != null && itemToSmelt.itemID == currentAlloy.outputType.MeltedItemID)
{
this.addMetal(MetalRegistry.instance.getMetalFromItem(itemToSmelt), (short) 1);
currentAlloy.outputAmount++;
if(stackToSmelt.getItemDamage()+1 >= storage[0].getMaxDamage()) {
storage[0] = new ItemStack(TFCItems.CeramicMold,1,1);
} else {
stackToSmelt.setItemDamage(stackToSmelt.getItemDamage() + 1);
}
}
else
{
this.addMetal(MetalRegistry.instance.getMetalFromItem(itemToSmelt), (short) 1);
if(stackToSmelt.getItemDamage()+1 >= stackToSmelt.getMaxDamage()) {
storage[0] = new ItemStack(TFCItems.CeramicMold,1,1);
} else {
stackToSmelt.setItemDamage(stackToSmelt.getItemDamage() + 1);
}
}
inputTick = 0;
updateGui((byte) 0);
}
}
else if(itemToSmelt instanceof ISmeltable && ((ISmeltable)itemToSmelt).isSmeltable(stackToSmelt) && !TFC_Core.isOreIron(stackToSmelt)
&& temperature >= TFC_ItemHeat.getMeltingPoint(stackToSmelt))
{
Metal mType =((ISmeltable)itemToSmelt).GetMetalType(stackToSmelt);
if(addMetal(mType, ((ISmeltable)itemToSmelt).GetMetalReturnAmount(stackToSmelt)))
{
temperature *= 0.9f;
if(stackToSmelt.stackSize <= 1) {
storage[0] = null;
}
updateGui((byte) 0);
}
}
}
//Metal Output handling
if(currentAlloy != null && storage[1] != null && currentAlloy.outputType != null && outputTick >= 3 && temperature >= TFC_ItemHeat.getMeltingPoint(currentAlloy.outputType))
{
if(storage[1].itemID == TFCItems.CeramicMold.itemID)
{
storage[1] = new ItemStack(Item.itemsList[currentAlloy.outputType.MeltedItemID], 1, 99);
TFC_ItemHeat.SetTemperature(storage[1], temperature);
currentAlloy.outputAmount--;
updateGui((byte) 1);
}
else if(storage[1].itemID == currentAlloy.outputType.MeltedItemID && storage[1].getItemDamage() > 0)
{
storage[1].setItemDamage(storage[1].getItemDamage()-1);
float inTemp =TFC_ItemHeat.GetTemperature(storage[1]);
float temp = Math.abs(temperature - inTemp) / 2;
TFC_ItemHeat.SetTemperature(storage[1], inTemp+temp);
currentAlloy.outputAmount--;
storage[1].stackSize = 1;
updateGui((byte) 1);
}
outputTick = 0;
}
if(currentAlloy != null && currentAlloy.outputAmount <= 0) {
metals = new HashMap();
updateCurrentAlloy();
this.updateGui((byte) 2);
}
if(storage[1] != null && storage[1].stackSize <= 0) {
storage[1].stackSize = 1;
}
if(inputTick > 5) {
inputTick = 0;
}
if(outputTick >= 3) {
outputTick = 0;
}
}
}
| public void updateEntity()
{
if(!worldObj.isRemote)
{
inputTick++;
outputTick++;
tempTick++;
/*Heat the crucible based on the Forge beneath it*/
if(worldObj.getBlockId(xCoord,yCoord-1,zCoord) == TFCBlocks.Forge.blockID)
{
TileEntityForge te = (TileEntityForge) worldObj.getBlockTileEntity(xCoord, yCoord-1, zCoord);
if(te.fireTemperature > temperature) {
temperature++;
}
}
if(tempTick > 22)
{
tempTick = 0;
if(temperature > TFC_Climate.getHeightAdjustedTemp(xCoord, yCoord, zCoord)) {
temperature--;
}
}
ItemStack stackToSmelt = storage[0];
if(stackToSmelt != null)
{
Item itemToSmelt = stackToSmelt.getItem();
if(itemToSmelt instanceof ItemMeltedMetal && TFC_ItemHeat.getIsLiquid(storage[0]))
{
if(inputTick > 5)
{
if(currentAlloy != null && currentAlloy.outputType != null && itemToSmelt.itemID == currentAlloy.outputType.MeltedItemID)
{
this.addMetal(MetalRegistry.instance.getMetalFromItem(itemToSmelt), (short) 1);
if(stackToSmelt.getItemDamage()+1 >= storage[0].getMaxDamage()) {
storage[0] = new ItemStack(TFCItems.CeramicMold,1,1);
} else {
stackToSmelt.setItemDamage(stackToSmelt.getItemDamage() + 1);
}
}
else
{
this.addMetal(MetalRegistry.instance.getMetalFromItem(itemToSmelt), (short) 1);
if(stackToSmelt.getItemDamage()+1 >= stackToSmelt.getMaxDamage()) {
storage[0] = new ItemStack(TFCItems.CeramicMold,1,1);
} else {
stackToSmelt.setItemDamage(stackToSmelt.getItemDamage() + 1);
}
}
inputTick = 0;
updateGui((byte) 0);
}
}
else if(itemToSmelt instanceof ISmeltable && ((ISmeltable)itemToSmelt).isSmeltable(stackToSmelt) && !TFC_Core.isOreIron(stackToSmelt)
&& temperature >= TFC_ItemHeat.getMeltingPoint(stackToSmelt))
{
Metal mType =((ISmeltable)itemToSmelt).GetMetalType(stackToSmelt);
if(addMetal(mType, ((ISmeltable)itemToSmelt).GetMetalReturnAmount(stackToSmelt)))
{
temperature *= 0.9f;
if(stackToSmelt.stackSize <= 1) {
storage[0] = null;
}
updateGui((byte) 0);
}
}
}
//Metal Output handling
if(currentAlloy != null && storage[1] != null && currentAlloy.outputType != null && outputTick >= 3 && temperature >= TFC_ItemHeat.getMeltingPoint(currentAlloy.outputType))
{
if(storage[1].itemID == TFCItems.CeramicMold.itemID)
{
storage[1] = new ItemStack(Item.itemsList[currentAlloy.outputType.MeltedItemID], 1, 99);
TFC_ItemHeat.SetTemperature(storage[1], temperature);
currentAlloy.outputAmount--;
updateGui((byte) 1);
}
else if(storage[1].itemID == currentAlloy.outputType.MeltedItemID && storage[1].getItemDamage() > 0)
{
storage[1].setItemDamage(storage[1].getItemDamage()-1);
float inTemp =TFC_ItemHeat.GetTemperature(storage[1]);
float temp = Math.abs(temperature - inTemp) / 2;
TFC_ItemHeat.SetTemperature(storage[1], inTemp+temp);
currentAlloy.outputAmount--;
storage[1].stackSize = 1;
updateGui((byte) 1);
}
outputTick = 0;
}
if(currentAlloy != null && currentAlloy.outputAmount <= 0) {
metals = new HashMap();
updateCurrentAlloy();
this.updateGui((byte) 2);
currentAlloy = null;
}
if(storage[1] != null && storage[1].stackSize <= 0) {
storage[1].stackSize = 1;
}
if(inputTick > 5) {
inputTick = 0;
}
if(outputTick >= 3) {
outputTick = 0;
}
}
}
|
diff --git a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/FlexoMainPane.java b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/FlexoMainPane.java
index ae2ec8246..a28e38893 100644
--- a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/FlexoMainPane.java
+++ b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/FlexoMainPane.java
@@ -1,635 +1,636 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenFlexo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.RadialGradientPaint;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ChangeListener;
import org.openflexo.AdvancedPrefs;
import org.openflexo.ch.FCH;
import org.openflexo.swing.TabbedPane;
import org.openflexo.swing.TabbedPane.TabHeaderRenderer;
import org.openflexo.swing.layout.JXMultiSplitPane;
import org.openflexo.swing.layout.JXMultiSplitPane.DividerPainter;
import org.openflexo.swing.layout.MultiSplitLayout;
import org.openflexo.swing.layout.MultiSplitLayout.Divider;
import org.openflexo.swing.layout.MultiSplitLayout.Leaf;
import org.openflexo.swing.layout.MultiSplitLayout.Node;
import org.openflexo.swing.layout.MultiSplitLayout.Split;
import org.openflexo.toolbox.PropertyChangeListenerRegistrationManager;
import org.openflexo.view.controller.FlexoController;
import org.openflexo.view.controller.model.ControllerModel;
import org.openflexo.view.controller.model.FlexoPerspective;
/**
* Abstract view managing global layout of a FlexoModule
*
* @author sguerin
*/
public class FlexoMainPane extends JPanel implements PropertyChangeListener {
protected static final Logger logger = Logger.getLogger(FlexoMainPane.class.getPackage().getName());
public static enum LayoutPosition {
TOP_LEFT, MIDDLE_LEFT, BOTTOM_LEFT, TOP_CENTER, MIDDLE_CENTER, BOTTOM_CENTER, TOP_RIGHT, MIDDLE_RIGHT, BOTTOM_RIGHT;
}
public static enum LayoutColumns {
LEFT, CENTER, RIGHT;
}
private class EmptyPanel extends JPanel {
@Override
protected final void addImpl(Component comp, Object constraints, int index) {
}
}
private FlexoController controller;
private FlexoPerspective perspective;
private ModuleView<?> moduleView;
private MainPaneTopBar topBar;
private JXMultiSplitPane centerPanel;
private JComponent moduleViewContainerPanel;
private JComponent footer;
private MultiSplitLayout centerLayout;
private PropertyChangeListenerRegistrationManager registrationManager;
private TabbedPane<ModuleView<?>> tabbedPane;
private static final int KNOB_SIZE = 5;
private static final int KNOB_SPACE = 2;
private static final int DIVIDER_SIZE = KNOB_SIZE + 2 * KNOB_SPACE;
private static final int DIVIDER_KNOB_SIZE = 3 * KNOB_SIZE + 2 * KNOB_SPACE;
private static final Paint KNOB_PAINTER = new RadialGradientPaint(new Point((KNOB_SIZE - 1) / 2, (KNOB_SIZE - 1) / 2),
(KNOB_SIZE - 1) / 2, new float[] { 0.0f, 1.0f }, new Color[] { Color.GRAY, Color.LIGHT_GRAY });
public FlexoMainPane(FlexoController controller) {
super(new BorderLayout());
this.controller = controller;
this.centerLayout = new MultiSplitLayout(false);
this.centerLayout.setLayoutMode(MultiSplitLayout.NO_MIN_SIZE_LAYOUT);
registrationManager = new PropertyChangeListenerRegistrationManager();
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.CURRENT_OBJECT, this, controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.CURRENT_PERPSECTIVE, this,
controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.LEFT_VIEW_VISIBLE, this, controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.RIGHT_VIEW_VISIBLE, this,
controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(FlexoController.MODULE_VIEWS, this, controller);
perspective = controller.getCurrentPerspective();
tabbedPane = new TabbedPane<ModuleView<?>>(new TabHeaderRenderer<ModuleView<?>>() {
@Override
public Icon getTabHeaderIcon(ModuleView<?> tab) {
return FlexoController.iconForObject(tab.getRepresentedObject());
}
@Override
public String getTabHeaderTitle(ModuleView<?> tab) {
return FlexoMainPane.this.controller.getWindowTitleforObject(tab.getRepresentedObject());
}
@Override
public String getTabHeaderTooltip(ModuleView<?> tab) {
return null;
}
@Override
public boolean isTabHeaderVisible(ModuleView<?> tab) {
return !(tab instanceof org.openflexo.view.EmptyPanel<?>)
&& (AdvancedPrefs.getShowAllTabs() || tab.getRepresentedObject() != null
+ && tab.getRepresentedObject().getProject() != null
&& tab.getRepresentedObject().getProject()
.equals(FlexoMainPane.this.controller.getControllerModel().getCurrentProject()));
}
});
tabbedPane.setUseTabBody(false);
tabbedPane.addToTabListeners(new TabbedPane.TabListener<ModuleView<?>>() {
@Override
public void tabSelected(ModuleView<?> tab) {
if (tab != null) {
FlexoMainPane.this.controller.getControllerModel().setCurrentObjectAndPerspective(tab.getRepresentedObject(),
tab.getPerspective());
} else {
FlexoMainPane.this.controller.getControllerModel().setCurrentObject(null);
}
setModuleView(tab);
}
@Override
public void tabClosed(ModuleView<?> tab) {
tab.deleteModuleView();
FlexoMainPane.this.controller.setCurrentEditedObjectAsModuleView(null);
}
});
add(topBar = new MainPaneTopBar(controller), BorderLayout.NORTH);
add(centerPanel = new JXMultiSplitPane(centerLayout));
centerPanel.setDividerSize(DIVIDER_SIZE);
centerPanel.setDividerPainter(new DividerPainter() {
@Override
protected void doPaint(Graphics2D g, Divider divider, int width, int height) {
if (!divider.isVisible()) {
return;
}
if (divider.isVertical()) {
int x = (width - KNOB_SIZE) / 2;
int y = (height - DIVIDER_KNOB_SIZE) / 2;
for (int i = 0; i < 3; i++) {
Graphics2D graph = (Graphics2D) g.create(x, y + i * (KNOB_SIZE + KNOB_SPACE), KNOB_SIZE + 1, KNOB_SIZE + 1);
graph.setPaint(KNOB_PAINTER);
graph.fillOval(0, 0, KNOB_SIZE, KNOB_SIZE);
}
} else {
int x = (width - DIVIDER_KNOB_SIZE) / 2;
int y = (height - KNOB_SIZE) / 2;
for (int i = 0; i < 3; i++) {
Graphics2D graph = (Graphics2D) g.create(x + i * (KNOB_SIZE + KNOB_SPACE), y, KNOB_SIZE + 1, KNOB_SIZE + 1);
graph.setPaint(KNOB_PAINTER);
graph.fillOval(0, 0, KNOB_SIZE, KNOB_SIZE);
}
}
}
});
moduleViewContainerPanel = new JPanel();
moduleViewContainerPanel.setBorder(BorderFactory.createEmptyBorder(centerPanel.getDividerSize(), 0, 0, 0));
moduleViewContainerPanel.setLayout(new BorderLayout());
moduleViewContainerPanel.add(tabbedPane.getTabHeaders(), BorderLayout.NORTH);
}
public FlexoController getController() {
return controller;
}
public void dispose() {
saveLayout();
registrationManager.delete();
}
public void resetModuleView() {
setModuleView(null);
}
private void setModuleView(ModuleView<?> moduleView) {
if (this.moduleView == moduleView) {
return;
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("setModuleView() with " + moduleView + " perspective " + moduleView.getPerspective());
}
try {
if (this.moduleView != null) {
this.moduleView.willHide();
}
} catch (RuntimeException e) {
e.printStackTrace();
if (logger.isLoggable(Level.SEVERE)) {
logger.severe("willHide call failed on " + moduleView);
}
}
if (this.moduleView != null && this.moduleView instanceof SelectionSynchronizedModuleView) {
controller.getSelectionManager().removeFromSelectionListeners(
((SelectionSynchronizedModuleView<?>) this.moduleView).getSelectionListeners());
}
this.moduleView = moduleView;
if (moduleView != null && moduleView instanceof SelectionSynchronizedModuleView) {
controller.getSelectionManager().addToSelectionListeners(
((SelectionSynchronizedModuleView<?>) moduleView).getSelectionListeners());
}
JComponent newCenterView = null;
if (moduleView != null) {
if (moduleView.isAutoscrolled()) {
newCenterView = (JComponent) moduleView;
} else {
JScrollPane scrollPane = new JScrollPane((JComponent) moduleView, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
if (scrollPane.getVerticalScrollBar() != null) {
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
scrollPane.getVerticalScrollBar().setBlockIncrement(50);
}
if (scrollPane.getHorizontalScrollBar() != null) {
scrollPane.getHorizontalScrollBar().setUnitIncrement(10);
scrollPane.getHorizontalScrollBar().setBlockIncrement(50);
}
scrollPane.getHorizontalScrollBar().setFocusable(false);
scrollPane.getVerticalScrollBar().setFocusable(false);
if (moduleView instanceof ChangeListener) {
scrollPane.getViewport().addChangeListener((ChangeListener) moduleView);
}
newCenterView = scrollPane;
}
try {
moduleView.willShow();
} catch (RuntimeException e) {
e.printStackTrace();
if (logger.isLoggable(Level.SEVERE)) {
logger.severe("willShow call failed on " + moduleView);
}
}
FCH.setHelpItem((JComponent) moduleView, FCH.getModuleViewItemFor(controller.getModule(), moduleView));
newCenterView.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.LIGHT_GRAY));
} else {
newCenterView = new JPanel();
}
updateLayoutForPerspective();
Component centerComponent = ((BorderLayout) moduleViewContainerPanel.getLayout()).getLayoutComponent(BorderLayout.CENTER);
if (centerComponent != null) {
moduleViewContainerPanel.remove(centerComponent);
}
moduleViewContainerPanel.add(newCenterView);
moduleViewContainerPanel.revalidate();
moduleViewContainerPanel.repaint();
updateComponent(moduleViewContainerPanel, LayoutPosition.MIDDLE_CENTER);
centerPanel.revalidate();
revalidate();
repaint();
controller.getFlexoFrame().updateTitle();
if (moduleView != null) {
controller.getCurrentPerspective().notifyModuleViewDisplayed(moduleView);
}
if (controller.getFlexoFrame().isValid()) {
FCH.validateWindow(controller.getFlexoFrame());
}
}
private boolean updateBottomCenterView() {
JComponent newBottomCenterView = perspective.getBottomCenterView();
updateComponent(newBottomCenterView, LayoutPosition.BOTTOM_CENTER);
return newBottomCenterView != null;
}
private boolean updateBottomRightView() {
JComponent newBottomRightView = perspective.getBottomRightView();
updateComponent(newBottomRightView, LayoutPosition.BOTTOM_RIGHT);
return newBottomRightView != null;
}
private boolean updateBottomLeftView() {
JComponent newBottomLeftView = perspective.getBottomLeftView();
updateComponent(newBottomLeftView, LayoutPosition.BOTTOM_LEFT);
return newBottomLeftView != null;
}
private boolean updateMiddleRightView() {
JComponent newMiddleRightView = perspective.getMiddleRightView();
updateComponent(newMiddleRightView, LayoutPosition.MIDDLE_RIGHT);
return newMiddleRightView != null;
}
private boolean updateMiddleLeftView() {
JComponent newMiddleLeftView = perspective.getMiddleLeftView();
updateComponent(newMiddleLeftView, LayoutPosition.MIDDLE_LEFT);
return newMiddleLeftView != null;
}
private boolean updateTopCenterView() {
JComponent newTopCenterView = perspective.getTopCenterView();
updateComponent(newTopCenterView, LayoutPosition.TOP_CENTER);
return newTopCenterView != null;
}
private boolean updateTopRightView() {
JComponent newTopRightView = perspective.getTopRightView();
updateComponent(newTopRightView, LayoutPosition.TOP_RIGHT);
return newTopRightView != null;
}
private boolean updateTopLeftView() {
JComponent newTopLeftView = perspective.getTopLeftView();
updateComponent(newTopLeftView, LayoutPosition.TOP_LEFT);
return newTopLeftView != null;
}
private void updateFooter() {
if (footer != controller.getCurrentPerspective().getFooter()) {
if (footer != null) {
remove(footer);
}
if (controller.getCurrentPerspective().getFooter() != null) {
add(controller.getCurrentPerspective().getFooter(), BorderLayout.SOUTH);
}
footer = controller.getCurrentPerspective().getFooter();
}
}
private void updateHeader() {
if (moduleView != null) {
topBar.setHeader(controller.getCurrentPerspective().getHeader());
} else {
topBar.setHeader(null);
}
}
private void updateComponent(JComponent next, LayoutPosition position) {
JComponent previous = getComponentForPosition(position);
JComponent toAdd = next != null ? next : new EmptyPanel();
if (previous != toAdd) {
if (previous != null) {
centerPanel.remove(previous);
}
toAdd.setPreferredSize(new Dimension(0, 0));
centerPanel.add(toAdd, position.name());
centerLayout.displayNode(position.name(), next != null);
Node node = centerLayout.getNodeForName(position.name());
Split parent = node.getParent();
if (parent != centerLayout.getNodeForName(LayoutColumns.CENTER.name())) {
fixWeightForNodeChildren(parent);
}
centerPanel.revalidate();
}
}
protected void fixWeightForNodeChildren(Split split) {
int visibleChildren = 0;
// double weight = 0.0;
for (Node child : split.getChildren()) {
if (!(child instanceof Divider) && child.isVisible()) {
visibleChildren++;
// weight+=child.getWeight();
}
}
for (Node child : split.getChildren()) {
if (!(child instanceof Divider) && child.isVisible()) {
child.setWeight(1.0 / visibleChildren);
}
}
}
private void saveLayout() {
if (perspective != null) {
getController().getControllerModel().setLayoutForPerspective(perspective, centerLayout.getModel());
}
}
private void restoreLayout() {
if (perspective == null) {
return;
}
Node layoutModel = getController().getControllerModel().getLayoutForPerspective(perspective);
if (layoutModel == null) {
layoutModel = getDefaultLayout();
perspective.setupDefaultLayout(layoutModel);
}
centerLayout.setModel(layoutModel);
centerPanel.revalidate();
}
private Split getDefaultLayout() {
Split root = new Split();
root.setName("ROOT");
Split left = getVerticalSplit(LayoutPosition.TOP_LEFT, LayoutPosition.MIDDLE_LEFT, LayoutPosition.BOTTOM_LEFT);
left.setWeight(0.2);
left.setName(LayoutColumns.LEFT.name());
Split center = getVerticalSplit(LayoutPosition.TOP_CENTER, LayoutPosition.MIDDLE_CENTER, LayoutPosition.BOTTOM_CENTER);
center.setWeight(0.6);
center.setName(LayoutColumns.CENTER.name());
Split right = getVerticalSplit(LayoutPosition.TOP_RIGHT, LayoutPosition.MIDDLE_RIGHT, LayoutPosition.BOTTOM_RIGHT);
right.setWeight(0.2);
right.setName(LayoutColumns.RIGHT.name());
root.setChildren(left, new Divider(), center, new Divider(), right);
return root;
}
private Split getVerticalSplit(LayoutPosition position1, LayoutPosition position2, LayoutPosition position3) {
Split split = new Split();
split.setRowLayout(false);
Leaf l1 = new Leaf(position1.name());
l1.setWeight(0.2);
Leaf l2 = new Leaf(position2.name());
l2.setWeight(0.6);
Leaf l3 = new Leaf(position3.name());
l3.setWeight(0.2);
split.setChildren(l1, new Divider(), l2, new Divider(), l3);
return split;
}
private Node getNodeForName(Node root, String name) {
if (root instanceof Split) {
Split split = (Split) root;
if (name.equals(split.getName())) {
return split;
}
for (Node child : split.getChildren()) {
Node n = getNodeForName(child, name);
if (n != null) {
return n;
}
}
} else if (root instanceof Leaf) {
Leaf leaf = (Leaf) root;
if (name.equals(leaf.getName())) {
return leaf;
}
}
return null;
}
private JComponent getComponentForPosition(LayoutPosition position) {
Node node = centerLayout.getNodeForName(position.name());
if (node != null) {
return (JComponent) centerLayout.getComponentForNode(node);
} else {
return null;
}
}
public ModuleView<?> getModuleView() {
return moduleView;
}
public void showControlPanel() {
topBar.setVisible(true);
}
public void hideControlPanel() {
topBar.setVisible(false);
}
private void updateLeftViewVisibility() {
Node left = getNodeForName(centerLayout.getModel(), LayoutColumns.LEFT.name());
updateVisibility(left, controller.getControllerModel().isLeftViewVisible());
centerPanel.revalidate();
}
private void updateRightViewVisibility() {
Node right = getNodeForName(centerLayout.getModel(), LayoutColumns.RIGHT.name());
updateVisibility(right, controller.getControllerModel().isRightViewVisible());
centerPanel.revalidate();
}
private void updateVisibility(Node root, boolean visible) {
if (root instanceof Leaf) {
Component componentForNode = centerLayout.getComponentForNode(root);
if (componentForNode instanceof EmptyPanel) {
// EmptyPanel means that there is nothing to display/hide here
} else {
centerLayout.displayNode(((Leaf) root).getName(), visible);
}
} else if (root instanceof Split) {
Split split = (Split) root;
centerLayout.displayNode(split.getName(), visible);
for (Node child : split.getChildren()) {
updateVisibility(child, visible);
}
fixWeightForNodeChildren(split);
}
centerPanel.revalidate();
centerPanel.repaint();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() == controller.getControllerModel()) {
if (evt.getPropertyName().equals(ControllerModel.CURRENT_PERPSECTIVE)) {
FlexoPerspective previous = (FlexoPerspective) evt.getOldValue();
FlexoPerspective next = (FlexoPerspective) evt.getNewValue();
saveLayout();
perspective = next;
ModuleView<?> moduleView = controller.moduleViewForObject(controller.getCurrentDisplayedObjectAsModuleView());
if (moduleView != null) {
tabbedPane.selectTab(moduleView);
}
updatePropertyChangeListener(previous, next);
updateLayoutForPerspective();
} else if (evt.getPropertyName().equals(ControllerModel.LEFT_VIEW_VISIBLE)) {
updateLeftViewVisibility();
} else if (evt.getPropertyName().equals(ControllerModel.RIGHT_VIEW_VISIBLE)) {
updateRightViewVisibility();
} else if (evt.getPropertyName().equals(ControllerModel.CURRENT_OBJECT)) {
if (controller.getControllerModel().getCurrentObject() != null) {
ModuleView<?> moduleView = controller.moduleViewForObject(controller.getControllerModel().getCurrentObject());
if (moduleView != null) {
tabbedPane.selectTab(moduleView);
}
}
}
} else if (evt.getSource() == controller.getCurrentPerspective()) {
if (evt.getPropertyName().equals(FlexoPerspective.HEADER)) {
updateHeader();
} else if (evt.getPropertyName().equals(FlexoPerspective.FOOTER)) {
updateFooter();
} else if (evt.getPropertyName().equals(FlexoPerspective.TOP_LEFT_VIEW)) {
updateTopLeftView();
} else if (evt.getPropertyName().equals(FlexoPerspective.TOP_RIGHT_VIEW)) {
updateTopRightView();
} else if (evt.getPropertyName().equals(FlexoPerspective.TOP_CENTER_VIEW)) {
updateTopCenterView();
} else if (evt.getPropertyName().equals(FlexoPerspective.MIDDLE_LEFT_VIEW)) {
updateMiddleLeftView();
} else if (evt.getPropertyName().equals(FlexoPerspective.MIDDLE_RIGHT_VIEW)) {
updateMiddleRightView();
} else if (evt.getPropertyName().equals(FlexoPerspective.BOTTOM_LEFT_VIEW)) {
updateBottomLeftView();
} else if (evt.getPropertyName().equals(FlexoPerspective.BOTTOM_RIGHT_VIEW)) {
updateBottomRightView();
} else if (evt.getPropertyName().equals(FlexoPerspective.BOTTOM_CENTER_VIEW)) {
updateBottomCenterView();
}
} else if (evt.getSource() == controller) {
if (evt.getPropertyName().equals(FlexoController.MODULE_VIEWS)) {
if (evt.getNewValue() != null) {
tabbedPane.addTab((ModuleView<?>) evt.getNewValue());
} else if (evt.getOldValue() != null) {
tabbedPane.removeTab((ModuleView<?>) evt.getOldValue());
}
}
}
}
private void updateLayoutForPerspective() {
if (perspective == null) {
return;
}
restoreLayout();
boolean hasLeftView = false;
boolean hasRightView = false;
hasLeftView |= updateTopLeftView();
hasRightView |= updateTopRightView();
updateTopCenterView();
hasLeftView |= updateMiddleLeftView();
hasRightView |= updateMiddleRightView();
hasLeftView |= updateBottomLeftView();
hasRightView |= updateBottomRightView();
updateBottomCenterView();
updateHeader();
updateFooter();
updateLeftViewVisibility();
updateRightViewVisibility();
topBar.setLeftViewToggle(hasLeftView);
topBar.setRightViewToggle(hasRightView);
}
private void updatePropertyChangeListener(FlexoPerspective previous, FlexoPerspective next) {
if (previous != null) {
for (String property : FlexoPerspective.PROPERTIES) {
registrationManager.removeListener(property, this, next);
}
}
if (next != null) {
for (String property : FlexoPerspective.PROPERTIES) {
registrationManager.new PropertyChangeListenerRegistration(property, this, next);
}
}
}
}
| true | true | public FlexoMainPane(FlexoController controller) {
super(new BorderLayout());
this.controller = controller;
this.centerLayout = new MultiSplitLayout(false);
this.centerLayout.setLayoutMode(MultiSplitLayout.NO_MIN_SIZE_LAYOUT);
registrationManager = new PropertyChangeListenerRegistrationManager();
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.CURRENT_OBJECT, this, controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.CURRENT_PERPSECTIVE, this,
controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.LEFT_VIEW_VISIBLE, this, controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.RIGHT_VIEW_VISIBLE, this,
controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(FlexoController.MODULE_VIEWS, this, controller);
perspective = controller.getCurrentPerspective();
tabbedPane = new TabbedPane<ModuleView<?>>(new TabHeaderRenderer<ModuleView<?>>() {
@Override
public Icon getTabHeaderIcon(ModuleView<?> tab) {
return FlexoController.iconForObject(tab.getRepresentedObject());
}
@Override
public String getTabHeaderTitle(ModuleView<?> tab) {
return FlexoMainPane.this.controller.getWindowTitleforObject(tab.getRepresentedObject());
}
@Override
public String getTabHeaderTooltip(ModuleView<?> tab) {
return null;
}
@Override
public boolean isTabHeaderVisible(ModuleView<?> tab) {
return !(tab instanceof org.openflexo.view.EmptyPanel<?>)
&& (AdvancedPrefs.getShowAllTabs() || tab.getRepresentedObject() != null
&& tab.getRepresentedObject().getProject()
.equals(FlexoMainPane.this.controller.getControllerModel().getCurrentProject()));
}
});
tabbedPane.setUseTabBody(false);
tabbedPane.addToTabListeners(new TabbedPane.TabListener<ModuleView<?>>() {
@Override
public void tabSelected(ModuleView<?> tab) {
if (tab != null) {
FlexoMainPane.this.controller.getControllerModel().setCurrentObjectAndPerspective(tab.getRepresentedObject(),
tab.getPerspective());
} else {
FlexoMainPane.this.controller.getControllerModel().setCurrentObject(null);
}
setModuleView(tab);
}
@Override
public void tabClosed(ModuleView<?> tab) {
tab.deleteModuleView();
FlexoMainPane.this.controller.setCurrentEditedObjectAsModuleView(null);
}
});
add(topBar = new MainPaneTopBar(controller), BorderLayout.NORTH);
add(centerPanel = new JXMultiSplitPane(centerLayout));
centerPanel.setDividerSize(DIVIDER_SIZE);
centerPanel.setDividerPainter(new DividerPainter() {
@Override
protected void doPaint(Graphics2D g, Divider divider, int width, int height) {
if (!divider.isVisible()) {
return;
}
if (divider.isVertical()) {
int x = (width - KNOB_SIZE) / 2;
int y = (height - DIVIDER_KNOB_SIZE) / 2;
for (int i = 0; i < 3; i++) {
Graphics2D graph = (Graphics2D) g.create(x, y + i * (KNOB_SIZE + KNOB_SPACE), KNOB_SIZE + 1, KNOB_SIZE + 1);
graph.setPaint(KNOB_PAINTER);
graph.fillOval(0, 0, KNOB_SIZE, KNOB_SIZE);
}
} else {
int x = (width - DIVIDER_KNOB_SIZE) / 2;
int y = (height - KNOB_SIZE) / 2;
for (int i = 0; i < 3; i++) {
Graphics2D graph = (Graphics2D) g.create(x + i * (KNOB_SIZE + KNOB_SPACE), y, KNOB_SIZE + 1, KNOB_SIZE + 1);
graph.setPaint(KNOB_PAINTER);
graph.fillOval(0, 0, KNOB_SIZE, KNOB_SIZE);
}
}
}
});
moduleViewContainerPanel = new JPanel();
moduleViewContainerPanel.setBorder(BorderFactory.createEmptyBorder(centerPanel.getDividerSize(), 0, 0, 0));
moduleViewContainerPanel.setLayout(new BorderLayout());
moduleViewContainerPanel.add(tabbedPane.getTabHeaders(), BorderLayout.NORTH);
}
| public FlexoMainPane(FlexoController controller) {
super(new BorderLayout());
this.controller = controller;
this.centerLayout = new MultiSplitLayout(false);
this.centerLayout.setLayoutMode(MultiSplitLayout.NO_MIN_SIZE_LAYOUT);
registrationManager = new PropertyChangeListenerRegistrationManager();
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.CURRENT_OBJECT, this, controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.CURRENT_PERPSECTIVE, this,
controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.LEFT_VIEW_VISIBLE, this, controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(ControllerModel.RIGHT_VIEW_VISIBLE, this,
controller.getControllerModel());
registrationManager.new PropertyChangeListenerRegistration(FlexoController.MODULE_VIEWS, this, controller);
perspective = controller.getCurrentPerspective();
tabbedPane = new TabbedPane<ModuleView<?>>(new TabHeaderRenderer<ModuleView<?>>() {
@Override
public Icon getTabHeaderIcon(ModuleView<?> tab) {
return FlexoController.iconForObject(tab.getRepresentedObject());
}
@Override
public String getTabHeaderTitle(ModuleView<?> tab) {
return FlexoMainPane.this.controller.getWindowTitleforObject(tab.getRepresentedObject());
}
@Override
public String getTabHeaderTooltip(ModuleView<?> tab) {
return null;
}
@Override
public boolean isTabHeaderVisible(ModuleView<?> tab) {
return !(tab instanceof org.openflexo.view.EmptyPanel<?>)
&& (AdvancedPrefs.getShowAllTabs() || tab.getRepresentedObject() != null
&& tab.getRepresentedObject().getProject() != null
&& tab.getRepresentedObject().getProject()
.equals(FlexoMainPane.this.controller.getControllerModel().getCurrentProject()));
}
});
tabbedPane.setUseTabBody(false);
tabbedPane.addToTabListeners(new TabbedPane.TabListener<ModuleView<?>>() {
@Override
public void tabSelected(ModuleView<?> tab) {
if (tab != null) {
FlexoMainPane.this.controller.getControllerModel().setCurrentObjectAndPerspective(tab.getRepresentedObject(),
tab.getPerspective());
} else {
FlexoMainPane.this.controller.getControllerModel().setCurrentObject(null);
}
setModuleView(tab);
}
@Override
public void tabClosed(ModuleView<?> tab) {
tab.deleteModuleView();
FlexoMainPane.this.controller.setCurrentEditedObjectAsModuleView(null);
}
});
add(topBar = new MainPaneTopBar(controller), BorderLayout.NORTH);
add(centerPanel = new JXMultiSplitPane(centerLayout));
centerPanel.setDividerSize(DIVIDER_SIZE);
centerPanel.setDividerPainter(new DividerPainter() {
@Override
protected void doPaint(Graphics2D g, Divider divider, int width, int height) {
if (!divider.isVisible()) {
return;
}
if (divider.isVertical()) {
int x = (width - KNOB_SIZE) / 2;
int y = (height - DIVIDER_KNOB_SIZE) / 2;
for (int i = 0; i < 3; i++) {
Graphics2D graph = (Graphics2D) g.create(x, y + i * (KNOB_SIZE + KNOB_SPACE), KNOB_SIZE + 1, KNOB_SIZE + 1);
graph.setPaint(KNOB_PAINTER);
graph.fillOval(0, 0, KNOB_SIZE, KNOB_SIZE);
}
} else {
int x = (width - DIVIDER_KNOB_SIZE) / 2;
int y = (height - KNOB_SIZE) / 2;
for (int i = 0; i < 3; i++) {
Graphics2D graph = (Graphics2D) g.create(x + i * (KNOB_SIZE + KNOB_SPACE), y, KNOB_SIZE + 1, KNOB_SIZE + 1);
graph.setPaint(KNOB_PAINTER);
graph.fillOval(0, 0, KNOB_SIZE, KNOB_SIZE);
}
}
}
});
moduleViewContainerPanel = new JPanel();
moduleViewContainerPanel.setBorder(BorderFactory.createEmptyBorder(centerPanel.getDividerSize(), 0, 0, 0));
moduleViewContainerPanel.setLayout(new BorderLayout());
moduleViewContainerPanel.add(tabbedPane.getTabHeaders(), BorderLayout.NORTH);
}
|
diff --git a/src/main/java/org/spoutcraft/launcher/gui/LoginForm.java b/src/main/java/org/spoutcraft/launcher/gui/LoginForm.java
index 55b95e9..017b77a 100644
--- a/src/main/java/org/spoutcraft/launcher/gui/LoginForm.java
+++ b/src/main/java/org/spoutcraft/launcher/gui/LoginForm.java
@@ -1,764 +1,764 @@
/*
* This file is part of Spoutcraft Launcher (http://wiki.getspout.org/).
*
* Spoutcraft Launcher is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Spoutcraft Launcher is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.spoutcraft.launcher.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import org.spoutcraft.launcher.*;
import org.spoutcraft.launcher.async.DownloadListener;
import org.spoutcraft.launcher.exception.*;
public class LoginForm extends JFrame implements ActionListener, DownloadListener, KeyListener, WindowListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPasswordField passwordField;
private JComboBox usernameField = new JComboBox();
private JButton loginButton = new JButton("Login");
JButton optionsButton = new JButton("Options");
private JCheckBox rememberCheckbox = new JCheckBox("Remember");
private JButton loginSkin1;
private List<JButton> loginSkin1Image;
private JButton loginSkin2;
private List<JButton> loginSkin2Image;
private TumblerFeedParsingWorker tumblerFeed;
public final JProgressBar progressBar;
HashMap<String, UserPasswordInformation> usernames = new HashMap<String, UserPasswordInformation>();
public boolean mcUpdate = false;
public boolean spoutUpdate = false;
public static UpdateDialog updateDialog;
private static String pass = null;
public static String[] values = null;
private int success = LauncherFrame.ERROR_IN_LAUNCH;
public static final GameUpdater gameUpdater = new GameUpdater();
OptionDialog options = new OptionDialog();
Container loginPane = new Container();
Container offlinePane = new Container();
public LoginForm() {
LoginForm.updateDialog = new UpdateDialog(this);
gameUpdater.setListener(this);
this.addWindowListener(this);
SwingWorker<Object, Object> updateThread = new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
MinecraftYML.updateMinecraftYMLCache();
SpoutcraftYML.updateSpoutcraftYMLCache();
LibrariesYML.updateLibrariesYMLCache();
- SpecialYML.updateMinecraftYMLCache();
+ SpecialYML.updateSpecialYMLCache();
return null;
}
protected void done() {
options.updateBuildsList();
}
};
updateThread.execute();
options.setVisible(false);
loginButton.setFont(new Font("Arial", Font.PLAIN, 11));
loginButton.setBounds(272, 13, 86, 23);
loginButton.setOpaque(false);
loginButton.addActionListener(this);
loginButton.setEnabled(false); //disable until login info is read
optionsButton.setFont(new Font("Arial", Font.PLAIN, 11));
optionsButton.setOpaque(false);
optionsButton.addActionListener(this);
usernameField.setFont(new Font("Arial", Font.PLAIN, 11));
usernameField.addActionListener(this);
usernameField.setOpaque(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(LoginForm.class.getResource("/org/spoutcraft/launcher/favicon.png")));
setResizable(false);
setTitle("Spoutcraft Launcher");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((dim.width - 860) / 2, (dim.height - 500) / 2, 860, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JLabel lblLogo = new JLabel("");
lblLogo.setBounds(8, 0, 294, 99);
lblLogo.setIcon(new ImageIcon(LoginForm.class.getResource("/org/spoutcraft/launcher/spoutcraft.png")));
JLabel lblMinecraftUsername = new JLabel("Minecraft Username: ");
lblMinecraftUsername.setFont(new Font("Arial", Font.PLAIN, 11));
lblMinecraftUsername.setHorizontalAlignment(SwingConstants.RIGHT);
lblMinecraftUsername.setBounds(-17, 17, 150, 14);
JLabel lblPassword = new JLabel("Password: ");
lblPassword.setFont(new Font("Arial", Font.PLAIN, 11));
lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
lblPassword.setBounds(33, 42, 100, 20);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Arial", Font.PLAIN, 11));
passwordField.setBounds(143, 42, 119, 22);
loginSkin1 = new JButton("Login as Player");
loginSkin1.setFont(new Font("Arial", Font.PLAIN, 11));
loginSkin1.setBounds(72, 428, 119, 23);
loginSkin1.setOpaque(false);
loginSkin1.addActionListener(this);
loginSkin1.setVisible(false);
loginSkin1Image = new ArrayList<JButton>();
loginSkin2 = new JButton("Login as Player");
loginSkin2.setFont(new Font("Arial", Font.PLAIN, 11));
loginSkin2.setBounds(261, 428, 119, 23);
loginSkin2.setOpaque(false);
loginSkin2.addActionListener(this);
loginSkin2.setVisible(false);
loginSkin2Image = new ArrayList<JButton>();
progressBar = new JProgressBar();
progressBar.setBounds(30, 100, 400, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
JLabel purchaseAccount = new HyperlinkJLabel("<html><u>Need a minecraft account?</u></html>", "http://www.minecraft.net/register.jsp");
purchaseAccount.setHorizontalAlignment(SwingConstants.RIGHT);
purchaseAccount.setBounds(243, 70, 111, 14);
purchaseAccount.setText("<html><u>Need an account?</u></html>");
purchaseAccount.setFont(new Font("Arial", Font.PLAIN, 11));
purchaseAccount.setForeground(new Color(0, 0, 255));
usernameField.setBounds(143, 14, 119, 25);
rememberCheckbox.setFont(new Font("Arial", Font.PLAIN, 11));
rememberCheckbox.setOpaque(false);
final JTextPane editorPane = new JTextPane();
editorPane.setContentType("text/html");
tumblerFeed = new TumblerFeedParsingWorker(editorPane);
tumblerFeed.execute();
readUsedUsernames();
editorPane.setEditable(false);
editorPane.setOpaque(false);
JLabel trans2;
JScrollPane scrollPane = new JScrollPane(editorPane);
scrollPane.setBounds(473, 11, 372, 340);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
editorPane.setCaretPosition(0);
trans2 = new JLabel();
trans2.setBackground(new Color(229, 246, 255, 100));
trans2.setOpaque(true);
trans2.setBounds(473, 11, 372, 340);
JLabel login = new JLabel();
login.setBackground(new Color(255, 255, 255, 120));
login.setOpaque(true);
login.setBounds(473, 362, 372, 99);
JLabel trans;
trans = new JLabel();
trans.setBackground(new Color(229, 246, 255, 60));
trans.setOpaque(true);
trans.setBounds(0, 0, 854, 480);
usernameField.getEditor().addActionListener(this);
passwordField.addKeyListener(this);
rememberCheckbox.addKeyListener(this);
usernameField.setEditable(true);
contentPane.setLayout(null);
rememberCheckbox.setBounds(144, 66, 93, 23);
contentPane.add(lblLogo);
optionsButton.setBounds(272, 41, 86, 23);
contentPane.add(loginSkin1);
contentPane.add(loginSkin2);
loginPane.setBounds(473, 362, 372, 99);
loginPane.add(lblPassword);
loginPane.add(lblMinecraftUsername);
loginPane.add(passwordField);
loginPane.add(usernameField);
loginPane.add(loginButton);
loginPane.add(rememberCheckbox);
loginPane.add(purchaseAccount);
loginPane.add(optionsButton);
contentPane.add(loginPane);
JLabel offlineMessage = new JLabel("Could not connect to minecraft.net");
offlineMessage.setFont(new Font("Arial", Font.PLAIN, 14));
offlineMessage.setBounds(25, 40, 217, 17);
JButton tryAgain = new JButton("Try Again");
tryAgain.setOpaque(false);
tryAgain.setFont(new Font("Arial", Font.PLAIN, 12));
tryAgain.setBounds(257, 20, 100, 25);
JButton offlineMode = new JButton("Offline Mode");
offlineMode.setOpaque(false);
offlineMode.setFont(new Font("Arial", Font.PLAIN, 12));
offlineMode.setBounds(257, 52, 100, 25);
offlinePane.setBounds(473, 362, 372, 99);
offlinePane.add(tryAgain);
offlinePane.add(offlineMode);
offlinePane.add(offlineMessage);
offlinePane.setVisible(false);
contentPane.add(offlinePane);
contentPane.add(scrollPane);
contentPane.add(trans2);
contentPane.add(login);
contentPane.add(trans);
contentPane.add(progressBar);
final JLabel background = new JLabel("Loading...");
background.setVerticalAlignment(SwingConstants.CENTER);
background.setHorizontalAlignment(SwingConstants.CENTER);
background.setBounds(0, 0, 854, 480);
contentPane.add(background);
//TODO: remove this after next release
(new File(PlatformUtils.getWorkingDirectory(), "launcher_cache.jpg")).delete();
File cacheDir = new File(PlatformUtils.getWorkingDirectory(), "cache");
cacheDir.mkdir();
File backgroundImage = new File(cacheDir, "launcher_background.jpg");
(new BackgroundImageWorker(backgroundImage, background)).execute();
Vector<Component> order = new Vector<Component>(5);
order.add(usernameField.getEditor().getEditorComponent());
order.add(passwordField);
order.add(rememberCheckbox);
order.add(loginButton);
order.add(optionsButton);
setFocusTraversalPolicy(new SpoutFocusTraversalPolicy(order));
loginButton.setEnabled(true); //enable once logins are read
}
public void stateChanged(String fileName, float progress) {
int intProgress = Math.round(progress);
progressBar.setValue(intProgress);
if (fileName.length() > 60) {
fileName = fileName.substring(0, 60) + "...";
}
progressBar.setString(intProgress + "% " + fileName);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (loginButton.isEnabled() && e.getKeyCode() == KeyEvent.VK_ENTER) {
doLogin();
}
}
public void keyReleased(KeyEvent e) {
}
private void readUsedUsernames() {
int i = 0;
try {
File lastLogin = new File(PlatformUtils.getWorkingDirectory(), "lastlogin");
if (!lastLogin.exists())
return;
Cipher cipher = getCipher(2, "passwordfile");
DataInputStream dis;
if (cipher != null)
dis = new DataInputStream(new CipherInputStream(new FileInputStream(lastLogin), cipher));
else {
dis = new DataInputStream(new FileInputStream(lastLogin));
}
try {
// noinspection InfiniteLoopStatement
while (true) {
String user = dis.readUTF();
boolean isHash = dis.readBoolean();
if (isHash) {
byte[] hash = new byte[32];
dis.read(hash);
usernames.put(user, new UserPasswordInformation(hash));
} else {
String pass = dis.readUTF();
if (!pass.isEmpty()) {
i++;
if (i == 1) {
tumblerFeed.setUser(user);
loginSkin1.setText(user);
loginSkin1.setVisible(true);
ImageUtils.drawCharacter(contentPane, this, "http://s3.amazonaws.com/MinecraftSkins/" + user + ".png", 103, 170, loginSkin1Image);
} else if (i == 2) {
loginSkin2.setText(user);
loginSkin2.setVisible(true);
ImageUtils.drawCharacter(contentPane, this, "http://s3.amazonaws.com/MinecraftSkins/" + user + ".png", 293, 170, loginSkin2Image);
}
}
usernames.put(user, new UserPasswordInformation(pass));
}
this.usernameField.addItem(user);
if (SettingsUtil.isFastLogin()) {
if (!usernameField.getSelectedItem().toString().trim().isEmpty() && !passwordField.getPassword().toString().trim().isEmpty()) {
doLogin();
}
}
}
} catch (EOFException ignored) {
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
updatePasswordField();
}
private void writeUsernameList() {
try {
File lastLogin = new File(PlatformUtils.getWorkingDirectory(), "lastlogin");
Cipher cipher = getCipher(1, "passwordfile");
DataOutputStream dos;
if (cipher != null)
dos = new DataOutputStream(new CipherOutputStream(new FileOutputStream(lastLogin), cipher));
else {
dos = new DataOutputStream(new FileOutputStream(lastLogin, true));
}
for (String user : usernames.keySet()) {
dos.writeUTF(user);
UserPasswordInformation info = usernames.get(user);
dos.writeBoolean(info.isHash);
if (info.isHash) {
dos.write(info.passwordHash);
} else {
dos.writeUTF(info.password);
}
}
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent event) {
String eventId = event.getActionCommand();
if (event.getSource() == loginSkin1 || event.getSource() == loginSkin2) {
eventId = "Login";
this.usernameField.setSelectedItem(((JButton) event.getSource()).getText());
} else if(loginSkin1Image.contains(event.getSource())) {
eventId = "Login";
this.usernameField.setSelectedItem(loginSkin1.getText());
} else if(loginSkin2Image.contains(event.getSource())) {
eventId = "Login";
this.usernameField.setSelectedItem(loginSkin2.getText());
}
if ((eventId.equals("Login") || eventId.equals(usernameField.getSelectedItem())) && loginButton.isEnabled()) {
doLogin();
} else if (eventId.equals("Options")) {
options.setVisible(true);
options.setBounds((int) Math.max(1, getBounds().getCenterX() - (320/2)), (int) Math.max(1, getBounds().getCenterY() - (365/2)), 320, 365);
} else if (eventId.equals("comboBoxChanged")) {
updatePasswordField();
}
}
private void updatePasswordField() {
if (this.usernameField.getSelectedItem() != null){
UserPasswordInformation info = usernames.get(this.usernameField.getSelectedItem().toString());
if (info != null) {
if (info.isHash) {
this.passwordField.setText("");
this.rememberCheckbox.setSelected(false);
} else {
this.passwordField.setText(info.password);
this.rememberCheckbox.setSelected(true);
}
}
}
}
public void doLogin() {
doLogin(usernameField.getSelectedItem().toString(), new String(passwordField.getPassword()), false);
}
public void doLogin(final String user, final String pass) {
doLogin(user, pass, true);
}
public void doLogin(final String user, final String pass, final boolean cmdLine) {
if (user == null || pass == null) {
return;
}
this.loginButton.setEnabled(false);
this.optionsButton.setEnabled(false);
this.loginSkin1.setEnabled(false);
this.loginSkin2.setEnabled(false);
options.setVisible(false);
passwordField.setEnabled(false);
rememberCheckbox.setEnabled(false);
usernameField.setEnabled(false);
SwingWorker<Boolean, Boolean> loginThread = new SwingWorker<Boolean, Boolean>() {
protected Boolean doInBackground() throws Exception {
progressBar.setVisible(true);
progressBar.setString("Connecting to www.minecraft.net...");
try {
values = MinecraftUtils.doLogin(user, pass, progressBar);
return true;
} catch (BadLoginException e) {
JOptionPane.showMessageDialog(getParent(), "Incorrect usernameField/passwordField combination");
this.cancel(true);
progressBar.setVisible(false);
} catch (MinecraftUserNotPremiumException e){
JOptionPane.showMessageDialog(getParent(), "You purchase a minecraft account to play");
this.cancel(true);
progressBar.setVisible(false);
} catch (MCNetworkException e) {
UserPasswordInformation info = null;
for (String username : usernames.keySet()) {
if (username.equalsIgnoreCase(user)) {
info = usernames.get(username);
break;
}
}
boolean authFailed = (info == null);
if (!authFailed) {
if (info.isHash) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(pass.getBytes());
for (int i = 0; i < hash.length; i++) {
if (hash[i] != info.passwordHash[i]) {
authFailed = true;
break;
}
}
}
catch (NoSuchAlgorithmException ex) {
authFailed = true;
}
} else {
authFailed = !(pass.equals(info.password));
}
}
if (authFailed) {
JOptionPane.showMessageDialog(getParent(), "Unable to authenticate account with minecraft.net");
} else {
int result = JOptionPane.showConfirmDialog(getParent(), "Would you like to run in offline mode?", "Unable to Connect to Minecraft.net", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
values = new String[] { "0", "0", user, "0" };
return true;
}
}
this.cancel(true);
progressBar.setVisible(false);
} catch (OutdatedMCLauncherException e) {
JOptionPane.showMessageDialog(getParent(), "Incompatible Login Version.");
progressBar.setVisible(false);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
this.cancel(true);
progressBar.setVisible(false);
} catch (Exception e) {
e.printStackTrace();
}
loginButton.setEnabled(true);
optionsButton.setEnabled(true);
loginSkin1.setEnabled(true);
loginSkin2.setEnabled(true);
passwordField.setEnabled(true);
rememberCheckbox.setEnabled(true);
usernameField.setEnabled(true);
this.cancel(true);
return false;
}
protected void done() {
if (values == null || values.length < 4)
return;
LoginForm.pass = pass;
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
}
gameUpdater.user = values[2].trim();
gameUpdater.downloadTicket = values[1].trim();
if (cmdLine == false) {
String password = new String(passwordField.getPassword());
if (rememberCheckbox.isSelected()) {
usernames.put(gameUpdater.user, new UserPasswordInformation(password));
}
else {
if (digest == null) {
usernames.put(gameUpdater.user, new UserPasswordInformation(""));
}
else {
usernames.put(gameUpdater.user, new UserPasswordInformation(digest.digest(password.getBytes())));
}
}
writeUsernameList();
}
SwingWorker<Boolean, String> updateThread = new SwingWorker<Boolean, String>() {
protected Boolean doInBackground() throws Exception {
publish("Checking for Minecraft Update...\n");
try {
mcUpdate = gameUpdater.checkMCUpdate("Checking for Minecraft Update...\n");
} catch (Exception e) {
mcUpdate = false;
}
publish("Checking for Spoutcraft update...\n");
try {
spoutUpdate = mcUpdate || gameUpdater.isSpoutcraftUpdateAvailable("Checking for Spoutcraft update...\n");
} catch (Exception e) {
spoutUpdate = false;
}
return true;
}
protected void done() {
if (mcUpdate) {
updateDialog.setToUpdate("Minecraft");
} else if (spoutUpdate) {
updateDialog.setToUpdate("Spoutcraft");
}
if (mcUpdate || spoutUpdate) {
if (SettingsUtil.isAcceptUpdates()) {
updateThread();
}
else {
LoginForm.updateDialog.setVisible(true);
}
} else {
runGame();
}
this.cancel(true);
}
protected void process(List<String> chunks) {
progressBar.setString(chunks.get(0));
}
};
updateThread.execute();
this.cancel(true);
}
};
loginThread.execute();
}
public void updateThread() {
SwingWorker<Boolean, String> updateThread = new SwingWorker<Boolean, String>() {
boolean error = false;
protected void done() {
progressBar.setVisible(false);
if (!error){
runGame();
}
this.cancel(true);
}
protected Boolean doInBackground() throws Exception {
try {
if (mcUpdate) {
gameUpdater.updateMC();
}
if (spoutUpdate) {
gameUpdater.updateSpoutcraft();
}
}
catch (NoMirrorsAvailableException e) {
JOptionPane.showMessageDialog(getParent(), "No mirrors available to download from!\nTry again later.");
error = true;
loginButton.setEnabled(true);
optionsButton.setEnabled(true);
loginSkin1.setEnabled(true);
loginSkin2.setEnabled(true);
passwordField.setEnabled(true);
rememberCheckbox.setEnabled(true);
usernameField.setEnabled(true);
this.cancel(true);
return false;
}
catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(getParent(), "Download Interrupted!");
error = true;
loginButton.setEnabled(true);
optionsButton.setEnabled(true);
loginSkin1.setEnabled(true);
loginSkin2.setEnabled(true);
passwordField.setEnabled(true);
rememberCheckbox.setEnabled(true);
usernameField.setEnabled(true);
this.cancel(true);
return false;
}
return true;
}
protected void process(List<String> chunks) {
progressBar.setString(chunks.get(0));
}
};
updateThread.execute();
}
private Cipher getCipher(int mode, String password) throws Exception {
Random random = new Random(43287234L);
byte[] salt = new byte[8];
random.nextBytes(salt);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 5);
SecretKey pbeKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec(password.toCharArray()));
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(mode, pbeKey, pbeParamSpec);
return cipher;
}
public void runGame() {
LauncherFrame launcher = new LauncherFrame();
launcher.setLoginForm(this);
int result = launcher.runGame(values[2].trim(), values[3].trim(), values[1].trim(), pass);
if (result == LauncherFrame.SUCCESSFUL_LAUNCH) {
LoginForm.updateDialog.dispose();
LoginForm.updateDialog = null;
setVisible(false);
dispose();
}
else if (result == LauncherFrame.ERROR_IN_LAUNCH){
loginButton.setEnabled(true);
optionsButton.setEnabled(true);
loginSkin1.setEnabled(true);
loginSkin2.setEnabled(true);
progressBar.setVisible(false);
passwordField.setEnabled(true);
rememberCheckbox.setEnabled(true);
usernameField.setEnabled(true);
}
this.success = result;
//Do nothing for retrying launch
}
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
if (success == LauncherFrame.ERROR_IN_LAUNCH) {
System.out.println("Exiting the Spoutcraft Launcher");
System.exit(0);
}
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
private static final class UserPasswordInformation {
public boolean isHash;
public byte[] passwordHash = null;
public String password = null;
public UserPasswordInformation(String pass) {
isHash = false;
password = pass;
}
public UserPasswordInformation(byte[] hash) {
isHash = true;
passwordHash = hash;
}
}
}
| true | true | public LoginForm() {
LoginForm.updateDialog = new UpdateDialog(this);
gameUpdater.setListener(this);
this.addWindowListener(this);
SwingWorker<Object, Object> updateThread = new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
MinecraftYML.updateMinecraftYMLCache();
SpoutcraftYML.updateSpoutcraftYMLCache();
LibrariesYML.updateLibrariesYMLCache();
SpecialYML.updateMinecraftYMLCache();
return null;
}
protected void done() {
options.updateBuildsList();
}
};
updateThread.execute();
options.setVisible(false);
loginButton.setFont(new Font("Arial", Font.PLAIN, 11));
loginButton.setBounds(272, 13, 86, 23);
loginButton.setOpaque(false);
loginButton.addActionListener(this);
loginButton.setEnabled(false); //disable until login info is read
optionsButton.setFont(new Font("Arial", Font.PLAIN, 11));
optionsButton.setOpaque(false);
optionsButton.addActionListener(this);
usernameField.setFont(new Font("Arial", Font.PLAIN, 11));
usernameField.addActionListener(this);
usernameField.setOpaque(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(LoginForm.class.getResource("/org/spoutcraft/launcher/favicon.png")));
setResizable(false);
setTitle("Spoutcraft Launcher");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((dim.width - 860) / 2, (dim.height - 500) / 2, 860, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JLabel lblLogo = new JLabel("");
lblLogo.setBounds(8, 0, 294, 99);
lblLogo.setIcon(new ImageIcon(LoginForm.class.getResource("/org/spoutcraft/launcher/spoutcraft.png")));
JLabel lblMinecraftUsername = new JLabel("Minecraft Username: ");
lblMinecraftUsername.setFont(new Font("Arial", Font.PLAIN, 11));
lblMinecraftUsername.setHorizontalAlignment(SwingConstants.RIGHT);
lblMinecraftUsername.setBounds(-17, 17, 150, 14);
JLabel lblPassword = new JLabel("Password: ");
lblPassword.setFont(new Font("Arial", Font.PLAIN, 11));
lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
lblPassword.setBounds(33, 42, 100, 20);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Arial", Font.PLAIN, 11));
passwordField.setBounds(143, 42, 119, 22);
loginSkin1 = new JButton("Login as Player");
loginSkin1.setFont(new Font("Arial", Font.PLAIN, 11));
loginSkin1.setBounds(72, 428, 119, 23);
loginSkin1.setOpaque(false);
loginSkin1.addActionListener(this);
loginSkin1.setVisible(false);
loginSkin1Image = new ArrayList<JButton>();
loginSkin2 = new JButton("Login as Player");
loginSkin2.setFont(new Font("Arial", Font.PLAIN, 11));
loginSkin2.setBounds(261, 428, 119, 23);
loginSkin2.setOpaque(false);
loginSkin2.addActionListener(this);
loginSkin2.setVisible(false);
loginSkin2Image = new ArrayList<JButton>();
progressBar = new JProgressBar();
progressBar.setBounds(30, 100, 400, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
JLabel purchaseAccount = new HyperlinkJLabel("<html><u>Need a minecraft account?</u></html>", "http://www.minecraft.net/register.jsp");
purchaseAccount.setHorizontalAlignment(SwingConstants.RIGHT);
purchaseAccount.setBounds(243, 70, 111, 14);
purchaseAccount.setText("<html><u>Need an account?</u></html>");
purchaseAccount.setFont(new Font("Arial", Font.PLAIN, 11));
purchaseAccount.setForeground(new Color(0, 0, 255));
usernameField.setBounds(143, 14, 119, 25);
rememberCheckbox.setFont(new Font("Arial", Font.PLAIN, 11));
rememberCheckbox.setOpaque(false);
final JTextPane editorPane = new JTextPane();
editorPane.setContentType("text/html");
tumblerFeed = new TumblerFeedParsingWorker(editorPane);
tumblerFeed.execute();
readUsedUsernames();
editorPane.setEditable(false);
editorPane.setOpaque(false);
JLabel trans2;
JScrollPane scrollPane = new JScrollPane(editorPane);
scrollPane.setBounds(473, 11, 372, 340);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
editorPane.setCaretPosition(0);
trans2 = new JLabel();
trans2.setBackground(new Color(229, 246, 255, 100));
trans2.setOpaque(true);
trans2.setBounds(473, 11, 372, 340);
JLabel login = new JLabel();
login.setBackground(new Color(255, 255, 255, 120));
login.setOpaque(true);
login.setBounds(473, 362, 372, 99);
JLabel trans;
trans = new JLabel();
trans.setBackground(new Color(229, 246, 255, 60));
trans.setOpaque(true);
trans.setBounds(0, 0, 854, 480);
usernameField.getEditor().addActionListener(this);
passwordField.addKeyListener(this);
rememberCheckbox.addKeyListener(this);
usernameField.setEditable(true);
contentPane.setLayout(null);
rememberCheckbox.setBounds(144, 66, 93, 23);
contentPane.add(lblLogo);
optionsButton.setBounds(272, 41, 86, 23);
contentPane.add(loginSkin1);
contentPane.add(loginSkin2);
loginPane.setBounds(473, 362, 372, 99);
loginPane.add(lblPassword);
loginPane.add(lblMinecraftUsername);
loginPane.add(passwordField);
loginPane.add(usernameField);
loginPane.add(loginButton);
loginPane.add(rememberCheckbox);
loginPane.add(purchaseAccount);
loginPane.add(optionsButton);
contentPane.add(loginPane);
JLabel offlineMessage = new JLabel("Could not connect to minecraft.net");
offlineMessage.setFont(new Font("Arial", Font.PLAIN, 14));
offlineMessage.setBounds(25, 40, 217, 17);
JButton tryAgain = new JButton("Try Again");
tryAgain.setOpaque(false);
tryAgain.setFont(new Font("Arial", Font.PLAIN, 12));
tryAgain.setBounds(257, 20, 100, 25);
JButton offlineMode = new JButton("Offline Mode");
offlineMode.setOpaque(false);
offlineMode.setFont(new Font("Arial", Font.PLAIN, 12));
offlineMode.setBounds(257, 52, 100, 25);
offlinePane.setBounds(473, 362, 372, 99);
offlinePane.add(tryAgain);
offlinePane.add(offlineMode);
offlinePane.add(offlineMessage);
offlinePane.setVisible(false);
contentPane.add(offlinePane);
contentPane.add(scrollPane);
contentPane.add(trans2);
contentPane.add(login);
contentPane.add(trans);
contentPane.add(progressBar);
final JLabel background = new JLabel("Loading...");
background.setVerticalAlignment(SwingConstants.CENTER);
background.setHorizontalAlignment(SwingConstants.CENTER);
background.setBounds(0, 0, 854, 480);
contentPane.add(background);
//TODO: remove this after next release
(new File(PlatformUtils.getWorkingDirectory(), "launcher_cache.jpg")).delete();
File cacheDir = new File(PlatformUtils.getWorkingDirectory(), "cache");
cacheDir.mkdir();
File backgroundImage = new File(cacheDir, "launcher_background.jpg");
(new BackgroundImageWorker(backgroundImage, background)).execute();
Vector<Component> order = new Vector<Component>(5);
order.add(usernameField.getEditor().getEditorComponent());
order.add(passwordField);
order.add(rememberCheckbox);
order.add(loginButton);
order.add(optionsButton);
setFocusTraversalPolicy(new SpoutFocusTraversalPolicy(order));
loginButton.setEnabled(true); //enable once logins are read
}
| public LoginForm() {
LoginForm.updateDialog = new UpdateDialog(this);
gameUpdater.setListener(this);
this.addWindowListener(this);
SwingWorker<Object, Object> updateThread = new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
MinecraftYML.updateMinecraftYMLCache();
SpoutcraftYML.updateSpoutcraftYMLCache();
LibrariesYML.updateLibrariesYMLCache();
SpecialYML.updateSpecialYMLCache();
return null;
}
protected void done() {
options.updateBuildsList();
}
};
updateThread.execute();
options.setVisible(false);
loginButton.setFont(new Font("Arial", Font.PLAIN, 11));
loginButton.setBounds(272, 13, 86, 23);
loginButton.setOpaque(false);
loginButton.addActionListener(this);
loginButton.setEnabled(false); //disable until login info is read
optionsButton.setFont(new Font("Arial", Font.PLAIN, 11));
optionsButton.setOpaque(false);
optionsButton.addActionListener(this);
usernameField.setFont(new Font("Arial", Font.PLAIN, 11));
usernameField.addActionListener(this);
usernameField.setOpaque(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(LoginForm.class.getResource("/org/spoutcraft/launcher/favicon.png")));
setResizable(false);
setTitle("Spoutcraft Launcher");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((dim.width - 860) / 2, (dim.height - 500) / 2, 860, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JLabel lblLogo = new JLabel("");
lblLogo.setBounds(8, 0, 294, 99);
lblLogo.setIcon(new ImageIcon(LoginForm.class.getResource("/org/spoutcraft/launcher/spoutcraft.png")));
JLabel lblMinecraftUsername = new JLabel("Minecraft Username: ");
lblMinecraftUsername.setFont(new Font("Arial", Font.PLAIN, 11));
lblMinecraftUsername.setHorizontalAlignment(SwingConstants.RIGHT);
lblMinecraftUsername.setBounds(-17, 17, 150, 14);
JLabel lblPassword = new JLabel("Password: ");
lblPassword.setFont(new Font("Arial", Font.PLAIN, 11));
lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
lblPassword.setBounds(33, 42, 100, 20);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Arial", Font.PLAIN, 11));
passwordField.setBounds(143, 42, 119, 22);
loginSkin1 = new JButton("Login as Player");
loginSkin1.setFont(new Font("Arial", Font.PLAIN, 11));
loginSkin1.setBounds(72, 428, 119, 23);
loginSkin1.setOpaque(false);
loginSkin1.addActionListener(this);
loginSkin1.setVisible(false);
loginSkin1Image = new ArrayList<JButton>();
loginSkin2 = new JButton("Login as Player");
loginSkin2.setFont(new Font("Arial", Font.PLAIN, 11));
loginSkin2.setBounds(261, 428, 119, 23);
loginSkin2.setOpaque(false);
loginSkin2.addActionListener(this);
loginSkin2.setVisible(false);
loginSkin2Image = new ArrayList<JButton>();
progressBar = new JProgressBar();
progressBar.setBounds(30, 100, 400, 23);
progressBar.setVisible(false);
progressBar.setStringPainted(true);
progressBar.setOpaque(true);
JLabel purchaseAccount = new HyperlinkJLabel("<html><u>Need a minecraft account?</u></html>", "http://www.minecraft.net/register.jsp");
purchaseAccount.setHorizontalAlignment(SwingConstants.RIGHT);
purchaseAccount.setBounds(243, 70, 111, 14);
purchaseAccount.setText("<html><u>Need an account?</u></html>");
purchaseAccount.setFont(new Font("Arial", Font.PLAIN, 11));
purchaseAccount.setForeground(new Color(0, 0, 255));
usernameField.setBounds(143, 14, 119, 25);
rememberCheckbox.setFont(new Font("Arial", Font.PLAIN, 11));
rememberCheckbox.setOpaque(false);
final JTextPane editorPane = new JTextPane();
editorPane.setContentType("text/html");
tumblerFeed = new TumblerFeedParsingWorker(editorPane);
tumblerFeed.execute();
readUsedUsernames();
editorPane.setEditable(false);
editorPane.setOpaque(false);
JLabel trans2;
JScrollPane scrollPane = new JScrollPane(editorPane);
scrollPane.setBounds(473, 11, 372, 340);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
editorPane.setCaretPosition(0);
trans2 = new JLabel();
trans2.setBackground(new Color(229, 246, 255, 100));
trans2.setOpaque(true);
trans2.setBounds(473, 11, 372, 340);
JLabel login = new JLabel();
login.setBackground(new Color(255, 255, 255, 120));
login.setOpaque(true);
login.setBounds(473, 362, 372, 99);
JLabel trans;
trans = new JLabel();
trans.setBackground(new Color(229, 246, 255, 60));
trans.setOpaque(true);
trans.setBounds(0, 0, 854, 480);
usernameField.getEditor().addActionListener(this);
passwordField.addKeyListener(this);
rememberCheckbox.addKeyListener(this);
usernameField.setEditable(true);
contentPane.setLayout(null);
rememberCheckbox.setBounds(144, 66, 93, 23);
contentPane.add(lblLogo);
optionsButton.setBounds(272, 41, 86, 23);
contentPane.add(loginSkin1);
contentPane.add(loginSkin2);
loginPane.setBounds(473, 362, 372, 99);
loginPane.add(lblPassword);
loginPane.add(lblMinecraftUsername);
loginPane.add(passwordField);
loginPane.add(usernameField);
loginPane.add(loginButton);
loginPane.add(rememberCheckbox);
loginPane.add(purchaseAccount);
loginPane.add(optionsButton);
contentPane.add(loginPane);
JLabel offlineMessage = new JLabel("Could not connect to minecraft.net");
offlineMessage.setFont(new Font("Arial", Font.PLAIN, 14));
offlineMessage.setBounds(25, 40, 217, 17);
JButton tryAgain = new JButton("Try Again");
tryAgain.setOpaque(false);
tryAgain.setFont(new Font("Arial", Font.PLAIN, 12));
tryAgain.setBounds(257, 20, 100, 25);
JButton offlineMode = new JButton("Offline Mode");
offlineMode.setOpaque(false);
offlineMode.setFont(new Font("Arial", Font.PLAIN, 12));
offlineMode.setBounds(257, 52, 100, 25);
offlinePane.setBounds(473, 362, 372, 99);
offlinePane.add(tryAgain);
offlinePane.add(offlineMode);
offlinePane.add(offlineMessage);
offlinePane.setVisible(false);
contentPane.add(offlinePane);
contentPane.add(scrollPane);
contentPane.add(trans2);
contentPane.add(login);
contentPane.add(trans);
contentPane.add(progressBar);
final JLabel background = new JLabel("Loading...");
background.setVerticalAlignment(SwingConstants.CENTER);
background.setHorizontalAlignment(SwingConstants.CENTER);
background.setBounds(0, 0, 854, 480);
contentPane.add(background);
//TODO: remove this after next release
(new File(PlatformUtils.getWorkingDirectory(), "launcher_cache.jpg")).delete();
File cacheDir = new File(PlatformUtils.getWorkingDirectory(), "cache");
cacheDir.mkdir();
File backgroundImage = new File(cacheDir, "launcher_background.jpg");
(new BackgroundImageWorker(backgroundImage, background)).execute();
Vector<Component> order = new Vector<Component>(5);
order.add(usernameField.getEditor().getEditorComponent());
order.add(passwordField);
order.add(rememberCheckbox);
order.add(loginButton);
order.add(optionsButton);
setFocusTraversalPolicy(new SpoutFocusTraversalPolicy(order));
loginButton.setEnabled(true); //enable once logins are read
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.