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/bundles/core/org.openhab.core.autoupdate/src/main/java/org/openhab/core/autoupdate/internal/AutoUpdateBinding.java b/bundles/core/org.openhab.core.autoupdate/src/main/java/org/openhab/core/autoupdate/internal/AutoUpdateBinding.java
index defedfbf..3bc33f50 100644
--- a/bundles/core/org.openhab.core.autoupdate/src/main/java/org/openhab/core/autoupdate/internal/AutoUpdateBinding.java
+++ b/bundles/core/org.openhab.core.autoupdate/src/main/java/org/openhab/core/autoupdate/internal/AutoUpdateBinding.java
@@ -1,103 +1,106 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2012, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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 (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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.core.autoupdate.internal;
import org.openhab.core.autoupdate.AutoUpdateBindingProvider;
import org.openhab.core.events.AbstractEventSubscriberBinding;
import org.openhab.core.events.EventPublisher;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>The AutoUpdate-Binding is no 'normal' binding as it doesn't connect any hardware
* to openHAB. In fact it takes care of updating the State of an item with respect
* to the received command automatically or not. By default the State is getting
* updated automatically which is desired behavior in most of the cases. However
* it could be useful to disable this default behavior.</p>
* <p>For example when implementing validation steps before changing a State one
* needs to control the State-Update himself.</p>
*
* @author Thomas.Eichstaedt-Engelen
* @since 0.9.1
*/
public class AutoUpdateBinding extends AbstractEventSubscriberBinding<AutoUpdateBindingProvider> {
private static final Logger logger = LoggerFactory.getLogger(AutoUpdateBinding.class);
protected EventPublisher eventPublisher = null;
public void setEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void unsetEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = null;
}
/**
* <p>Iterates through all registered {@link AutoUpdateBindingProvider}s and
* checks whether an autoupdate configuration is available for <code>itemName</code>.</p>
*
* <p>If there are more then one {@link AutoUpdateBindingProvider}s providing
* a configuration the results are combined by a logical <em>OR</em>. If no
* configuration is provided at all the autoupdate defaults to <code>true</code>
* and an update is posted for the corresponding {@link State}.</p>
*
* @param itemName the item for which to find an autoupdate configuration
* @param command the command being received and posted as {@link State}
* update if <code>command</code> is instance of {@link State} as well.
*/
@Override
public void receiveCommand(String itemName, Command command) {
Boolean autoUpdate = null;
for (AutoUpdateBindingProvider provider : providers) {
- autoUpdate = provider.autoUpdate(itemName);
- if (Boolean.TRUE.equals(autoUpdate)) {
- break;
+ Boolean au = provider.autoUpdate(itemName);
+ if (au != null) {
+ autoUpdate = au;
+ if (Boolean.TRUE.equals(autoUpdate)) {
+ break;
+ }
}
}
// we didn't find any autoupdate configuration, so apply the default now
if (autoUpdate == null) {
autoUpdate = Boolean.TRUE;
}
if (autoUpdate && command instanceof State) {
eventPublisher.postUpdate(itemName, (State) command);
} else {
logger.trace("Item '{}' is not configured to updated it's State automatically -> please update State manually");
}
}
}
| true | true | public void receiveCommand(String itemName, Command command) {
Boolean autoUpdate = null;
for (AutoUpdateBindingProvider provider : providers) {
autoUpdate = provider.autoUpdate(itemName);
if (Boolean.TRUE.equals(autoUpdate)) {
break;
}
}
// we didn't find any autoupdate configuration, so apply the default now
if (autoUpdate == null) {
autoUpdate = Boolean.TRUE;
}
if (autoUpdate && command instanceof State) {
eventPublisher.postUpdate(itemName, (State) command);
} else {
logger.trace("Item '{}' is not configured to updated it's State automatically -> please update State manually");
}
}
| public void receiveCommand(String itemName, Command command) {
Boolean autoUpdate = null;
for (AutoUpdateBindingProvider provider : providers) {
Boolean au = provider.autoUpdate(itemName);
if (au != null) {
autoUpdate = au;
if (Boolean.TRUE.equals(autoUpdate)) {
break;
}
}
}
// we didn't find any autoupdate configuration, so apply the default now
if (autoUpdate == null) {
autoUpdate = Boolean.TRUE;
}
if (autoUpdate && command instanceof State) {
eventPublisher.postUpdate(itemName, (State) command);
} else {
logger.trace("Item '{}' is not configured to updated it's State automatically -> please update State manually");
}
}
|
diff --git a/baixing_quanleimu/src/com/quanleimu/imageCache/LazyImageLoader.java b/baixing_quanleimu/src/com/quanleimu/imageCache/LazyImageLoader.java
index 6849bd8d..5a82bb68 100644
--- a/baixing_quanleimu/src/com/quanleimu/imageCache/LazyImageLoader.java
+++ b/baixing_quanleimu/src/com/quanleimu/imageCache/LazyImageLoader.java
@@ -1,408 +1,408 @@
/**
*LazyImageLoader.java
*2011-10-13 下午10:05:53
*Touch Android
*http://bbs.droidstouch.com
*/
package com.quanleimu.imageCache;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.apache.commons.httpclient.HttpException;
import com.quanleimu.activity.QuanleimuApplication;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class LazyImageLoader
{
private static final int MESSAGE_ID =1;
public static final int MESSAGE_FAIL = 2;
public static final String EXTRA_IMG_URL="extra_img_url";
public static final String EXTRA_IMG="extra_img";
private ImageManager imgManger = new ImageManager(QuanleimuApplication.context);
private Vector<String> urlDequeDiskIO = new Vector<String>();
private DiskIOImageThread diskIOImgThread = new DiskIOImageThread();
private Vector<String> urlDequeDownload = new Vector<String>();
private DownloadImageThread downloadImgThread = new DownloadImageThread();
private CallbackManager callbackManager = new CallbackManager();
public void forceRecycle(){
this.imgManger.forceRecycle();
}
public void enableSampleSize(){
this.imgManger.enableSampleSize(true);
}
public void disableSampleSize(){
this.imgManger.enableSampleSize(false);
}
public Bitmap get(String url,ImageLoaderCallback callback, final int defaultImgRes)
{
Bitmap bitmap = null;//ImageManager.userDefualtHead;
//1. try to get from memory cache
if(imgManger.contains(url))
{
bitmap = imgManger.getFromMemoryCache(url);
// if(bitmap!=null && bitmap.isRecycled()){
// Log.d("imageCache", "bitmap in cache, but it is recycled and reclaimed, oOH...");
// }
}
if(bitmap!=null){//if found in memory cache, just return that to the caller
return bitmap;
}else
{//else, try try to load from disk cache
callbackManager.put(url, callback);
startFetchingTread(url);
}
return bitmap;
}
public Bitmap get(String url,ImageLoaderCallback callback)
{
Bitmap bitmap = null;//ImageManager.userDefualtHead;
//1. try to get from memory cache
if(imgManger.contains(url))
{
bitmap = imgManger.getFromMemoryCache(url);
// if(bitmap!=null && bitmap.isRecycled()){
// Log.d("imageCache", "bitmap in cache, but it is recycled and reclaimed, oOH...");
// }
}
if(bitmap!=null){//if found in memory cache, just return that to the caller
return bitmap;
}else
{//else, try try to load from disk cache
callbackManager.put(url, callback);
startFetchingTread(url);
}
return bitmap;
}
public void AdjustPriority(ArrayList<String> urls){
while(urls.size() > 0){
String url = urls.remove(urls.size() - 1);
if(urlDequeDiskIO.remove(url)){
urlDequeDiskIO.add(0, url);
}
if(urlDequeDownload.remove(url)){
urlDequeDownload.add(0, url);
}
}
}
public void forceRecycle(String url){
this.imgManger.forceRecycle(url);
}
public void Cancel(List<String> urls){
for(int i = 0; i < urls.size(); ++i){
String url = urls.get(i);
urlDequeDiskIO.remove(url);
urlDequeDownload.remove(url);
callbackManager.remove(url);
// Log.d("cancel", "hahaha, in cancel call1 forceRecycle: " + url);
// imgManger.forceRecycle(url);
// Log.d("cancel", "hahaha, end in cancel call1 forceRecycle: " + url);
}
}
public void Cancel(String url, Object object) {
if(callbackManager.remove(url, object)){
urlDequeDiskIO.remove(url);
urlDequeDownload.remove(url);
// Log.d("cancel", "hahaha, in cancel call2 forceRecycle: " + url);
// imgManger.forceRecycle(url);
// Log.d("cancel", "hahaha, end in cancel call2 forceRecycle: " + url);
}
}
public boolean checkWithImmediateIO(String url){
Bitmap result = null;
if(imgManger.contains(url)){
result = imgManger.getFromMemoryCache(url);
}
else{
result = imgManger.safeGetFromFileCacheOrAssets(url);
}
return (result != null);
}
public Bitmap getWithImmediateIO(String url,ImageLoaderCallback callback){
Bitmap result = null;
if(imgManger.contains(url)){
result = imgManger.getFromMemoryCache(url);
}
else{
result = imgManger.safeGetFromFileCacheOrAssets(url);
if(result == null){
callbackManager.put(url, callback);
putToDownloadDeque(url);
startDownloadingTread();
}
}
return result;
}
protected void putToDownloadDeque(String url) {
if(!urlDequeDownload.contains(url))
{
urlDequeDownload.add(url);
}
}
private void startFetchingTread(String url)
{
//put url to load-deque for disk-cache, and start loading-from-disk-cache if necessary
putUrlToUrlQueue(url);
State state = diskIOImgThread.getState();
if(state== State.NEW)
{
diskIOImgThread.start();
}
else if(state == State.TERMINATED)
{
diskIOImgThread = new DiskIOImageThread();
diskIOImgThread.start();
}
}
synchronized private void startDownloadingTread()
{
State state = downloadImgThread.getState();
if(state== State.NEW)
{
downloadImgThread.start();
}
else if(state == State.TERMINATED)
{
downloadImgThread = new DownloadImageThread();
downloadImgThread.start();
}
}
private void putUrlToUrlQueue(String url)
{
if(!urlDequeDiskIO.contains(url) && !urlDequeDownload.contains(url))
{
urlDequeDiskIO.add(url);
}
}
Handler handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch(msg.what)
{
case MESSAGE_ID :
{
Bundle bundle = msg.getData();
String url =bundle.getString(EXTRA_IMG_URL);
Bitmap bitmap = bundle.getParcelable(EXTRA_IMG);
callbackManager.callback(url, bitmap);
break;
}
case MESSAGE_FAIL:
{
Bundle bundle = msg.getData();
String url =bundle.getString(EXTRA_IMG_URL);
callbackManager.fail(url);
break;
}
}
};
};
private void notifyFail(String url)
{
callbackManager.fail(url);
}
private class DiskIOImageThread extends Thread
{
private boolean isRun=true;
private String mCurrentUrl = null;
public void shutDown()
{
isRun =false;
}
// public void cancel(String url){
// synchronized(mCurrentUrl){
// if(mCurrentUrl != null && mCurrentUrl.equals(url)){
//
// }
// }
// }
public void run()
{
try
{
while(isRun && urlDequeDiskIO.size() > 0)
{
// synchronized(mCurrentUrl){
mCurrentUrl = urlDequeDiskIO.remove(0);
// }
if(null == mCurrentUrl){
continue;
}
Bitmap bitmap=imgManger.safeGetFromDiskCache(mCurrentUrl);
if(bitmap==null){//if not in disk cache, put the url to download-deque for further downloading
putToDownloadDeque(mCurrentUrl);
startDownloadingTread();
}else{
Message msg=handler.obtainMessage(MESSAGE_ID);
Bundle bundle =msg.getData();
bundle.putSerializable(EXTRA_IMG_URL, mCurrentUrl);
bundle.putParcelable(EXTRA_IMG, bitmap);
handler.sendMessage(msg);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
shutDown();
}
}
}
private class DownloadImageThread extends Thread
{
private boolean isRun=true;
public void shutDown()
{
isRun =false;
}
public void run()
{
try
{
while(isRun && urlDequeDownload.size() > 0)
{
String url= urlDequeDownload.remove(0);
- if(null == url){
+ if(null == url || !url.trim().startsWith("http")){
continue;
}
Bitmap bitmap = imgManger.safeGetFromNetwork(url);
if(null != bitmap){
Message msg=handler.obtainMessage(MESSAGE_ID);
Bundle bundle =msg.getData();
bundle.putSerializable(EXTRA_IMG_URL, url);
bundle.putParcelable(EXTRA_IMG, bitmap);
handler.sendMessage(msg);
}else{
//Log.d("LazyImageLoader", "bitmap download failed for url: "+url+" !!!");
urlDequeDownload.add(url);
notifyFail(url);
// Message msg = handler.obtainMessage(MESSAGE_FAIL);
// Bundle bundle =msg.getData();
// bundle.putSerializable(EXTRA_IMG_URL, url);
//
// handler.sendMessage(msg);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
shutDown();
}
}
}
public Bitmap getBitmapInMemory(String url){
if(url == null || url.equals("")) return null;
return imgManger.getFromMemoryCache(url);
}
public String getFileInDiskCache(String url) {
return imgManger.getFileInDiskCache(url);
}
}
| true | true | public void run()
{
try
{
while(isRun && urlDequeDownload.size() > 0)
{
String url= urlDequeDownload.remove(0);
if(null == url){
continue;
}
Bitmap bitmap = imgManger.safeGetFromNetwork(url);
if(null != bitmap){
Message msg=handler.obtainMessage(MESSAGE_ID);
Bundle bundle =msg.getData();
bundle.putSerializable(EXTRA_IMG_URL, url);
bundle.putParcelable(EXTRA_IMG, bitmap);
handler.sendMessage(msg);
}else{
//Log.d("LazyImageLoader", "bitmap download failed for url: "+url+" !!!");
urlDequeDownload.add(url);
notifyFail(url);
// Message msg = handler.obtainMessage(MESSAGE_FAIL);
// Bundle bundle =msg.getData();
// bundle.putSerializable(EXTRA_IMG_URL, url);
//
// handler.sendMessage(msg);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
shutDown();
}
}
| public void run()
{
try
{
while(isRun && urlDequeDownload.size() > 0)
{
String url= urlDequeDownload.remove(0);
if(null == url || !url.trim().startsWith("http")){
continue;
}
Bitmap bitmap = imgManger.safeGetFromNetwork(url);
if(null != bitmap){
Message msg=handler.obtainMessage(MESSAGE_ID);
Bundle bundle =msg.getData();
bundle.putSerializable(EXTRA_IMG_URL, url);
bundle.putParcelable(EXTRA_IMG, bitmap);
handler.sendMessage(msg);
}else{
//Log.d("LazyImageLoader", "bitmap download failed for url: "+url+" !!!");
urlDequeDownload.add(url);
notifyFail(url);
// Message msg = handler.obtainMessage(MESSAGE_FAIL);
// Bundle bundle =msg.getData();
// bundle.putSerializable(EXTRA_IMG_URL, url);
//
// handler.sendMessage(msg);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
shutDown();
}
}
|
diff --git a/nuxeo-core-storage-sql/nuxeo-core-storage-sql-test/src/test/java/org/nuxeo/ecm/core/storage/sql/TestSQLRepositoryAPI.java b/nuxeo-core-storage-sql/nuxeo-core-storage-sql-test/src/test/java/org/nuxeo/ecm/core/storage/sql/TestSQLRepositoryAPI.java
index 0ec5e72e5..c437e6ced 100644
--- a/nuxeo-core-storage-sql/nuxeo-core-storage-sql-test/src/test/java/org/nuxeo/ecm/core/storage/sql/TestSQLRepositoryAPI.java
+++ b/nuxeo-core-storage-sql/nuxeo-core-storage-sql-test/src/test/java/org/nuxeo/ecm/core/storage/sql/TestSQLRepositoryAPI.java
@@ -1,3625 +1,3625 @@
/*
* Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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:
* Florent Guillaume
*/
package org.nuxeo.ecm.core.storage.sql;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.nuxeo.common.collections.ScopeType;
import org.nuxeo.common.collections.ScopedMap;
import org.nuxeo.common.utils.FileUtils;
import org.nuxeo.common.utils.Path;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.ClientRuntimeException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DataModel;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelIterator;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.Filter;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.ListDiff;
import org.nuxeo.ecm.core.api.PathRef;
import org.nuxeo.ecm.core.api.VersionModel;
import org.nuxeo.ecm.core.api.facet.VersioningDocument;
import org.nuxeo.ecm.core.api.impl.DocumentModelImpl;
import org.nuxeo.ecm.core.api.impl.DocumentModelTreeImpl;
import org.nuxeo.ecm.core.api.impl.DocumentModelTreeNodeComparator;
import org.nuxeo.ecm.core.api.impl.FacetFilter;
import org.nuxeo.ecm.core.api.impl.VersionModelImpl;
import org.nuxeo.ecm.core.api.impl.blob.ByteArrayBlob;
import org.nuxeo.ecm.core.api.impl.blob.StreamingBlob;
import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
import org.nuxeo.ecm.core.api.model.DocumentPart;
import org.nuxeo.ecm.core.api.model.Property;
import org.nuxeo.ecm.core.api.model.PropertyNotFoundException;
import org.nuxeo.ecm.core.api.security.ACE;
import org.nuxeo.ecm.core.api.security.ACL;
import org.nuxeo.ecm.core.api.security.ACP;
import org.nuxeo.ecm.core.api.security.impl.ACLImpl;
import org.nuxeo.ecm.core.api.security.impl.ACPImpl;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventService;
import org.nuxeo.ecm.core.event.impl.EventServiceImpl;
import org.nuxeo.ecm.core.schema.FacetNames;
import org.nuxeo.ecm.core.schema.SchemaManager;
import org.nuxeo.ecm.core.storage.EventConstants;
import org.nuxeo.ecm.core.storage.sql.listeners.DummyBeforeModificationListener;
import org.nuxeo.ecm.core.storage.sql.listeners.DummyTestListener;
import org.nuxeo.runtime.api.Framework;
/**
* NOTE: to run these tests in Eclipse, make sure your test runner allocates at
* least -Xmx200M to the JVM.
*
* @author Florent Guillaume
*/
public class TestSQLRepositoryAPI extends SQLRepositoryTestCase {
public TestSQLRepositoryAPI(String name) {
super(name);
}
@Override
public void setUp() throws Exception {
super.setUp();
deployContrib("org.nuxeo.ecm.core.storage.sql.test.tests",
"OSGI-INF/test-repo-core-types-contrib.xml");
openSession();
}
@Override
public void tearDown() throws Exception {
session.cancel();
closeSession();
super.tearDown();
}
public void testBasics() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel child = new DocumentModelImpl("/", "domain", "MyDocType");
child = session.createDocument(child);
session.save();
child.setProperty("dublincore", "title", "The title");
// use local tz
Calendar cal = new GregorianCalendar(2008, Calendar.JULY, 14, 12, 34,
56);
child.setProperty("dublincore", "modified", cal);
session.saveDocument(child);
session.save();
closeSession();
// ----- new session -----
openSession();
// root = session.getRootDocument();
child = session.getChild(root.getRef(), "domain");
String title = (String) child.getProperty("dublincore", "title");
assertEquals("The title", title);
String description = (String) child.getProperty("dublincore",
"description");
assertNull(description);
Calendar modified = (Calendar) child.getProperty("dublincore",
"modified");
assertEquals(cal, modified);
}
public void testLists() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel child = new DocumentModelImpl("/", "domain", "MyDocType");
child = session.createDocument(child);
session.save();
// simple list as array
child.setProperty("dublincore", "subjects", new String[] { "a", "b" });
// simple list as List
child.setProperty("dublincore", "contributors", new ArrayList<String>(
Arrays.asList("c", "d")));
// simple list as non-serializable array
child.setProperty("testList", "strings", new Object[] { "e", "f" });
// complex list as List
child.setProperty("testList", "participants", new ArrayList<String>(
Arrays.asList("c", "d")));
session.saveDocument(child);
session.save();
closeSession();
// ----- new session -----
openSession();
root = session.getRootDocument();
child = session.getChild(root.getRef(), "domain");
Object subjects = child.getProperty("dublincore", "subjects");
assertTrue(subjects instanceof String[]);
assertEquals(Arrays.asList("a", "b"),
Arrays.asList((String[]) subjects));
Object contributors = child.getProperty("dublincore", "contributors");
assertTrue(contributors instanceof String[]);
assertEquals(Arrays.asList("c", "d"),
Arrays.asList((String[]) contributors));
Object strings = child.getProperty("testList", "strings");
assertTrue(strings instanceof String[]);
assertEquals(Arrays.asList("e", "f"), Arrays.asList((String[]) strings));
Object participants = child.getProperty("testList", "participants");
assertTrue(participants instanceof List);
assertEquals(Arrays.asList("c", "d"), participants);
}
public void testPathWithExtraSlash() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "doc", "MyDocType");
doc = session.createDocument(doc);
session.save();
DocumentModelList children = session.getChildren(new PathRef("/"));
assertEquals(1, children.size());
children = session.getChildren(new PathRef("/doc"));
assertEquals(0, children.size());
children = session.getChildren(new PathRef("/doc/"));
assertEquals(0, children.size());
}
public void testComplexType() throws Exception {
// boiler plate to handle the asynchronous full-text indexing of blob
// content in a deterministic way
EventServiceImpl eventService = (EventServiceImpl) Framework.getLocalService(EventService.class);
deployBundle("org.nuxeo.ecm.core.convert");
deployBundle("org.nuxeo.ecm.core.convert.plugins");
DocumentModel doc = new DocumentModelImpl("/", "complex-doc",
"ComplexDoc");
doc = session.createDocument(doc);
DocumentRef docRef = doc.getRef();
session.save();
// test setting and reading a map with an empty list
closeSession();
openSession();
doc = session.getDocument(docRef);
Map<String, Object> attachedFile = new HashMap<String, Object>();
List<Map<String, Object>> vignettes = new ArrayList<Map<String, Object>>();
- attachedFile.put("name", "some name");
+ attachedFile.put("name", "somename");
attachedFile.put("vignettes", vignettes);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
doc = session.getDocument(docRef);
assertEquals(attachedFile,
doc.getProperty("cmpf:attachedFile").getValue());
assertEquals(attachedFile.get("vignettes"),
doc.getProperty("cmpf:attachedFile/vignettes").getValue());
// test fulltext indexing of complex property at level one
DocumentModelList results = session.query(
- "SELECT * FROM Document WHERE ecm:fulltext = 'some name'", 1);
+ "SELECT * FROM Document WHERE ecm:fulltext = 'somename'", 1);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test setting and reading a list of maps without a complex type in the
// maps
Map<String, Object> vignette = new HashMap<String, Object>();
vignette.put("width", Long.valueOf(0));
vignette.put("height", Long.valueOf(0));
vignette.put(
"content",
StreamingBlob.createFromString("textblob content", "text/plain"));
vignette.put("label", "vignettelabel");
vignettes.add(vignette);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
doc = session.getDocument(docRef);
assertEquals(
"text/plain",
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/content/mime-type").getValue());
assertEquals(
Long.valueOf(0),
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/height").getValue());
assertEquals(
"vignettelabel",
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/label").getValue());
// test fulltext indexing of complex property at level 3
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'vignettelabel'", 2);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test fulltext indexing of complex property at level 3 in blob
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'textblob content'", 2);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test setting and reading a list of maps with a blob inside the map
byte[] binaryContent = "01AB".getBytes();
Blob blob = StreamingBlob.createFromByteArray(binaryContent,
"application/octet-stream");
blob.setFilename("file.bin");
vignette.put("content", blob);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
assertEquals(
Long.valueOf(0),
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/height").getValue());
assertEquals(
"vignettelabel",
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/label").getValue());
// this doesn't work due to core restrictions (BlobProperty):
// assertEquals(blob.getFilename(), doc.getProperty(
// "cmpf:attachedFile/vignettes/vignette[0]/content/name").getValue());
Blob b = (Blob) doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/content").getValue();
assertEquals("file.bin", b.getFilename());
// test deleting the list of vignette and ensure that the fulltext index
// has been properly updated (regression test for NXP-6315)
doc.setPropertyValue("cmpf:attachedFile/vignettes",
new ArrayList<Map<String, Object>>());
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'vignettelabel'", 2);
assertNotNull(results);
assertEquals(0, results.size());
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'textblob content'", 2);
assertNotNull(results);
assertEquals(0, results.size());
}
public void testComplexTypeOrdering() throws Exception {
if (database instanceof DatabaseOracle) {
// Oracle has problems opening and closing many connections in a
// short time span (Listener refused the connection with the
// following error: ORA-12519, TNS:no appropriate service handler
// found)
// It seems to have something to do with how closed sessions are not
// immediately accounted for by Oracle's PMON (process monitor)
// So don't run this test with Oracle.
return;
}
// test case to reproduce an ordering content related Heisenbug on
// postgresql: NXP-2810: Preserve creation order of children of a
// complex type property in SQL storage with PostgreSQL
// create documents with a list of ordered vignettes
createComplexDocs(0, 5);
// check that the created docs hold their complex content in the
// creation order
checkComplexDocs(0, 5);
// add some more docs
createComplexDocs(5, 10);
// check that both the old and new document still hold their complex
// content in the same creation order
checkComplexDocs(0, 10);
}
protected void createComplexDocs(int iMin, int iMax) throws ClientException {
for (int i = iMin; i < iMax; i++) {
DocumentModel doc = session.createDocumentModel("/", "doc" + i,
"ComplexDoc");
Map<String, Object> attachedFile = new HashMap<String, Object>();
List<Map<String, Object>> vignettes = new ArrayList<Map<String, Object>>();
attachedFile.put("name", "some name");
attachedFile.put("vignettes", vignettes);
for (int j = 0; j < 3; j++) {
Map<String, Object> vignette = new HashMap<String, Object>();
vignette.put("width", Long.valueOf(j));
vignette.put("height", Long.valueOf(j));
vignette.put("content",
StreamingBlob.createFromString(String.format(
"document %d, vignette %d", i, j)));
vignettes.add(vignette);
}
doc.setPropertyValue("cmpf:attachedFile",
(Serializable) attachedFile);
doc = session.createDocument(doc);
session.save();
closeSession();
openSession();
}
}
protected void checkComplexDocs(int iMin, int iMax) throws ClientException,
IOException {
for (int i = iMin; i < iMax; i++) {
DocumentModel doc = session.getDocument(new PathRef("/doc" + i));
for (int j = 0; j < 3; j++) {
String propertyPath = String.format(
"cmpf:attachedFile/vignettes/%d/", j);
assertEquals(Long.valueOf(j),
doc.getProperty(propertyPath + "height").getValue());
assertEquals(Long.valueOf(j),
doc.getProperty(propertyPath + "width").getValue());
assertEquals(
String.format("document %d, vignette %d", i, j),
doc.getProperty(propertyPath + "content").getValue(
Blob.class).getString());
}
closeSession();
openSession();
}
}
public void testMarkDirty() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "doc", "MyDocType");
doc = session.createDocument(doc);
session.save();
doc.setProperty("dublincore", "title", "title1");
doc.setProperty("testList", "participants", new ArrayList<String>(
Arrays.asList("a", "b")));
session.saveDocument(doc);
session.save();
doc.setProperty("dublincore", "title", "title2");
doc.setProperty("testList", "participants", new ArrayList<String>(
Arrays.asList("c", "d")));
session.saveDocument(doc);
session.save();
// ----- new session -----
closeSession();
openSession();
// root = session.getRootDocument();
doc = session.getDocument(new PathRef("/doc"));
String title = (String) doc.getProperty("dublincore", "title");
assertEquals("title2", title);
Object participants = doc.getProperty("testList", "participants");
assertEquals(Arrays.asList("c", "d"), participants);
}
public void testMarkDirtyForList() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "doc", "ComplexDoc");
Map<String, Object> attachedFile = new HashMap<String, Object>();
List<Map<String, Object>> vignettes = new ArrayList<Map<String, Object>>();
attachedFile.put("vignettes", vignettes);
Map<String, Object> vignette = new HashMap<String, Object>();
vignette.put("width", 111L);
vignettes.add(vignette);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
doc = session.createDocument(doc);
session.save();
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/width").setValue(
222L);
session.saveDocument(doc);
session.save();
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/width").setValue(
333L);
session.saveDocument(doc);
session.save();
// ----- new session -----
closeSession();
openSession();
doc = session.getDocument(new PathRef("/doc"));
assertEquals(
333L,
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/width").getValue());
}
//
//
// ----------------------------------------------------
// ----- copied from TestAPI in nuxeo-core-facade -----
// ----------------------------------------------------
//
//
protected final Random random = new Random(new Date().getTime());
protected String generateUnique() {
return String.valueOf(random.nextLong());
}
protected DocumentModel createChildDocument(DocumentModel childFolder)
throws ClientException {
DocumentModel ret = session.createDocument(childFolder);
assertNotNull(ret);
assertNotNull(ret.getName());
assertNotNull(ret.getId());
assertNotNull(ret.getRef());
assertNotNull(ret.getPathAsString());
return ret;
}
protected List<DocumentModel> createChildDocuments(
List<DocumentModel> childFolders) throws ClientException {
List<DocumentModel> rets = new ArrayList<DocumentModel>();
Collections.addAll(
rets,
session.createDocument(childFolders.toArray(new DocumentModel[0])));
assertNotNull(rets);
assertEquals(childFolders.size(), rets.size());
for (DocumentModel createdChild : rets) {
assertNotNull(createdChild);
assertNotNull(createdChild.getName());
assertNotNull(createdChild.getRef());
assertNotNull(createdChild.getPathAsString());
assertNotNull(createdChild.getId());
}
return rets;
}
public void testGetRootDocument() throws ClientException {
DocumentModel root = session.getRootDocument();
assertNotNull(root);
assertNotNull(root.getId());
assertNotNull(root.getRef());
assertNotNull(root.getPathAsString());
}
@SuppressWarnings({ "SimplifiableJUnitAssertion" })
public void testDocumentReferenceEqualitySameInstance()
throws ClientException {
DocumentModel root = session.getRootDocument();
assertTrue(root.getRef().equals(root.getRef()));
}
public void testCancel() throws ClientException {
DocumentModel root = session.getRootDocument();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), "folder#" + generateUnique(), "Folder");
childFolder = createChildDocument(childFolder);
session.cancel();
// TODO, cancel unimplemented
// assertFalse(session.exists(childFolder.getRef()));
}
public void testCreateDomainDocumentRefDocumentModel()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "domain#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Domain");
childFolder = createChildDocument(childFolder);
assertEquals("Domain", childFolder.getType());
assertEquals(name, childFolder.getName());
}
public void testCreateFolderDocumentRefDocumentModel()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
childFolder = createChildDocument(childFolder);
assertEquals("Folder", childFolder.getType());
assertEquals(name, childFolder.getName());
}
public void testCreateFileDocumentRefDocumentModel() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name, "File");
childFile = createChildDocument(childFile);
assertEquals("File", childFile.getType());
assertEquals(name, childFile.getName());
}
public void testCreateFolderDocumentRefDocumentModelArray()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "folder#" + generateUnique();
DocumentModel childFolder2 = new DocumentModelImpl(
root.getPathAsString(), name2, "Folder");
List<DocumentModel> childFolders = new ArrayList<DocumentModel>();
childFolders.add(childFolder);
childFolders.add(childFolder2);
List<DocumentModel> returnedChildFolders = createChildDocuments(childFolders);
assertEquals(name, returnedChildFolders.get(0).getName());
assertEquals(name2, returnedChildFolders.get(1).getName());
}
public void testCreateFileDocumentRefDocumentModelArray()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name, "File");
String name2 = "file#" + generateUnique();
DocumentModel childFile2 = new DocumentModelImpl(
root.getPathAsString(), name2, "File");
List<DocumentModel> childFiles = new ArrayList<DocumentModel>();
childFiles.add(childFile);
childFiles.add(childFile2);
List<DocumentModel> returnedChildFiles = createChildDocuments(childFiles);
assertEquals(name, returnedChildFiles.get(0).getName());
assertEquals(name2, returnedChildFiles.get(1).getName());
}
public void testExists() throws ClientException {
DocumentModel root = session.getRootDocument();
assertTrue(session.exists(root.getRef()));
}
public void testGetChild() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
DocumentModel retrievedChild = session.getChild(root.getRef(), name);
assertNotNull(retrievedChild);
assertNotNull(retrievedChild.getId());
assertNotNull(retrievedChild.getPathAsString());
assertNotNull(retrievedChild.getName());
assertNotNull(retrievedChild.getRef());
assertEquals(name, retrievedChild.getName());
retrievedChild = session.getChild(root.getRef(), name2);
assertNotNull(retrievedChild);
assertNotNull(retrievedChild.getId());
assertNotNull(retrievedChild.getPathAsString());
assertNotNull(retrievedChild.getName());
assertNotNull(retrievedChild.getRef());
assertEquals(name2, retrievedChild.getName());
}
public void testGetChildrenDocumentRef() throws ClientException {
DocumentModel root = session.getRootDocument();
List<DocumentModel> docs = session.getChildren(root.getRef());
assertEquals(0, docs.size());
}
public void testGetChildrenDocumentRef2() throws ClientException {
DocumentModel root = session.getRootDocument();
DocumentModelIterator docs = session.getChildrenIterator(root.getRef());
assertFalse(docs.hasNext());
}
public void testGetFileChildrenDocumentRefString() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
// get file childs
List<DocumentModel> retrievedChilds = session.getChildren(
root.getRef(), "File");
assertNotNull(retrievedChilds);
assertEquals(1, retrievedChilds.size());
assertNotNull(retrievedChilds.get(0));
assertNotNull(retrievedChilds.get(0).getId());
assertNotNull(retrievedChilds.get(0).getName());
assertNotNull(retrievedChilds.get(0).getPathAsString());
assertNotNull(retrievedChilds.get(0).getRef());
assertEquals(name2, retrievedChilds.get(0).getName());
assertEquals("File", retrievedChilds.get(0).getType());
}
public void testGetFileChildrenDocumentRefString2() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
// get file childs
DocumentModelIterator retrievedChilds = session.getChildrenIterator(
root.getRef(), "File");
assertNotNull(retrievedChilds);
assertTrue(retrievedChilds.hasNext());
DocumentModel doc = retrievedChilds.next();
assertFalse(retrievedChilds.hasNext());
assertNotNull(doc);
assertNotNull(doc.getId());
assertNotNull(doc.getName());
assertNotNull(doc.getPathAsString());
assertNotNull(doc.getRef());
assertEquals(name2, doc.getName());
assertEquals("File", doc.getType());
}
public void testGetFolderChildrenDocumentRefString() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
// get folder childs
List<DocumentModel> retrievedChilds = session.getChildren(
root.getRef(), "Folder");
assertNotNull(retrievedChilds);
assertEquals(1, retrievedChilds.size());
assertNotNull(retrievedChilds.get(0));
assertNotNull(retrievedChilds.get(0).getId());
assertNotNull(retrievedChilds.get(0).getName());
assertNotNull(retrievedChilds.get(0).getPathAsString());
assertNotNull(retrievedChilds.get(0).getRef());
assertEquals(name, retrievedChilds.get(0).getName());
assertEquals("Folder", retrievedChilds.get(0).getType());
}
public void testGetFolderChildrenDocumentRefString2()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
// get folder childs
DocumentModelIterator retrievedChilds = session.getChildrenIterator(
root.getRef(), "Folder");
assertNotNull(retrievedChilds);
assertTrue(retrievedChilds.hasNext());
DocumentModel doc = retrievedChilds.next();
assertFalse(retrievedChilds.hasNext());
assertNotNull(doc);
assertNotNull(doc.getId());
assertNotNull(doc.getName());
assertNotNull(doc.getPathAsString());
assertNotNull(doc.getRef());
assertEquals(name, doc.getName());
assertEquals("Folder", doc.getType());
}
public void testGetChildrenDocumentRefStringFilter() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "folder#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "Folder");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
/*
* Filter filter = new NameFilter(name2); // get folder children
* List<DocumentModel> retrievedChilds =
* session.getChildren(root.getRef(), null, null, filter, null);
*
* assertNotNull(retrievedChilds); assertEquals(1,
* retrievedChilds.size());
*
* assertNotNull(retrievedChilds.get(0));
* assertNotNull(retrievedChilds.get(0).getId());
* assertNotNull(retrievedChilds.get(0).getName());
* assertNotNull(retrievedChilds.get(0).getPathAsString());
* assertNotNull(retrievedChilds.get(0).getRef());
*
* assertEquals(name2, retrievedChilds.get(0).getName());
*/
}
// FIXME: same as testGetChildrenDocumentRefStringFilter. Remove?
public void testGetChildrenDocumentRefStringFilter2()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "folder#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "Folder");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
/*
* Filter filter = new NameFilter(name2); // get folder childs
* DocumentModelIterator retrievedChilds = session.getChildrenIterator(
* root.getRef(), null, null, filter);
*
* assertNotNull(retrievedChilds);
*
* assertTrue(retrievedChilds.hasNext()); DocumentModel doc =
* retrievedChilds.next(); assertFalse(retrievedChilds.hasNext());
*
* assertNotNull(doc); assertNotNull(doc.getId());
* assertNotNull(doc.getName()); assertNotNull(doc.getPathAsString());
* assertNotNull(doc.getRef());
*
* assertEquals(name2, doc.getName());
*/
}
/**
* Test for NXP-741: Search based getChildren.
*
* @throws ClientException
*/
public void testGetChildrenInFolderWithSearch() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel folder = new DocumentModelImpl(root.getPathAsString(),
name, "FolderWithSearch");
folder = createChildDocument(folder);
// create more children
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
for (int i = 0; i < 5; i++) {
name = "File_" + i;
DocumentModel childFile = new DocumentModelImpl(
folder.getPathAsString(), name, "File");
childDocs.add(childFile);
}
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
int i = 0;
for (DocumentModel retChild : returnedChildDocs) {
name = "File_" + i;
assertEquals(name, retChild.getName());
i++;
}
}
public void testGetDocumentDocumentRef() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
DocumentModel doc = session.getDocument(returnedChildDocs.get(0).getRef());
assertNotNull(doc);
assertNotNull(doc.getRef());
assertNotNull(doc.getName());
assertNotNull(doc.getId());
assertNotNull(doc.getPathAsString());
assertEquals(name, doc.getName());
assertEquals("Folder", doc.getType());
}
// TODO: fix this test.
public void XXXtestGetDocumentDocumentRefStringArray()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
session.save();
childFile.setProperty("file", "filename", "second name");
childFile.setProperty("dublincore", "title", "f1");
childFile.setProperty("dublincore", "description", "desc 1");
session.saveDocument(childFile);
session.save();
DocumentModel returnedDocument = session.getDocument(childFile.getRef());
assertNotNull(returnedDocument);
assertNotNull(returnedDocument.getRef());
assertNotNull(returnedDocument.getId());
assertNotNull(returnedDocument.getName());
assertNotNull(returnedDocument.getPathAsString());
assertNotNull(returnedDocument.getType());
assertNotNull(returnedDocument.getSchemas());
// TODO: should it contain 3 or 1 schemas? not sure about that.
List<String> schemas = Arrays.asList(returnedDocument.getSchemas());
assertEquals(3, schemas.size());
assertTrue(schemas.contains("common"));
assertTrue(schemas.contains("file"));
assertTrue(schemas.contains("dublincore"));
assertEquals("f1", returnedDocument.getProperty("dublincore", "title"));
assertEquals("desc 1",
returnedDocument.getProperty("dublincore", "description"));
assertNull(returnedDocument.getProperty("file", "filename"));
returnedDocument = session.getDocument(childFile.getRef());
assertNotNull(returnedDocument);
assertNotNull(returnedDocument.getRef());
assertNotNull(returnedDocument.getId());
assertNotNull(returnedDocument.getName());
assertNotNull(returnedDocument.getPathAsString());
assertNotNull(returnedDocument.getType());
assertNotNull(returnedDocument.getSchemas());
schemas = Arrays.asList(returnedDocument.getSchemas());
assertEquals(3, schemas.size());
assertTrue(schemas.contains("common"));
assertTrue(schemas.contains("file"));
assertTrue(schemas.contains("dublincore"));
assertEquals("f1", returnedDocument.getProperty("dublincore", "title"));
assertEquals("desc 1",
returnedDocument.getProperty("dublincore", "description"));
assertEquals("second name",
returnedDocument.getProperty("file", "filename"));
}
public void testGetFilesDocumentRef() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
// get file childs
List<DocumentModel> retrievedChilds = session.getFiles(root.getRef());
assertNotNull(retrievedChilds);
assertEquals(1, retrievedChilds.size());
assertNotNull(retrievedChilds.get(0));
assertNotNull(retrievedChilds.get(0).getId());
assertNotNull(retrievedChilds.get(0).getPathAsString());
assertNotNull(retrievedChilds.get(0).getName());
assertNotNull(retrievedChilds.get(0).getRef());
assertEquals(name2, retrievedChilds.get(0).getName());
assertEquals("File", retrievedChilds.get(0).getType());
}
public void testGetFilesDocumentRef2() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
// get file childs
DocumentModelIterator retrievedChilds = session.getFilesIterator(root.getRef());
assertNotNull(retrievedChilds);
assertTrue(retrievedChilds.hasNext());
DocumentModel doc = retrievedChilds.next();
assertFalse(retrievedChilds.hasNext());
assertNotNull(doc);
assertNotNull(doc.getId());
assertNotNull(doc.getPathAsString());
assertNotNull(doc.getName());
assertNotNull(doc.getRef());
assertEquals(name2, doc.getName());
assertEquals("File", doc.getType());
}
// public void testGetFilesDocumentRefFilterSorter() {
// not used at the moment
//
// }
public void testGetFoldersDocumentRef() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
// get folder childs
List<DocumentModel> retrievedChilds = session.getFolders(root.getRef());
assertNotNull(retrievedChilds);
assertEquals(1, retrievedChilds.size());
assertNotNull(retrievedChilds.get(0));
assertNotNull(retrievedChilds.get(0).getId());
assertNotNull(retrievedChilds.get(0).getPathAsString());
assertNotNull(retrievedChilds.get(0).getName());
assertNotNull(retrievedChilds.get(0).getRef());
assertEquals(name, retrievedChilds.get(0).getName());
assertEquals("Folder", retrievedChilds.get(0).getType());
}
public void testGetFoldersDocumentRef2() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
// get folder childs
DocumentModelIterator retrievedChilds = session.getFoldersIterator(root.getRef());
assertNotNull(retrievedChilds);
assertTrue(retrievedChilds.hasNext());
DocumentModel doc = retrievedChilds.next();
assertFalse(retrievedChilds.hasNext());
assertNotNull(doc);
assertNotNull(doc.getId());
assertNotNull(doc.getPathAsString());
assertNotNull(doc.getName());
assertNotNull(doc.getRef());
assertEquals(name, doc.getName());
assertEquals("Folder", doc.getType());
}
// public void testGetFoldersDocumentRefFilterSorter() {
// not used at the moment
// }
public void testGetParentDocument() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
DocumentModel shouldBeRoot = session.getParentDocument(returnedChildDocs.get(
0).getRef());
assertEquals(root.getPathAsString(), shouldBeRoot.getPathAsString());
}
public void testHasChildren() throws ClientException {
DocumentModel root = session.getRootDocument();
// the root document at the moment has no children
assertFalse(session.hasChildren(root.getRef()));
}
public void testRemoveChildren() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
session.removeChildren(root.getRef());
assertFalse(session.exists(returnedChildDocs.get(0).getRef()));
assertFalse(session.exists(returnedChildDocs.get(1).getRef()));
}
public void testRemoveDocument() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
session.removeDocument(returnedChildDocs.get(0).getRef());
assertFalse(session.exists(returnedChildDocs.get(0).getRef()));
}
public void TODOtestQuery() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String fname1 = "file1#" + generateUnique();
DocumentModel childFile1 = new DocumentModelImpl(
root.getPathAsString(), fname1, "File");
childFile1.setProperty("dublincore", "title", "abc");
String fname2 = "file2#" + generateUnique();
DocumentModel childFile2 = new DocumentModelImpl(
root.getPathAsString(), fname2, "HiddenFile");
childFile2.setProperty("dublincore", "title", "def");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile1);
childDocs.add(childFile2);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
returnedChildDocs.get(1).setProperty("file", "filename", "f1");
returnedChildDocs.get(2).setProperty("file", "filename", "f2");
session.saveDocuments(returnedChildDocs.toArray(new DocumentModel[0]));
session.save();
DocumentModelList list = session.query("SELECT name FROM File");
assertEquals(1, list.size());
DocumentModel docModel = list.get(0);
List<String> schemas = Arrays.asList(docModel.getSchemas());
// TODO: is it 3 or 4? (should "uid" be in the list or not?)
// assertEquals(3, schemas.size());
assertTrue(schemas.contains("common"));
assertTrue(schemas.contains("file"));
assertTrue(schemas.contains("dublincore"));
// if we select filename, the returned docModel
// should have both schemas "file" and "common"
list = session.query("SELECT filename FROM File");
assertEquals(1, list.size());
docModel = list.get(0);
schemas = Arrays.asList(docModel.getSchemas());
// assertEquals(3, schemas.size());
assertTrue(schemas.contains("common"));
assertTrue(schemas.contains("file"));
assertTrue(schemas.contains("dublincore"));
// if we select all properties, the returned docModel
// should have at least the schemas "file" and "common"
// (it seems to also have "dublincore")
list = session.query("SELECT * FROM File");
assertEquals(1, list.size());
docModel = list.get(0);
schemas = Arrays.asList(docModel.getSchemas());
// assertEquals(3, schemas.size());
assertTrue(schemas.contains("common"));
assertTrue(schemas.contains("file"));
assertTrue(schemas.contains("dublincore"));
// if we select all files using the filter, we should get only one
Filter facetFilter = new FacetFilter("HiddenInNavigation", true);
list = session.query("SELECT * FROM HiddenFile", facetFilter);
assertEquals(1, list.size());
docModel = list.get(0);
schemas = Arrays.asList(docModel.getSchemas());
assertTrue(schemas.contains("common"));
assertTrue(schemas.contains("dublincore"));
// if we select all documents, we get the folder and the two files
list = session.query("SELECT * FROM Document");
assertEquals(3, list.size());
docModel = list.get(0);
schemas = Arrays.asList(docModel.getSchemas());
// assertEquals(3, schemas.size());
assertTrue(schemas.contains("common"));
assertTrue(schemas.contains("dublincore"));
list = session.query("SELECT * FROM Document WHERE dc:title = 'abc'");
assertEquals(1, list.size());
list = session.query("SELECT * FROM Document WHERE dc:title = 'abc' OR dc:title = 'def'");
assertEquals(2, list.size());
session.removeDocument(returnedChildDocs.get(0).getRef());
session.removeDocument(returnedChildDocs.get(1).getRef());
}
public void TODOtestQueryAfterEdit() throws ClientException, IOException {
DocumentModel root = session.getRootDocument();
String fname1 = "file1#" + generateUnique();
DocumentModel childFile1 = new DocumentModelImpl(
root.getPathAsString(), fname1, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFile1);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(1, returnedChildDocs.size());
childFile1 = returnedChildDocs.get(0);
childFile1.setProperty("file", "filename", "f1");
// add a blob
StringBlob sb = new StringBlob(
"<html><head/><body>La la la!</body></html>");
byte[] bytes = sb.getByteArray();
Blob blob = new ByteArrayBlob(bytes, "text/html");
childFile1.setProperty("file", "content", blob);
session.saveDocument(childFile1);
session.save();
DocumentModelList list;
DocumentModel docModel;
list = session.query("SELECT * FROM Document");
assertEquals(1, list.size());
docModel = list.get(0);
// read the properties
docModel.getProperty("dublincore", "title");
// XXX: FIXME: OG the following throws a class cast exception since the
// get property returns an HashMap instance instead of a LazyBlob when
// the tests are all run together:
// LazyBlob blob2 = (LazyBlob) docModel.getProperty("file", "content");
// assertEquals(-1, blob2.getLength());
// assertEquals("text/html", blob2.getMimeType());
// assertEquals(42, blob2.getByteArray().length);
// edit the title without touching the blob
docModel.setProperty("dublincore", "title", "edited title");
docModel.setProperty("dublincore", "description", "edited description");
session.saveDocument(docModel);
session.save();
list = session.query("SELECT * FROM Document");
assertEquals(1, list.size());
docModel = list.get(0);
session.removeDocument(docModel.getRef());
}
public void testRemoveDocuments() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
DocumentRef[] refs = { returnedChildDocs.get(0).getRef(),
returnedChildDocs.get(1).getRef() };
session.removeDocuments(refs);
assertFalse(session.exists(returnedChildDocs.get(0).getRef()));
assertFalse(session.exists(returnedChildDocs.get(1).getRef()));
}
/*
* case where some documents are actually children of other ones from the
* list
*/
public void testRemoveDocumentsWithDeps() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
// careless removing this one after the folder would fail
String name2 = "file#" + generateUnique();
DocumentModel folderChildFile = new DocumentModelImpl(
childFolder.getPathAsString(), name2, "File");
// one more File object, whose path is greater than the folder's
String name3 = "file#" + generateUnique();
DocumentModel folderChildFile2 = new DocumentModelImpl(
childFolder.getPathAsString(), name3, "File");
// one more File object at the root,
// whose path is greater than the folder's
String name4 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name4, "File");
// one more File object at the root, whose path is greater than the
// folder's and with name conflict resolved by core directly, see
// NXP-3240
DocumentModel childFile2 = new DocumentModelImpl(
root.getPathAsString(), name4, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(folderChildFile);
childDocs.add(folderChildFile2);
childDocs.add(childFile);
childDocs.add(childFile2);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
assertEquals(name3, returnedChildDocs.get(2).getName());
assertEquals(name4, returnedChildDocs.get(3).getName());
// not the same here: conflict resolved by core session
String name5 = returnedChildDocs.get(4).getName();
assertNotSame(name4, name5);
assertTrue(name5.startsWith(name4));
DocumentRef[] refs = { returnedChildDocs.get(0).getRef(),
returnedChildDocs.get(1).getRef(),
returnedChildDocs.get(2).getRef(),
returnedChildDocs.get(3).getRef(),
returnedChildDocs.get(4).getRef() };
session.removeDocuments(refs);
assertFalse(session.exists(returnedChildDocs.get(0).getRef()));
assertFalse(session.exists(returnedChildDocs.get(1).getRef()));
assertFalse(session.exists(returnedChildDocs.get(2).getRef()));
assertFalse(session.exists(returnedChildDocs.get(3).getRef()));
assertFalse(session.exists(returnedChildDocs.get(4).getRef()));
}
/*
* Same as testRemoveDocumentWithDeps with a different given ordering of
* documents to delete
*/
public void testRemoveDocumentsWithDeps2() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
// careless removing this one after the folder would fail
String name2 = "file#" + generateUnique();
DocumentModel folderChildFile = new DocumentModelImpl(
childFolder.getPathAsString(), name2, "File");
// one more File object, whose path is greater than the folder's
String name3 = "file#" + generateUnique();
DocumentModel folderChildFile2 = new DocumentModelImpl(
childFolder.getPathAsString(), name3, "File");
// one more File object at the root,
// whose path is greater than the folder's
String name4 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name4, "File");
// one more File object at the root, whose path is greater than the
// folder's and with name conflict resolved by core directly, see
// NXP-3240
DocumentModel childFile2 = new DocumentModelImpl(
root.getPathAsString(), name4, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(folderChildFile);
childDocs.add(folderChildFile2);
childDocs.add(childFile);
childDocs.add(childFile2);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
assertEquals(name3, returnedChildDocs.get(2).getName());
assertEquals(name4, returnedChildDocs.get(3).getName());
// not the same here: conflict resolved by core session
String name5 = returnedChildDocs.get(4).getName();
assertNotSame(name4, name5);
assertTrue(name5.startsWith(name4));
// here's the different ordering
DocumentRef[] refs = { returnedChildDocs.get(1).getRef(),
returnedChildDocs.get(0).getRef(),
returnedChildDocs.get(4).getRef(),
returnedChildDocs.get(3).getRef(),
returnedChildDocs.get(2).getRef() };
session.removeDocuments(refs);
assertFalse(session.exists(returnedChildDocs.get(0).getRef()));
assertFalse(session.exists(returnedChildDocs.get(1).getRef()));
assertFalse(session.exists(returnedChildDocs.get(2).getRef()));
assertFalse(session.exists(returnedChildDocs.get(3).getRef()));
assertFalse(session.exists(returnedChildDocs.get(4).getRef()));
}
public void testRemoveDocumentTreeWithSecurity() throws Exception {
ACP acp;
ACL acl;
DocumentModelList dml;
DocumentModel root = session.getRootDocument();
DocumentModel f1 = session.createDocumentModel("/", "f1", "Folder");
f1 = session.createDocument(f1);
DocumentModel doc1 = session.createDocumentModel("/f1", "doc1", "File");
doc1 = session.createDocument(doc1);
DocumentModel doc2 = session.createDocumentModel("/f1", "doc2", "File");
doc2 = session.createDocument(doc2);
// set ACP on root
acp = new ACPImpl();
acl = new ACLImpl();
acl.add(new ACE("Administrator", "Everything", true));
acl.add(new ACE("bob", "Everything", true));
acp.addACL(acl);
root.setACP(acp, true);
// set ACP on doc1 to block bob
acp = new ACPImpl();
acl = new ACLImpl();
acl.add(new ACE("bob", "Everything", false));
acp.addACL(acl);
doc1.setACP(acp, true);
session.save();
// check admin sees doc1 and doc2
dml = session.query("SELECT * FROM Document WHERE ecm:path STARTSWITH '/f1'");
assertEquals(2, dml.size());
// as bob
closeSession();
session = openSessionAs("bob");
// check bob doesn't see doc1
dml = session.query("SELECT * FROM Document WHERE ecm:path STARTSWITH '/f1'");
assertEquals(1, dml.size());
// do copy
session.copy(f1.getRef(), root.getRef(), "f2");
// save is mandatory to propagate read acls after a copy
session.save();
// check bob doesn't see doc1's copy
dml = session.query("SELECT * FROM Document WHERE ecm:path STARTSWITH '/f2'");
assertEquals(1, dml.size());
}
public void testSave() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
childFolder = createChildDocument(childFolder);
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
session.save();
// TODO: this should be tested across sessions - when it can be done
assertTrue(session.exists(childFolder.getRef()));
assertTrue(session.exists(childFile.getRef()));
}
public void testSaveFolder() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
childFolder = createChildDocument(childFolder);
childFolder.setProperty("dublincore", "title", "f1");
childFolder.setProperty("dublincore", "description", "desc 1");
session.saveDocument(childFolder);
// TODO: this should be tested across sessions - when it can be done
assertTrue(session.exists(childFolder.getRef()));
assertEquals("f1", childFolder.getProperty("dublincore", "title"));
assertEquals("desc 1",
childFolder.getProperty("dublincore", "description"));
}
public void testSaveFile() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name, "File");
childFile.setProperty("dublincore", "title", "f1");
childFile.setProperty("dublincore", "description", "desc 1");
childFile.setProperty("file", "filename", "filename1");
childFile = createChildDocument(childFile);
Property p = childFile.getProperty("/file:/filename");
// System.out.println(p.getPath());
// TODO: this should be tested across sessions - when it can be done
assertTrue(session.exists(childFile.getRef()));
DocumentModel retrievedFile = session.getDocument(childFile.getRef());
assertEquals("f1", retrievedFile.getProperty("dublincore", "title"));
assertEquals("desc 1",
retrievedFile.getProperty("dublincore", "description"));
assertEquals("filename1", retrievedFile.getProperty("file", "filename"));
}
public void testSaveDocuments() throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
childFolder = createChildDocument(childFolder);
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
DocumentModel[] docs = { childFolder, childFile };
session.saveDocuments(docs);
// TODO: this should be tested across sessions - when it can be done
assertTrue(session.exists(childFolder.getRef()));
assertTrue(session.exists(childFile.getRef()));
}
public void testGetDataModel() throws ClientException {
DocumentModel root = session.getRootDocument();
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
session.save();
childFile.setProperty("file", "filename", "second name");
childFile.setProperty("dublincore", "title", "f1");
childFile.setProperty("dublincore", "description", "desc 1");
session.saveDocument(childFile);
DataModel dm = session.getDataModel(childFile.getRef(), "dublincore");
assertNotNull(dm);
assertNotNull(dm.getMap());
assertNotNull(dm.getSchema());
assertEquals("dublincore", dm.getSchema());
assertEquals("f1", dm.getData("title"));
assertEquals("desc 1", dm.getData("description"));
dm = session.getDataModel(childFile.getRef(), "file");
assertNotNull(dm);
assertNotNull(dm.getMap());
assertNotNull(dm.getSchema());
assertEquals("file", dm.getSchema());
assertEquals("second name", dm.getData("filename"));
}
public void testGetDataModelField() throws ClientException {
DocumentModel root = session.getRootDocument();
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
session.save();
childFile.setProperty("file", "filename", "second name");
childFile.setProperty("dublincore", "title", "f1");
childFile.setProperty("dublincore", "description", "desc 1");
session.saveDocument(childFile);
assertEquals("f1", session.getDataModelField(childFile.getRef(),
"dublincore", "title"));
assertEquals("desc 1", session.getDataModelField(childFile.getRef(),
"dublincore", "description"));
assertEquals("second name", session.getDataModelField(
childFile.getRef(), "file", "filename"));
}
public void testGetDataModelFields() throws ClientException {
DocumentModel root = session.getRootDocument();
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
session.save();
childFile.setProperty("file", "filename", "second name");
childFile.setProperty("dublincore", "title", "f1");
childFile.setProperty("dublincore", "description", "desc 1");
session.saveDocument(childFile);
String[] fields = { "title", "description" };
Object[] values = session.getDataModelFields(childFile.getRef(),
"dublincore", fields);
assertNotNull(values);
assertEquals(2, values.length);
assertEquals("f1", values[0]);
assertEquals("desc 1", values[1]);
String[] fields2 = { "filename" };
values = session.getDataModelFields(childFile.getRef(), "file", fields2);
assertNotNull(values);
assertEquals(1, values.length);
assertEquals("second name", values[0]);
}
public void testDocumentReferenceEqualityDifferentInstances()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
DocumentModel retrievedChild = session.getChild(root.getRef(), name);
assertNotNull(retrievedChild);
assertNotNull(retrievedChild.getId());
assertNotNull(retrievedChild.getPathAsString());
assertNotNull(retrievedChild.getName());
assertNotNull(retrievedChild.getRef());
assertEquals(name, retrievedChild.getName());
assertEquals(root.getRef(), retrievedChild.getParentRef());
retrievedChild = session.getChild(root.getRef(), name2);
assertNotNull(retrievedChild);
assertNotNull(retrievedChild.getId());
assertNotNull(retrievedChild.getPathAsString());
assertNotNull(retrievedChild.getName());
assertNotNull(retrievedChild.getRef());
assertEquals(name2, retrievedChild.getName());
assertEquals(root.getRef(), retrievedChild.getParentRef());
}
public void testDocumentReferenceNonEqualityDifferentInstances()
throws ClientException {
DocumentModel root = session.getRootDocument();
String name = "folder#" + generateUnique();
DocumentModel childFolder = new DocumentModelImpl(
root.getPathAsString(), name, "Folder");
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
List<DocumentModel> childDocs = new ArrayList<DocumentModel>();
childDocs.add(childFolder);
childDocs.add(childFile);
List<DocumentModel> returnedChildDocs = createChildDocuments(childDocs);
assertEquals(name, returnedChildDocs.get(0).getName());
assertEquals(name2, returnedChildDocs.get(1).getName());
DocumentModel retrievedChild = session.getChild(root.getRef(), name);
assertNotNull(retrievedChild);
assertNotNull(retrievedChild.getId());
assertNotNull(retrievedChild.getPathAsString());
assertNotNull(retrievedChild.getName());
assertNotNull(retrievedChild.getRef());
assertEquals(name, retrievedChild.getName());
assertFalse(retrievedChild.getRef().equals(root.getRef()));
assertFalse(retrievedChild.getRef().equals(
retrievedChild.getParentRef()));
}
public void testFolderFacet() throws Exception {
DocumentModel child1 = new DocumentModelImpl("/", "file1", "File");
DocumentModel child2 = new DocumentModelImpl("/", "fold1", "Folder");
DocumentModel child3 = new DocumentModelImpl("/", "ws1", "Workspace");
List<DocumentModel> returnedChildFiles = createChildDocuments(Arrays.asList(
child1, child2, child3));
assertFalse(returnedChildFiles.get(0).isFolder());
assertTrue(returnedChildFiles.get(1).isFolder());
assertTrue(returnedChildFiles.get(2).isFolder());
}
public void testFacetAPI() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "foo", "File");
doc = session.createDocument(doc);
session.save();
DocumentModelList dml;
// facet not yet present
assertFalse(doc.hasFacet("Aged"));
assertFalse(doc.hasFacet(FacetNames.HIDDEN_IN_NAVIGATION));
Set<String> baseFacets = new HashSet<String>(Arrays.asList(
FacetNames.DOWNLOADABLE, FacetNames.VERSIONABLE,
FacetNames.PUBLISHABLE, FacetNames.COMMENTABLE,
FacetNames.HAS_RELATED_TEXT));
assertEquals(baseFacets, doc.getFacets());
try {
doc.setPropertyValue("age:age", "123");
fail();
} catch (PropertyNotFoundException e) {
// ok
}
dml = session.query("SELECT * FROM File WHERE ecm:mixinType = 'Aged'");
assertEquals(0, dml.size());
dml = session.query("SELECT * FROM Document WHERE ecm:mixinType <> 'Aged'");
assertEquals(1, dml.size());
// cannot add nonexistent facet
try {
doc.addFacet("nosuchfacet");
fail();
} catch (ClientRuntimeException e) {
assertTrue(e.getMessage(), e.getMessage().contains("No such facet"));
}
assertEquals(baseFacets, doc.getFacets());
assertFalse(doc.removeFacet("nosuchfacet"));
assertEquals(baseFacets, doc.getFacets());
// add facet
assertTrue(doc.addFacet("Aged"));
assertTrue(doc.hasFacet("Aged"));
assertEquals(baseFacets.size() + 1, doc.getFacets().size());
doc.setPropertyValue("age:age", "123");
doc = session.saveDocument(doc);
assertTrue(doc.hasFacet("Aged"));
assertEquals(baseFacets.size() + 1, doc.getFacets().size());
assertEquals("123", doc.getPropertyValue("age:age"));
session.save();
closeSession();
openSession();
doc = session.getDocument(doc.getRef());
assertTrue(doc.hasFacet("Aged"));
assertEquals(baseFacets.size() + 1, doc.getFacets().size());
assertEquals("123", doc.getPropertyValue("age:age"));
dml = session.query("SELECT * FROM File WHERE ecm:mixinType = 'Aged'");
assertEquals(1, dml.size());
dml = session.query("SELECT * FROM Document WHERE ecm:mixinType <> 'Aged'");
assertEquals(0, dml.size());
// add twice
assertFalse(doc.addFacet("Aged"));
assertEquals(baseFacets.size() + 1, doc.getFacets().size());
// add other facet with no schema
assertTrue(doc.addFacet(FacetNames.HIDDEN_IN_NAVIGATION));
assertTrue(doc.hasFacet("Aged"));
assertTrue(doc.hasFacet(FacetNames.HIDDEN_IN_NAVIGATION));
assertEquals(baseFacets.size() + 2, doc.getFacets().size());
// remove first facet
assertTrue(doc.removeFacet("Aged"));
assertFalse(doc.hasFacet("Aged"));
assertTrue(doc.hasFacet(FacetNames.HIDDEN_IN_NAVIGATION));
assertEquals(baseFacets.size() + 1, doc.getFacets().size());
try {
doc.getPropertyValue("age:age");
fail();
} catch (PropertyNotFoundException e) {
// ok
}
doc = session.saveDocument(doc);
assertFalse(doc.hasFacet("Aged"));
assertTrue(doc.hasFacet(FacetNames.HIDDEN_IN_NAVIGATION));
assertEquals(baseFacets.size() + 1, doc.getFacets().size());
try {
doc.getPropertyValue("age:age");
fail();
} catch (PropertyNotFoundException e) {
// ok
}
session.save();
closeSession();
openSession();
doc = session.getDocument(doc.getRef());
assertFalse(doc.hasFacet("Aged"));
assertTrue(doc.hasFacet(FacetNames.HIDDEN_IN_NAVIGATION));
assertEquals(baseFacets.size() + 1, doc.getFacets().size());
try {
doc.getPropertyValue("age:age");
fail();
} catch (PropertyNotFoundException e) {
// ok
}
dml = session.query("SELECT * FROM File WHERE ecm:mixinType = 'Aged'");
assertEquals(0, dml.size());
dml = session.query("SELECT * FROM Document WHERE ecm:mixinType <> 'Aged'");
assertEquals(1, dml.size());
// remove twice
assertFalse(doc.removeFacet("Aged"));
assertEquals(baseFacets.size() + 1, doc.getFacets().size());
// remove other facet
assertTrue(doc.removeFacet(FacetNames.HIDDEN_IN_NAVIGATION));
assertFalse(doc.hasFacet("Aged"));
assertFalse(doc.hasFacet(FacetNames.HIDDEN_IN_NAVIGATION));
assertEquals(baseFacets, doc.getFacets());
}
public void testFacetIncludedInPrimaryType() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "foo", "DocWithAge");
doc.setPropertyValue("age:age", "123");
doc = session.createDocument(doc);
session.save();
// new session
closeSession();
openSession();
doc = session.getDocument(doc.getRef());
assertEquals("123", doc.getPropertyValue("age:age"));
// API on doc whose type has a facet
assertEquals(Collections.singleton("Aged"), doc.getFacets());
assertTrue(doc.hasFacet("Aged"));
assertFalse(doc.addFacet("Aged"));
assertFalse(doc.removeFacet("Aged"));
}
public void testFacetAddRemove() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "foo", "File");
doc = session.createDocument(doc);
session.save();
// mixin not there
try {
doc.getPropertyValue("age:age");
fail();
} catch (PropertyNotFoundException e) {
// ok
}
// add
assertTrue(doc.addFacet("Aged"));
doc.setPropertyValue("age:age", "123");
session.save();
// remove
assertTrue(doc.removeFacet("Aged"));
session.save();
// mixin not there anymore
try {
doc.getPropertyValue("age:age");
fail();
} catch (PropertyNotFoundException e) {
// ok
}
}
// mixin on doc with same schema in primary type does no harm
public void testFacetAddRemove2() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "foo", "DocWithAge");
doc.setPropertyValue("age:age", "123");
doc = session.createDocument(doc);
session.save();
assertFalse(doc.addFacet("Aged"));
assertEquals("123", doc.getPropertyValue("age:age"));
assertFalse(doc.removeFacet("Aged"));
assertEquals("123", doc.getPropertyValue("age:age"));
}
public void testFacetWithSamePropertyName() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "foo", "File");
doc.setPropertyValue("dc:title", "bar");
doc = session.createDocument(doc);
session.save();
doc.addFacet("Aged");
doc.setPropertyValue("age:title", "gee");
doc = session.saveDocument(doc);
session.save();
assertEquals("bar", doc.getPropertyValue("dc:title"));
assertEquals("gee", doc.getPropertyValue("age:title"));
// refetch
doc = session.getDocument(doc.getRef());
assertEquals("bar", doc.getPropertyValue("dc:title"));
assertEquals("gee", doc.getPropertyValue("age:title"));
}
public void testFacetCopy() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "foo", "File");
doc.addFacet("Aged");
doc.setPropertyValue("age:age", "123");
doc = session.createDocument(doc);
session.save();
// copy the doc
DocumentModel copy = session.copy(doc.getRef(),
session.getRootDocument().getRef(), "bar");
assertTrue(copy.hasFacet("Aged"));
assertEquals("123", copy.getPropertyValue("age:age"));
}
public void testFacetFulltext() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "foo", "File");
doc.addFacet("Aged");
doc.setPropertyValue("age:age", "barbar");
doc = session.createDocument(doc);
session.save();
DatabaseHelper.DATABASE.sleepForFulltext();
DocumentModelList list = session.query("SELECT * FROM File WHERE ecm:fulltext = 'barbar'");
assertEquals(1, list.size());
}
public void testFacetQueryContent() throws Exception {
DocumentModel doc = new DocumentModelImpl("/", "foo", "File");
doc.addFacet("Aged");
doc.setPropertyValue("age:age", "barbar");
doc = session.createDocument(doc);
session.save();
DocumentModelList list = session.query("SELECT * FROM File WHERE age:age = 'barbar'");
assertEquals(1, list.size());
}
public void testLifeCycleAPI() throws ClientException {
DocumentModel root = session.getRootDocument();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
"file#" + generateUnique(), "File");
childFile = createChildDocument(childFile);
assertEquals("default", session.getLifeCyclePolicy(childFile.getRef()));
assertEquals("project",
session.getCurrentLifeCycleState(childFile.getRef()));
Collection<String> allowedStateTransitions = session.getAllowedStateTransitions(childFile.getRef());
assertEquals(3, allowedStateTransitions.size());
assertTrue(allowedStateTransitions.contains("approve"));
assertTrue(allowedStateTransitions.contains("obsolete"));
assertTrue(allowedStateTransitions.contains("delete"));
assertTrue(session.followTransition(childFile.getRef(), "approve"));
assertEquals("approved",
session.getCurrentLifeCycleState(childFile.getRef()));
allowedStateTransitions = session.getAllowedStateTransitions(childFile.getRef());
assertEquals(2, allowedStateTransitions.size());
assertTrue(allowedStateTransitions.contains("delete"));
assertTrue(allowedStateTransitions.contains("backToProject"));
session.reinitLifeCycleState(childFile.getRef());
assertEquals("project",
session.getCurrentLifeCycleState(childFile.getRef()));
}
public void testDataModelLifeCycleAPI() throws ClientException {
DocumentModel root = session.getRootDocument();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
"file#" + generateUnique(), "File");
childFile = createChildDocument(childFile);
assertEquals("default", childFile.getLifeCyclePolicy());
assertEquals("project", childFile.getCurrentLifeCycleState());
Collection<String> allowedStateTransitions = childFile.getAllowedStateTransitions();
assertEquals(3, allowedStateTransitions.size());
assertTrue(allowedStateTransitions.contains("approve"));
assertTrue(allowedStateTransitions.contains("obsolete"));
assertTrue(allowedStateTransitions.contains("delete"));
assertTrue(childFile.followTransition("obsolete"));
assertEquals("obsolete", childFile.getCurrentLifeCycleState());
allowedStateTransitions = childFile.getAllowedStateTransitions();
assertEquals(2, allowedStateTransitions.size());
assertTrue(allowedStateTransitions.contains("delete"));
assertTrue(allowedStateTransitions.contains("backToProject"));
}
public void testCopy() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel folder1 = new DocumentModelImpl(root.getPathAsString(),
"folder1", "Folder");
DocumentModel folder2 = new DocumentModelImpl(root.getPathAsString(),
"folder2", "Folder");
DocumentModel file = new DocumentModelImpl(folder1.getPathAsString(),
"file", "File");
folder1 = createChildDocument(folder1);
folder2 = createChildDocument(folder2);
file = createChildDocument(file);
session.save();
assertTrue(session.exists(new PathRef("folder1/file")));
assertFalse(session.exists(new PathRef("folder2/file")));
// copy using orig name
DocumentModel copy1 = session.copy(file.getRef(), folder2.getRef(),
null);
assertTrue(session.exists(new PathRef("folder1/file")));
assertTrue(session.exists(new PathRef("folder2/file")));
assertFalse(session.exists(new PathRef("folder2/fileCopy")));
assertTrue(session.getChildren(folder2.getRef()).contains(copy1));
// copy using another name
DocumentModel copy2 = session.copy(file.getRef(), folder2.getRef(),
"fileCopy");
assertTrue(session.exists(new PathRef("folder1/file")));
assertTrue(session.exists(new PathRef("folder2/file")));
assertTrue(session.exists(new PathRef("folder2/fileCopy")));
assertTrue(session.getChildren(folder2.getRef()).contains(copy2));
// copy again to same space
DocumentModel copy3 = session.copy(file.getRef(), folder2.getRef(),
null);
assertTrue(session.exists(new PathRef("folder1/file")));
assertTrue(session.exists(new PathRef("folder2/file")));
assertTrue(session.getChildren(folder2.getRef()).contains(copy3));
assertNotSame(copy1.getName(), copy3.getName());
// copy again again to same space
if (System.getProperty("os.name").startsWith("Windows")) {
// windows has too coarse time granularity
// for SQLSession.findFreeName
Thread.sleep(1000);
}
DocumentModel copy4 = session.copy(file.getRef(), folder2.getRef(),
null);
assertTrue(session.exists(new PathRef("folder1/file")));
assertTrue(session.exists(new PathRef("folder2/file")));
assertTrue(session.getChildren(folder2.getRef()).contains(copy4));
assertNotSame(copy1.getName(), copy4.getName());
assertNotSame(copy3.getName(), copy4.getName());
// copy inplace
DocumentModel copy5 = session.copy(file.getRef(), folder1.getRef(),
null);
assertTrue(session.exists(new PathRef("folder1/file")));
assertTrue(session.exists(new PathRef("folder2/file")));
assertTrue(session.getChildren(folder1.getRef()).contains(copy5));
assertNotSame(copy1.getName(), copy5.getName());
session.cancel();
}
public void testCopyProxyAsDocument() throws Exception {
// create a folder tree
DocumentModel root = session.getRootDocument();
DocumentModel folder1 = new DocumentModelImpl(root.getPathAsString(),
"folder1", "Folder");
DocumentModel folder2 = new DocumentModelImpl(root.getPathAsString(),
"folder2", "Folder");
DocumentModel folder3 = new DocumentModelImpl(root.getPathAsString(),
"folder3", "Folder");
DocumentModel file = new DocumentModelImpl(folder1.getPathAsString(),
"copyProxyAsDocument_test", "File");
folder1 = createChildDocument(folder1);
folder2 = createChildDocument(folder2);
folder3 = createChildDocument(folder3);
file = createChildDocument(file);
session.save();
// create a file in folder 1
file.setProperty("dublincore", "title", "the title");
file = session.saveDocument(file);
// create a proxy in folder2
DocumentModel proxy = session.publishDocument(file, folder2);
assertTrue(proxy.isProxy());
// copy proxy into folder3
DocumentModel copy1 = session.copyProxyAsDocument(proxy.getRef(),
folder3.getRef(), null);
assertFalse(copy1.isProxy());
assertEquals(proxy.getName(), copy1.getName());
assertEquals(proxy.getProperty("dublincore", "title"),
copy1.getProperty("dublincore", "title"));
// copy proxy using another name
DocumentModel copy2 = session.copyProxyAsDocument(proxy.getRef(),
folder3.getRef(), "foo");
assertFalse(copy2.isProxy());
assertEquals("foo", copy2.getName());
assertEquals(file.getProperty("dublincore", "title"),
copy2.getProperty("dublincore", "title"));
session.cancel();
}
public void testCopyVersionable() throws Exception {
DocumentModel note = new DocumentModelImpl("/", "note", "Note");
DocumentModel folder = new DocumentModelImpl("/", "folder", "Folder");
note = session.createDocument(note);
folder = session.createDocument(folder);
session.save();
assertTrue(session.exists(new PathRef("note")));
assertTrue(session.exists(new PathRef("folder")));
// no versions at first
List<DocumentRef> versions = session.getVersionsRefs(note.getRef());
assertEquals(0, versions.size());
// version the note
note.setProperty("dublincore", "title", "blah");
ScopedMap context = note.getContextData();
context.putScopedValue(ScopeType.REQUEST,
VersioningDocument.CREATE_SNAPSHOT_ON_SAVE_KEY, Boolean.TRUE);
session.saveDocument(note);
session.save();
// check versions
versions = session.getVersionsRefs(note.getRef());
assertEquals(1, versions.size());
// copy
DocumentModel copy = session.copy(note.getRef(), folder.getRef(), null);
// check no versions on copy
versions = session.getVersionsRefs(copy.getRef());
assertEquals(0, versions.size());
session.cancel();
}
public void testCopyFolderOfVersionable() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel folder = new DocumentModelImpl("/", "folder", "Folder");
DocumentModel note = new DocumentModelImpl("/folder", "note", "Note");
folder = session.createDocument(folder);
note = session.createDocument(note);
session.save();
assertTrue(session.exists(new PathRef("/folder")));
assertTrue(session.exists(new PathRef("/folder/note")));
// no versions at first
List<DocumentRef> versions = session.getVersionsRefs(note.getRef());
assertEquals(0, versions.size());
// version the note
note.setProperty("dublincore", "title", "blah");
ScopedMap context = note.getContextData();
context.putScopedValue(ScopeType.REQUEST,
VersioningDocument.CREATE_SNAPSHOT_ON_SAVE_KEY, Boolean.TRUE);
session.saveDocument(note);
session.save();
// check versions
versions = session.getVersionsRefs(note.getRef());
assertEquals(1, versions.size());
// copy folder, use an all-digit name to test for xpath escaping
DocumentModel copy = session.copy(folder.getRef(), root.getRef(), "123");
// check no versions on copied note
DocumentModel note2 = session.getChild(copy.getRef(), "note");
versions = session.getVersionsRefs(note2.getRef());
assertEquals(0, versions.size());
session.cancel();
}
public void testMove() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel folder1 = new DocumentModelImpl(root.getPathAsString(),
"folder1", "Folder");
DocumentModel folder2 = new DocumentModelImpl(root.getPathAsString(),
"folder2", "Folder");
DocumentModel file = new DocumentModelImpl(folder1.getPathAsString(),
"file", "File");
folder1 = createChildDocument(folder1);
folder2 = createChildDocument(folder2);
file = createChildDocument(file);
assertTrue(session.exists(new PathRef("folder1/file")));
assertFalse(session.exists(new PathRef("folder2/file")));
assertFalse(session.exists(new PathRef("folder1/fileMove")));
// move using orig name
session.move(file.getRef(), folder2.getRef(), null);
assertFalse(session.exists(new PathRef("folder1/file")));
assertTrue(session.exists(new PathRef("folder2/file")));
file = session.getChild(folder2.getRef(), "file");
session.move(file.getRef(), folder1.getRef(), "fileMove");
assertTrue(session.exists(new PathRef("folder1/fileMove")));
DocumentModel file2 = new DocumentModelImpl(folder2.getPathAsString(),
"file2", "File");
file2 = createChildDocument(file2);
assertTrue(session.exists(new PathRef("folder2/file2")));
DocumentModel newFile2 = session.move(file.getRef(), folder2.getRef(),
"file2"); // collision
String newName = newFile2.getName();
assertFalse("file2".equals(newName));
assertTrue(session.exists(new PathRef("folder2/file2")));
assertTrue(session.exists(new PathRef("folder2/" + newName)));
// move with null dest (rename)
DocumentModel newFile3 = session.move(file.getRef(), null, "file3");
assertEquals("file3", newFile3.getName());
}
// TODO: fix this test
public void XXXtestScalarList() throws Exception {
DocumentModel root = session.getRootDocument();
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
String[] str = { "a", "b", "c" };
childFile.setProperty("dublincore", "participants", str);
session.saveDocument(childFile);
childFile = session.getChild(root.getRef(), childFile.getName());
str = (String[]) childFile.getProperty("dublincore", "participants");
assertNotNull(str);
List<String> list = Arrays.asList(str);
assertTrue(list.contains("a"));
assertTrue(list.contains("b"));
assertTrue(list.contains("c"));
// modify the array
str = new String[] { "a", "b" };
childFile.setProperty("dublincore", "participants", str);
session.saveDocument(childFile);
str = (String[]) childFile.getProperty("dublincore", "participants");
childFile = session.getChild(root.getRef(), childFile.getName());
str = (String[]) childFile.getProperty("dublincore", "participants");
assertNotNull(str);
list = Arrays.asList(str);
assertTrue(list.contains("a"));
assertTrue(list.contains("b"));
}
public void testBlob() throws Exception {
DocumentModel root = session.getRootDocument();
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
session.save();
byte[] bytes = FileUtils.readBytes(Blob.class.getResourceAsStream("Blob.class"));
Blob blob = new ByteArrayBlob(bytes, "java/class");
blob.setDigest("XXX");
blob.setFilename("blob.txt");
blob.setEncoding("UTF8");
long length = blob.getLength();
byte[] content = blob.getByteArray();
childFile.setProperty("file", "filename", "deprectaed filename");
childFile.setProperty("dublincore", "title", "Blob test");
childFile.setProperty("dublincore", "description", "this is a test");
childFile.setProperty("file", "content", blob);
session.saveDocument(childFile);
childFile = session.getDocument(childFile.getRef());
blob = (Blob) childFile.getProperty("file", "content");
assertEquals("XXX", blob.getDigest());
assertEquals("blob.txt", blob.getFilename());
assertEquals(length, blob.getLength());
assertEquals("UTF8", blob.getEncoding());
assertEquals("java/class", blob.getMimeType());
assertTrue(Arrays.equals(content, blob.getByteArray()));
}
public void testRetrieveSamePropertyInAncestors() throws ClientException {
DocumentModel root = session.getRootDocument();
DocumentModel folder1 = new DocumentModelImpl(root.getPathAsString(),
"folder1", "Folder");
folder1 = createChildDocument(folder1);
folder1.setProperty("dublincore", "title", "folder #1");
assertEquals("folder #1", folder1.getProperty("dublincore", "title"));
DocumentModel folder2 = new DocumentModelImpl(
folder1.getPathAsString(), "folder2", "Folder");
folder2 = createChildDocument(folder2);
folder2.setProperty("dublincore", "title", "folder #2");
assertEquals("folder #2", folder2.getProperty("dublincore", "title"));
DocumentModel file = new DocumentModelImpl(folder2.getPathAsString(),
"file", "File");
file = createChildDocument(file);
file.setProperty("dublincore", "title", "file ##");
assertEquals("file ##", file.getProperty("dublincore", "title"));
assertTrue(session.exists(new PathRef("/folder1")));
assertTrue(session.exists(new PathRef("folder1/folder2")));
assertTrue(session.exists(new PathRef("folder1/folder2/file")));
// need to save them before getting properties from schemas...
session.saveDocument(folder1);
session.saveDocument(folder2);
session.saveDocument(file);
session.save();
final DocumentRef[] ancestorRefs = session.getParentDocumentRefs(file.getRef());
assertNotNull(ancestorRefs);
assertEquals(3, ancestorRefs.length);
assertEquals(folder2.getRef(), ancestorRefs[0]);
assertEquals(folder1.getRef(), ancestorRefs[1]);
assertEquals(root.getRef(), ancestorRefs[2]);
final Object[] fieldValues = session.getDataModelsField(ancestorRefs,
"dublincore", "title");
assertNotNull(fieldValues);
assertEquals(3, fieldValues.length);
assertEquals("folder #2", fieldValues[0]);
assertEquals("folder #1", fieldValues[1]);
final Object[] fieldValuesBis = session.getDataModelsFieldUp(
file.getRef(), "dublincore", "title");
assertNotNull(fieldValuesBis);
assertEquals(4, fieldValuesBis.length);
assertEquals("file ##", fieldValuesBis[0]);
assertEquals("folder #2", fieldValuesBis[1]);
assertEquals("folder #1", fieldValuesBis[2]);
}
// TODO: fix and reenable.
public void XXXtestDocumentAdapter() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel file = new DocumentModelImpl(root.getPathAsString(),
"file", "File");
file = createChildDocument(file);
/*
* AnnotatedDocument adoc = file.getAdapter(AnnotatedDocument.class);
* assertNotNull(adoc); adoc.putAnnotation("key1", "val1");
* adoc.putAnnotation("key2", "val2"); assertEquals("val1",
* adoc.getAnnotation("key1")); assertEquals("val2",
* adoc.getAnnotation("key2"));
*
* adoc = file.getAdapter(AnnotatedDocument.class); assertEquals("val1",
* adoc.getAnnotation("key1")); assertEquals("val2",
* adoc.getAnnotation("key2"));
*/
}
public void testGetSourceId() throws ClientException {
DocumentModel root = session.getRootDocument();
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
// Same identifier here since no version yet.
String sourceId = childFile.getSourceId();
assertNotNull(sourceId);
assertEquals(childFile.getId(), sourceId);
session.save();
session.checkIn(childFile.getRef(), null, null);
// Different source ids now.
assertNotNull(childFile.getSourceId());
assertEquals(sourceId, childFile.getSourceId());
// TODO: look at this test.
// assertFalse(childFile.getId().equals(childFile.getSourceId()));
}
public void testGetRepositoryName() throws ClientException {
DocumentModel root = session.getRootDocument();
String name2 = "file#" + generateUnique();
DocumentModel childFile = new DocumentModelImpl(root.getPathAsString(),
name2, "File");
childFile = createChildDocument(childFile);
assertNotNull(childFile.getRepositoryName());
assertEquals("test", childFile.getRepositoryName());
}
// TODO: fix and reenable, is this a bug?
public void XXXtestRetrieveProxies() throws ClientException {
DocumentModel root = session.getRootDocument();
// Section A
String name = "section" + generateUnique();
DocumentModel sectionA = new DocumentModelImpl(root.getPathAsString(),
name, "Section");
sectionA = createChildDocument(sectionA);
assertEquals("Section", sectionA.getType());
assertEquals(name, sectionA.getName());
// Section B
name = "section" + generateUnique();
DocumentModel sectionB = new DocumentModelImpl(root.getPathAsString(),
name, "Section");
sectionB = createChildDocument(sectionB);
assertEquals("Section", sectionB.getType());
assertEquals(name, sectionB.getName());
// File
name = "file" + generateUnique();
DocumentModel file = new DocumentModelImpl(root.getPathAsString(),
name, "File");
file = createChildDocument(file);
assertEquals("File", file.getType());
assertEquals(name, file.getName());
// Versioning
// session.saveDocumentAsNewVersion(file);
// Publishing
session.publishDocument(file, sectionA);
// session.publishDocument(file, sectionB);
// Retrieving proxies
DocumentModelList proxies = session.getProxies(file.getRef(),
sectionA.getRef());
assertFalse(proxies.isEmpty());
assertEquals(1, proxies.size());
// assertEquals(2, proxies.size());
}
public void testCreateDocumentModel() throws ClientException {
// first method: only the typename
DocumentModel docModel = session.createDocumentModel("File");
assertEquals("File", docModel.getType());
// bad type should fail with ClientException
try {
session.createDocumentModel("NotAValidTypeName");
fail();
} catch (ClientException e) {
}
// same as previously with path info
docModel = session.createDocumentModel("/path/to/parent", "some-id",
"File");
assertEquals("File", docModel.getType());
assertEquals("/path/to/parent/some-id", docModel.getPathAsString());
// providing additional contextual data to feed a core event listener
// with
Map<String, Object> context = new HashMap<String, Object>();
context.put("Meteo", "Today is a beautiful day");
docModel = session.createDocumentModel("File", context);
assertEquals("File", docModel.getType());
}
@SuppressWarnings({ "unchecked" })
public void testCopyContent() throws ClientException {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"original", "File");
doc.setProperty("dublincore", "title", "t");
doc.setProperty("dublincore", "description", "d");
doc.setProperty("dublincore", "subjects", new String[] { "a", "b" });
doc.setProperty("file", "filename", "f");
List<Object> files = new ArrayList<Object>(2);
Map<String, Object> f = new HashMap<String, Object>();
f.put("filename", "f1");
files.add(f);
f = new HashMap<String, Object>();
f.put("filename", "f2");
f.put("file", new StringBlob("myfile", "text/test", "UTF-8"));
files.add(f);
doc.setProperty("files", "files", files);
doc = session.createDocument(doc);
session.save();
DocumentModel copy = new DocumentModelImpl(root.getPathAsString(),
"copy", "File");
copy.copyContent(doc);
copy = session.createDocument(copy);
session.save();
assertEquals("t", copy.getProperty("dublincore", "title"));
assertEquals("d", copy.getProperty("dublincore", "description"));
assertEquals(Arrays.asList("a", "b"),
Arrays.asList((String[]) copy.getProperty("dublincore",
"subjects")));
assertEquals("f", copy.getProperty("file", "filename"));
Object fileso = copy.getProperty("files", "files");
assertNotNull(fileso);
List<Map<String, Object>> newfiles = (List<Map<String, Object>>) fileso;
assertEquals(2, newfiles.size());
assertEquals("f1", newfiles.get(0).get("filename"));
assertEquals("f2", newfiles.get(1).get("filename"));
Blob bb = (Blob) newfiles.get(1).get("file");
assertNotNull(bb);
assertEquals("text/test", bb.getMimeType());
assertEquals("UTF-8", bb.getEncoding());
String content;
try {
content = bb.getString();
} catch (IOException e) {
throw new ClientException(e);
}
assertEquals("myfile", content);
}
@SuppressWarnings("unchecked")
public void testDocumentModelTreeSort() throws Exception {
// create a folder tree
DocumentModel root = session.getRootDocument();
DocumentModel a_folder = new DocumentModelImpl(root.getPathAsString(),
"a_folder", "Folder");
a_folder.setProperty("dublincore", "title", "Z title for a_folder");
DocumentModel b_folder = new DocumentModelImpl(root.getPathAsString(),
"b_folder", "Folder");
b_folder.setProperty("dublincore", "title", "B title for b_folder");
DocumentModel c_folder = new DocumentModelImpl(root.getPathAsString(),
"c_folder", "Folder");
c_folder.setProperty("dublincore", "title", "C title for c_folder");
DocumentModel a1_folder = new DocumentModelImpl(
a_folder.getPathAsString(), "a1_folder", "Folder");
a1_folder.setProperty("dublincore", "title", "ZZ title for a1_folder");
DocumentModel a2_folder = new DocumentModelImpl(
a_folder.getPathAsString(), "a2_folder", "Folder");
a2_folder.setProperty("dublincore", "title", "AA title for a2_folder");
DocumentModel b1_folder = new DocumentModelImpl(
b_folder.getPathAsString(), "b1_folder", "Folder");
b1_folder.setProperty("dublincore", "title", "A title for b1_folder");
DocumentModel b2_folder = new DocumentModelImpl(
b_folder.getPathAsString(), "b2_folder", "Folder");
b2_folder.setProperty("dublincore", "title", "B title for b2_folder");
a_folder = createChildDocument(a_folder);
b_folder = createChildDocument(b_folder);
c_folder = createChildDocument(c_folder);
a1_folder = createChildDocument(a1_folder);
a2_folder = createChildDocument(a2_folder);
b1_folder = createChildDocument(b1_folder);
b2_folder = createChildDocument(b2_folder);
DocumentModelTreeImpl tree = new DocumentModelTreeImpl();
tree.add(a_folder, 1);
tree.add(a1_folder, 2);
tree.add(a2_folder, 2);
tree.add(b_folder, 1);
tree.add(b1_folder, 2);
tree.add(b2_folder, 2);
tree.add(c_folder, 1);
// sort using title
DocumentModelTreeNodeComparator comp = new DocumentModelTreeNodeComparator(
tree.getPathTitles());
Collections.sort((ArrayList) tree, comp);
assertEquals(b_folder, tree.get(0).getDocument());
assertEquals(b1_folder, tree.get(1).getDocument());
assertEquals(b2_folder, tree.get(2).getDocument());
assertEquals(c_folder, tree.get(3).getDocument());
assertEquals(a_folder, tree.get(4).getDocument());
assertEquals(a2_folder, tree.get(5).getDocument());
assertEquals(a1_folder, tree.get(6).getDocument());
session.cancel();
}
// ------------------------------------
// ----- copied from TestLocalAPI -----
// ------------------------------------
public void testPropertyModel() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"theDoc", "MyDocType");
doc = session.createDocument(doc);
DocumentPart dp = doc.getPart("myschema");
Property p = dp.get("long");
assertTrue(p.isPhantom());
assertNull(p.getValue());
p.setValue(12);
assertEquals(new Long(12), p.getValue());
session.saveDocument(doc);
dp = doc.getPart("myschema");
p = dp.get("long");
assertFalse(p.isPhantom());
assertEquals(new Long(12), p.getValue());
p.setValue(null);
assertFalse(p.isPhantom());
assertNull(p.getValue());
session.saveDocument(doc);
dp = doc.getPart("myschema");
p = dp.get("long");
// assertTrue(p.isPhantom());
assertNull(p.getValue());
p.setValue(new Long(13));
p.remove();
assertTrue(p.isRemoved());
assertNull(p.getValue());
session.saveDocument(doc);
dp = doc.getPart("myschema");
p = dp.get("long");
// assertTrue(p.isPhantom()); not applicable to SQL
assertNull(p.getValue());
}
public void testOrdering() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel parent = new DocumentModelImpl(root.getPathAsString(),
"theParent", "OrderedFolder");
parent = session.createDocument(parent);
DocumentModel doc1 = new DocumentModelImpl(parent.getPathAsString(),
"the1", "File");
doc1 = session.createDocument(doc1);
DocumentModel doc2 = new DocumentModelImpl(parent.getPathAsString(),
"the2", "File");
doc2 = session.createDocument(doc2);
session.save(); // XXX
String name1 = doc1.getName();
String name2 = doc2.getName();
DocumentModelList children = session.getChildren(parent.getRef());
assertEquals(2, children.size());
assertEquals(name1, children.get(0).getName());
assertEquals(name2, children.get(1).getName());
session.orderBefore(parent.getRef(), name2, name1);
children = session.getChildren(parent.getRef());
assertEquals(2, children.size());
assertEquals(name2, children.get(0).getName());
assertEquals(name1, children.get(1).getName());
session.orderBefore(parent.getRef(), name2, null);
children = session.getChildren(parent.getRef());
assertEquals(2, children.size());
assertEquals(name1, children.get(0).getName());
assertEquals(name2, children.get(1).getName());
}
public void testPropertyXPath() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel parent = new DocumentModelImpl(root.getPathAsString(),
"theParent", "OrderedFolder");
parent = session.createDocument(parent);
DocumentModel doc = new DocumentModelImpl(parent.getPathAsString(),
"theDoc", "File");
doc.setProperty("dublincore", "title", "my title");
assertEquals("my title", doc.getPropertyValue("dc:title"));
doc.setProperty("file", "filename", "the file name");
assertEquals("the file name", doc.getPropertyValue("filename"));
assertEquals("the file name", doc.getPropertyValue("file:filename"));
}
@SuppressWarnings("unchecked")
public void testComplexList() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"mydoc", "MyDocType");
doc = session.createDocument(doc);
List list = (List) doc.getProperty("testList", "attachments");
assertNotNull(list);
assertTrue(list.isEmpty());
ListDiff diff = new ListDiff();
/*
* diff.add(new Attachment("at1", "value1").asMap()); diff.add(new
* Attachment("at2", "value2").asMap()); doc.setProperty("testList",
* "attachments", diff); doc = session.saveDocument(doc);
*
* list = (List) doc.getProperty("testList", "attachments");
* assertNotNull(list); assertEquals(2, list.size());
*
* Blob blob; blob = (Blob) ((Map) list.get(0)).get("content");
* assertEquals("value1", blob.getString()); blob = (Blob) ((Map)
* list.get(1)).get("content"); assertEquals("value2",
* blob.getString());
*
* diff = new ListDiff(); diff.remove(0); diff.insert(0, new
* Attachment("at1.bis", "value1.bis").asMap());
* doc.setProperty("testList", "attachments", diff); doc =
* session.saveDocument(doc);
*
* list = (List) doc.getProperty("testList", "attachments");
* assertNotNull(list); assertEquals(2, list.size());
*
* blob = (Blob) ((Map) list.get(0)).get("content");
* assertEquals("value1.bis", blob.getString()); blob = (Blob) ((Map)
* list.get(1)).get("content"); assertEquals("value2",
* blob.getString());
*
* diff = new ListDiff(); diff.move(0, 1); doc.setProperty("testList",
* "attachments", diff); doc = session.saveDocument(doc);
*
* list = (List) doc.getProperty("testList", "attachments");
* assertNotNull(list); assertEquals(2, list.size()); blob = (Blob)
* ((Map) list.get(0)).get("content"); assertEquals("value2",
* blob.getString()); blob = (Blob) ((Map) list.get(1)).get("content");
* assertEquals("value1.bis", blob.getString());
*
* diff = new ListDiff(); diff.removeAll(); doc.setProperty("testList",
* "attachments", diff); doc = session.saveDocument(doc);
*
* list = (List) doc.getProperty("testList", "attachments");
* assertNotNull(list); assertEquals(0, list.size());
*/
}
public void testDataModel() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"mydoc", "Book");
doc = session.createDocument(doc);
DataModel dm = doc.getDataModel("book");
dm.setValue("title", "my title");
assertEquals("my title", dm.getValue("title"));
dm.setValue("title", "my title2");
assertEquals("my title2", dm.getValue("title"));
dm.setValue("price", 123);
assertEquals(123L, dm.getValue("price"));
dm.setValue("price", 124);
assertEquals(124L, dm.getValue("price"));
dm.setValue("author/pJob", "Programmer");
assertEquals("Programmer", dm.getValue("author/pJob"));
dm.setValue("author/pJob", "Programmer2");
assertEquals("Programmer2", dm.getValue("author/pJob"));
dm.setValue("author/pName/FirstName", "fname");
assertEquals("fname", dm.getValue("author/pName/FirstName"));
dm.setValue("author/pName/FirstName", "fname2");
assertEquals("fname2", dm.getValue("author/pName/FirstName"));
// list test
doc = new DocumentModelImpl(root.getPathAsString(), "mydoc2",
"MyDocType");
doc = session.createDocument(doc);
List list = (List) doc.getProperty("testList", "attachments");
assertNotNull(list);
assertTrue(list.isEmpty());
ListDiff diff = new ListDiff();
/*
* diff.add(new Attachment("at1", "value1").asMap()); diff.add(new
* Attachment("at2", "value2").asMap()); doc.setProperty("testList",
* "attachments", diff); doc = session.saveDocument(doc);
*
* dm = doc.getDataModel("testList");
*
* dm.setValue("attachments/item[0]/name", "at1-modif");
* assertEquals("at1-modif", dm.getValue("attachments/item[0]/name"));
* dm.setValue("attachments/item[0]/name", "at1-modif2");
* assertEquals("at1-modif2", dm.getValue("attachments/item[0]/name"));
* dm.setValue("attachments/item[1]/name", "at2-modif");
* assertEquals("at2-modif", dm.getValue("attachments/item[1]/name"));
* dm.setValue("attachments/item[1]/name", "at2-modif2");
* assertEquals("at2-modif2", dm.getValue("attachments/item[1]/name"));
*/
}
public void testGetChildrenRefs() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"mydoc", "Book");
doc = session.createDocument(doc);
DocumentModel doc2 = new DocumentModelImpl(root.getPathAsString(),
"mydoc2", "MyDocType");
doc2 = session.createDocument(doc2);
List<DocumentRef> childrenRefs = session.getChildrenRefs(root.getRef(),
null);
assertEquals(2, childrenRefs.size());
Set<String> expected = new HashSet<String>();
expected.add(doc.getId());
expected.add(doc2.getId());
Set<String> actual = new HashSet<String>();
actual.add(childrenRefs.get(0).toString());
actual.add(childrenRefs.get(1).toString());
assertEquals(expected, actual);
}
public void testProxyChildren() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc1 = new DocumentModelImpl(root.getPathAsString(),
"doc1", "Book");
doc1 = session.createDocument(doc1);
DocumentModel doc2 = new DocumentModelImpl(root.getPathAsString(),
"doc2", "Book");
doc2 = session.createDocument(doc2);
// create proxy pointing to doc1
DocumentModel proxy1 = session.publishDocument(doc1, root);
// check proxy1 children methods
DocumentModelList children = session.getChildren(proxy1.getRef());
assertEquals(0, children.size());
assertFalse(session.hasChildren(proxy1.getRef()));
// create proxy pointing to doc2, under proxy1
DocumentModel proxy2 = session.publishDocument(doc2, proxy1);
session.save();
// check that sub proxy really exists
assertEquals(proxy2, session.getDocument(proxy2.getRef()));
// check proxy1 children methods
children = session.getChildren(proxy1.getRef());
assertEquals(1, children.size());
assertEquals(proxy2, children.get(0));
assertEquals(proxy2,
session.getChild(proxy1.getRef(), proxy2.getName()));
assertTrue(session.hasChildren(proxy1.getRef()));
}
public static byte[] createBytes(int size, byte val) {
byte[] bytes = new byte[size];
Arrays.fill(bytes, val);
return bytes;
}
// badly named
public void testLazyBlob() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"mydoc", "File");
doc = session.createDocument(doc);
byte[] bytes = createBytes(1024 * 1024, (byte) 24);
Blob blob = new ByteArrayBlob(bytes);
doc.getPart("file").get("content").setValue(blob);
doc = session.saveDocument(doc);
blob = (Blob) doc.getPart("file").get("content").getValue();
assertTrue(Arrays.equals(bytes, blob.getByteArray()));
// reset not implemented (not needed) for SQLBlob's Binary
// XXX blob.getStream().reset();
blob = (Blob) doc.getPart("file").get("content").getValue();
assertTrue(Arrays.equals(bytes, blob.getByteArray()));
}
public void testProxy() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"proxy_test", "File");
doc = session.createDocument(doc);
doc.setProperty("dublincore", "title", "the title");
doc = session.saveDocument(doc);
DocumentModel proxy = session.publishDocument(doc, root);
session.save();
// re-modify doc
doc.setProperty("dublincore", "title", "the title modified");
doc = session.saveDocument(doc);
assertEquals("the title", proxy.getProperty("dublincore", "title"));
assertEquals("the title modified",
doc.getProperty("dublincore", "title"));
// make another proxy
session.publishDocument(doc, root);
DocumentModelList list = session.getChildren(root.getRef());
assertEquals(2, list.size());
for (DocumentModel model : list) {
assertEquals("File", model.getType());
}
session.removeDocument(proxy.getRef());
list = session.getChildren(root.getRef());
assertEquals(1, list.size());
// create folder to hold proxies
DocumentModel folder = new DocumentModelImpl(root.getPathAsString(),
"folder", "Folder");
folder = session.createDocument(folder);
session.save();
folder = session.getDocument(folder.getRef());
// publishDocument API
proxy = session.publishDocument(doc, root);
session.save(); // needed for publish-by-copy to work
assertEquals(3, session.getChildrenRefs(root.getRef(), null).size());
assertTrue(proxy.isProxy());
assertFalse(proxy.isVersion());
assertTrue(proxy.isImmutable());
assertTrue(proxy.hasFacet(FacetNames.IMMUTABLE)); // dynamic facet
assertTrue(proxy.hasFacet(FacetNames.VERSIONABLE)); // facet from type
// republish a proxy
DocumentModel proxy2 = session.publishDocument(proxy, folder);
session.save();
assertTrue(proxy2.isProxy());
assertFalse(proxy2.isVersion());
assertTrue(proxy2.isImmutable());
assertEquals(1, session.getChildrenRefs(folder.getRef(), null).size());
assertEquals(3, session.getChildrenRefs(root.getRef(), null).size());
// a second time to check overwrite
session.publishDocument(proxy, folder);
session.save();
assertEquals(1, session.getChildrenRefs(folder.getRef(), null).size());
assertEquals(3, session.getChildrenRefs(root.getRef(), null).size());
// and without overwrite
session.publishDocument(proxy, folder, false);
session.save();
assertEquals(2, session.getChildrenRefs(folder.getRef(), null).size());
assertEquals(3, session.getChildrenRefs(root.getRef(), null).size());
// publish a version directly
DocumentModel ver = session.getLastDocumentVersion(doc.getRef());
DocumentModel proxy3 = session.publishDocument(ver, folder, false);
session.save();
assertFalse(proxy3.isVersion());
assertTrue(proxy3.isProxy());
assertEquals(doc.getVersionSeriesId(), proxy3.getVersionSeriesId());
assertEquals(ver.getVersionLabel(), proxy3.getVersionLabel());
}
public void testProxyLive() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"proxy_test", "File");
doc = session.createDocument(doc);
doc.setProperty("dublincore", "title", "the title");
doc = session.saveDocument(doc);
session.save();
// create live proxy
DocumentModel proxy = session.createProxy(doc.getRef(), root.getRef());
assertTrue(proxy.isProxy());
assertFalse(proxy.isVersion());
assertFalse(proxy.isImmutable());
session.save();
assertEquals("the title", proxy.getProperty("dublincore", "title"));
assertEquals("the title", doc.getProperty("dublincore", "title"));
// modify live doc
doc.setProperty("dublincore", "title", "the title modified");
doc = session.saveDocument(doc);
session.save();
// check visible from proxy
proxy = session.getDocument(proxy.getRef());
assertTrue(proxy.isProxy());
assertFalse(proxy.isVersion());
assertFalse(proxy.isImmutable());
assertEquals("the title modified",
proxy.getProperty("dublincore", "title"));
// modify proxy
proxy.setProperty("dublincore", "title", "the title again");
doc = session.saveDocument(proxy);
session.save();
// check visible from live doc
doc = session.getDocument(doc.getRef());
assertEquals("the title again", doc.getProperty("dublincore", "title"));
}
public void testUpdatePublishedDocument() throws Exception {
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"proxy_test", "File");
doc = session.createDocument(doc);
doc.setProperty("dublincore", "title", "the title");
doc = session.saveDocument(doc);
// create folder to hold proxies
DocumentModel folder = new DocumentModelImpl(root.getPathAsString(),
"folder", "Folder");
folder = session.createDocument(folder);
session.save();
folder = session.getDocument(folder.getRef());
// publishDocument API
DocumentModel proxy = session.publishDocument(doc, folder);
session.save();
assertEquals(1, session.getChildrenRefs(folder.getRef(), null).size());
assertEquals("the title", proxy.getProperty("dublincore", "title"));
assertEquals("the title", doc.getProperty("dublincore", "title"));
assertTrue(proxy.isProxy());
assertFalse(proxy.isVersion());
// republish a proxy
DocumentModel proxy2 = session.publishDocument(doc, folder);
session.save();
assertTrue(proxy2.isProxy());
assertFalse(proxy2.isVersion());
assertEquals(1, session.getChildrenRefs(folder.getRef(), null).size());
assertEquals(proxy.getId(), proxy2.getId());
}
public void testImport() throws Exception {
DocumentModel folder = new DocumentModelImpl("/", "folder", "Folder");
folder.setProperty("dublincore", "title", "the title");
folder = session.createDocument(folder);
session.save();
String folderId = folder.getId();
// create a version by import
String id = "aaaaaaaa-1234-1234-1234-fedcba987654"; // versionable
String vid = "12345678-1234-1234-1234-fedcba987654"; // ver id
String typeName = "File";
DocumentRef parentRef = null;
String name = "foobar";
DocumentModel ver = new DocumentModelImpl((String) null, typeName, vid,
new Path(name), null, null, parentRef, null, null, null, null);
Calendar vcr = new GregorianCalendar(2009, Calendar.JANUARY, 1, 2, 3, 4);
ver.putContextData(CoreSession.IMPORT_VERSION_VERSIONABLE_ID, id);
ver.putContextData(CoreSession.IMPORT_VERSION_CREATED, vcr);
ver.putContextData(CoreSession.IMPORT_VERSION_LABEL, "v1");
ver.putContextData(CoreSession.IMPORT_VERSION_DESCRIPTION, "v descr");
ver.putContextData(CoreSession.IMPORT_IS_VERSION, Boolean.TRUE);
ver.putContextData(CoreSession.IMPORT_VERSION_IS_LATEST, Boolean.TRUE);
ver.putContextData(CoreSession.IMPORT_VERSION_IS_LATEST_MAJOR,
Boolean.FALSE);
ver.putContextData(CoreSession.IMPORT_VERSION_MAJOR, Long.valueOf(3));
ver.putContextData(CoreSession.IMPORT_VERSION_MINOR, Long.valueOf(14));
ver.putContextData(CoreSession.IMPORT_LIFECYCLE_POLICY, "v lcp");
ver.putContextData(CoreSession.IMPORT_LIFECYCLE_STATE, "v lcst");
ver.setProperty("dublincore", "title", "Ver title");
Calendar mod = new GregorianCalendar(2008, Calendar.JULY, 14, 12, 34,
56);
ver.setProperty("dublincore", "modified", mod);
session.importDocuments(Collections.singletonList(ver));
session.save();
closeSession();
openSession();
ver = session.getDocument(new IdRef(vid));
// assertEquals(name, doc.getName()); // no path -> no name...
assertEquals("Ver title",
(String) ver.getProperty("dublincore", "title"));
assertEquals(mod, ver.getProperty("dublincore", "modified"));
assertEquals("v lcp", ver.getLifeCyclePolicy());
assertEquals("v lcst", ver.getCurrentLifeCycleState());
assertEquals(Long.valueOf(3), ver.getProperty("uid", "major_version"));
assertEquals(Long.valueOf(14), ver.getProperty("uid", "minor_version"));
assertTrue(ver.isVersion());
assertFalse(ver.isProxy());
// lookup version by label
VersionModel versionModel = new VersionModelImpl();
versionModel.setLabel("v1");
ver = session.getVersion(id, versionModel);
assertNotNull(ver);
assertEquals(vid, ver.getId());
assertEquals("v descr", versionModel.getDescription());
assertEquals(vcr, versionModel.getCreated());
// create a proxy by import
String pid = "00000000-1234-1234-1234-fedcba987654"; // proxy id
typeName = CoreSession.IMPORT_PROXY_TYPE;
parentRef = new IdRef(folderId);
name = "myproxy";
DocumentModel proxy = new DocumentModelImpl((String) null, typeName,
pid, new Path(name), null, null, parentRef, null, null, null,
null);
proxy.putContextData(CoreSession.IMPORT_PROXY_TARGET_ID, vid);
proxy.putContextData(CoreSession.IMPORT_PROXY_VERSIONABLE_ID, id);
session.importDocuments(Collections.singletonList(proxy));
session.save();
closeSession();
openSession();
proxy = session.getDocument(new IdRef(pid));
assertEquals(name, proxy.getName());
assertEquals("Ver title",
(String) proxy.getProperty("dublincore", "title"));
assertEquals(mod, proxy.getProperty("dublincore", "modified"));
assertEquals("v lcp", proxy.getLifeCyclePolicy());
assertEquals("v lcst", proxy.getCurrentLifeCycleState());
assertFalse(proxy.isVersion());
assertTrue(proxy.isProxy());
// create a normal doc by import
typeName = "File";
parentRef = new IdRef(folderId);
name = "mydoc";
DocumentModel doc = new DocumentModelImpl((String) null, typeName, id,
new Path(name), null, null, parentRef, null, null, null, null);
doc.putContextData(CoreSession.IMPORT_LIFECYCLE_POLICY, "lcp");
doc.putContextData(CoreSession.IMPORT_LIFECYCLE_STATE, "lcst");
Calendar lockCreated = new GregorianCalendar(2011, Calendar.JANUARY, 1,
5, 5, 5);
doc.putContextData(CoreSession.IMPORT_LOCK_OWNER, "bob");
doc.putContextData(CoreSession.IMPORT_LOCK_CREATED, lockCreated);
doc.putContextData(CoreSession.IMPORT_CHECKED_IN, Boolean.TRUE);
doc.putContextData(CoreSession.IMPORT_BASE_VERSION_ID, vid);
doc.putContextData(CoreSession.IMPORT_VERSION_MAJOR, Long.valueOf(8));
doc.putContextData(CoreSession.IMPORT_VERSION_MINOR, Long.valueOf(1));
doc.setProperty("dublincore", "title", "Live title");
session.importDocuments(Collections.singletonList(doc));
session.save();
closeSession();
openSession();
doc = session.getDocument(new IdRef(id));
assertEquals(name, doc.getName());
assertEquals("Live title",
(String) doc.getProperty("dublincore", "title"));
assertEquals(folderId, doc.getParentRef().toString());
assertEquals("lcp", doc.getLifeCyclePolicy());
assertEquals("lcst", doc.getCurrentLifeCycleState());
assertEquals(Long.valueOf(8), doc.getProperty("uid", "major_version"));
assertEquals(Long.valueOf(1), doc.getProperty("uid", "minor_version"));
assertTrue(doc.isLocked());
assertEquals("bob", doc.getLockInfo().getOwner());
assertEquals(lockCreated, doc.getLockInfo().getCreated());
assertFalse(doc.isVersion());
assertFalse(doc.isProxy());
}
/**
* Check that lifecycle and dc:issued can be updated on a version. (Fields
* defined in SQLSimpleProperty.VERSION_WRITABLE_PROPS).
*/
public void testVersionUpdatableFields() throws Exception {
Calendar cal1 = new GregorianCalendar(2008, Calendar.JULY, 14, 12, 34,
56);
Calendar cal2 = new GregorianCalendar(2010, Calendar.JANUARY, 1, 0, 0,
0);
Calendar cal3 = new GregorianCalendar(2010, Calendar.APRIL, 11, 11, 11,
11);
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"doc", "File");
doc = session.createDocument(doc);
doc.setProperty("dublincore", "title", "t1");
doc.setProperty("dublincore", "issued", cal1);
doc = session.saveDocument(doc);
session.checkIn(doc.getRef(), null, null);
session.checkOut(doc.getRef());
doc.setProperty("dublincore", "title", "t2");
doc.setProperty("dublincore", "issued", cal2);
doc = session.saveDocument(doc);
// get version
DocumentModel ver = session.getLastDocumentVersion(doc.getRef());
assertTrue(ver.isVersion());
assertEquals("project", ver.getCurrentLifeCycleState());
assertEquals("t1", ver.getProperty("dublincore", "title"));
assertEquals(cal1, ver.getProperty("dublincore", "issued"));
// change lifecycle
ver.followTransition("approve");
// change dc:issued
ver.setProperty("dublincore", "issued", cal3);
session.saveDocument(ver);
session.save();
closeSession();
openSession();
doc = session.getDocument(new PathRef("/doc"));
ver = session.getLastDocumentVersion(doc.getRef());
assertEquals("t1", ver.getProperty("dublincore", "title"));
assertEquals("approved", ver.getCurrentLifeCycleState());
assertEquals(cal3, ver.getProperty("dublincore", "issued"));
}
/**
* Check that the "incrementBeforeUpdate" and "beforeDocumentModification"
* are not fired on a DocumentModel where the {@code isImmutable()} returns
* {@code true}.
*/
public void testDoNotFireBeforeUpdateEventsOnVersion() throws Exception {
deployContrib("org.nuxeo.ecm.core.storage.sql.test.tests",
"OSGI-INF/test-listeners-contrib.xml");
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"doc", "File");
doc = session.createDocument(doc);
doc.setProperty("dublincore", "title", "t1");
doc = session.saveDocument(doc);
session.checkIn(doc.getRef(), null, null);
session.checkOut(doc.getRef());
doc.setProperty("dublincore", "title", "t2");
doc = session.saveDocument(doc);
session.save();
// Reset the listener
DummyTestListener.EVENTS_RECEIVED.clear();
DocumentModel versionDoc = session.getLastDocumentVersion(doc.getRef());
versionDoc.setProperty("dublincore", "issued", new GregorianCalendar());
session.saveDocument(versionDoc);
session.save();
assertTrue(DummyTestListener.EVENTS_RECEIVED.isEmpty());
}
@SuppressWarnings("unchecked")
public void testInvalidationEvents() throws Exception {
Event event;
Boolean local;
Set<String> set;
deployContrib("org.nuxeo.ecm.core.storage.sql.test.tests",
"OSGI-INF/test-listeners-invalidations-contrib.xml");
DocumentModel root = session.getRootDocument();
DocumentModel doc = new DocumentModelImpl(root.getPathAsString(),
"doc", "File");
doc = session.createDocument(doc);
DummyTestListener.EVENTS_RECEIVED.clear();
session.save(); // should send invalidations
assertEquals(1, DummyTestListener.EVENTS_RECEIVED.size());
event = DummyTestListener.EVENTS_RECEIVED.get(0);
// NXP-5808 cannot distinguish cluster invalidations
// local = (Boolean) event.getContext().getProperty(
// EventConstants.INVAL_LOCAL);
// assertEquals(Boolean.TRUE, local);
set = (Set<String>) event.getContext().getProperty(
EventConstants.INVAL_MODIFIED_DOC_IDS);
assertEquals(1, set.size()); // doc created seen as modified
set = (Set<String>) event.getContext().getProperty(
EventConstants.INVAL_MODIFIED_PARENT_IDS);
assertEquals(2, set.size());
// spurious doc "parent" modified, due to its complex property
assertEquals(
new HashSet<String>(Arrays.asList(doc.getId(), root.getId())),
set);
// change just one property
doc.setProperty("dublincore", "title", "t1");
doc = session.saveDocument(doc);
DummyTestListener.EVENTS_RECEIVED.clear();
session.save(); // should send invalidations
assertEquals(1, DummyTestListener.EVENTS_RECEIVED.size());
event = DummyTestListener.EVENTS_RECEIVED.get(0);
// NXP-5808 cannot distinguish cluster invalidations
// local = (Boolean) event.getContext().getProperty(
// EventConstants.INVAL_LOCAL);
// assertEquals(Boolean.TRUE, local);
set = (Set<String>) event.getContext().getProperty(
EventConstants.INVAL_MODIFIED_DOC_IDS);
assertEquals(1, set.size());
assertEquals(doc.getId(), set.iterator().next());
set = (Set<String>) event.getContext().getProperty(
EventConstants.INVAL_MODIFIED_PARENT_IDS);
assertEquals(0, set.size());
}
public void testPlacelessDocument() throws Exception {
DocumentModel doc = new DocumentModelImpl((String) null, "mydoc",
"MyDocType");
doc.setProperty("dublincore", "title", "The title");
doc = session.createDocument(doc);
assertNull(doc.getParentRef()); // placeless
session.save();
DocumentModel doc2 = session.createDocumentModel(null, "other",
"MyDocType");
doc2.setProperty("dublincore", "title", "Other");
doc2 = session.createDocument(doc2);
assertNull(doc2.getParentRef()); // placeless
session.save();
closeSession();
// ----- new session -----
openSession();
doc = session.getDocument(new IdRef(doc.getId()));
assertNull(doc.getParentRef());
assertEquals("The title",
(String) doc.getProperty("dublincore", "title"));
assertNull(doc.getProperty("dublincore", "description"));
doc2 = session.getDocument(new IdRef(doc2.getId()));
assertNull(doc2.getParentRef());
// remove
session.removeDocument(doc.getRef());
session.save();
}
public void testRelation() throws Exception {
DocumentModel rel = session.createDocumentModel(null, "myrel",
"Relation");
rel.setProperty("relation", "source", "1234");
rel.setProperty("dublincore", "title", "My Rel");
rel = session.createDocument(rel);
assertNull(rel.getParentRef()); // placeless
session.save();
// query
String query = "SELECT * FROM Relation WHERE relation:source = '1234'";
DocumentModelList list = session.query(query);
assertEquals(1, list.size());
DocumentModel doc = list.get(0);
assertNull(doc.getParentRef());
assertEquals("My Rel", doc.getProperty("dublincore", "title"));
// remove
session.removeDocument(rel.getRef());
session.save();
list = session.query(query);
assertEquals(0, list.size());
}
/**
* Checks that a before document modification event can change the
* DocumentModel name and provoke a rename. And that PREVIOUS_DOCUMENT_MODEL
* received by the event holds the correct info.
*/
public void testBeforeModificationListenerRename() throws Exception {
deployContrib("org.nuxeo.ecm.core.storage.sql.test.tests",
"OSGI-INF/test-listener-beforemod-contrib.xml");
DocumentModel doc = session.createDocumentModel("/", "doc", "File");
doc.setProperty("dublincore", "title", "t1");
doc = session.createDocument(doc);
session.save();
assertEquals("t1-rename", doc.getName());
doc.setProperty("dublincore", "title", "t2");
DummyBeforeModificationListener.previousTitle = null;
doc = session.saveDocument(doc);
session.save();
assertEquals("t2-rename", doc.getName());
assertEquals("/t2-rename", doc.getPathAsString());
assertEquals("t1", DummyBeforeModificationListener.previousTitle);
}
public void testObsoleteType() throws Throwable {
DocumentRef rootRef = session.getRootDocument().getRef();
DocumentModel doc = session.createDocumentModel("/", "doc", "MyDocType");
doc = session.createDocument(doc);
DocumentRef docRef = new IdRef(doc.getId());
session.save();
assertEquals(1, session.getChildren(rootRef).size());
assertNotNull(session.getDocument(docRef));
assertNotNull(session.getChild(rootRef, "doc"));
closeSession();
openSession();
// remove MyDocType from known types
SchemaManager schemaManager = Framework.getService(SchemaManager.class);
schemaManager.unregisterDocumentType("MyDocType");
assertEquals(0, session.getChildren(rootRef).size());
try {
session.getDocument(docRef);
fail("shouldn't be able to get doc with obsolete type");
} catch (ClientException e) {
assertTrue(e.getMessage(),
e.getMessage().contains("Failed to get document"));
}
try {
session.getChild(rootRef, "doc");
fail("shouldn't be able to get doc with obsolete type");
} catch (ClientException e) {
assertTrue(e.getMessage(),
e.getMessage().contains("Failed to get child doc"));
}
}
}
| false | true | public void testComplexType() throws Exception {
// boiler plate to handle the asynchronous full-text indexing of blob
// content in a deterministic way
EventServiceImpl eventService = (EventServiceImpl) Framework.getLocalService(EventService.class);
deployBundle("org.nuxeo.ecm.core.convert");
deployBundle("org.nuxeo.ecm.core.convert.plugins");
DocumentModel doc = new DocumentModelImpl("/", "complex-doc",
"ComplexDoc");
doc = session.createDocument(doc);
DocumentRef docRef = doc.getRef();
session.save();
// test setting and reading a map with an empty list
closeSession();
openSession();
doc = session.getDocument(docRef);
Map<String, Object> attachedFile = new HashMap<String, Object>();
List<Map<String, Object>> vignettes = new ArrayList<Map<String, Object>>();
attachedFile.put("name", "some name");
attachedFile.put("vignettes", vignettes);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
doc = session.getDocument(docRef);
assertEquals(attachedFile,
doc.getProperty("cmpf:attachedFile").getValue());
assertEquals(attachedFile.get("vignettes"),
doc.getProperty("cmpf:attachedFile/vignettes").getValue());
// test fulltext indexing of complex property at level one
DocumentModelList results = session.query(
"SELECT * FROM Document WHERE ecm:fulltext = 'some name'", 1);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test setting and reading a list of maps without a complex type in the
// maps
Map<String, Object> vignette = new HashMap<String, Object>();
vignette.put("width", Long.valueOf(0));
vignette.put("height", Long.valueOf(0));
vignette.put(
"content",
StreamingBlob.createFromString("textblob content", "text/plain"));
vignette.put("label", "vignettelabel");
vignettes.add(vignette);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
doc = session.getDocument(docRef);
assertEquals(
"text/plain",
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/content/mime-type").getValue());
assertEquals(
Long.valueOf(0),
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/height").getValue());
assertEquals(
"vignettelabel",
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/label").getValue());
// test fulltext indexing of complex property at level 3
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'vignettelabel'", 2);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test fulltext indexing of complex property at level 3 in blob
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'textblob content'", 2);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test setting and reading a list of maps with a blob inside the map
byte[] binaryContent = "01AB".getBytes();
Blob blob = StreamingBlob.createFromByteArray(binaryContent,
"application/octet-stream");
blob.setFilename("file.bin");
vignette.put("content", blob);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
assertEquals(
Long.valueOf(0),
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/height").getValue());
assertEquals(
"vignettelabel",
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/label").getValue());
// this doesn't work due to core restrictions (BlobProperty):
// assertEquals(blob.getFilename(), doc.getProperty(
// "cmpf:attachedFile/vignettes/vignette[0]/content/name").getValue());
Blob b = (Blob) doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/content").getValue();
assertEquals("file.bin", b.getFilename());
// test deleting the list of vignette and ensure that the fulltext index
// has been properly updated (regression test for NXP-6315)
doc.setPropertyValue("cmpf:attachedFile/vignettes",
new ArrayList<Map<String, Object>>());
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'vignettelabel'", 2);
assertNotNull(results);
assertEquals(0, results.size());
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'textblob content'", 2);
assertNotNull(results);
assertEquals(0, results.size());
}
| public void testComplexType() throws Exception {
// boiler plate to handle the asynchronous full-text indexing of blob
// content in a deterministic way
EventServiceImpl eventService = (EventServiceImpl) Framework.getLocalService(EventService.class);
deployBundle("org.nuxeo.ecm.core.convert");
deployBundle("org.nuxeo.ecm.core.convert.plugins");
DocumentModel doc = new DocumentModelImpl("/", "complex-doc",
"ComplexDoc");
doc = session.createDocument(doc);
DocumentRef docRef = doc.getRef();
session.save();
// test setting and reading a map with an empty list
closeSession();
openSession();
doc = session.getDocument(docRef);
Map<String, Object> attachedFile = new HashMap<String, Object>();
List<Map<String, Object>> vignettes = new ArrayList<Map<String, Object>>();
attachedFile.put("name", "somename");
attachedFile.put("vignettes", vignettes);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
doc = session.getDocument(docRef);
assertEquals(attachedFile,
doc.getProperty("cmpf:attachedFile").getValue());
assertEquals(attachedFile.get("vignettes"),
doc.getProperty("cmpf:attachedFile/vignettes").getValue());
// test fulltext indexing of complex property at level one
DocumentModelList results = session.query(
"SELECT * FROM Document WHERE ecm:fulltext = 'somename'", 1);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test setting and reading a list of maps without a complex type in the
// maps
Map<String, Object> vignette = new HashMap<String, Object>();
vignette.put("width", Long.valueOf(0));
vignette.put("height", Long.valueOf(0));
vignette.put(
"content",
StreamingBlob.createFromString("textblob content", "text/plain"));
vignette.put("label", "vignettelabel");
vignettes.add(vignette);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
doc = session.getDocument(docRef);
assertEquals(
"text/plain",
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/content/mime-type").getValue());
assertEquals(
Long.valueOf(0),
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/height").getValue());
assertEquals(
"vignettelabel",
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/label").getValue());
// test fulltext indexing of complex property at level 3
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'vignettelabel'", 2);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test fulltext indexing of complex property at level 3 in blob
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'textblob content'", 2);
assertNotNull(results);
assertEquals(1, results.size());
assertEquals("complex-doc", results.get(0).getTitle());
// test setting and reading a list of maps with a blob inside the map
byte[] binaryContent = "01AB".getBytes();
Blob blob = StreamingBlob.createFromByteArray(binaryContent,
"application/octet-stream");
blob.setFilename("file.bin");
vignette.put("content", blob);
doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
assertEquals(
Long.valueOf(0),
doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/height").getValue());
assertEquals(
"vignettelabel",
doc.getProperty("cmpf:attachedFile/vignettes/vignette[0]/label").getValue());
// this doesn't work due to core restrictions (BlobProperty):
// assertEquals(blob.getFilename(), doc.getProperty(
// "cmpf:attachedFile/vignettes/vignette[0]/content/name").getValue());
Blob b = (Blob) doc.getProperty(
"cmpf:attachedFile/vignettes/vignette[0]/content").getValue();
assertEquals("file.bin", b.getFilename());
// test deleting the list of vignette and ensure that the fulltext index
// has been properly updated (regression test for NXP-6315)
doc.setPropertyValue("cmpf:attachedFile/vignettes",
new ArrayList<Map<String, Object>>());
session.saveDocument(doc);
session.save();
closeSession();
eventService.waitForAsyncCompletion();
DatabaseHelper.DATABASE.sleepForFulltext();
openSession();
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'vignettelabel'", 2);
assertNotNull(results);
assertEquals(0, results.size());
results = session.query("SELECT * FROM Document"
+ " WHERE ecm:fulltext = 'textblob content'", 2);
assertNotNull(results);
assertEquals(0, results.size());
}
|
diff --git a/geoserver/src/org/vfny/geoserver/action/data/DataDataStoresEditorAction.java b/geoserver/src/org/vfny/geoserver/action/data/DataDataStoresEditorAction.java
index da902721c0..db7f09c5ad 100644
--- a/geoserver/src/org/vfny/geoserver/action/data/DataDataStoresEditorAction.java
+++ b/geoserver/src/org/vfny/geoserver/action/data/DataDataStoresEditorAction.java
@@ -1,168 +1,168 @@
/* 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.action.data;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFactorySpi;
import org.geotools.data.DataStoreFactorySpi.Param;
import org.vfny.geoserver.action.ConfigAction;
import org.vfny.geoserver.config.DataConfig;
import org.vfny.geoserver.config.DataStoreConfig;
import org.vfny.geoserver.form.data.DataDataStoresEditorForm;
import org.vfny.geoserver.global.UserContainer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* DOCUMENT ME!
*
* @author rgould To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class DataDataStoresEditorAction extends ConfigAction {
public ActionForward execute(ActionMapping mapping, ActionForm form,
UserContainer user, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
DataDataStoresEditorForm dataStoresForm = (DataDataStoresEditorForm) form;
String dataStoreID = dataStoresForm.getDataStoreId();
String namespace = dataStoresForm.getNamespaceId();
String description = dataStoresForm.getDescription();
DataConfig dataConfig = (DataConfig) getDataConfig();
DataStoreConfig config = null;
config = (DataStoreConfig) dataConfig.getDataStore(dataStoreID);
if( config == null ) {
// we are creating a new one.
dataConfig.addDataStore(getUserContainer(request).getDataStoreConfig());
config = (DataStoreConfig) dataConfig.getDataStore(dataStoreID);
}
// After extracting params into a map
Map paramValues = new HashMap();
Map paramTexts = new HashMap();
Map params = dataStoresForm.getParams();
DataStoreFactorySpi factory = config.getFactory();
Param[] info = factory.getParametersInfo();
// Convert Params into the kind of Map we actually need
//
for (Iterator i = params.keySet().iterator(); i.hasNext();) {
String key = (String) i.next();
Param param = DataStoreUtils.find(info, key);
if (param == null) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
- return mapping.findForward("config.data.store");
+ return mapping.findForward("config.data.store.editor");
}
Object value;
try {
value = param.lookUp(params);
} catch (IOException erp) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
- return mapping.findForward("config.data.store");
+ return mapping.findForward("config.data.store.editor");
}
if (value != null) {
paramValues.put(key, value);
String text = param.text(value);
paramTexts.put(key, text);
}
}
// put magic namespace into the mix
//
paramValues.put("namespace", dataStoresForm.getNamespaceId());
paramTexts.put("namespace", dataStoresForm.getNamespaceId());
if (!factory.canProcess(paramValues)) {
// We could not use these params!
//
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
- return mapping.findForward("config.data.store");
+ return mapping.findForward("config.data.store.editor");
}
try {
DataStore victim = factory.createDataStore(paramValues);
System.out.println("temporary datastore:" + victim);
if (victim == null) {
// We *really* could not use these params!
//
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalidConnectionParams"));
saveErrors(request, errors);
- return mapping.findForward("config.data.store");
+ return mapping.findForward("config.data.store.editor");
}
} catch (Throwable throwable) {
throwable.printStackTrace();
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.exception", throwable.getMessage()));
saveErrors(request, errors);
- return mapping.findForward("config.data.store");
+ return mapping.findForward("config.data.store.editor");
}
boolean enabled = dataStoresForm.isEnabled();
if (dataStoresForm.isEnabledChecked() == false) {
enabled = false;
}
config.setEnabled(enabled);
config.setNameSpaceId(namespace);
config.setAbstract(description);
config.setConnectionParams(paramTexts);
dataConfig.addDataStore(config);
getUserContainer(request).setDataStoreConfig(null);
getApplicationState().notifyConfigChanged();
return mapping.findForward("config.data.store");
}
}
| false | true | public ActionForward execute(ActionMapping mapping, ActionForm form,
UserContainer user, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
DataDataStoresEditorForm dataStoresForm = (DataDataStoresEditorForm) form;
String dataStoreID = dataStoresForm.getDataStoreId();
String namespace = dataStoresForm.getNamespaceId();
String description = dataStoresForm.getDescription();
DataConfig dataConfig = (DataConfig) getDataConfig();
DataStoreConfig config = null;
config = (DataStoreConfig) dataConfig.getDataStore(dataStoreID);
if( config == null ) {
// we are creating a new one.
dataConfig.addDataStore(getUserContainer(request).getDataStoreConfig());
config = (DataStoreConfig) dataConfig.getDataStore(dataStoreID);
}
// After extracting params into a map
Map paramValues = new HashMap();
Map paramTexts = new HashMap();
Map params = dataStoresForm.getParams();
DataStoreFactorySpi factory = config.getFactory();
Param[] info = factory.getParametersInfo();
// Convert Params into the kind of Map we actually need
//
for (Iterator i = params.keySet().iterator(); i.hasNext();) {
String key = (String) i.next();
Param param = DataStoreUtils.find(info, key);
if (param == null) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
return mapping.findForward("config.data.store");
}
Object value;
try {
value = param.lookUp(params);
} catch (IOException erp) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
return mapping.findForward("config.data.store");
}
if (value != null) {
paramValues.put(key, value);
String text = param.text(value);
paramTexts.put(key, text);
}
}
// put magic namespace into the mix
//
paramValues.put("namespace", dataStoresForm.getNamespaceId());
paramTexts.put("namespace", dataStoresForm.getNamespaceId());
if (!factory.canProcess(paramValues)) {
// We could not use these params!
//
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
return mapping.findForward("config.data.store");
}
try {
DataStore victim = factory.createDataStore(paramValues);
System.out.println("temporary datastore:" + victim);
if (victim == null) {
// We *really* could not use these params!
//
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalidConnectionParams"));
saveErrors(request, errors);
return mapping.findForward("config.data.store");
}
} catch (Throwable throwable) {
throwable.printStackTrace();
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.exception", throwable.getMessage()));
saveErrors(request, errors);
return mapping.findForward("config.data.store");
}
boolean enabled = dataStoresForm.isEnabled();
if (dataStoresForm.isEnabledChecked() == false) {
enabled = false;
}
config.setEnabled(enabled);
config.setNameSpaceId(namespace);
config.setAbstract(description);
config.setConnectionParams(paramTexts);
dataConfig.addDataStore(config);
getUserContainer(request).setDataStoreConfig(null);
getApplicationState().notifyConfigChanged();
return mapping.findForward("config.data.store");
}
| public ActionForward execute(ActionMapping mapping, ActionForm form,
UserContainer user, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
DataDataStoresEditorForm dataStoresForm = (DataDataStoresEditorForm) form;
String dataStoreID = dataStoresForm.getDataStoreId();
String namespace = dataStoresForm.getNamespaceId();
String description = dataStoresForm.getDescription();
DataConfig dataConfig = (DataConfig) getDataConfig();
DataStoreConfig config = null;
config = (DataStoreConfig) dataConfig.getDataStore(dataStoreID);
if( config == null ) {
// we are creating a new one.
dataConfig.addDataStore(getUserContainer(request).getDataStoreConfig());
config = (DataStoreConfig) dataConfig.getDataStore(dataStoreID);
}
// After extracting params into a map
Map paramValues = new HashMap();
Map paramTexts = new HashMap();
Map params = dataStoresForm.getParams();
DataStoreFactorySpi factory = config.getFactory();
Param[] info = factory.getParametersInfo();
// Convert Params into the kind of Map we actually need
//
for (Iterator i = params.keySet().iterator(); i.hasNext();) {
String key = (String) i.next();
Param param = DataStoreUtils.find(info, key);
if (param == null) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
return mapping.findForward("config.data.store.editor");
}
Object value;
try {
value = param.lookUp(params);
} catch (IOException erp) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
return mapping.findForward("config.data.store.editor");
}
if (value != null) {
paramValues.put(key, value);
String text = param.text(value);
paramTexts.put(key, text);
}
}
// put magic namespace into the mix
//
paramValues.put("namespace", dataStoresForm.getNamespaceId());
paramTexts.put("namespace", dataStoresForm.getNamespaceId());
if (!factory.canProcess(paramValues)) {
// We could not use these params!
//
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.cannotProcessConnectionParams"));
saveErrors(request, errors);
return mapping.findForward("config.data.store.editor");
}
try {
DataStore victim = factory.createDataStore(paramValues);
System.out.println("temporary datastore:" + victim);
if (victim == null) {
// We *really* could not use these params!
//
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalidConnectionParams"));
saveErrors(request, errors);
return mapping.findForward("config.data.store.editor");
}
} catch (Throwable throwable) {
throwable.printStackTrace();
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.exception", throwable.getMessage()));
saveErrors(request, errors);
return mapping.findForward("config.data.store.editor");
}
boolean enabled = dataStoresForm.isEnabled();
if (dataStoresForm.isEnabledChecked() == false) {
enabled = false;
}
config.setEnabled(enabled);
config.setNameSpaceId(namespace);
config.setAbstract(description);
config.setConnectionParams(paramTexts);
dataConfig.addDataStore(config);
getUserContainer(request).setDataStoreConfig(null);
getApplicationState().notifyConfigChanged();
return mapping.findForward("config.data.store");
}
|
diff --git a/E-EYE-O_DAOHibernateImpl/src/com/jtbdevelopment/e_eye_o/hibernate/DAO/HibernateReadOnlyDAO.java b/E-EYE-O_DAOHibernateImpl/src/com/jtbdevelopment/e_eye_o/hibernate/DAO/HibernateReadOnlyDAO.java
index a5d4f11..238544e 100644
--- a/E-EYE-O_DAOHibernateImpl/src/com/jtbdevelopment/e_eye_o/hibernate/DAO/HibernateReadOnlyDAO.java
+++ b/E-EYE-O_DAOHibernateImpl/src/com/jtbdevelopment/e_eye_o/hibernate/DAO/HibernateReadOnlyDAO.java
@@ -1,178 +1,182 @@
package com.jtbdevelopment.e_eye_o.hibernate.DAO;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.jtbdevelopment.e_eye_o.DAO.ReadOnlyDAO;
import com.jtbdevelopment.e_eye_o.entities.*;
import com.jtbdevelopment.e_eye_o.entities.Observable;
import com.jtbdevelopment.e_eye_o.entities.wrapper.DAOIdObjectWrapperFactory;
import com.jtbdevelopment.e_eye_o.hibernate.entities.impl.HibernateIdObject;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nullable;
import java.util.*;
/**
* Date: 11/18/12
* Time: 10:29 PM
*/
@SuppressWarnings("unused")
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public class HibernateReadOnlyDAO implements ReadOnlyDAO {
private final static Logger logger = LoggerFactory.getLogger(HibernateReadOnlyDAO.class);
protected final SessionFactory sessionFactory;
protected final DAOIdObjectWrapperFactory wrapperFactory;
@Autowired
public HibernateReadOnlyDAO(final SessionFactory sessionFactory, final DAOIdObjectWrapperFactory wrapperFactory) {
this.sessionFactory = sessionFactory;
this.wrapperFactory = wrapperFactory;
}
@Override
// TODO - paging
@SuppressWarnings("unchecked")
public Set<AppUser> getUsers() {
Set<AppUser> returnSet = new LinkedHashSet<>();
returnSet.addAll((List<AppUser>) sessionFactory.getCurrentSession().createQuery("from AppUser").list());
return returnSet;
}
@Override
@SuppressWarnings("unchecked")
public AppUser getUser(final String emailAddress) {
final Query query = sessionFactory.getCurrentSession().createQuery("from AppUser where emailAddress = :emailAddress");
query.setParameter("emailAddress", emailAddress);
List<AppUser> users = (List<AppUser>) query.list();
if (users.isEmpty()) {
return null;
}
if (users.size() > 1) {
throw new IllegalStateException("Duplicate users with same emailAddress - not possible");
}
return users.get(0);
}
@Override
@SuppressWarnings("unchecked")
public <T extends IdObject> T get(final Class<T> entityType, final String id) {
final String entityName = getHibernateEntityName(entityType);
logger.info("Fetching entityType = '" + entityName + "', id = '" + id + "'");
return (T) sessionFactory.getCurrentSession().get(entityName, id);
}
@Override
@SuppressWarnings("unchecked")
public <T extends AppUserOwnedObject> Set<T> getEntitiesForUser(final Class<T> entityType, final AppUser appUser) {
Query query = sessionFactory.getCurrentSession().createQuery("from " + getHibernateEntityName(entityType) + " where appUser = :user");
query.setParameter("user", appUser);
return new HashSet<>(Collections2.filter((List<T>) query.list(), new Predicate<T>() {
@Override
public boolean apply(@Nullable final T input) {
return (input != null) && ((entityType == DeletedObject.class) || !(input instanceof DeletedObject));
}
}));
}
@Override
public <T extends AppUserOwnedObject> Set<T> getActiveEntitiesForUser(final Class<T> entityType, final AppUser appUser) {
return getEntitiesForUser(entityType, appUser, false);
}
@Override
public <T extends AppUserOwnedObject> Set<T> getArchivedEntitiesForUser(final Class<T> entityType, final AppUser appUser) {
return getEntitiesForUser(entityType, appUser, true);
}
@Override
@SuppressWarnings("unchecked")
public <T extends AppUserOwnedObject> Set<T> getEntitiesModifiedSince(final Class<T> entityType, final AppUser appUser, final DateTime since) {
Query query = sessionFactory.getCurrentSession().createQuery("from " + getHibernateEntityName(entityType) + " where appUser = :user and modificationTimestamp > :since");
query.setParameter("user", appUser);
query.setParameter("since", since);
TreeSet<T> sortedResults = new TreeSet<>(new Comparator<T>() {
@Override
public int compare(final T o1, final T o2) {
- return o1.getModificationTimestamp().compareTo(o2.getModificationTimestamp());
+ int i = o1.getModificationTimestamp().compareTo(o2.getModificationTimestamp());
+ if (i == 0) {
+ return o1.getId().compareTo(o2.getId());
+ }
+ return i;
}
});
sortedResults.addAll((List<T>) query.list());
return sortedResults;
}
@SuppressWarnings("unchecked")
public <T extends AppUserOwnedObject> Set<T> getEntitiesForUser(final Class<T> entityType, final AppUser appUser, final boolean archivedFlag) {
return new HashSet<>(Collections2.filter(getEntitiesForUser(entityType, appUser), new Predicate<T>() {
@Override
public boolean apply(@Nullable final T input) {
return (input != null) && (input.isArchived() == archivedFlag);
}
}));
}
@Override
@SuppressWarnings("unchecked")
public List<Photo> getAllPhotosForEntity(final AppUserOwnedObject ownedObject) {
Query query = sessionFactory.getCurrentSession().createQuery("from Photo where photoFor = :photoFor");
query.setParameter("photoFor", ownedObject);
return (List<Photo>) query.list();
}
@Override
public LocalDateTime getLastObservationTimestampForEntity(final Observable observable) {
Query query = sessionFactory.getCurrentSession().createQuery("select max(observationTimestamp) from Observation where observationSubject = :observationSubject");
query.setParameter("observationSubject", observable);
LocalDateTime result = (LocalDateTime) query.uniqueResult();
return result == null ? Observable.NEVER_OBSERVED : result;
}
@Override
@SuppressWarnings("unchecked")
public List<Observation> getAllObservationsForEntity(final Observable observable) {
Query query = sessionFactory.getCurrentSession().createQuery("from Observation where observationSubject = :observationSubject");
query.setParameter("observationSubject", observable);
return (List<Observation>) query.list();
}
@Override
@SuppressWarnings("unchecked")
public List<Observation> getAllObservationsForObservationCategory(final ObservationCategory observationCategory) {
Query query = sessionFactory.getCurrentSession().createQuery("from Observation as O where :category member of O.categories");
query.setParameter("category", observationCategory);
return (List<Observation>) query.list();
}
@Override
@SuppressWarnings("unchecked")
public List<Student> getAllStudentsForClassList(final ClassList classList) {
Query query = sessionFactory.getCurrentSession().createQuery("from Student as S where :classList member of S.classLists");
query.setParameter("classList", classList);
return (List<Student>) query.list();
}
protected <T extends IdObject> String getHibernateEntityName(final Class<T> entityType) {
Class<T> wrapperFor;
if (!HibernateIdObject.class.isAssignableFrom(entityType)) {
wrapperFor = wrapperFactory.getWrapperForEntity(entityType);
if (wrapperFor == null) {
throw new IllegalArgumentException("Unknown entity type " + entityType.getSimpleName());
}
} else {
wrapperFor = entityType;
}
return sessionFactory.getClassMetadata(wrapperFor).getEntityName();
}
}
| true | true | public <T extends AppUserOwnedObject> Set<T> getEntitiesModifiedSince(final Class<T> entityType, final AppUser appUser, final DateTime since) {
Query query = sessionFactory.getCurrentSession().createQuery("from " + getHibernateEntityName(entityType) + " where appUser = :user and modificationTimestamp > :since");
query.setParameter("user", appUser);
query.setParameter("since", since);
TreeSet<T> sortedResults = new TreeSet<>(new Comparator<T>() {
@Override
public int compare(final T o1, final T o2) {
return o1.getModificationTimestamp().compareTo(o2.getModificationTimestamp());
}
});
sortedResults.addAll((List<T>) query.list());
return sortedResults;
}
| public <T extends AppUserOwnedObject> Set<T> getEntitiesModifiedSince(final Class<T> entityType, final AppUser appUser, final DateTime since) {
Query query = sessionFactory.getCurrentSession().createQuery("from " + getHibernateEntityName(entityType) + " where appUser = :user and modificationTimestamp > :since");
query.setParameter("user", appUser);
query.setParameter("since", since);
TreeSet<T> sortedResults = new TreeSet<>(new Comparator<T>() {
@Override
public int compare(final T o1, final T o2) {
int i = o1.getModificationTimestamp().compareTo(o2.getModificationTimestamp());
if (i == 0) {
return o1.getId().compareTo(o2.getId());
}
return i;
}
});
sortedResults.addAll((List<T>) query.list());
return sortedResults;
}
|
diff --git a/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/generic_node/dialogs/param_dialog/list_editor/ListEditorDialog.java b/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/generic_node/dialogs/param_dialog/list_editor/ListEditorDialog.java
index c4a2890..16b51be 100644
--- a/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/generic_node/dialogs/param_dialog/list_editor/ListEditorDialog.java
+++ b/com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/generic_node/dialogs/param_dialog/list_editor/ListEditorDialog.java
@@ -1,204 +1,208 @@
/**
* Copyright (c) 2012, Stephan Aiche.
*
* This file is part of GenericKnimeNodes.
*
* GenericKnimeNodes 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.
*
* 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 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 com.genericworkflownodes.knime.generic_node.dialogs.param_dialog.list_editor;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.genericworkflownodes.knime.generic_node.dialogs.UIHelper;
import com.genericworkflownodes.knime.parameter.ListParameter;
import com.genericworkflownodes.knime.parameter.Parameter;
/**
* ListEditor dialog for StringList and NumericalList parameters.
*
* @author aiche
*/
public class ListEditorDialog extends JDialog {
private static final int TABLE_HEIGHT = 500;
private static final int COLUMN_WIDTH = 1000;
/**
*
*/
private static final long serialVersionUID = 9130341015527518732L;
private ListParameter parameter;
private final static String TITLE = "List Editor <%s> (%s)";
private ListEditorDialogModel model;
private JTable table;
private ListCellEditor cellEditor;
/**
* Initialize the editor.
*/
public ListEditorDialog(ListParameter p) {
super();
setTitle(String.format(TITLE, ((Parameter<?>) p).getKey(),
((Parameter<?>) p).getMnemonic()));
init(p);
}
private void init(ListParameter p) {
parameter = p;
Container pane = getContentPane();
pane.setLayout(new GridBagLayout());
model = new ListEditorDialogModel(parameter);
table = new JTable(model);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
cellEditor = new ListCellEditor(p);
table.setCellEditor(cellEditor);
table.getColumnModel().getColumn(0).setCellEditor(cellEditor);
table.setMinimumSize(new Dimension(COLUMN_WIDTH, TABLE_HEIGHT));
// adapt width of column
adjustColumnSize();
// remove the tableheader
table.setTableHeader(null);
JScrollPane listScrollPane = new JScrollPane(table);
UIHelper.addComponent(pane, listScrollPane, 0, 0, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.BOTH, 2, 2);
addButtons(pane);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
UIHelper.centerDialog(this);
pack();
}
private void adjustColumnSize() {
table.doLayout();
}
private void addButtons(Container pane) {
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
+ if (table.isEditing())
+ table.getCellEditor().stopCellEditing();
final int addedIndex = model.addValue();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
table.setRowSelectionInterval(addedIndex, addedIndex);
}
});
}
});
final JButton removeButton = new JButton("Delete");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
+ if (table.isEditing())
+ table.getCellEditor().stopCellEditing();
model.removeRow(table.getSelectedRow());
}
});
removeButton.setEnabled(false);
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (table.isEditing())
table.getCellEditor().stopCellEditing();
model.transferToParameter();
ListEditorDialog.this.dispose();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ListEditorDialog.this.dispose();
}
});
makeButtonWidthEqual(addButton, removeButton, okButton, cancelButton);
Box box = Box.createVerticalBox();
box.add(addButton);
box.add(removeButton);
box.add(okButton);
box.add(cancelButton);
box.add(Box.createVerticalGlue());
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
if (event.getSource() == table.getSelectionModel()) {
removeButton.setEnabled((table.getSelectedRow() != -1));
}
}
});
UIHelper.addComponent(pane, box, 1, 0, 1, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, 0, 0);
}
/**
* Customize buttons size to the maximal value.
*
* @param buttons
* The buttons to customize.
*/
private static void makeButtonWidthEqual(JButton... buttons) {
int maxWidth = Integer.MIN_VALUE;
for (JButton button : buttons) {
maxWidth = Math.max(maxWidth, button.getPreferredSize().width);
}
for (JButton button : buttons) {
Dimension size = new Dimension(maxWidth,
button.getPreferredSize().height);
button.setPreferredSize(size);
button.setMinimumSize(size);
button.setMaximumSize(size);
}
}
}
| false | true | private void addButtons(Container pane) {
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
final int addedIndex = model.addValue();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
table.setRowSelectionInterval(addedIndex, addedIndex);
}
});
}
});
final JButton removeButton = new JButton("Delete");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.removeRow(table.getSelectedRow());
}
});
removeButton.setEnabled(false);
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (table.isEditing())
table.getCellEditor().stopCellEditing();
model.transferToParameter();
ListEditorDialog.this.dispose();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ListEditorDialog.this.dispose();
}
});
makeButtonWidthEqual(addButton, removeButton, okButton, cancelButton);
Box box = Box.createVerticalBox();
box.add(addButton);
box.add(removeButton);
box.add(okButton);
box.add(cancelButton);
box.add(Box.createVerticalGlue());
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
if (event.getSource() == table.getSelectionModel()) {
removeButton.setEnabled((table.getSelectedRow() != -1));
}
}
});
UIHelper.addComponent(pane, box, 1, 0, 1, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, 0, 0);
}
| private void addButtons(Container pane) {
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (table.isEditing())
table.getCellEditor().stopCellEditing();
final int addedIndex = model.addValue();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
table.setRowSelectionInterval(addedIndex, addedIndex);
}
});
}
});
final JButton removeButton = new JButton("Delete");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (table.isEditing())
table.getCellEditor().stopCellEditing();
model.removeRow(table.getSelectedRow());
}
});
removeButton.setEnabled(false);
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (table.isEditing())
table.getCellEditor().stopCellEditing();
model.transferToParameter();
ListEditorDialog.this.dispose();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ListEditorDialog.this.dispose();
}
});
makeButtonWidthEqual(addButton, removeButton, okButton, cancelButton);
Box box = Box.createVerticalBox();
box.add(addButton);
box.add(removeButton);
box.add(okButton);
box.add(cancelButton);
box.add(Box.createVerticalGlue());
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
if (event.getSource() == table.getSelectionModel()) {
removeButton.setEnabled((table.getSelectedRow() != -1));
}
}
});
UIHelper.addComponent(pane, box, 1, 0, 1, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, 0, 0);
}
|
diff --git a/src/org/python/modules/types.java b/src/org/python/modules/types.java
index 4864d0cf..6a3a04f5 100644
--- a/src/org/python/modules/types.java
+++ b/src/org/python/modules/types.java
@@ -1,60 +1,60 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.modules;
import org.python.core.*;
public class types implements ClassDictInit {
public static PyString __doc__ = new PyString(
"Define names for all type symbols known in the standard "+
"interpreter.\n"+
"\n"+
"Types that are part of optional modules (e.g. array) "+
"are not listed.\n"
);
// xxx change some of these
public static void classDictInit(PyObject dict) {
dict.__setitem__("ArrayType", PyType.fromClass(PyArray.class));
dict.__setitem__("BuiltinFunctionType",
PyType.fromClass(PyReflectedFunction.class));
dict.__setitem__("BuiltinMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("ClassType", PyType.fromClass(PyClass.class));
dict.__setitem__("CodeType", PyType.fromClass(PyCode.class));
dict.__setitem__("ComplexType", PyType.fromClass(PyComplex.class));
dict.__setitem__("DictType", PyType.fromClass(PyDictionary.class));
dict.__setitem__("DictionaryType",
PyType.fromClass(PyDictionary.class));
dict.__setitem__("EllipsisType",
PyType.fromClass(PyEllipsis.class));
dict.__setitem__("FileType", PyType.fromClass(PyFile.class));
dict.__setitem__("FloatType", PyType.fromClass(PyFloat.class));
dict.__setitem__("FrameType", PyType.fromClass(PyFrame.class));
dict.__setitem__("FunctionType",
PyType.fromClass(PyFunction.class));
dict.__setitem__("GeneratorType",
PyType.fromClass(PyGenerator.class));
dict.__setitem__("InstanceType",
PyType.fromClass(PyInstance.class));
dict.__setitem__("IntType", PyType.fromClass(PyInteger.class));
dict.__setitem__("LambdaType", PyType.fromClass(PyFunction.class));
dict.__setitem__("ListType", PyType.fromClass(PyList.class));
dict.__setitem__("LongType", PyType.fromClass(PyLong.class));
dict.__setitem__("MethodType", PyType.fromClass(PyMethod.class));
dict.__setitem__("ModuleType", PyType.fromClass(PyModule.class));
dict.__setitem__("NoneType", PyType.fromClass(PyNone.class));
dict.__setitem__("SliceType", PyType.fromClass(PySlice.class));
dict.__setitem__("StringType", PyType.fromClass(PyString.class));
dict.__setitem__("TracebackType",
PyType.fromClass(PyTraceback.class));
dict.__setitem__("TupleType", PyType.fromClass(PyTuple.class));
dict.__setitem__("TypeType", PyType.fromClass(PyJavaClass.class));
dict.__setitem__("UnboundMethodType",
PyType.fromClass(PyMethod.class));
- dict.__setitem__("UnicodeType", PyType.fromClass(PyString.class));
+ dict.__setitem__("UnicodeType", PyType.fromClass(PyUnicode.class));
dict.__setitem__("XRangeType", PyType.fromClass(PyXRange.class));
dict.__setitem__("StringTypes", new PyTuple(new PyObject[] {
PyType.fromClass(PyString.class), PyType.fromClass(PyUnicode.class)
}));
}
}
| true | true | public static void classDictInit(PyObject dict) {
dict.__setitem__("ArrayType", PyType.fromClass(PyArray.class));
dict.__setitem__("BuiltinFunctionType",
PyType.fromClass(PyReflectedFunction.class));
dict.__setitem__("BuiltinMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("ClassType", PyType.fromClass(PyClass.class));
dict.__setitem__("CodeType", PyType.fromClass(PyCode.class));
dict.__setitem__("ComplexType", PyType.fromClass(PyComplex.class));
dict.__setitem__("DictType", PyType.fromClass(PyDictionary.class));
dict.__setitem__("DictionaryType",
PyType.fromClass(PyDictionary.class));
dict.__setitem__("EllipsisType",
PyType.fromClass(PyEllipsis.class));
dict.__setitem__("FileType", PyType.fromClass(PyFile.class));
dict.__setitem__("FloatType", PyType.fromClass(PyFloat.class));
dict.__setitem__("FrameType", PyType.fromClass(PyFrame.class));
dict.__setitem__("FunctionType",
PyType.fromClass(PyFunction.class));
dict.__setitem__("GeneratorType",
PyType.fromClass(PyGenerator.class));
dict.__setitem__("InstanceType",
PyType.fromClass(PyInstance.class));
dict.__setitem__("IntType", PyType.fromClass(PyInteger.class));
dict.__setitem__("LambdaType", PyType.fromClass(PyFunction.class));
dict.__setitem__("ListType", PyType.fromClass(PyList.class));
dict.__setitem__("LongType", PyType.fromClass(PyLong.class));
dict.__setitem__("MethodType", PyType.fromClass(PyMethod.class));
dict.__setitem__("ModuleType", PyType.fromClass(PyModule.class));
dict.__setitem__("NoneType", PyType.fromClass(PyNone.class));
dict.__setitem__("SliceType", PyType.fromClass(PySlice.class));
dict.__setitem__("StringType", PyType.fromClass(PyString.class));
dict.__setitem__("TracebackType",
PyType.fromClass(PyTraceback.class));
dict.__setitem__("TupleType", PyType.fromClass(PyTuple.class));
dict.__setitem__("TypeType", PyType.fromClass(PyJavaClass.class));
dict.__setitem__("UnboundMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("UnicodeType", PyType.fromClass(PyString.class));
dict.__setitem__("XRangeType", PyType.fromClass(PyXRange.class));
dict.__setitem__("StringTypes", new PyTuple(new PyObject[] {
PyType.fromClass(PyString.class), PyType.fromClass(PyUnicode.class)
}));
}
| public static void classDictInit(PyObject dict) {
dict.__setitem__("ArrayType", PyType.fromClass(PyArray.class));
dict.__setitem__("BuiltinFunctionType",
PyType.fromClass(PyReflectedFunction.class));
dict.__setitem__("BuiltinMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("ClassType", PyType.fromClass(PyClass.class));
dict.__setitem__("CodeType", PyType.fromClass(PyCode.class));
dict.__setitem__("ComplexType", PyType.fromClass(PyComplex.class));
dict.__setitem__("DictType", PyType.fromClass(PyDictionary.class));
dict.__setitem__("DictionaryType",
PyType.fromClass(PyDictionary.class));
dict.__setitem__("EllipsisType",
PyType.fromClass(PyEllipsis.class));
dict.__setitem__("FileType", PyType.fromClass(PyFile.class));
dict.__setitem__("FloatType", PyType.fromClass(PyFloat.class));
dict.__setitem__("FrameType", PyType.fromClass(PyFrame.class));
dict.__setitem__("FunctionType",
PyType.fromClass(PyFunction.class));
dict.__setitem__("GeneratorType",
PyType.fromClass(PyGenerator.class));
dict.__setitem__("InstanceType",
PyType.fromClass(PyInstance.class));
dict.__setitem__("IntType", PyType.fromClass(PyInteger.class));
dict.__setitem__("LambdaType", PyType.fromClass(PyFunction.class));
dict.__setitem__("ListType", PyType.fromClass(PyList.class));
dict.__setitem__("LongType", PyType.fromClass(PyLong.class));
dict.__setitem__("MethodType", PyType.fromClass(PyMethod.class));
dict.__setitem__("ModuleType", PyType.fromClass(PyModule.class));
dict.__setitem__("NoneType", PyType.fromClass(PyNone.class));
dict.__setitem__("SliceType", PyType.fromClass(PySlice.class));
dict.__setitem__("StringType", PyType.fromClass(PyString.class));
dict.__setitem__("TracebackType",
PyType.fromClass(PyTraceback.class));
dict.__setitem__("TupleType", PyType.fromClass(PyTuple.class));
dict.__setitem__("TypeType", PyType.fromClass(PyJavaClass.class));
dict.__setitem__("UnboundMethodType",
PyType.fromClass(PyMethod.class));
dict.__setitem__("UnicodeType", PyType.fromClass(PyUnicode.class));
dict.__setitem__("XRangeType", PyType.fromClass(PyXRange.class));
dict.__setitem__("StringTypes", new PyTuple(new PyObject[] {
PyType.fromClass(PyString.class), PyType.fromClass(PyUnicode.class)
}));
}
|
diff --git a/src/java/com/android/internal/telephony/uicc/AdnRecordLoader.java b/src/java/com/android/internal/telephony/uicc/AdnRecordLoader.java
index 20ec787..eea397b 100644
--- a/src/java/com/android/internal/telephony/uicc/AdnRecordLoader.java
+++ b/src/java/com/android/internal/telephony/uicc/AdnRecordLoader.java
@@ -1,316 +1,321 @@
/*
* 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.internal.telephony.uicc;
import java.util.ArrayList;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.telephony.Rlog;
import com.android.internal.telephony.uicc.IccConstants;
public class AdnRecordLoader extends Handler {
final static String LOG_TAG = "AdnRecordLoader";
final static boolean VDBG = false;
//***** Instance Variables
private IccFileHandler mFh;
int mEf;
int mExtensionEF;
int mPendingExtLoads;
Message mUserResponse;
String mPin2;
// For "load one"
int mRecordNumber;
// for "load all"
ArrayList<AdnRecord> mAdns; // only valid after EVENT_ADN_LOAD_ALL_DONE
// Either an AdnRecord or a reference to adns depending
// if this is a load one or load all operation
Object mResult;
//***** Event Constants
static final int EVENT_ADN_LOAD_DONE = 1;
static final int EVENT_EXT_RECORD_LOAD_DONE = 2;
static final int EVENT_ADN_LOAD_ALL_DONE = 3;
static final int EVENT_EF_LINEAR_RECORD_SIZE_DONE = 4;
static final int EVENT_UPDATE_RECORD_DONE = 5;
//***** Constructor
AdnRecordLoader(IccFileHandler fh) {
// The telephony unit-test cases may create AdnRecords
// in secondary threads
super(Looper.getMainLooper());
mFh = fh;
}
private String getEFPath(int efid) {
if (efid == IccConstants.EF_ADN) {
return IccConstants.MF_SIM + IccConstants.DF_TELECOM;
}
return null;
}
/**
* Resulting AdnRecord is placed in response.obj.result
* or response.obj.exception is set
*/
public void
loadFromEF(int ef, int extensionEF, int recordNumber,
Message response) {
mEf = ef;
mExtensionEF = extensionEF;
mRecordNumber = recordNumber;
mUserResponse = response;
if (ef == IccConstants.EF_ADN) {
mFh.loadEFLinearFixed(
ef, getEFPath(ef), recordNumber,
obtainMessage(EVENT_ADN_LOAD_DONE));
} else {
mFh.loadEFLinearFixed(
ef, recordNumber,
obtainMessage(EVENT_ADN_LOAD_DONE));
}
}
/**
* Resulting ArrayList<adnRecord> is placed in response.obj.result
* or response.obj.exception is set
*/
public void
loadAllFromEF(int ef, int extensionEF,
Message response) {
mEf = ef;
mExtensionEF = extensionEF;
mUserResponse = response;
/* If we are loading from EF_ADN, specifically
* specify the path as well, since, on some cards,
* the fileid is not unique.
*/
if (ef == IccConstants.EF_ADN) {
mFh.loadEFLinearFixedAll(
ef, getEFPath(ef),
obtainMessage(EVENT_ADN_LOAD_ALL_DONE));
} else {
mFh.loadEFLinearFixedAll(
ef,
obtainMessage(EVENT_ADN_LOAD_ALL_DONE));
}
}
/**
* Write adn to a EF SIM record
* It will get the record size of EF record and compose hex adn array
* then write the hex array to EF record
*
* @param adn is set with alphaTag and phone number
* @param ef EF fileid
* @param extensionEF extension EF fileid
* @param recordNumber 1-based record index
* @param pin2 for CHV2 operations, must be null if pin2 is not needed
* @param response will be sent to its handler when completed
*/
public void
updateEF(AdnRecord adn, int ef, int extensionEF, int recordNumber,
String pin2, Message response) {
mEf = ef;
mExtensionEF = extensionEF;
mRecordNumber = recordNumber;
mUserResponse = response;
mPin2 = pin2;
if (ef == IccConstants.EF_ADN) {
mFh.getEFLinearRecordSize( ef, getEFPath(ef),
obtainMessage(EVENT_EF_LINEAR_RECORD_SIZE_DONE, adn));
} else {
mFh.getEFLinearRecordSize( ef,
obtainMessage(EVENT_EF_LINEAR_RECORD_SIZE_DONE, adn));
}
}
//***** Overridden from Handler
@Override
public void
handleMessage(Message msg) {
AsyncResult ar;
byte data[];
AdnRecord adn;
try {
switch (msg.what) {
case EVENT_EF_LINEAR_RECORD_SIZE_DONE:
ar = (AsyncResult)(msg.obj);
adn = (AdnRecord)(ar.userObj);
if (ar.exception != null) {
throw new RuntimeException("get EF record size failed",
ar.exception);
}
int[] recordSize = (int[])ar.result;
// recordSize is int[3] array
// int[0] is the record length
// int[1] is the total length of the EF file
// int[2] is the number of records in the EF file
// So int[0] * int[2] = int[1]
if (recordSize.length != 3 || mRecordNumber > recordSize[2]) {
throw new RuntimeException("get wrong EF record size format",
ar.exception);
}
data = adn.buildAdnString(recordSize[0]);
if(data == null) {
throw new RuntimeException("wrong ADN format",
ar.exception);
}
- mFh.updateEFLinearFixed(mEf, mRecordNumber,
- data, mPin2, obtainMessage(EVENT_UPDATE_RECORD_DONE));
+ if (mEf == IccConstants.EF_ADN) {
+ mFh.updateEFLinearFixed(mEf, getEFPath(mEf), mRecordNumber,
+ data, mPin2, obtainMessage(EVENT_UPDATE_RECORD_DONE));
+ } else {
+ mFh.updateEFLinearFixed(mEf, mRecordNumber,
+ data, mPin2, obtainMessage(EVENT_UPDATE_RECORD_DONE));
+ }
mPendingExtLoads = 1;
break;
case EVENT_UPDATE_RECORD_DONE:
ar = (AsyncResult)(msg.obj);
if (ar.exception != null) {
throw new RuntimeException("update EF adn record failed",
ar.exception);
}
mPendingExtLoads = 0;
mResult = null;
break;
case EVENT_ADN_LOAD_DONE:
ar = (AsyncResult)(msg.obj);
data = (byte[])(ar.result);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
if (VDBG) {
Rlog.d(LOG_TAG,"ADN EF: 0x"
+ Integer.toHexString(mEf)
+ ":" + mRecordNumber
+ "\n" + IccUtils.bytesToHexString(data));
}
adn = new AdnRecord(mEf, mRecordNumber, data);
mResult = adn;
if (adn.hasExtendedRecord()) {
// If we have a valid value in the ext record field,
// we're not done yet: we need to read the corresponding
// ext record and append it
mPendingExtLoads = 1;
mFh.loadEFLinearFixed(
mExtensionEF, adn.mExtRecord,
obtainMessage(EVENT_EXT_RECORD_LOAD_DONE, adn));
}
break;
case EVENT_EXT_RECORD_LOAD_DONE:
ar = (AsyncResult)(msg.obj);
data = (byte[])(ar.result);
adn = (AdnRecord)(ar.userObj);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
Rlog.d(LOG_TAG,"ADN extension EF: 0x"
+ Integer.toHexString(mExtensionEF)
+ ":" + adn.mExtRecord
+ "\n" + IccUtils.bytesToHexString(data));
adn.appendExtRecord(data);
mPendingExtLoads--;
// result should have been set in
// EVENT_ADN_LOAD_DONE or EVENT_ADN_LOAD_ALL_DONE
break;
case EVENT_ADN_LOAD_ALL_DONE:
ar = (AsyncResult)(msg.obj);
ArrayList<byte[]> datas = (ArrayList<byte[]>)(ar.result);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
mAdns = new ArrayList<AdnRecord>(datas.size());
mResult = mAdns;
mPendingExtLoads = 0;
for(int i = 0, s = datas.size() ; i < s ; i++) {
adn = new AdnRecord(mEf, 1 + i, datas.get(i));
mAdns.add(adn);
if (adn.hasExtendedRecord()) {
// If we have a valid value in the ext record field,
// we're not done yet: we need to read the corresponding
// ext record and append it
mPendingExtLoads++;
mFh.loadEFLinearFixed(
mExtensionEF, adn.mExtRecord,
obtainMessage(EVENT_EXT_RECORD_LOAD_DONE, adn));
}
}
break;
}
} catch (RuntimeException exc) {
if (mUserResponse != null) {
AsyncResult.forMessage(mUserResponse)
.exception = exc;
mUserResponse.sendToTarget();
// Loading is all or nothing--either every load succeeds
// or we fail the whole thing.
mUserResponse = null;
}
return;
}
if (mUserResponse != null && mPendingExtLoads == 0) {
AsyncResult.forMessage(mUserResponse).result
= mResult;
mUserResponse.sendToTarget();
mUserResponse = null;
}
}
}
| true | true | public void
handleMessage(Message msg) {
AsyncResult ar;
byte data[];
AdnRecord adn;
try {
switch (msg.what) {
case EVENT_EF_LINEAR_RECORD_SIZE_DONE:
ar = (AsyncResult)(msg.obj);
adn = (AdnRecord)(ar.userObj);
if (ar.exception != null) {
throw new RuntimeException("get EF record size failed",
ar.exception);
}
int[] recordSize = (int[])ar.result;
// recordSize is int[3] array
// int[0] is the record length
// int[1] is the total length of the EF file
// int[2] is the number of records in the EF file
// So int[0] * int[2] = int[1]
if (recordSize.length != 3 || mRecordNumber > recordSize[2]) {
throw new RuntimeException("get wrong EF record size format",
ar.exception);
}
data = adn.buildAdnString(recordSize[0]);
if(data == null) {
throw new RuntimeException("wrong ADN format",
ar.exception);
}
mFh.updateEFLinearFixed(mEf, mRecordNumber,
data, mPin2, obtainMessage(EVENT_UPDATE_RECORD_DONE));
mPendingExtLoads = 1;
break;
case EVENT_UPDATE_RECORD_DONE:
ar = (AsyncResult)(msg.obj);
if (ar.exception != null) {
throw new RuntimeException("update EF adn record failed",
ar.exception);
}
mPendingExtLoads = 0;
mResult = null;
break;
case EVENT_ADN_LOAD_DONE:
ar = (AsyncResult)(msg.obj);
data = (byte[])(ar.result);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
if (VDBG) {
Rlog.d(LOG_TAG,"ADN EF: 0x"
+ Integer.toHexString(mEf)
+ ":" + mRecordNumber
+ "\n" + IccUtils.bytesToHexString(data));
}
adn = new AdnRecord(mEf, mRecordNumber, data);
mResult = adn;
if (adn.hasExtendedRecord()) {
// If we have a valid value in the ext record field,
// we're not done yet: we need to read the corresponding
// ext record and append it
mPendingExtLoads = 1;
mFh.loadEFLinearFixed(
mExtensionEF, adn.mExtRecord,
obtainMessage(EVENT_EXT_RECORD_LOAD_DONE, adn));
}
break;
case EVENT_EXT_RECORD_LOAD_DONE:
ar = (AsyncResult)(msg.obj);
data = (byte[])(ar.result);
adn = (AdnRecord)(ar.userObj);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
Rlog.d(LOG_TAG,"ADN extension EF: 0x"
+ Integer.toHexString(mExtensionEF)
+ ":" + adn.mExtRecord
+ "\n" + IccUtils.bytesToHexString(data));
adn.appendExtRecord(data);
mPendingExtLoads--;
// result should have been set in
// EVENT_ADN_LOAD_DONE or EVENT_ADN_LOAD_ALL_DONE
break;
case EVENT_ADN_LOAD_ALL_DONE:
ar = (AsyncResult)(msg.obj);
ArrayList<byte[]> datas = (ArrayList<byte[]>)(ar.result);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
mAdns = new ArrayList<AdnRecord>(datas.size());
mResult = mAdns;
mPendingExtLoads = 0;
for(int i = 0, s = datas.size() ; i < s ; i++) {
adn = new AdnRecord(mEf, 1 + i, datas.get(i));
mAdns.add(adn);
if (adn.hasExtendedRecord()) {
// If we have a valid value in the ext record field,
// we're not done yet: we need to read the corresponding
// ext record and append it
mPendingExtLoads++;
mFh.loadEFLinearFixed(
mExtensionEF, adn.mExtRecord,
obtainMessage(EVENT_EXT_RECORD_LOAD_DONE, adn));
}
}
break;
}
} catch (RuntimeException exc) {
if (mUserResponse != null) {
AsyncResult.forMessage(mUserResponse)
.exception = exc;
mUserResponse.sendToTarget();
// Loading is all or nothing--either every load succeeds
// or we fail the whole thing.
mUserResponse = null;
}
return;
}
if (mUserResponse != null && mPendingExtLoads == 0) {
AsyncResult.forMessage(mUserResponse).result
= mResult;
mUserResponse.sendToTarget();
mUserResponse = null;
}
}
| public void
handleMessage(Message msg) {
AsyncResult ar;
byte data[];
AdnRecord adn;
try {
switch (msg.what) {
case EVENT_EF_LINEAR_RECORD_SIZE_DONE:
ar = (AsyncResult)(msg.obj);
adn = (AdnRecord)(ar.userObj);
if (ar.exception != null) {
throw new RuntimeException("get EF record size failed",
ar.exception);
}
int[] recordSize = (int[])ar.result;
// recordSize is int[3] array
// int[0] is the record length
// int[1] is the total length of the EF file
// int[2] is the number of records in the EF file
// So int[0] * int[2] = int[1]
if (recordSize.length != 3 || mRecordNumber > recordSize[2]) {
throw new RuntimeException("get wrong EF record size format",
ar.exception);
}
data = adn.buildAdnString(recordSize[0]);
if(data == null) {
throw new RuntimeException("wrong ADN format",
ar.exception);
}
if (mEf == IccConstants.EF_ADN) {
mFh.updateEFLinearFixed(mEf, getEFPath(mEf), mRecordNumber,
data, mPin2, obtainMessage(EVENT_UPDATE_RECORD_DONE));
} else {
mFh.updateEFLinearFixed(mEf, mRecordNumber,
data, mPin2, obtainMessage(EVENT_UPDATE_RECORD_DONE));
}
mPendingExtLoads = 1;
break;
case EVENT_UPDATE_RECORD_DONE:
ar = (AsyncResult)(msg.obj);
if (ar.exception != null) {
throw new RuntimeException("update EF adn record failed",
ar.exception);
}
mPendingExtLoads = 0;
mResult = null;
break;
case EVENT_ADN_LOAD_DONE:
ar = (AsyncResult)(msg.obj);
data = (byte[])(ar.result);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
if (VDBG) {
Rlog.d(LOG_TAG,"ADN EF: 0x"
+ Integer.toHexString(mEf)
+ ":" + mRecordNumber
+ "\n" + IccUtils.bytesToHexString(data));
}
adn = new AdnRecord(mEf, mRecordNumber, data);
mResult = adn;
if (adn.hasExtendedRecord()) {
// If we have a valid value in the ext record field,
// we're not done yet: we need to read the corresponding
// ext record and append it
mPendingExtLoads = 1;
mFh.loadEFLinearFixed(
mExtensionEF, adn.mExtRecord,
obtainMessage(EVENT_EXT_RECORD_LOAD_DONE, adn));
}
break;
case EVENT_EXT_RECORD_LOAD_DONE:
ar = (AsyncResult)(msg.obj);
data = (byte[])(ar.result);
adn = (AdnRecord)(ar.userObj);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
Rlog.d(LOG_TAG,"ADN extension EF: 0x"
+ Integer.toHexString(mExtensionEF)
+ ":" + adn.mExtRecord
+ "\n" + IccUtils.bytesToHexString(data));
adn.appendExtRecord(data);
mPendingExtLoads--;
// result should have been set in
// EVENT_ADN_LOAD_DONE or EVENT_ADN_LOAD_ALL_DONE
break;
case EVENT_ADN_LOAD_ALL_DONE:
ar = (AsyncResult)(msg.obj);
ArrayList<byte[]> datas = (ArrayList<byte[]>)(ar.result);
if (ar.exception != null) {
throw new RuntimeException("load failed", ar.exception);
}
mAdns = new ArrayList<AdnRecord>(datas.size());
mResult = mAdns;
mPendingExtLoads = 0;
for(int i = 0, s = datas.size() ; i < s ; i++) {
adn = new AdnRecord(mEf, 1 + i, datas.get(i));
mAdns.add(adn);
if (adn.hasExtendedRecord()) {
// If we have a valid value in the ext record field,
// we're not done yet: we need to read the corresponding
// ext record and append it
mPendingExtLoads++;
mFh.loadEFLinearFixed(
mExtensionEF, adn.mExtRecord,
obtainMessage(EVENT_EXT_RECORD_LOAD_DONE, adn));
}
}
break;
}
} catch (RuntimeException exc) {
if (mUserResponse != null) {
AsyncResult.forMessage(mUserResponse)
.exception = exc;
mUserResponse.sendToTarget();
// Loading is all or nothing--either every load succeeds
// or we fail the whole thing.
mUserResponse = null;
}
return;
}
if (mUserResponse != null && mPendingExtLoads == 0) {
AsyncResult.forMessage(mUserResponse).result
= mResult;
mUserResponse.sendToTarget();
mUserResponse = null;
}
}
|
diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java
index ac4ebe2ea..5a2ecf412 100644
--- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java
+++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java
@@ -1,366 +1,366 @@
// ========================================================================
// Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.security.authentication;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.http.security.Constraint;
import org.eclipse.jetty.http.security.Credential;
import org.eclipse.jetty.security.Authenticator.AuthConfiguration;
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.security.UserAuthentication;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.Authentication.User;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
*
* The nonce max age in ms can be set with the {@link SecurityHandler#setInitParameter(String, String)}
* using the name "maxNonceAge"
*/
public class DigestAuthenticator extends LoginAuthenticator
{
private static final Logger LOG = Log.getLogger(DigestAuthenticator.class);
SecureRandom _random = new SecureRandom();
private long _maxNonceAgeMs = 60*1000;
private ConcurrentMap<String, Nonce> _nonceCount = new ConcurrentHashMap<String, Nonce>();
private Queue<Nonce> _nonceQueue = new ConcurrentLinkedQueue<Nonce>();
private static class Nonce
{
final String _nonce;
final long _ts;
AtomicInteger _nc=new AtomicInteger();
public Nonce(String nonce, long ts)
{
_nonce=nonce;
_ts=ts;
}
}
/* ------------------------------------------------------------ */
public DigestAuthenticator()
{
super();
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.AuthConfiguration)
*/
@Override
public void setConfiguration(AuthConfiguration configuration)
{
super.setConfiguration(configuration);
String mna=configuration.getInitParameter("maxNonceAge");
if (mna!=null)
_maxNonceAgeMs=Long.valueOf(mna);
}
/* ------------------------------------------------------------ */
public String getAuthMethod()
{
return Constraint.__DIGEST_AUTH;
}
/* ------------------------------------------------------------ */
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
{
return true;
}
/* ------------------------------------------------------------ */
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
if (!mandatory)
return _deferred;
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
String credentials = request.getHeader(HttpHeaders.AUTHORIZATION);
try
{
boolean stale = false;
if (credentials != null)
{
if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials);
QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
final Digest digest = new Digest(request.getMethod());
String last = null;
String name = null;
while (tokenizer.hasMoreTokens())
{
String tok = tokenizer.nextToken();
char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
switch (c)
{
case '=':
name = last;
last = tok;
break;
case ',':
name = null;
break;
case ' ':
break;
default:
last = tok;
if (name != null)
{
if ("username".equalsIgnoreCase(name))
digest.username = tok;
else if ("realm".equalsIgnoreCase(name))
digest.realm = tok;
else if ("nonce".equalsIgnoreCase(name))
digest.nonce = tok;
else if ("nc".equalsIgnoreCase(name))
digest.nc = tok;
else if ("cnonce".equalsIgnoreCase(name))
digest.cnonce = tok;
else if ("qop".equalsIgnoreCase(name))
digest.qop = tok;
else if ("uri".equalsIgnoreCase(name))
digest.uri = tok;
else if ("response".equalsIgnoreCase(name))
digest.response = tok;
name=null;
}
}
}
int n = checkNonce(digest,(Request)request);
if (n > 0)
{
UserIdentity user = _loginService.login(digest.username,digest);
if (user!=null)
{
renewSessionOnAuthentication(request,response);
return new UserAuthentication(getAuthMethod(),user);
}
}
else if (n == 0)
stale = true;
}
if (!_deferred.isDeferred(response))
{
String domain = request.getContextPath();
if (domain == null)
domain = "/";
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"" + _loginService.getName()
+ "\", domain=\""
+ domain
+ "\", nonce=\""
+ newNonce((Request)request)
- + "\", algorithm=MD5, qop=\"auth\""
+ + "\", algorithm=MD5, qop=\"auth\","
+ " stale=" + stale);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return Authentication.SEND_CONTINUE;
}
return Authentication.UNAUTHENTICATED;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
}
/* ------------------------------------------------------------ */
public String newNonce(Request request)
{
Nonce nonce;
do
{
byte[] nounce = new byte[24];
_random.nextBytes(nounce);
nonce = new Nonce(new String(B64Code.encode(nounce)),request.getTimeStamp());
}
while (_nonceCount.putIfAbsent(nonce._nonce,nonce)!=null);
_nonceQueue.add(nonce);
return nonce._nonce;
}
/**
* @param nstring nonce to check
* @param request
* @return -1 for a bad nonce, 0 for a stale none, 1 for a good nonce
*/
/* ------------------------------------------------------------ */
private int checkNonce(Digest digest, Request request)
{
// firstly let's expire old nonces
long expired = request.getTimeStamp()-_maxNonceAgeMs;
Nonce nonce=_nonceQueue.peek();
while (nonce!=null && nonce._ts<expired)
{
_nonceQueue.remove();
_nonceCount.remove(nonce._nonce);
nonce=_nonceQueue.peek();
}
try
{
nonce = _nonceCount.get(digest.nonce);
if (nonce==null)
return 0;
long count = Long.parseLong(digest.nc,16);
if (count>Integer.MAX_VALUE)
return 0;
int old=nonce._nc.get();
while (!nonce._nc.compareAndSet(old,(int)count))
old=nonce._nc.get();
if (count<=old)
return -1;
return 1;
}
catch (Exception e)
{
LOG.ignore(e);
}
return -1;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private static class Digest extends Credential
{
private static final long serialVersionUID = -2484639019549527724L;
final String method;
String username = "";
String realm = "";
String nonce = "";
String nc = "";
String cnonce = "";
String qop = "";
String uri = "";
String response = "";
/* ------------------------------------------------------------ */
Digest(String m)
{
method = m;
}
/* ------------------------------------------------------------ */
@Override
public boolean check(Object credentials)
{
if (credentials instanceof char[])
credentials=new String((char[])credentials);
String password = (credentials instanceof String) ? (String) credentials : credentials.toString();
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] ha1;
if (credentials instanceof Credential.MD5)
{
// Credentials are already a MD5 digest - assume it's in
// form user:realm:password (we have no way to know since
// it's a digest, alright?)
ha1 = ((Credential.MD5) credentials).getDigest();
}
else
{
// calc A1 digest
md.update(username.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(realm.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(password.getBytes(StringUtil.__ISO_8859_1));
ha1 = md.digest();
}
// calc A2 digest
md.reset();
md.update(method.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(uri.getBytes(StringUtil.__ISO_8859_1));
byte[] ha2 = md.digest();
// calc digest
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
// nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
// <">
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
// ) > <">
md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(nonce.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(nc.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(cnonce.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(qop.getBytes(StringUtil.__ISO_8859_1));
md.update((byte) ':');
md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1));
byte[] digest = md.digest();
// check digest
return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response));
}
catch (Exception e)
{
LOG.warn(e);
}
return false;
}
public String toString()
{
return username + "," + response;
}
}
}
| true | true | public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
if (!mandatory)
return _deferred;
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
String credentials = request.getHeader(HttpHeaders.AUTHORIZATION);
try
{
boolean stale = false;
if (credentials != null)
{
if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials);
QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
final Digest digest = new Digest(request.getMethod());
String last = null;
String name = null;
while (tokenizer.hasMoreTokens())
{
String tok = tokenizer.nextToken();
char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
switch (c)
{
case '=':
name = last;
last = tok;
break;
case ',':
name = null;
break;
case ' ':
break;
default:
last = tok;
if (name != null)
{
if ("username".equalsIgnoreCase(name))
digest.username = tok;
else if ("realm".equalsIgnoreCase(name))
digest.realm = tok;
else if ("nonce".equalsIgnoreCase(name))
digest.nonce = tok;
else if ("nc".equalsIgnoreCase(name))
digest.nc = tok;
else if ("cnonce".equalsIgnoreCase(name))
digest.cnonce = tok;
else if ("qop".equalsIgnoreCase(name))
digest.qop = tok;
else if ("uri".equalsIgnoreCase(name))
digest.uri = tok;
else if ("response".equalsIgnoreCase(name))
digest.response = tok;
name=null;
}
}
}
int n = checkNonce(digest,(Request)request);
if (n > 0)
{
UserIdentity user = _loginService.login(digest.username,digest);
if (user!=null)
{
renewSessionOnAuthentication(request,response);
return new UserAuthentication(getAuthMethod(),user);
}
}
else if (n == 0)
stale = true;
}
if (!_deferred.isDeferred(response))
{
String domain = request.getContextPath();
if (domain == null)
domain = "/";
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"" + _loginService.getName()
+ "\", domain=\""
+ domain
+ "\", nonce=\""
+ newNonce((Request)request)
+ "\", algorithm=MD5, qop=\"auth\""
+ " stale=" + stale);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return Authentication.SEND_CONTINUE;
}
return Authentication.UNAUTHENTICATED;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
}
| public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
if (!mandatory)
return _deferred;
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
String credentials = request.getHeader(HttpHeaders.AUTHORIZATION);
try
{
boolean stale = false;
if (credentials != null)
{
if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials);
QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
final Digest digest = new Digest(request.getMethod());
String last = null;
String name = null;
while (tokenizer.hasMoreTokens())
{
String tok = tokenizer.nextToken();
char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
switch (c)
{
case '=':
name = last;
last = tok;
break;
case ',':
name = null;
break;
case ' ':
break;
default:
last = tok;
if (name != null)
{
if ("username".equalsIgnoreCase(name))
digest.username = tok;
else if ("realm".equalsIgnoreCase(name))
digest.realm = tok;
else if ("nonce".equalsIgnoreCase(name))
digest.nonce = tok;
else if ("nc".equalsIgnoreCase(name))
digest.nc = tok;
else if ("cnonce".equalsIgnoreCase(name))
digest.cnonce = tok;
else if ("qop".equalsIgnoreCase(name))
digest.qop = tok;
else if ("uri".equalsIgnoreCase(name))
digest.uri = tok;
else if ("response".equalsIgnoreCase(name))
digest.response = tok;
name=null;
}
}
}
int n = checkNonce(digest,(Request)request);
if (n > 0)
{
UserIdentity user = _loginService.login(digest.username,digest);
if (user!=null)
{
renewSessionOnAuthentication(request,response);
return new UserAuthentication(getAuthMethod(),user);
}
}
else if (n == 0)
stale = true;
}
if (!_deferred.isDeferred(response))
{
String domain = request.getContextPath();
if (domain == null)
domain = "/";
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"" + _loginService.getName()
+ "\", domain=\""
+ domain
+ "\", nonce=\""
+ newNonce((Request)request)
+ "\", algorithm=MD5, qop=\"auth\","
+ " stale=" + stale);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return Authentication.SEND_CONTINUE;
}
return Authentication.UNAUTHENTICATED;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
}
|
diff --git a/src/test/com/mongodb/DBRefTest.java b/src/test/com/mongodb/DBRefTest.java
index 67b4ab446..048a951e7 100644
--- a/src/test/com/mongodb/DBRefTest.java
+++ b/src/test/com/mongodb/DBRefTest.java
@@ -1,156 +1,156 @@
/**
* Copyright (C) 2008 10gen 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.mongodb;
import java.net.*;
import java.util.*;
import org.bson.*;
import org.bson.types.*;
import org.testng.annotations.*;
import com.mongodb.util.*;
public class DBRefTest extends TestCase {
public DBRefTest() {
try {
cleanupMongo = new Mongo( "127.0.0.1" );
cleanupDB = "com_monogodb_unittest_DBRefTest";
_db = cleanupMongo.getDB( cleanupDB );
}
catch(UnknownHostException e) {
throw new MongoException("couldn't connect");
}
}
@Test(groups = {"basic"})
public void testDBRefBaseToString(){
ObjectId id = new ObjectId("123456789012345678901234");
DBRefBase ref = new DBRefBase(_db, "foo.bar", id);
assertEquals("{ \"$ref\" : \"foo.bar\", \"$id\" : \"123456789012345678901234\" }", ref.toString());
}
@Test(groups = {"basic"})
public void testDBRef(){
DBRef ref = new DBRef(_db, "hello", (Object)"world");
DBObject o = new BasicDBObject("!", ref);
OutMessage out = new OutMessage( cleanupMongo );
out.putObject( o );
DefaultDBCallback cb = new DefaultDBCallback( null );
BSONDecoder decoder = new BasicBSONDecoder();
decoder.decode( out.toByteArray() , cb );
DBObject read = cb.dbget();
- String correct = null;
- correct = "{\"!\":{\"$ref\":\"hello\",\"$id\":\"world\"}}";
+ String correct = null;
+ correct = "{\"!\":{\"$ref\":\"hello\",\"$id\":\"world\"}}";
String got = read.toString().replaceAll( " +" , "" );
assertEquals( correct , got );
}
@Test(groups = {"basic"})
public void testDBRefFetches(){
DBCollection coll = _db.getCollection("x");
coll.drop();
BasicDBObject obj = new BasicDBObject("_id", 321325243);
coll.save(obj);
DBRef ref = new DBRef(_db, "x", 321325243);
DBObject deref = ref.fetch();
assertTrue(deref != null);
assertEquals(321325243, ((Number)deref.get("_id")).intValue());
DBObject refobj = BasicDBObjectBuilder.start().add("$ref", "x").add("$id", 321325243).get();
deref = DBRef.fetch(_db, refobj);
assertTrue(deref != null);
assertEquals(321325243, ((Number)deref.get("_id")).intValue());
}
@SuppressWarnings("unchecked")
@Test
public void testRefListRoundTrip(){
DBCollection a = _db.getCollection( "reflistfield" );
List<DBRef> refs = new ArrayList<DBRef>();
refs.add(new DBRef(_db, "other", 12));
refs.add(new DBRef(_db, "other", 14));
refs.add(new DBRef(_db, "other", 16));
a.save( BasicDBObjectBuilder.start( "refs" , refs).get() );
DBObject loaded = a.findOne();
assertNotNull( loaded );
List<DBRef> refsLoaded = (List<DBRef>) loaded.get("refs");
assertNotNull( refsLoaded );
assertEquals(3, refsLoaded.size());
assertEquals(DBRef.class, refsLoaded.get(0).getClass());
assertEquals(12, refsLoaded.get(0).getId());
assertEquals(14, refsLoaded.get(1).getId());
assertEquals(16, refsLoaded.get(2).getId());
}
@Test
public void testRoundTrip(){
DBCollection a = _db.getCollection( "refroundtripa" );
DBCollection b = _db.getCollection( "refroundtripb" );
a.drop();
b.drop();
a.save( BasicDBObjectBuilder.start( "_id" , 17 ).add( "n" , 111 ).get() );
b.save( BasicDBObjectBuilder.start( "n" , 12 ).add( "l" , new DBRef( _db , "refroundtripa" , 17 ) ).get() );
assertEquals( 12 , b.findOne().get( "n" ) );
assertEquals( DBRef.class , b.findOne().get( "l" ).getClass() );
assertEquals( 111 , ((DBRef)(b.findOne().get( "l" ))).fetch().get( "n" ) );
}
@Test
public void testFindByDBRef(){
DBCollection b = _db.getCollection( "b" );
b.drop();
DBRef ref = new DBRef( _db , "fake" , 17 );
b.save( BasicDBObjectBuilder.start( "n" , 12 ).add( "l" , ref ).get() );
assertEquals( 12 , b.findOne().get( "n" ) );
assertEquals( DBRef.class , b.findOne().get( "l" ).getClass() );
DBObject loaded = b.findOne(BasicDBObjectBuilder.start( "l" , ref ).get() );
assertEquals( 12 , loaded.get( "n" ) );
assertEquals( DBRef.class , loaded.get( "l" ).getClass() );
assertEquals( ref.getId(), ((DBRef)loaded.get( "l" )).getId());
assertEquals( ref.getRef(), ((DBRef)loaded.get( "l" )).getRef());
assertEquals( ref.getDB(), ((DBRef)loaded.get( "l" )).getDB());
}
DB _db;
public static void main( String args[] ) {
(new DBRefTest()).runConsole();
}
}
| true | true | public void testDBRef(){
DBRef ref = new DBRef(_db, "hello", (Object)"world");
DBObject o = new BasicDBObject("!", ref);
OutMessage out = new OutMessage( cleanupMongo );
out.putObject( o );
DefaultDBCallback cb = new DefaultDBCallback( null );
BSONDecoder decoder = new BasicBSONDecoder();
decoder.decode( out.toByteArray() , cb );
DBObject read = cb.dbget();
String correct = null;
correct = "{\"!\":{\"$ref\":\"hello\",\"$id\":\"world\"}}";
String got = read.toString().replaceAll( " +" , "" );
assertEquals( correct , got );
}
| public void testDBRef(){
DBRef ref = new DBRef(_db, "hello", (Object)"world");
DBObject o = new BasicDBObject("!", ref);
OutMessage out = new OutMessage( cleanupMongo );
out.putObject( o );
DefaultDBCallback cb = new DefaultDBCallback( null );
BSONDecoder decoder = new BasicBSONDecoder();
decoder.decode( out.toByteArray() , cb );
DBObject read = cb.dbget();
String correct = null;
correct = "{\"!\":{\"$ref\":\"hello\",\"$id\":\"world\"}}";
String got = read.toString().replaceAll( " +" , "" );
assertEquals( correct , got );
}
|
diff --git a/core/src/org/icepdf/core/pobjects/Form.java b/core/src/org/icepdf/core/pobjects/Form.java
index 428fd4c2..044c2683 100644
--- a/core/src/org/icepdf/core/pobjects/Form.java
+++ b/core/src/org/icepdf/core/pobjects/Form.java
@@ -1,223 +1,223 @@
/*
* Copyright 2006-2012 ICEsoft Technologies 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 org.icepdf.core.pobjects;
import org.icepdf.core.io.SeekableInputConstrainedWrapper;
import org.icepdf.core.pobjects.graphics.GraphicsState;
import org.icepdf.core.pobjects.graphics.Shapes;
import org.icepdf.core.util.Library;
import org.icepdf.core.util.content.ContentParser;
import org.icepdf.core.util.content.ContentParserFactory;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Form XObject class. Not currently part of the public api.
* <p/>
* Forms are grouped into the 'Resource' category and can be shared. As a result we need to make sure
* that the init method are synchronized as they can be accessed by different page loading threads.
*
* @since 1.0
*/
public class Form extends Stream {
private static final Logger logger =
Logger.getLogger(Form.class.toString());
public static final Name GROUP_KEY = new Name("Group");
public static final Name I_KEY = new Name("I");
public static final Name K_KEY = new Name("K");
public static final Name MATRIX_KEY = new Name("Matrix");
public static final Name BBOX_KEY = new Name("BBox");
public static final Name RESOURCES_KEY = new Name("Resources");
private AffineTransform matrix = new AffineTransform();
private Rectangle2D bbox;
private Shapes shapes;
// Graphics state object to be used by content parser
private GraphicsState graphicsState;
private Resources resources;
private Resources parentResource;
// transparency grouping data
private boolean transparencyGroup;
private boolean isolated;
private boolean knockOut;
private boolean inited = false;
/**
* Creates a new instance of the xObject.
*
* @param l document library
* @param h xObject dictionary entries.
* @param streamInputWrapper content stream of image or post script commands.
*/
public Form(Library l, HashMap h, SeekableInputConstrainedWrapper streamInputWrapper) {
super(l, h, streamInputWrapper);
// check for grouping flags so we can do special handling during the
// xform content stream parsing.
HashMap group = library.getDictionary(entries, GROUP_KEY);
if (group != null) {
transparencyGroup = true;
isolated = library.getBoolean(group, I_KEY);
knockOut = library.getBoolean(group, K_KEY);
}
}
/**
* Sets the GraphicsState which should be used by the content parser when
* parsing the Forms content stream. The GraphicsState should be set
* before init() is called, or it will have not effect on the rendered
* content.
*
* @param graphicsState current graphic state
*/
public void setGraphicsState(GraphicsState graphicsState) {
if (graphicsState != null) {
this.graphicsState = graphicsState;
}
}
/**
* Utility method for parsing a vector of affinetranform values to an
* affine transform.
*
* @param v vectory containing affine transform values.
* @return affine tansform based on v
*/
private static AffineTransform getAffineTransform(List v) {
float f[] = new float[6];
for (int i = 0; i < 6; i++) {
f[i] = ((Number) v.get(i)).floatValue();
}
return new AffineTransform(f);
}
/**
* As of the PDF 1.2 specification, a resource entry is not required for
* a XObject and thus it needs to point to the parent resource to enable
* to correctly load the content stream.
*
* @param parentResource parent objects resourse when available.
*/
public void setParentResources(Resources parentResource) {
this.parentResource = parentResource;
}
/**
*
*/
public synchronized void init() {
if (inited) {
return;
}
List v = (List) library.getObject(entries, MATRIX_KEY);
if (v != null) {
matrix = getAffineTransform(v);
}
bbox = library.getRectangle(entries, BBOX_KEY);
// try and find the form's resources dictionary.
Resources leafResources = library.getResources(entries, RESOURCES_KEY);
// apply parent resource, if the current resources is null
if (leafResources != null) {
resources = leafResources;
} else {
leafResources = parentResource;
}
// Build a new content parser for the content streams and apply the
// content stream of the calling content stream.
ContentParser cp = ContentParserFactory.getInstance()
- .getContentParser(library, resources);
+ .getContentParser(library, leafResources);
cp.setGraphicsState(graphicsState);
byte[] in = getDecodedStreamBytes();
if (in != null) {
try {
if (logger.isLoggable(Level.FINER)) {
logger.finer("Parsing form " + getPObjectReference());
}
shapes = cp.parse(new byte[][]{in}).getShapes();
} catch (Throwable e) {
// reset shapes vector, we don't want to mess up the paint stack
shapes = new Shapes();
logger.log(Level.FINE, "Error parsing Form content stream.", e);
}
}
inited = true;
}
/**
* Gets the shapes that where parsed from the content stream.
*
* @return shapes object for xObject.
*/
public Shapes getShapes() {
return shapes;
}
/**
* Gets the bounding box for the xObject.
*
* @return rectangle in PDF coordinate space representing xObject bounds.
*/
public Rectangle2D getBBox() {
return bbox;
}
/**
* Gets the optional matrix which describes how to convert the coordinate
* system in xObject space to the parent coordinates space.
*
* @return affine transform representing the xObject's pdf to xObject space
* transform.
*/
public AffineTransform getMatrix() {
return matrix;
}
/**
* If the xObject has a transparency group flag.
*
* @return true if a transparency group exists, false otherwise.
*/
public boolean isTransparencyGroup() {
return transparencyGroup;
}
/**
* Only present if a transparency group is present. Isolated groups are
* composed on a fully transparent back drop rather then the groups.
*
* @return true if the transparency group is isolated.
*/
public boolean isIsolated() {
return isolated;
}
/**
* Only present if a transparency group is present. Knockout groups individual
* elements composed with the groups initial back drop rather then the stack.
*
* @return true if the transparency group is a knockout.
*/
public boolean isKnockOut() {
return knockOut;
}
}
| true | true | public synchronized void init() {
if (inited) {
return;
}
List v = (List) library.getObject(entries, MATRIX_KEY);
if (v != null) {
matrix = getAffineTransform(v);
}
bbox = library.getRectangle(entries, BBOX_KEY);
// try and find the form's resources dictionary.
Resources leafResources = library.getResources(entries, RESOURCES_KEY);
// apply parent resource, if the current resources is null
if (leafResources != null) {
resources = leafResources;
} else {
leafResources = parentResource;
}
// Build a new content parser for the content streams and apply the
// content stream of the calling content stream.
ContentParser cp = ContentParserFactory.getInstance()
.getContentParser(library, resources);
cp.setGraphicsState(graphicsState);
byte[] in = getDecodedStreamBytes();
if (in != null) {
try {
if (logger.isLoggable(Level.FINER)) {
logger.finer("Parsing form " + getPObjectReference());
}
shapes = cp.parse(new byte[][]{in}).getShapes();
} catch (Throwable e) {
// reset shapes vector, we don't want to mess up the paint stack
shapes = new Shapes();
logger.log(Level.FINE, "Error parsing Form content stream.", e);
}
}
inited = true;
}
| public synchronized void init() {
if (inited) {
return;
}
List v = (List) library.getObject(entries, MATRIX_KEY);
if (v != null) {
matrix = getAffineTransform(v);
}
bbox = library.getRectangle(entries, BBOX_KEY);
// try and find the form's resources dictionary.
Resources leafResources = library.getResources(entries, RESOURCES_KEY);
// apply parent resource, if the current resources is null
if (leafResources != null) {
resources = leafResources;
} else {
leafResources = parentResource;
}
// Build a new content parser for the content streams and apply the
// content stream of the calling content stream.
ContentParser cp = ContentParserFactory.getInstance()
.getContentParser(library, leafResources);
cp.setGraphicsState(graphicsState);
byte[] in = getDecodedStreamBytes();
if (in != null) {
try {
if (logger.isLoggable(Level.FINER)) {
logger.finer("Parsing form " + getPObjectReference());
}
shapes = cp.parse(new byte[][]{in}).getShapes();
} catch (Throwable e) {
// reset shapes vector, we don't want to mess up the paint stack
shapes = new Shapes();
logger.log(Level.FINE, "Error parsing Form content stream.", e);
}
}
inited = true;
}
|
diff --git a/Pos/src/com/rtt_ku/pos/Add_Activity.java b/Pos/src/com/rtt_ku/pos/Add_Activity.java
index 87122c3..47ed7a8 100644
--- a/Pos/src/com/rtt_ku/pos/Add_Activity.java
+++ b/Pos/src/com/rtt_ku/pos/Add_Activity.java
@@ -1,101 +1,101 @@
package com.rtt_ku.pos;
import com.database.pos.Database;
import com.rtt_store.pos.StoreController;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* activity on add button.
* @author Suttanan
*
*/
public class Add_Activity extends Activity {
StoreController sCT ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_layout);
// view matching
Button okButton = (Button)findViewById(R.id.OK_button);
Button cancelButton = (Button)findViewById(R.id.cancel_button);
Database myDb = new Database(this);
myDb.getWritableDatabase();
sCT = new StoreController(myDb);;
// add function on click at OK button.
okButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText pc = (EditText)findViewById(R.id.pc_text);
EditText n = (EditText)findViewById(R.id.name_text);
EditText quan = (EditText)findViewById(R.id.quantity_text);
EditText p =(EditText)findViewById(R.id.price_text);
// toString
String product_code = pc.getText().toString();
String name = n.getText().toString();
String quantityString = quan.getText().toString();
String priceString = p.getText().toString();
if (!(product_code.equals("") || name.equals("") || quantityString.equals("") || priceString.equals("")))
{
if (name.equals("")) name = "empty";
int quantity;
quantity = Integer.parseInt(quan.getText().toString());
int price;
price = Integer.parseInt(p.getText().toString());
// when click add button
insertProduct(product_code, name, quantity, price,"","","","","","","");
}
else
{
Toast.makeText(Add_Activity.this,"miss some necessary details", Toast.LENGTH_SHORT).show();
}
}
});
// add function on click at cancel button.
cancelButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
- setContentView(R.layout.activity_main);
- startActivity(new Intent(Add_Activity.this, Tab_Inventory_Activity.class));
+ //setContentView(R.layout.activity_main);
+ startActivity(new Intent(Add_Activity.this, main_activity.class));
}
});
}
/**
* insert product on list view.
* @param product_code code of each product.
* @param name name of product.
* @param quantity quantity of product.
* @param price price of product.
*/
public void insertProduct(String productCode, String name, int quantity, int price, String type, String date,
String barcode, String picture, String lastedit, String status, String stage)
{
int temp = sCT.addProduct(productCode, name, quantity, price,type,date,barcode,picture,lastedit,status,stage);
if (temp == 1) Toast.makeText(Add_Activity.this,"added <" + productCode + "> " + name + " Complete.", Toast.LENGTH_SHORT).show();
else if (temp == -1) Toast.makeText(Add_Activity.this, productCode + " is already exist.", Toast.LENGTH_SHORT).show();
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_layout);
// view matching
Button okButton = (Button)findViewById(R.id.OK_button);
Button cancelButton = (Button)findViewById(R.id.cancel_button);
Database myDb = new Database(this);
myDb.getWritableDatabase();
sCT = new StoreController(myDb);;
// add function on click at OK button.
okButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText pc = (EditText)findViewById(R.id.pc_text);
EditText n = (EditText)findViewById(R.id.name_text);
EditText quan = (EditText)findViewById(R.id.quantity_text);
EditText p =(EditText)findViewById(R.id.price_text);
// toString
String product_code = pc.getText().toString();
String name = n.getText().toString();
String quantityString = quan.getText().toString();
String priceString = p.getText().toString();
if (!(product_code.equals("") || name.equals("") || quantityString.equals("") || priceString.equals("")))
{
if (name.equals("")) name = "empty";
int quantity;
quantity = Integer.parseInt(quan.getText().toString());
int price;
price = Integer.parseInt(p.getText().toString());
// when click add button
insertProduct(product_code, name, quantity, price,"","","","","","","");
}
else
{
Toast.makeText(Add_Activity.this,"miss some necessary details", Toast.LENGTH_SHORT).show();
}
}
});
// add function on click at cancel button.
cancelButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.activity_main);
startActivity(new Intent(Add_Activity.this, Tab_Inventory_Activity.class));
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_layout);
// view matching
Button okButton = (Button)findViewById(R.id.OK_button);
Button cancelButton = (Button)findViewById(R.id.cancel_button);
Database myDb = new Database(this);
myDb.getWritableDatabase();
sCT = new StoreController(myDb);;
// add function on click at OK button.
okButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText pc = (EditText)findViewById(R.id.pc_text);
EditText n = (EditText)findViewById(R.id.name_text);
EditText quan = (EditText)findViewById(R.id.quantity_text);
EditText p =(EditText)findViewById(R.id.price_text);
// toString
String product_code = pc.getText().toString();
String name = n.getText().toString();
String quantityString = quan.getText().toString();
String priceString = p.getText().toString();
if (!(product_code.equals("") || name.equals("") || quantityString.equals("") || priceString.equals("")))
{
if (name.equals("")) name = "empty";
int quantity;
quantity = Integer.parseInt(quan.getText().toString());
int price;
price = Integer.parseInt(p.getText().toString());
// when click add button
insertProduct(product_code, name, quantity, price,"","","","","","","");
}
else
{
Toast.makeText(Add_Activity.this,"miss some necessary details", Toast.LENGTH_SHORT).show();
}
}
});
// add function on click at cancel button.
cancelButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//setContentView(R.layout.activity_main);
startActivity(new Intent(Add_Activity.this, main_activity.class));
}
});
}
|
diff --git a/src/main/java/org/candlepin/util/X509Util.java b/src/main/java/org/candlepin/util/X509Util.java
index b60ff5168..60a26a9eb 100644
--- a/src/main/java/org/candlepin/util/X509Util.java
+++ b/src/main/java/org/candlepin/util/X509Util.java
@@ -1,226 +1,228 @@
/**
* Copyright (c) 2009 - 2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.util;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.candlepin.model.Consumer;
import org.candlepin.model.Entitlement;
import org.candlepin.model.EntitlementCurator;
import org.candlepin.model.EnvironmentContent;
import org.candlepin.model.Product;
import org.candlepin.model.ProductContent;
import com.google.common.base.Predicate;
/**
* X509Util
*/
public abstract class X509Util {
private static Logger log = Logger.getLogger(X509Util.class);
public static final Predicate<Product>
PROD_FILTER_PREDICATE = new Predicate<Product>() {
@Override
public boolean apply(Product product) {
return product != null && StringUtils.isNumeric(product.getId());
}
};
public static final String ARCH_FACT = "uname.machine";
public static final String PRODUCT_ARCH_ATTR = "arch";
/**
* Scan the product content looking for any we should filter out.
*
* Will filter out any content which modifies another product if the consumer does
* not have an entitlement granting them access to that product.
*
* Will also filter out any content not promoted to the consumer's environment
* if environment filtering is enabled.
*
* @param prod the product who's content we should filter
* @param ent the original entitlement
* @param entCurator
* @param promotedContent
* @param filterEnvironment show content also be filtered by environment.
* @return ProductContent to include in the certificate.
*/
public Set<ProductContent> filterProductContent(Product prod, Entitlement ent,
EntitlementCurator entCurator, Map<String, EnvironmentContent> promotedContent,
boolean filterEnvironment) {
Set<ProductContent> filtered = new HashSet<ProductContent>();
for (ProductContent pc : prod.getProductContent()) {
// Filter any content not promoted to environment.
if (filterEnvironment) {
if (ent.getConsumer().getEnvironment() != null &&
!promotedContent.containsKey(pc.getContent().getId())) {
log.debug("Skipping content not promoted to environment: " +
pc.getContent().getId());
continue;
}
}
boolean include = true;
if (pc.getContent().getModifiedProductIds().size() > 0) {
include = false;
Set<String> prodIds = pc.getContent().getModifiedProductIds();
// If consumer has an entitlement to just one of the modified products,
// we will include this content set:
for (String prodId : prodIds) {
Set<Entitlement> entsProviding = entCurator.listProviding(
ent.getConsumer(), prodId, ent.getStartDate(), ent.getEndDate());
if (entsProviding.size() > 0) {
include = true;
break;
}
}
}
if (include) {
filtered.add(pc);
}
}
return filtered;
}
/**
* Creates a Content url from the prefix and the path
* @param contentPrefix to prepend to the path
* @param pc the product content
* @return the complete content path
*/
public String createFullContentPath(String contentPrefix, ProductContent pc) {
String prefix = "/";
String contentPath = pc.getContent().getContentUrl();
// Allow for the case wherethe content url is a true url.
// If that is true, then return it as is.
if (contentPath.startsWith("http://") ||
contentPath.startsWith("file://") ||
contentPath.startsWith("https://") ||
contentPath.startsWith("ftp://")) {
return contentPath;
}
if (!StringUtils.isEmpty(contentPrefix)) {
// Ensure there is no double // in the URL. See BZ952735
// remove them all except one.
prefix = StringUtils.stripEnd(contentPrefix, "/") + prefix;
}
contentPath = StringUtils.stripStart(contentPath, "/");
return prefix + contentPath;
}
/*
* remove content sets that do not match the consumers arch
*/
public Set<ProductContent> filterContentByContentArch(
Set<ProductContent> pcSet, Consumer consumer, Product product) {
Set<ProductContent> filtered = new HashSet<ProductContent>();
String consumerArch = consumer.getFact(ARCH_FACT);
log.debug("consumerArch: " + consumerArch);
if (consumerArch == null) {
log.debug("consumer: " + consumer.getId() + " has no " +
ARCH_FACT + " attribute.");
log.debug("Not filtering by arch");
return pcSet;
}
for (ProductContent pc : pcSet) {
boolean canUse = true;
Set<String> contentArches = Arch.parseArches(pc.getContent().getArches());
Set<String> productArches =
Arch.parseArches(product.getAttributeValue(PRODUCT_ARCH_ATTR));
log.debug("productContent arch list for " +
pc.getContent().getLabel());
log.debug("contentArches: " + contentArches);
log.debug("productArches: " + productArches);
// Empty or null Content.arches should result in
// inheriting the arches from the product
if (contentArches.isEmpty()) {
log.debug("Content set " + pc.getContent().getLabel() +
" does not specify content arches");
// No content arch, see if there is a Product arch
// and if so inherit it.
if (!productArches.isEmpty()) {
contentArches.addAll(productArches);
log.debug("Using the arches from the product " +
product.toString());
log.debug("productArches: " + productArches.toString());
}
else {
// No Product arches either, log it, but do
// not filter out this content
log.debug("No arch attributes found for content or product");
}
}
for (String contentArch : contentArches) {
log.debug("Checking consumerArch " + consumerArch +
" can use content for " + contentArch);
log.debug("arch.contentForConsumer" +
Arch.contentForConsumer(contentArch, consumerArch));
if (Arch.contentForConsumer(contentArch, consumerArch)) {
log.debug("Can use content " +
pc.getContent().getLabel() + " for arch " + contentArch);
+ canUse = true;
+ break;
}
else {
log.debug("Can not use content " +
pc.getContent().getLabel() + " for arch " +
contentArch);
canUse = false;
}
}
// If we found a workable arch for this content, include it
// also include content where no arch was found at all (on
// Content or on Product)
if (canUse) {
filtered.add(pc);
log.debug("Including content " +
pc.getContent().getLabel());
}
else {
log.debug("Skipping content " + pc.getContent().getLabel());
}
}
log.debug("Arch approriate content for " +
consumerArch + " includes: ");
for (ProductContent apc : filtered) {
log.debug("\t " + apc.toString());
}
return filtered;
}
}
| true | true | public Set<ProductContent> filterContentByContentArch(
Set<ProductContent> pcSet, Consumer consumer, Product product) {
Set<ProductContent> filtered = new HashSet<ProductContent>();
String consumerArch = consumer.getFact(ARCH_FACT);
log.debug("consumerArch: " + consumerArch);
if (consumerArch == null) {
log.debug("consumer: " + consumer.getId() + " has no " +
ARCH_FACT + " attribute.");
log.debug("Not filtering by arch");
return pcSet;
}
for (ProductContent pc : pcSet) {
boolean canUse = true;
Set<String> contentArches = Arch.parseArches(pc.getContent().getArches());
Set<String> productArches =
Arch.parseArches(product.getAttributeValue(PRODUCT_ARCH_ATTR));
log.debug("productContent arch list for " +
pc.getContent().getLabel());
log.debug("contentArches: " + contentArches);
log.debug("productArches: " + productArches);
// Empty or null Content.arches should result in
// inheriting the arches from the product
if (contentArches.isEmpty()) {
log.debug("Content set " + pc.getContent().getLabel() +
" does not specify content arches");
// No content arch, see if there is a Product arch
// and if so inherit it.
if (!productArches.isEmpty()) {
contentArches.addAll(productArches);
log.debug("Using the arches from the product " +
product.toString());
log.debug("productArches: " + productArches.toString());
}
else {
// No Product arches either, log it, but do
// not filter out this content
log.debug("No arch attributes found for content or product");
}
}
for (String contentArch : contentArches) {
log.debug("Checking consumerArch " + consumerArch +
" can use content for " + contentArch);
log.debug("arch.contentForConsumer" +
Arch.contentForConsumer(contentArch, consumerArch));
if (Arch.contentForConsumer(contentArch, consumerArch)) {
log.debug("Can use content " +
pc.getContent().getLabel() + " for arch " + contentArch);
}
else {
log.debug("Can not use content " +
pc.getContent().getLabel() + " for arch " +
contentArch);
canUse = false;
}
}
// If we found a workable arch for this content, include it
// also include content where no arch was found at all (on
// Content or on Product)
if (canUse) {
filtered.add(pc);
log.debug("Including content " +
pc.getContent().getLabel());
}
else {
log.debug("Skipping content " + pc.getContent().getLabel());
}
}
log.debug("Arch approriate content for " +
consumerArch + " includes: ");
for (ProductContent apc : filtered) {
log.debug("\t " + apc.toString());
}
return filtered;
}
| public Set<ProductContent> filterContentByContentArch(
Set<ProductContent> pcSet, Consumer consumer, Product product) {
Set<ProductContent> filtered = new HashSet<ProductContent>();
String consumerArch = consumer.getFact(ARCH_FACT);
log.debug("consumerArch: " + consumerArch);
if (consumerArch == null) {
log.debug("consumer: " + consumer.getId() + " has no " +
ARCH_FACT + " attribute.");
log.debug("Not filtering by arch");
return pcSet;
}
for (ProductContent pc : pcSet) {
boolean canUse = true;
Set<String> contentArches = Arch.parseArches(pc.getContent().getArches());
Set<String> productArches =
Arch.parseArches(product.getAttributeValue(PRODUCT_ARCH_ATTR));
log.debug("productContent arch list for " +
pc.getContent().getLabel());
log.debug("contentArches: " + contentArches);
log.debug("productArches: " + productArches);
// Empty or null Content.arches should result in
// inheriting the arches from the product
if (contentArches.isEmpty()) {
log.debug("Content set " + pc.getContent().getLabel() +
" does not specify content arches");
// No content arch, see if there is a Product arch
// and if so inherit it.
if (!productArches.isEmpty()) {
contentArches.addAll(productArches);
log.debug("Using the arches from the product " +
product.toString());
log.debug("productArches: " + productArches.toString());
}
else {
// No Product arches either, log it, but do
// not filter out this content
log.debug("No arch attributes found for content or product");
}
}
for (String contentArch : contentArches) {
log.debug("Checking consumerArch " + consumerArch +
" can use content for " + contentArch);
log.debug("arch.contentForConsumer" +
Arch.contentForConsumer(contentArch, consumerArch));
if (Arch.contentForConsumer(contentArch, consumerArch)) {
log.debug("Can use content " +
pc.getContent().getLabel() + " for arch " + contentArch);
canUse = true;
break;
}
else {
log.debug("Can not use content " +
pc.getContent().getLabel() + " for arch " +
contentArch);
canUse = false;
}
}
// If we found a workable arch for this content, include it
// also include content where no arch was found at all (on
// Content or on Product)
if (canUse) {
filtered.add(pc);
log.debug("Including content " +
pc.getContent().getLabel());
}
else {
log.debug("Skipping content " + pc.getContent().getLabel());
}
}
log.debug("Arch approriate content for " +
consumerArch + " includes: ");
for (ProductContent apc : filtered) {
log.debug("\t " + apc.toString());
}
return filtered;
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FetchMembersOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FetchMembersOperation.java
index add9a360b..4e268038e 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FetchMembersOperation.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FetchMembersOperation.java
@@ -1,147 +1,147 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.ui.operations;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.progress.IElementCollector;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.sync.IRemoteResource;
import org.eclipse.team.internal.ccvs.core.CVSException;
import org.eclipse.team.internal.ccvs.core.CVSTag;
import org.eclipse.team.internal.ccvs.core.ICVSFile;
import org.eclipse.team.internal.ccvs.core.ICVSRemoteFolder;
import org.eclipse.team.internal.ccvs.core.ICVSRemoteResource;
import org.eclipse.team.internal.ccvs.core.resources.RemoteFolder;
import org.eclipse.team.internal.ccvs.core.resources.RemoteFolderMemberFetcher;
import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin;
import org.eclipse.team.internal.ccvs.ui.Policy;
/**
* Fetch the members of a remote folder in the background, passing incremental
* results through an IElementCollector.
*/
public class FetchMembersOperation extends RemoteOperation {
private IElementCollector collector;
private RemoteFolderFilter filter = new RemoteFolderFilter();
public static class RemoteFolderFilter {
public ICVSRemoteResource[] filter(ICVSRemoteResource[] resource) {
return resource;
}
}
public class InternalRemoteFolderMemberFetcher extends RemoteFolderMemberFetcher {
int sendIncrement = 100;
int foldersSent = 0;
List unsent = new ArrayList();
protected InternalRemoteFolderMemberFetcher(RemoteFolder parentFolder, CVSTag tag) {
super(parentFolder, tag);
}
protected void parentDoesNotExist() {
super.parentDoesNotExist();
// Indicate that there are no children
collector.add(new Object[0], getProgressMonitor());
}
protected RemoteFolder recordFolder(String name) {
RemoteFolder folder = super.recordFolder(name);
unsent.add(folder);
if (unsent.size() == sendIncrement) {
sendFolders();
}
return folder;
}
protected IStatus performUpdate(IProgressMonitor progress) throws CVSException {
IStatus status = super.performUpdate(progress);
sendFolders();
return status;
}
protected void updateFileRevisions(ICVSFile[] files, IProgressMonitor monitor) throws CVSException {
super.updateFileRevisions(files, monitor);
sendFiles();
}
private void sendFolders() {
updateParentFolderChildren();
collector.add(filter.filter((ICVSRemoteFolder[]) unsent.toArray(new ICVSRemoteFolder[unsent.size()])), getProgressMonitor());
unsent.clear();
}
private void sendFiles() {
collector.add(getFiles(), getProgressMonitor());
unsent.clear();
}
private IProgressMonitor getProgressMonitor() {
return null;
}
}
public FetchMembersOperation(Shell shell, ICVSRemoteFolder folder, IElementCollector collector) {
super(shell, new ICVSRemoteResource[] { folder });
this.collector = collector;
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ccvs.ui.operations.CVSOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
*/
protected void execute(IProgressMonitor monitor) throws CVSException, InterruptedException {
ICVSRemoteFolder remote = getRemoteFolder();
- if (remote instanceof RemoteFolder) {
+ if (remote.getClass().equals(RemoteFolder.class)) {
monitor = Policy.monitorFor(monitor);
boolean isRoot = remote.getName().equals(ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME);
monitor.beginTask(null, 100 + (isRoot ? 30 : 0));
RemoteFolderMemberFetcher fetcher = new InternalRemoteFolderMemberFetcher((RemoteFolder)remote, remote.getTag());
fetcher.fetchMembers(Policy.subMonitorFor(monitor, 100));
if (isRoot) {
ICVSRemoteResource[] modules = CVSUIPlugin.getPlugin()
.getRepositoryManager()
.getRepositoryRootFor(remote.getRepository())
.getDefinedModules(remote.getTag(), Policy.subMonitorFor(monitor, 25));
collector.add(filter.filter(modules), Policy.subMonitorFor(monitor, 5));
}
} else {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(null, 100);
IRemoteResource[] children = remote.members(Policy.subMonitorFor(monitor, 95));
collector.add(children, Policy.subMonitorFor(monitor, 5));
} catch (TeamException e) {
throw CVSException.wrapException(e);
} finally {
monitor.done();
}
}
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ccvs.ui.operations.CVSOperation#getTaskName()
*/
protected String getTaskName() {
return Policy.bind("FetchMembersOperation.0", getRemoteFolder().getName()); //$NON-NLS-1$
}
private ICVSRemoteFolder getRemoteFolder() {
return (ICVSRemoteFolder)getRemoteResources()[0];
}
public RemoteFolderFilter getFilter() {
return filter;
}
public void setFilter(RemoteFolderFilter filter) {
this.filter = filter;
}
}
| true | true | protected void execute(IProgressMonitor monitor) throws CVSException, InterruptedException {
ICVSRemoteFolder remote = getRemoteFolder();
if (remote instanceof RemoteFolder) {
monitor = Policy.monitorFor(monitor);
boolean isRoot = remote.getName().equals(ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME);
monitor.beginTask(null, 100 + (isRoot ? 30 : 0));
RemoteFolderMemberFetcher fetcher = new InternalRemoteFolderMemberFetcher((RemoteFolder)remote, remote.getTag());
fetcher.fetchMembers(Policy.subMonitorFor(monitor, 100));
if (isRoot) {
ICVSRemoteResource[] modules = CVSUIPlugin.getPlugin()
.getRepositoryManager()
.getRepositoryRootFor(remote.getRepository())
.getDefinedModules(remote.getTag(), Policy.subMonitorFor(monitor, 25));
collector.add(filter.filter(modules), Policy.subMonitorFor(monitor, 5));
}
} else {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(null, 100);
IRemoteResource[] children = remote.members(Policy.subMonitorFor(monitor, 95));
collector.add(children, Policy.subMonitorFor(monitor, 5));
} catch (TeamException e) {
throw CVSException.wrapException(e);
} finally {
monitor.done();
}
}
}
| protected void execute(IProgressMonitor monitor) throws CVSException, InterruptedException {
ICVSRemoteFolder remote = getRemoteFolder();
if (remote.getClass().equals(RemoteFolder.class)) {
monitor = Policy.monitorFor(monitor);
boolean isRoot = remote.getName().equals(ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME);
monitor.beginTask(null, 100 + (isRoot ? 30 : 0));
RemoteFolderMemberFetcher fetcher = new InternalRemoteFolderMemberFetcher((RemoteFolder)remote, remote.getTag());
fetcher.fetchMembers(Policy.subMonitorFor(monitor, 100));
if (isRoot) {
ICVSRemoteResource[] modules = CVSUIPlugin.getPlugin()
.getRepositoryManager()
.getRepositoryRootFor(remote.getRepository())
.getDefinedModules(remote.getTag(), Policy.subMonitorFor(monitor, 25));
collector.add(filter.filter(modules), Policy.subMonitorFor(monitor, 5));
}
} else {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(null, 100);
IRemoteResource[] children = remote.members(Policy.subMonitorFor(monitor, 95));
collector.add(children, Policy.subMonitorFor(monitor, 5));
} catch (TeamException e) {
throw CVSException.wrapException(e);
} finally {
monitor.done();
}
}
}
|
diff --git a/nuxeo-web-mobile/src/main/java/org/nuxeo/ecm/mobile/webengine/document/PreviewAdapter.java b/nuxeo-web-mobile/src/main/java/org/nuxeo/ecm/mobile/webengine/document/PreviewAdapter.java
index 3f08ab7..d217972 100644
--- a/nuxeo-web-mobile/src/main/java/org/nuxeo/ecm/mobile/webengine/document/PreviewAdapter.java
+++ b/nuxeo-web-mobile/src/main/java/org/nuxeo/ecm/mobile/webengine/document/PreviewAdapter.java
@@ -1,58 +1,58 @@
/*
* (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* 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.
*
* Contributors:
* bjalon
*/
package org.nuxeo.ecm.mobile.webengine.document;
import javax.ws.rs.GET;
import org.nuxeo.ecm.platform.preview.helper.PreviewHelper;
import org.nuxeo.ecm.webengine.WebException;
import org.nuxeo.ecm.webengine.model.WebAdapter;
import org.nuxeo.ecm.webengine.model.impl.DefaultAdapter;
import org.nuxeo.runtime.api.Framework;
/**
* @author bjalon
*
*/
@WebAdapter(name="preview", type="Preview", targetType="MobileDocument")
public class PreviewAdapter extends DefaultAdapter {
private String nuxeoContextPath;
@GET
public Object doGet() {
return getView("index");
}
public String getPreviewURL() {
Object targetObject = ctx.getTargetObject();
if (!(targetObject instanceof MobileDocument)) {
throw new WebException("Target Object must be MobileDocument");
}
- return getNuxeoContextPath()
+ return getNuxeoContextPath() + "/"
+ PreviewHelper.getPreviewURL(((MobileDocument) targetObject).getDocument());
}
private String getNuxeoContextPath() {
if (nuxeoContextPath == null) {
nuxeoContextPath = Framework.getProperty("org.nuxeo.ecm.contextPath");
}
return nuxeoContextPath;
}
}
| true | true | public String getPreviewURL() {
Object targetObject = ctx.getTargetObject();
if (!(targetObject instanceof MobileDocument)) {
throw new WebException("Target Object must be MobileDocument");
}
return getNuxeoContextPath()
+ PreviewHelper.getPreviewURL(((MobileDocument) targetObject).getDocument());
}
| public String getPreviewURL() {
Object targetObject = ctx.getTargetObject();
if (!(targetObject instanceof MobileDocument)) {
throw new WebException("Target Object must be MobileDocument");
}
return getNuxeoContextPath() + "/"
+ PreviewHelper.getPreviewURL(((MobileDocument) targetObject).getDocument());
}
|
diff --git a/src/com/mick88/convoytrucking/player/PlayerEntity.java b/src/com/mick88/convoytrucking/player/PlayerEntity.java
index 6372156..6d05eb0 100644
--- a/src/com/mick88/convoytrucking/player/PlayerEntity.java
+++ b/src/com/mick88/convoytrucking/player/PlayerEntity.java
@@ -1,233 +1,233 @@
package com.mick88.convoytrucking.player;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mick88.convoytrucking.api.entities.ApiEntity;
import com.mick88.convoytrucking.houses.HouseEntity;
import com.mick88.convoytrucking.player.PlayerStat.StatType;
import com.mick88.util.TimeConverter;
public class PlayerEntity extends ApiEntity
{
private static final long serialVersionUID = 3826293643305147073L;
public enum StaffType
{
none,
administrator,
moderator,
jr_mod,
}
String name, rank, registrationDate, lastMissionDate;
int id, lastSeen, timeOffset, houseId, fines, wanted;
boolean policeBadge, vip;
StaffType staffType=StaffType.none;
String [] achievements;
int score, convoyScore, truckLoads,
statArtic,
statDumper,
statTanker,
statCement,
statTrash,
statArmored,
statVan,
statTow,
statCoach,
statLimo,
statArrests,
statGta,
statBurglar,
statHeist,
statPlane,
statHeli,
statFailed,
statOverloads,
statOdo,
statTime;
public PlayerEntity(JSONObject json) throws JSONException
{
super(json);
}
@Override
public void parseJson(JSONObject json) throws JSONException
{
name = json.getString("player_name");
id = json.getInt("player_id");
rank = json.getString("rank");
lastSeen = json.getInt("lastseen");
if (json.isNull("registration_date")) registrationDate = null;
else registrationDate = json.getString("registration_date");
lastMissionDate = json.getString("last_mission_date");
if (json.isNull("staff") == false)
{
staffType = StaffType.valueOf(json.getString("staff"));
}
JSONArray a = json.getJSONArray("achievements");
achievements = new String[a.length()];
for (int i=0; i < a.length(); i++)
{
achievements[i] = a.getString(i);
}
vip = json.getBoolean("vip");
policeBadge = json.getBoolean("police_badge");
if (json.isNull("house_id")) houseId = 0;
else houseId = json.getInt("house_id");
parseStats(json.getJSONObject("stats"));
}
private void parseStats(JSONObject json) throws JSONException
{
score = json.getInt("score");
convoyScore = json.getInt("convoy_score");
truckLoads = json.getInt("TRUCK_LOADS");
statArtic = json.getInt("ARTIC");
statDumper = json.getInt("DUMPER");
statTanker = json.getInt("TANKER");
statCement = json.getInt("CEMENT");
statTrash = json.getInt("TRASH");
statArmored = json.getInt("ARMORED");
statVan = json.getInt("VAN");
statTow = json.getInt("TOW");
statCoach = json.getInt("COACH");
statLimo = json.getInt("LIMO");
statArrests = json.getInt("ARRESTS");
statGta = json.getInt("GTA");
statBurglar = json.getInt("BURGLAR");
statHeist = json.getInt("HEIST");
statPlane = json.getInt("PLANE");
statHeli = json.getInt("HELI");
statFailed = json.getInt("FAILED");
statOverloads = json.getInt("OVERLOADS");
statOdo = json.getInt("ODOMETER");
statTime = json.getInt("TIME");
}
public PlayerStat [] getStats()
{
return new PlayerStat[]
{
new PlayerStat("Artic", statArtic),
new PlayerStat("Dumper", statDumper),
new PlayerStat("Fuel delivery", statTanker),
new PlayerStat("Cement", statCement),
new PlayerStat("Trashmaster", statTrash),
new PlayerStat("Coach", statCoach),
new PlayerStat("Limousine", statLimo),
new PlayerStat("Arrests", statArrests),
new PlayerStat("Vehicles stolen", statGta),
new PlayerStat("Burglaries", statBurglar),
new PlayerStat("Heists", statHeist),
new PlayerStat("Airplane flights", statPlane),
new PlayerStat("Helicopter flights", statHeli),
new PlayerStat("Armored van", statArmored),
new PlayerStat("Van", statVan),
new PlayerStat("Towtruck", statTow),
- new PlayerStat("Failer missions", statFailed),
+ new PlayerStat("Failed missions", statFailed),
new PlayerStat("Overloads", statOverloads),
new PlayerStat("Total distance", statOdo, StatType.Distance),
new PlayerStat("Time online", statTime, StatType.Time),
};
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public StaffType getStaffType()
{
return staffType;
}
public String getRank()
{
return rank;
}
public int getScore()
{
return score;
}
public String[] getAchievements()
{
return achievements;
}
public boolean getVip()
{
return vip;
}
public boolean getPoliceBadge()
{
return policeBadge;
}
public int getHouseId()
{
return houseId;
}
public String getRegistrationDate()
{
return registrationDate;
}
public String getLastMissionDate()
{
return lastMissionDate;
}
public int getLastSeen()
{
return lastSeen;
}
public int getLastSeenInterval()
{
return (int) ((new Date().getTime()/1000) - getLastSeen());
}
public CharSequence getLastSeenFormat()
{
return TimeConverter.breakDownSeconds(getLastSeenInterval());
}
public int getConvoyScore()
{
return convoyScore;
}
public int getTruckLoads()
{
return truckLoads;
}
}
| true | true | public PlayerStat [] getStats()
{
return new PlayerStat[]
{
new PlayerStat("Artic", statArtic),
new PlayerStat("Dumper", statDumper),
new PlayerStat("Fuel delivery", statTanker),
new PlayerStat("Cement", statCement),
new PlayerStat("Trashmaster", statTrash),
new PlayerStat("Coach", statCoach),
new PlayerStat("Limousine", statLimo),
new PlayerStat("Arrests", statArrests),
new PlayerStat("Vehicles stolen", statGta),
new PlayerStat("Burglaries", statBurglar),
new PlayerStat("Heists", statHeist),
new PlayerStat("Airplane flights", statPlane),
new PlayerStat("Helicopter flights", statHeli),
new PlayerStat("Armored van", statArmored),
new PlayerStat("Van", statVan),
new PlayerStat("Towtruck", statTow),
new PlayerStat("Failer missions", statFailed),
new PlayerStat("Overloads", statOverloads),
new PlayerStat("Total distance", statOdo, StatType.Distance),
new PlayerStat("Time online", statTime, StatType.Time),
};
}
| public PlayerStat [] getStats()
{
return new PlayerStat[]
{
new PlayerStat("Artic", statArtic),
new PlayerStat("Dumper", statDumper),
new PlayerStat("Fuel delivery", statTanker),
new PlayerStat("Cement", statCement),
new PlayerStat("Trashmaster", statTrash),
new PlayerStat("Coach", statCoach),
new PlayerStat("Limousine", statLimo),
new PlayerStat("Arrests", statArrests),
new PlayerStat("Vehicles stolen", statGta),
new PlayerStat("Burglaries", statBurglar),
new PlayerStat("Heists", statHeist),
new PlayerStat("Airplane flights", statPlane),
new PlayerStat("Helicopter flights", statHeli),
new PlayerStat("Armored van", statArmored),
new PlayerStat("Van", statVan),
new PlayerStat("Towtruck", statTow),
new PlayerStat("Failed missions", statFailed),
new PlayerStat("Overloads", statOverloads),
new PlayerStat("Total distance", statOdo, StatType.Distance),
new PlayerStat("Time online", statTime, StatType.Time),
};
}
|
diff --git a/src/main/java/org/basex/server/QueryListener.java b/src/main/java/org/basex/server/QueryListener.java
index 19780ff5f..0d085e21f 100644
--- a/src/main/java/org/basex/server/QueryListener.java
+++ b/src/main/java/org/basex/server/QueryListener.java
@@ -1,211 +1,213 @@
package org.basex.server;
import static org.basex.core.Text.*;
import static org.basex.io.serial.SerializerProp.*;
import static org.basex.query.util.Err.*;
import java.io.*;
import org.basex.core.*;
import org.basex.io.out.*;
import org.basex.io.serial.*;
import org.basex.query.*;
import org.basex.query.iter.*;
import org.basex.query.value.item.*;
import org.basex.util.*;
/**
* Server-side query session in the client-server architecture.
*
* @author BaseX Team 2005-12, BSD License
* @author Andreas Weiler
* @author Christian Gruen
*/
final class QueryListener extends Progress {
/** Performance. */
final Performance perf = new Performance();
/** Query info. */
private final QueryInfo qi = new QueryInfo();
/** Query string. */
private final String query;
/** Database context. */
private final Context ctx;
/** Query processor. */
private QueryProcessor qp;
/** Serialization options. */
private SerializerProp options;
/** Parsing flag. */
private boolean parsed;
/** Query info. */
private String info = "";
/**
* Constructor.
* @param qu query string
* @param c database context
*/
QueryListener(final String qu, final Context c) {
query = qu;
ctx = c;
}
/**
* Binds a value to a global variable.
* @param n name of variable
* @param v value to be bound
* @param t type
* @throws IOException query exception
*/
void bind(final String n, final Object v, final String t) throws IOException {
try {
init().bind(n, v, t);
} catch(final QueryException ex) {
throw new BaseXException(ex);
}
}
/**
* Binds a value to the context item.
* @param v value to be bound
* @param t type
* @throws IOException query exception
*/
void context(final Object v, final String t) throws IOException {
try {
init().context(v, t);
} catch(final QueryException ex) {
throw new BaseXException(ex);
}
}
/**
* Returns the query info.
* @return query info
*/
String info() {
return info;
}
/**
* Returns the serialization options.
* @return serialization options
* @throws IOException I/O Exception
*/
String options() throws IOException {
if(options == null) options = parse().ctx.serParams(false);
return options.toString();
}
/**
* Returns {@code true} if the query may perform updates.
* @return updating flag
* @throws IOException I/O Exception
*/
boolean updating() throws IOException {
return parse().updating;
}
/**
* Executes the query.
* @param iter iterative evaluation
* @param out output stream
* @param enc encode stream
* @param full return full type information
* @throws IOException I/O Exception
*/
void execute(final boolean iter, final OutputStream out, final boolean enc,
final boolean full) throws IOException {
try {
try {
// parses the query and registers the process
ctx.register(parse());
// create serializer
qp.compile();
qi.cmpl = perf.time();
final Iter ir = qp.iter();
qi.evlt = perf.time();
options();
final boolean wrap = !options.get(S_WRAP_PREFIX).isEmpty();
// iterate through results
final PrintOutput po = PrintOutput.get(enc ? new EncodingOutput(out) : out);
if(iter && wrap) po.write(1);
final Serializer ser = Serializer.get(po, full ? null : options);
int c = 0;
for(Item it; (it = ir.next()) != null;) {
if(iter && !wrap) {
if(full) {
po.write(it.xdmInfo());
} else {
po.write(it.typeId().asByte());
}
ser.reset();
}
ser.serialize(it);
if(iter && !wrap) {
po.flush();
out.write(0);
}
c++;
}
ser.close();
if(iter && wrap) out.write(0);
qi.srlz = perf.time();
// generate query info
info = qi.toString(qp, po, c, ctx.prop.is(Prop.QUERYINFO));
} catch(final QueryException ex) {
throw new BaseXException(ex);
} catch(final StackOverflowError ex) {
Util.debug(ex);
throw new BaseXException(BASX_STACKOVERFLOW.desc);
} catch(final ProgressException ex) {
throw new BaseXException(TIMEOUT_EXCEEDED);
}
} finally {
// close processor and unregisters the process
if(qp != null) {
qp.close();
- ctx.unregister(qp);
- parsed = false;
+ if(parsed) {
+ ctx.unregister(qp);
+ parsed = false;
+ }
qp = null;
}
}
}
/**
* Initializes the query.
* @return query processor
* @throws IOException I/O Exception
*/
private QueryProcessor parse() throws IOException {
if(!parsed) {
try {
perf.time();
init().parse();
qi.pars = perf.time();
parsed = true;
} catch(final QueryException ex) {
throw new BaseXException(ex);
}
}
return qp;
}
/**
* Returns an instance of the query processor.
* @return query processor
*/
private QueryProcessor init() {
if(parsed || qp == null) {
qp = new QueryProcessor(query, ctx);
parsed = false;
}
return qp;
}
}
| true | true | void execute(final boolean iter, final OutputStream out, final boolean enc,
final boolean full) throws IOException {
try {
try {
// parses the query and registers the process
ctx.register(parse());
// create serializer
qp.compile();
qi.cmpl = perf.time();
final Iter ir = qp.iter();
qi.evlt = perf.time();
options();
final boolean wrap = !options.get(S_WRAP_PREFIX).isEmpty();
// iterate through results
final PrintOutput po = PrintOutput.get(enc ? new EncodingOutput(out) : out);
if(iter && wrap) po.write(1);
final Serializer ser = Serializer.get(po, full ? null : options);
int c = 0;
for(Item it; (it = ir.next()) != null;) {
if(iter && !wrap) {
if(full) {
po.write(it.xdmInfo());
} else {
po.write(it.typeId().asByte());
}
ser.reset();
}
ser.serialize(it);
if(iter && !wrap) {
po.flush();
out.write(0);
}
c++;
}
ser.close();
if(iter && wrap) out.write(0);
qi.srlz = perf.time();
// generate query info
info = qi.toString(qp, po, c, ctx.prop.is(Prop.QUERYINFO));
} catch(final QueryException ex) {
throw new BaseXException(ex);
} catch(final StackOverflowError ex) {
Util.debug(ex);
throw new BaseXException(BASX_STACKOVERFLOW.desc);
} catch(final ProgressException ex) {
throw new BaseXException(TIMEOUT_EXCEEDED);
}
} finally {
// close processor and unregisters the process
if(qp != null) {
qp.close();
ctx.unregister(qp);
parsed = false;
qp = null;
}
}
}
| void execute(final boolean iter, final OutputStream out, final boolean enc,
final boolean full) throws IOException {
try {
try {
// parses the query and registers the process
ctx.register(parse());
// create serializer
qp.compile();
qi.cmpl = perf.time();
final Iter ir = qp.iter();
qi.evlt = perf.time();
options();
final boolean wrap = !options.get(S_WRAP_PREFIX).isEmpty();
// iterate through results
final PrintOutput po = PrintOutput.get(enc ? new EncodingOutput(out) : out);
if(iter && wrap) po.write(1);
final Serializer ser = Serializer.get(po, full ? null : options);
int c = 0;
for(Item it; (it = ir.next()) != null;) {
if(iter && !wrap) {
if(full) {
po.write(it.xdmInfo());
} else {
po.write(it.typeId().asByte());
}
ser.reset();
}
ser.serialize(it);
if(iter && !wrap) {
po.flush();
out.write(0);
}
c++;
}
ser.close();
if(iter && wrap) out.write(0);
qi.srlz = perf.time();
// generate query info
info = qi.toString(qp, po, c, ctx.prop.is(Prop.QUERYINFO));
} catch(final QueryException ex) {
throw new BaseXException(ex);
} catch(final StackOverflowError ex) {
Util.debug(ex);
throw new BaseXException(BASX_STACKOVERFLOW.desc);
} catch(final ProgressException ex) {
throw new BaseXException(TIMEOUT_EXCEEDED);
}
} finally {
// close processor and unregisters the process
if(qp != null) {
qp.close();
if(parsed) {
ctx.unregister(qp);
parsed = false;
}
qp = null;
}
}
}
|
diff --git a/test/java/org/apache/fop/fotreetest/ext/AssertElement.java b/test/java/org/apache/fop/fotreetest/ext/AssertElement.java
index 6d12073f7..ebd8335c1 100644
--- a/test/java/org/apache/fop/fotreetest/ext/AssertElement.java
+++ b/test/java/org/apache/fop/fotreetest/ext/AssertElement.java
@@ -1,72 +1,74 @@
/*
* Copyright 2005 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.
*/
/* $Id$ */
package org.apache.fop.fotreetest.ext;
import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.FONode;
import org.apache.fop.fo.FOPropertyMapping;
import org.apache.fop.fo.PropertyList;
import org.apache.fop.fo.properties.Property;
import org.apache.fop.fotreetest.ResultCollector;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
/**
* Defines the assert element for the FOP Test extension.
*/
public class AssertElement extends TestObj {
/**
* @see org.apache.fop.fo.FONode#FONode(FONode)
*/
public AssertElement(FONode parent) {
super(parent);
}
/**
* @see org.apache.fop.fo.FONode#processNode
*/
public void processNode(String elementName,
Locator locator,
Attributes attlist,
PropertyList propertyList) throws FOPException {
//super.processNode(elementName, locator, attlist, propertyList);
ResultCollector collector = ResultCollector.getInstance();
String propName = attlist.getValue("property");
int propID = FOPropertyMapping.getPropertyId(propName);
if (propID < 0) {
collector.notifyException(new IllegalArgumentException(
"Property not found: " + propName));
} else {
Property prop = propertyList.getParentPropertyList().get(propID);
String s = String.valueOf(prop);
String expected = attlist.getValue("expected");
if (!expected.equals(s)) {
collector.notifyException(new IllegalStateException("Property '" + propName
- + "' expected to evaluate to '" + expected + "' but got: " + s));
+ + "' expected to evaluate to '" + expected + "' but got: " + s
+ + "\nLine #" + locator.getLineNumber()
+ + " Column #" + locator.getColumnNumber()));
}
}
}
}
| true | true | public void processNode(String elementName,
Locator locator,
Attributes attlist,
PropertyList propertyList) throws FOPException {
//super.processNode(elementName, locator, attlist, propertyList);
ResultCollector collector = ResultCollector.getInstance();
String propName = attlist.getValue("property");
int propID = FOPropertyMapping.getPropertyId(propName);
if (propID < 0) {
collector.notifyException(new IllegalArgumentException(
"Property not found: " + propName));
} else {
Property prop = propertyList.getParentPropertyList().get(propID);
String s = String.valueOf(prop);
String expected = attlist.getValue("expected");
if (!expected.equals(s)) {
collector.notifyException(new IllegalStateException("Property '" + propName
+ "' expected to evaluate to '" + expected + "' but got: " + s));
}
}
}
| public void processNode(String elementName,
Locator locator,
Attributes attlist,
PropertyList propertyList) throws FOPException {
//super.processNode(elementName, locator, attlist, propertyList);
ResultCollector collector = ResultCollector.getInstance();
String propName = attlist.getValue("property");
int propID = FOPropertyMapping.getPropertyId(propName);
if (propID < 0) {
collector.notifyException(new IllegalArgumentException(
"Property not found: " + propName));
} else {
Property prop = propertyList.getParentPropertyList().get(propID);
String s = String.valueOf(prop);
String expected = attlist.getValue("expected");
if (!expected.equals(s)) {
collector.notifyException(new IllegalStateException("Property '" + propName
+ "' expected to evaluate to '" + expected + "' but got: " + s
+ "\nLine #" + locator.getLineNumber()
+ " Column #" + locator.getColumnNumber()));
}
}
}
|
diff --git a/android/src/com/sonyericsson/chkbugreport/LogViewer.java b/android/src/com/sonyericsson/chkbugreport/LogViewer.java
index 7dcd597..cf831e1 100644
--- a/android/src/com/sonyericsson/chkbugreport/LogViewer.java
+++ b/android/src/com/sonyericsson/chkbugreport/LogViewer.java
@@ -1,63 +1,63 @@
/*
* Copyright (C) 2013 Sony Mobile Communications AB
*
* This file is part of ChkBugReport.
*
* ChkBugReport 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.
*
* ChkBugReport 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 ChkBugReport. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sonyericsson.chkbugreport;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class LogViewer extends View {
private static final int SIZE = 100;
private String mLogs[] = new String[SIZE];
private int mIdx = 0;
private Paint mPaint = new Paint();
private int mTextHeight;
public LogViewer(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint.setColor(0xff00ff00);
mTextHeight = (int)mPaint.getTextSize();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xff000000);
- int count = getHeight() / mTextHeight;
+ int count = Math.min(SIZE, getHeight() / mTextHeight);
int y = mTextHeight;
for (int i = 0; i < count; i++) {
int idx = (mIdx + SIZE + i - count) % SIZE;
String string = mLogs[idx];
if (string != null) {
canvas.drawText(string, 0, y, mPaint);
}
y += mTextHeight;
}
}
public void log(String string) {
mLogs[mIdx] = string;
mIdx = (mIdx + 1) % SIZE;
postInvalidate();
}
}
| true | true | protected void onDraw(Canvas canvas) {
canvas.drawColor(0xff000000);
int count = getHeight() / mTextHeight;
int y = mTextHeight;
for (int i = 0; i < count; i++) {
int idx = (mIdx + SIZE + i - count) % SIZE;
String string = mLogs[idx];
if (string != null) {
canvas.drawText(string, 0, y, mPaint);
}
y += mTextHeight;
}
}
| protected void onDraw(Canvas canvas) {
canvas.drawColor(0xff000000);
int count = Math.min(SIZE, getHeight() / mTextHeight);
int y = mTextHeight;
for (int i = 0; i < count; i++) {
int idx = (mIdx + SIZE + i - count) % SIZE;
String string = mLogs[idx];
if (string != null) {
canvas.drawText(string, 0, y, mPaint);
}
y += mTextHeight;
}
}
|
diff --git a/src/JDBCtask.java b/src/JDBCtask.java
index 9d4d2b7..d991f0b 100644
--- a/src/JDBCtask.java
+++ b/src/JDBCtask.java
@@ -1,70 +1,70 @@
import java.sql.*;
import java.util.Scanner;
public class JDBCtask{
public static void main(String[] args) {
System.out.println("Table Creation Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
PreparedStatement preparedstatement=null;
ResultSet rs;
try{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(url, userName, password);
//con = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement st = con.createStatement();
String database =
"CREATE DATABASE "+dbName;
st.executeUpdate(database);
System.out.println("Table creation process successfully!");
String table =
"CREATE TABLE Film(year integer,film String,Director String,Country String)";
st.executeUpdate(table);
System.out.println("Table creation process successfully!");
}
catch(SQLException s){
System.out.println("Table allready exists!");
}
preparedstatement = con
.prepareStatement("insert into Film values (?,?,?,?)");
preparedstatement.setLong(1, 2010);
preparedstatement.setString(2,"Barney's Version" );
preparedstatement.setString(3,"Richard J. Lewis");
preparedstatement.setString(4,"Canada");
int x=0;
for (;x!=10;){
Scanner Sc=new Scanner(System.in);
x=Sc.nextInt();
if (x==1){
Statement stmt = con.createStatement();
-rs = stmt.executeQuery("SELECT film FROM Film WHERE Year = 2010"); // �������� ��������� ������ ������� ������ - No database selected
- // ���� �������� ����������� � ���� �� SELECT
+rs = stmt.executeQuery("SELECT film FROM Film WHERE Year = 2010"); // When I try to run your application twice I get the error: No database selected
+ // You should implement connection to already created database
while ( rs.next() ) {
System.out.println(rs.getString("film"));
}
}
/*if(x==2){
Scanner Sc1=new Scanner(System.in);
int y=Sc1.nextInt();
Statement stmt1 = con.createStatement();
- rs = stmt1.executeQuery("Select FROM Film WHERE Director =",y); // error! - ��� �� �������� ������, ��-����
+ rs = stmt1.executeQuery("Select FROM Film WHERE Director =",y); // error! - code doesn't compile at all :(
}*/
con.close();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
| false | true | public static void main(String[] args) {
System.out.println("Table Creation Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
PreparedStatement preparedstatement=null;
ResultSet rs;
try{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(url, userName, password);
//con = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement st = con.createStatement();
String database =
"CREATE DATABASE "+dbName;
st.executeUpdate(database);
System.out.println("Table creation process successfully!");
String table =
"CREATE TABLE Film(year integer,film String,Director String,Country String)";
st.executeUpdate(table);
System.out.println("Table creation process successfully!");
}
catch(SQLException s){
System.out.println("Table allready exists!");
}
preparedstatement = con
.prepareStatement("insert into Film values (?,?,?,?)");
preparedstatement.setLong(1, 2010);
preparedstatement.setString(2,"Barney's Version" );
preparedstatement.setString(3,"Richard J. Lewis");
preparedstatement.setString(4,"Canada");
int x=0;
for (;x!=10;){
Scanner Sc=new Scanner(System.in);
x=Sc.nextInt();
if (x==1){
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT film FROM Film WHERE Year = 2010"); // �������� ��������� ������ ������� ������ - No database selected
// ���� �������� ����������� � ���� �� SELECT
while ( rs.next() ) {
System.out.println(rs.getString("film"));
}
}
/*if(x==2){
Scanner Sc1=new Scanner(System.in);
int y=Sc1.nextInt();
Statement stmt1 = con.createStatement();
rs = stmt1.executeQuery("Select FROM Film WHERE Director =",y); // error! - ��� �� �������� ������, ��-����
}*/
con.close();
}
}
| public static void main(String[] args) {
System.out.println("Table Creation Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
PreparedStatement preparedstatement=null;
ResultSet rs;
try{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(url, userName, password);
//con = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement st = con.createStatement();
String database =
"CREATE DATABASE "+dbName;
st.executeUpdate(database);
System.out.println("Table creation process successfully!");
String table =
"CREATE TABLE Film(year integer,film String,Director String,Country String)";
st.executeUpdate(table);
System.out.println("Table creation process successfully!");
}
catch(SQLException s){
System.out.println("Table allready exists!");
}
preparedstatement = con
.prepareStatement("insert into Film values (?,?,?,?)");
preparedstatement.setLong(1, 2010);
preparedstatement.setString(2,"Barney's Version" );
preparedstatement.setString(3,"Richard J. Lewis");
preparedstatement.setString(4,"Canada");
int x=0;
for (;x!=10;){
Scanner Sc=new Scanner(System.in);
x=Sc.nextInt();
if (x==1){
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT film FROM Film WHERE Year = 2010"); // When I try to run your application twice I get the error: No database selected
// You should implement connection to already created database
while ( rs.next() ) {
System.out.println(rs.getString("film"));
}
}
/*if(x==2){
Scanner Sc1=new Scanner(System.in);
int y=Sc1.nextInt();
Statement stmt1 = con.createStatement();
rs = stmt1.executeQuery("Select FROM Film WHERE Director =",y); // error! - code doesn't compile at all :(
}*/
con.close();
}
}
|
diff --git a/keystore/java/android/security/ServiceCommand.java b/keystore/java/android/security/ServiceCommand.java
index 2f335be1..6178d59a 100644
--- a/keystore/java/android/security/ServiceCommand.java
+++ b/keystore/java/android/security/ServiceCommand.java
@@ -1,196 +1,196 @@
/*
* 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 android.security;
import android.net.LocalSocketAddress;
import android.net.LocalSocket;
import android.util.Config;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/*
* ServiceCommand is used to connect to a service throught the local socket,
* and send out the command, return the result to the caller.
* {@hide}
*/
public class ServiceCommand {
public static final String SUCCESS = "0";
public static final String FAILED = "-1";
// Opcodes for keystore commands.
public static final int LOCK = 0;
public static final int UNLOCK = 1;
public static final int PASSWD = 2;
public static final int GET_STATE = 3;
public static final int LIST_KEYS = 4;
public static final int GET_KEY = 5;
public static final int PUT_KEY = 6;
public static final int REMOVE_KEY = 7;
public static final int RESET = 8;
public static final int MAX_CMD_INDEX = 9;
public static final int BUFFER_LENGTH = 4096;
private String mServiceName;
private String mTag;
private InputStream mIn;
private OutputStream mOut;
private LocalSocket mSocket;
private boolean connect() {
if (mSocket != null) {
return true;
}
Log.i(mTag, "connecting...");
try {
mSocket = new LocalSocket();
LocalSocketAddress address = new LocalSocketAddress(
mServiceName, LocalSocketAddress.Namespace.RESERVED);
mSocket.connect(address);
mIn = mSocket.getInputStream();
mOut = mSocket.getOutputStream();
} catch (IOException ex) {
disconnect();
return false;
}
return true;
}
private void disconnect() {
Log.i(mTag,"disconnecting...");
try {
if (mSocket != null) mSocket.close();
} catch (IOException ex) { }
try {
if (mIn != null) mIn.close();
} catch (IOException ex) { }
try {
if (mOut != null) mOut.close();
} catch (IOException ex) { }
mSocket = null;
mIn = null;
mOut = null;
}
private boolean readBytes(byte buffer[], int len) {
int off = 0, count;
if (len < 0) return false;
while (off != len) {
try {
count = mIn.read(buffer, off, len - off);
if (count <= 0) {
Log.e(mTag, "read error " + count);
break;
}
off += count;
} catch (IOException ex) {
Log.e(mTag,"read exception");
break;
}
}
if (off == len) return true;
disconnect();
return false;
}
private Reply readReply() {
byte buf[] = new byte[4];
Reply reply = new Reply();
if (!readBytes(buf, 4)) return null;
reply.len = (((int) buf[0]) & 0xff) | ((((int) buf[1]) & 0xff) << 8) |
((((int) buf[2]) & 0xff) << 16) |
((((int) buf[3]) & 0xff) << 24);
if (!readBytes(buf, 4)) return null;
reply.returnCode = (((int) buf[0]) & 0xff) |
((((int) buf[1]) & 0xff) << 8) |
((((int) buf[2]) & 0xff) << 16) |
((((int) buf[3]) & 0xff) << 24);
if (reply.len > BUFFER_LENGTH) {
Log.e(mTag,"invalid reply length (" + reply.len + ")");
disconnect();
return null;
}
if (!readBytes(reply.data, reply.len)) return null;
return reply;
}
private boolean writeCommand(int cmd, String _data) {
byte buf[] = new byte[8];
- byte[] data = _data.getBytes();
+ byte[] data = (_data == null) ? new byte[0] : _data.getBytes();
int len = data.length;
// the length of data
buf[0] = (byte) (len & 0xff);
buf[1] = (byte) ((len >> 8) & 0xff);
buf[2] = (byte) ((len >> 16) & 0xff);
buf[3] = (byte) ((len >> 24) & 0xff);
// the opcode of the command
buf[4] = (byte) (cmd & 0xff);
buf[5] = (byte) ((cmd >> 8) & 0xff);
buf[6] = (byte) ((cmd >> 16) & 0xff);
buf[7] = (byte) ((cmd >> 24) & 0xff);
try {
mOut.write(buf, 0, 8);
mOut.write(data, 0, len);
} catch (IOException ex) {
Log.e(mTag,"write error");
disconnect();
return false;
}
return true;
}
private Reply executeCommand(int cmd, String data) {
if (!writeCommand(cmd, data)) {
/* If service died and restarted in the background
* (unlikely but possible) we'll fail on the next
* write (this one). Try to reconnect and write
* the command one more time before giving up.
*/
Log.e(mTag, "write command failed? reconnect!");
if (!connect() || !writeCommand(cmd, data)) {
return null;
}
}
return readReply();
}
public synchronized Reply execute(int cmd, String data) {
Reply result;
if (!connect()) {
Log.e(mTag, "connection failed");
return null;
}
result = executeCommand(cmd, data);
disconnect();
return result;
}
public ServiceCommand(String service) {
mServiceName = service;
mTag = service;
}
}
| true | true | private boolean writeCommand(int cmd, String _data) {
byte buf[] = new byte[8];
byte[] data = _data.getBytes();
int len = data.length;
// the length of data
buf[0] = (byte) (len & 0xff);
buf[1] = (byte) ((len >> 8) & 0xff);
buf[2] = (byte) ((len >> 16) & 0xff);
buf[3] = (byte) ((len >> 24) & 0xff);
// the opcode of the command
buf[4] = (byte) (cmd & 0xff);
buf[5] = (byte) ((cmd >> 8) & 0xff);
buf[6] = (byte) ((cmd >> 16) & 0xff);
buf[7] = (byte) ((cmd >> 24) & 0xff);
try {
mOut.write(buf, 0, 8);
mOut.write(data, 0, len);
} catch (IOException ex) {
Log.e(mTag,"write error");
disconnect();
return false;
}
return true;
}
| private boolean writeCommand(int cmd, String _data) {
byte buf[] = new byte[8];
byte[] data = (_data == null) ? new byte[0] : _data.getBytes();
int len = data.length;
// the length of data
buf[0] = (byte) (len & 0xff);
buf[1] = (byte) ((len >> 8) & 0xff);
buf[2] = (byte) ((len >> 16) & 0xff);
buf[3] = (byte) ((len >> 24) & 0xff);
// the opcode of the command
buf[4] = (byte) (cmd & 0xff);
buf[5] = (byte) ((cmd >> 8) & 0xff);
buf[6] = (byte) ((cmd >> 16) & 0xff);
buf[7] = (byte) ((cmd >> 24) & 0xff);
try {
mOut.write(buf, 0, 8);
mOut.write(data, 0, len);
} catch (IOException ex) {
Log.e(mTag,"write error");
disconnect();
return false;
}
return true;
}
|
diff --git a/src/scratchpad/src/org/apache/poi/hssf/record/formula/functions/Mid.java b/src/scratchpad/src/org/apache/poi/hssf/record/formula/functions/Mid.java
index d6c4399ae..191735543 100644
--- a/src/scratchpad/src/org/apache/poi/hssf/record/formula/functions/Mid.java
+++ b/src/scratchpad/src/org/apache/poi/hssf/record/formula/functions/Mid.java
@@ -1,99 +1,99 @@
/*
* 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.
*/
/*
* Created on May 15, 2005
*
*/
package org.apache.poi.hssf.record.formula.functions;
import org.apache.poi.hssf.record.formula.eval.BlankEval;
import org.apache.poi.hssf.record.formula.eval.ErrorEval;
import org.apache.poi.hssf.record.formula.eval.Eval;
import org.apache.poi.hssf.record.formula.eval.NumericValueEval;
import org.apache.poi.hssf.record.formula.eval.StringEval;
import org.apache.poi.hssf.record.formula.eval.StringValueEval;
import org.apache.poi.hssf.record.formula.eval.ValueEval;
/**
* An implementation of the MID function:
* Returns a specific number of characters from a text string,
* starting at the position you specify, based on the number
* of characters you specify.
* @author Manda Wilson < wilson at c bio dot msk cc dot org >
*/
public class Mid extends TextFunction {
/**
* Returns a specific number of characters from a text string,
* starting at the position you specify, based on the number
* of characters you specify.
*
* @see org.apache.poi.hssf.record.formula.eval.Eval
*/
public Eval evaluate(Eval[] operands, int srcCellRow, short srcCellCol) {
Eval retval = null;
String str = null;
int startNum = 0;
int numChars = 0;
switch (operands.length) {
default:
retval = ErrorEval.VALUE_INVALID;
case 3:
// first operand is text string containing characters to extract
// second operand is position of first character to extract
// third operand is the number of characters to return
ValueEval firstveval = singleOperandEvaluate(operands[0], srcCellRow, srcCellCol);
ValueEval secondveval = singleOperandEvaluate(operands[1], srcCellRow, srcCellCol);
ValueEval thirdveval = singleOperandEvaluate(operands[2], srcCellRow, srcCellCol);
if (firstveval instanceof StringValueEval
&& secondveval instanceof NumericValueEval
&& thirdveval instanceof NumericValueEval) {
StringValueEval strEval = (StringValueEval) firstveval;
str = strEval.getStringValue();
NumericValueEval startNumEval = (NumericValueEval) secondveval;
// NOTE: it is safe to cast to int here
// because in Excel =MID("test", 1, 1.7) returns t
// so 1.7 must be truncated to 1
// and =MID("test", 1.9, 2) returns te
// so 1.9 must be truncated to 1
startNum = (int) startNumEval.getNumberValue();
NumericValueEval numCharsEval = (NumericValueEval) thirdveval;
numChars = (int) numCharsEval.getNumberValue();
} else {
retval = ErrorEval.VALUE_INVALID;
}
}
if (retval == null) {
if (startNum < 1 || numChars < 0) {
retval = ErrorEval.VALUE_INVALID;
} else if (startNum > str.length() || numChars == 0) {
retval = BlankEval.INSTANCE;
} else if (startNum + numChars > str.length()) {
retval = new StringEval(str.substring(startNum - 1));
} else {
- retval = new StringEval(str.substring(startNum - 1, numChars));
+ retval = new StringEval(str.substring(startNum - 1, (numChars + startNum - 1)));
}
}
return retval;
}
}
| true | true | public Eval evaluate(Eval[] operands, int srcCellRow, short srcCellCol) {
Eval retval = null;
String str = null;
int startNum = 0;
int numChars = 0;
switch (operands.length) {
default:
retval = ErrorEval.VALUE_INVALID;
case 3:
// first operand is text string containing characters to extract
// second operand is position of first character to extract
// third operand is the number of characters to return
ValueEval firstveval = singleOperandEvaluate(operands[0], srcCellRow, srcCellCol);
ValueEval secondveval = singleOperandEvaluate(operands[1], srcCellRow, srcCellCol);
ValueEval thirdveval = singleOperandEvaluate(operands[2], srcCellRow, srcCellCol);
if (firstveval instanceof StringValueEval
&& secondveval instanceof NumericValueEval
&& thirdveval instanceof NumericValueEval) {
StringValueEval strEval = (StringValueEval) firstveval;
str = strEval.getStringValue();
NumericValueEval startNumEval = (NumericValueEval) secondveval;
// NOTE: it is safe to cast to int here
// because in Excel =MID("test", 1, 1.7) returns t
// so 1.7 must be truncated to 1
// and =MID("test", 1.9, 2) returns te
// so 1.9 must be truncated to 1
startNum = (int) startNumEval.getNumberValue();
NumericValueEval numCharsEval = (NumericValueEval) thirdveval;
numChars = (int) numCharsEval.getNumberValue();
} else {
retval = ErrorEval.VALUE_INVALID;
}
}
if (retval == null) {
if (startNum < 1 || numChars < 0) {
retval = ErrorEval.VALUE_INVALID;
} else if (startNum > str.length() || numChars == 0) {
retval = BlankEval.INSTANCE;
} else if (startNum + numChars > str.length()) {
retval = new StringEval(str.substring(startNum - 1));
} else {
retval = new StringEval(str.substring(startNum - 1, numChars));
}
}
return retval;
}
| public Eval evaluate(Eval[] operands, int srcCellRow, short srcCellCol) {
Eval retval = null;
String str = null;
int startNum = 0;
int numChars = 0;
switch (operands.length) {
default:
retval = ErrorEval.VALUE_INVALID;
case 3:
// first operand is text string containing characters to extract
// second operand is position of first character to extract
// third operand is the number of characters to return
ValueEval firstveval = singleOperandEvaluate(operands[0], srcCellRow, srcCellCol);
ValueEval secondveval = singleOperandEvaluate(operands[1], srcCellRow, srcCellCol);
ValueEval thirdveval = singleOperandEvaluate(operands[2], srcCellRow, srcCellCol);
if (firstveval instanceof StringValueEval
&& secondveval instanceof NumericValueEval
&& thirdveval instanceof NumericValueEval) {
StringValueEval strEval = (StringValueEval) firstveval;
str = strEval.getStringValue();
NumericValueEval startNumEval = (NumericValueEval) secondveval;
// NOTE: it is safe to cast to int here
// because in Excel =MID("test", 1, 1.7) returns t
// so 1.7 must be truncated to 1
// and =MID("test", 1.9, 2) returns te
// so 1.9 must be truncated to 1
startNum = (int) startNumEval.getNumberValue();
NumericValueEval numCharsEval = (NumericValueEval) thirdveval;
numChars = (int) numCharsEval.getNumberValue();
} else {
retval = ErrorEval.VALUE_INVALID;
}
}
if (retval == null) {
if (startNum < 1 || numChars < 0) {
retval = ErrorEval.VALUE_INVALID;
} else if (startNum > str.length() || numChars == 0) {
retval = BlankEval.INSTANCE;
} else if (startNum + numChars > str.length()) {
retval = new StringEval(str.substring(startNum - 1));
} else {
retval = new StringEval(str.substring(startNum - 1, (numChars + startNum - 1)));
}
}
return retval;
}
|
diff --git a/jpwgen/src/main/java/org/jpwgen/Main.java b/jpwgen/src/main/java/org/jpwgen/Main.java
index 2188e9f..4eba1a0 100644
--- a/jpwgen/src/main/java/org/jpwgen/Main.java
+++ b/jpwgen/src/main/java/org/jpwgen/Main.java
@@ -1,108 +1,108 @@
// Copyright (c) Andrew Smith. All rights reserved.
// The use and distribution terms for this software are covered by the
// Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
// which can be found in the file epl-v10.html at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by
// the terms of this license.
// You must not remove this notice, or any other, from this software.
package org.jpwgen;
import java.util.List;
import java.util.Random;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.CommandLine;
public class Main {
public static void main(String[] args) {
CommandLineParser parser = new PosixParser();
HelpFormatter formatter = new HelpFormatter();
Options options = new Options();
options.addOption("l", "lowercase", false,
"Include lowercase alpha characters");
options.addOption("u", "uppercase", false,
"Include uppercase alpha characters");
options.addOption("d", "digits", false, "Include digits");
options.addOption("p", "punctuation", false, "Include punctuation");
options.addOption("n", "number", true,
"Number of passwords to generate");
options.addOption("L", "length", true,
"Length of the generated passwords");
try {
CommandLine cmd = parser.parse(options, args);
boolean hasLower = cmd.hasOption('l');
boolean hasUpper = cmd.hasOption('u');
boolean hasDigits = cmd.hasOption('d');
boolean hasPunctuation = cmd.hasOption('p');
boolean hasLength = cmd.hasOption('L');
boolean hasNumber = cmd.hasOption('n');
// Check for options
if (hasLower || hasUpper || hasDigits || hasPunctuation) {
PasswordGenerator generator;
generator = new PasswordGenerator(new Random());
PasswordChars passwordChars = new PasswordChars(hasLower,
hasUpper, hasDigits, hasPunctuation);
// Number of passwords to generate by default
int number = 10;
// Length of passwords generated by default
int length = 10;
// If length has been specified by the user, use it
// in place of the default value.
if (hasLength) {
try {
length = Integer.parseInt(cmd.getOptionValue('L'));
} catch(NumberFormatException e) {
- System.out.println("Error: The argument to -L must be a number");
+ System.out.println("Error: The argument to length must be a number");
formatter.printHelp("pwgen", options);
System.exit(-1);
}
}
// If number has been specified by the user, use it
// in place of the default value.
if (hasNumber) {
try {
number = Integer.parseInt(cmd.getOptionValue('n'));
} catch(NumberFormatException e) {
System.out.println("Error: The argument to number must be a number");
formatter.printHelp("pwgen", options);
System.exit(-1);
}
}
final List<String> passwords;
passwords = generator.generateMultiple(passwordChars, number,
length);
for (String password : passwords) {
System.out.println(password);
}
} else {
// If none found, print the usage message.
formatter.printHelp("pwgen", options);
}
} catch (ParseException e) {
System.err.println("Error parsing the commandline: "
+ e.getMessage());
}
}
}
| true | true | public static void main(String[] args) {
CommandLineParser parser = new PosixParser();
HelpFormatter formatter = new HelpFormatter();
Options options = new Options();
options.addOption("l", "lowercase", false,
"Include lowercase alpha characters");
options.addOption("u", "uppercase", false,
"Include uppercase alpha characters");
options.addOption("d", "digits", false, "Include digits");
options.addOption("p", "punctuation", false, "Include punctuation");
options.addOption("n", "number", true,
"Number of passwords to generate");
options.addOption("L", "length", true,
"Length of the generated passwords");
try {
CommandLine cmd = parser.parse(options, args);
boolean hasLower = cmd.hasOption('l');
boolean hasUpper = cmd.hasOption('u');
boolean hasDigits = cmd.hasOption('d');
boolean hasPunctuation = cmd.hasOption('p');
boolean hasLength = cmd.hasOption('L');
boolean hasNumber = cmd.hasOption('n');
// Check for options
if (hasLower || hasUpper || hasDigits || hasPunctuation) {
PasswordGenerator generator;
generator = new PasswordGenerator(new Random());
PasswordChars passwordChars = new PasswordChars(hasLower,
hasUpper, hasDigits, hasPunctuation);
// Number of passwords to generate by default
int number = 10;
// Length of passwords generated by default
int length = 10;
// If length has been specified by the user, use it
// in place of the default value.
if (hasLength) {
try {
length = Integer.parseInt(cmd.getOptionValue('L'));
} catch(NumberFormatException e) {
System.out.println("Error: The argument to -L must be a number");
formatter.printHelp("pwgen", options);
System.exit(-1);
}
}
// If number has been specified by the user, use it
// in place of the default value.
if (hasNumber) {
try {
number = Integer.parseInt(cmd.getOptionValue('n'));
} catch(NumberFormatException e) {
System.out.println("Error: The argument to number must be a number");
formatter.printHelp("pwgen", options);
System.exit(-1);
}
}
final List<String> passwords;
passwords = generator.generateMultiple(passwordChars, number,
length);
for (String password : passwords) {
System.out.println(password);
}
} else {
// If none found, print the usage message.
formatter.printHelp("pwgen", options);
}
} catch (ParseException e) {
System.err.println("Error parsing the commandline: "
+ e.getMessage());
}
}
| public static void main(String[] args) {
CommandLineParser parser = new PosixParser();
HelpFormatter formatter = new HelpFormatter();
Options options = new Options();
options.addOption("l", "lowercase", false,
"Include lowercase alpha characters");
options.addOption("u", "uppercase", false,
"Include uppercase alpha characters");
options.addOption("d", "digits", false, "Include digits");
options.addOption("p", "punctuation", false, "Include punctuation");
options.addOption("n", "number", true,
"Number of passwords to generate");
options.addOption("L", "length", true,
"Length of the generated passwords");
try {
CommandLine cmd = parser.parse(options, args);
boolean hasLower = cmd.hasOption('l');
boolean hasUpper = cmd.hasOption('u');
boolean hasDigits = cmd.hasOption('d');
boolean hasPunctuation = cmd.hasOption('p');
boolean hasLength = cmd.hasOption('L');
boolean hasNumber = cmd.hasOption('n');
// Check for options
if (hasLower || hasUpper || hasDigits || hasPunctuation) {
PasswordGenerator generator;
generator = new PasswordGenerator(new Random());
PasswordChars passwordChars = new PasswordChars(hasLower,
hasUpper, hasDigits, hasPunctuation);
// Number of passwords to generate by default
int number = 10;
// Length of passwords generated by default
int length = 10;
// If length has been specified by the user, use it
// in place of the default value.
if (hasLength) {
try {
length = Integer.parseInt(cmd.getOptionValue('L'));
} catch(NumberFormatException e) {
System.out.println("Error: The argument to length must be a number");
formatter.printHelp("pwgen", options);
System.exit(-1);
}
}
// If number has been specified by the user, use it
// in place of the default value.
if (hasNumber) {
try {
number = Integer.parseInt(cmd.getOptionValue('n'));
} catch(NumberFormatException e) {
System.out.println("Error: The argument to number must be a number");
formatter.printHelp("pwgen", options);
System.exit(-1);
}
}
final List<String> passwords;
passwords = generator.generateMultiple(passwordChars, number,
length);
for (String password : passwords) {
System.out.println(password);
}
} else {
// If none found, print the usage message.
formatter.printHelp("pwgen", options);
}
} catch (ParseException e) {
System.err.println("Error parsing the commandline: "
+ e.getMessage());
}
}
|
diff --git a/app/controllers/Application.java b/app/controllers/Application.java
index 195ef83..93e5c8d 100644
--- a/app/controllers/Application.java
+++ b/app/controllers/Application.java
@@ -1,543 +1,543 @@
package controllers;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import model.Message;
import net.htmlparser.jericho.Attributes;
import net.htmlparser.jericho.OutputDocument;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.StartTag;
import net.htmlparser.jericho.Util;
import org.apache.commons.io.IOUtils;
import play.Logger;
import play.cache.Cache;
import play.data.Form;
import play.data.validation.ValidationError;
import play.libs.Comet;
import play.libs.F.Callback0;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
import views.html.messages;
import com.avaje.ebean.Ebean;
public class Application extends Controller {
private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22";
public static Result index() {
return ok(index.render(Form.form(Message.class), getList()));
}
private static List<Message> getList() {
String uuid=session("uuid");
if(uuid==null) {
uuid=java.util.UUID.randomUUID().toString();
session("uuid", uuid);
}
List<Message> list = (List<Message>) Cache.get(uuid+"list");
if(list == null) {
list = Message.find.setMaxRows(20).where().eq("parent", null).orderBy("timestamp desc").findList();
Cache.set(uuid+"list", list);
} else {
Logger.info("get CACHED");
}
return list;
}
public static Result list() {
Cache.remove(session("uuid")+"list");
return ok(messages.render(getList()));
}
public static Result post() {
Form<Message> m = Form.form(Message.class);
Form f = m.bindFromRequest();
if(f.hasErrors()) {
ValidationError e = f.error("");
flash("error", e.message());
f.fill(new Message());
return badRequest(index.render(f, Message.find.all()));
//return badRequest(f.errors().values()+"");
}
Message l = m.bindFromRequest().get();
try {
add(l, null);
flash("info", "elem added");
} catch (IOException e) {
flash("error", "ERROR: " + e);
e.printStackTrace();
}
return redirect("/");
}
public static Result asyncPost() {
final Message l;
Logger.info("asyncPost");
Form<Message> m = Form.form(Message.class);
final Form f = m.bindFromRequest();
if(f.hasErrors()) {
ValidationError e = f.error("");
flash("error", e.message());
f.fill(new Message());
// return badRequest(index.render(f, Message.find.all()));
//return badRequest(f.errors().values()+"");
l = null;
} else {
l = m.bindFromRequest().get();
}
/*
Chunks<String> chunks = new StringChunks() {
@Override
public void onReady(Chunks.Out<String> out) {
try {
add(l, out);
out.write("<script>alert('ssss');</script>");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
response().setContentType("text/html");
return ok(chunks);
*/
Comet comet = new Comet("parent.log") {
public void onConnected() {
try {
if(l == null) {
sendMessage("ERROR: "+f.error("").message());
close();
return;
}
add(l, this);
sendMessage("DONE");
close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
//response().setContentType("text/html");
return ok(comet);
}
public static String toBase64(URL url) throws IOException {
URLConnection c = url.openConnection();
InputStream in = c.getInputStream();
// return "data:"+c.getContentType()+";base64,"+org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(IOUtils.toByteArray(in));
return "data:"+c.getContentType()+";base64,"+org.apache.commons.codec.binary.Base64.encodeBase64String(IOUtils.toByteArray(in));
/*
File f = File.createTempFile(UUID.randomUUID().toString(), "");
FileOutputStream o = new FileOutputStream(f);
IOUtils.copy(in, o);
o.close();
return f;
*/
}
/**
* sciaga plik i zwraca gotowy obiekt message
* @param url1
* @return
* @throws IOException
*/
private static Message downloadFile(String url1) throws IOException {
Message l = new Message();
URL url = new URL(url1);
URLConnection c = url.openConnection();
c.addRequestProperty("User-Agent", DEFAULT_USER_AGENT);
InputStream in = c.getInputStream();
/**
* wada:
* jak jest przekierowanie Status 302,
* to np. zamiast zwrocic png, zwroci stronke html
*
* obsluga 302
*/
Integer code = null;
String location302 = null;
if(c instanceof HttpURLConnection) {
HttpURLConnection hc = (HttpURLConnection) c;
code = hc.getResponseCode();
if(code != null && code == 302) {
location302 = hc.getHeaderField("Location");
url1 = location302;
in.close();
url = new URL(location302);
c = url.openConnection();
c.addRequestProperty("User-Agent", DEFAULT_USER_AGENT);
in = c.getInputStream();
}
}
l.setUrl(url1);
l.setContentType(c.getContentType());
l.setContentEncoding(c.getContentEncoding());
l.setHeaderFields(c.getHeaderFields());
File f = File.createTempFile(UUID.randomUUID().toString(), "");
f.deleteOnExit();
FileOutputStream o = new FileOutputStream(f);
IOUtils.copy(in, o);
o.close();
in = new FileInputStream(f);
l.setData(IOUtils.toByteArray(in));
in.close();
return l;
}
private static void add(Message l, Comet comet) throws IOException {
if(comet != null) comet.sendMessage("adding...");
Logger.info("adding...");
URL url = new URL(l.getUrl());
URLConnection c = url.openConnection();
c.addRequestProperty("User-Agent", DEFAULT_USER_AGENT);
InputStream in = c.getInputStream();
l.setContentType(c.getContentType());
l.setContentEncoding(c.getContentEncoding());
Logger.info(c.getContentEncoding());
l.setHeaderFields(c.getHeaderFields());
File f = File.createTempFile(UUID.randomUUID().toString(), "");
f.deleteOnExit();
Logger.info(f.getAbsolutePath());
FileOutputStream o = new FileOutputStream(f);
IOUtils.copy(in, o);
o.close();
/*
if(c.getContentType().startsWith("text/html")) {
List<Message> m = parse(f, l.getUrl());
}
*/
if(c.getContentType().startsWith("text/html")) {
Object[] o1 = process(f, l.getUrl(), comet);
OutputDocument doc = (OutputDocument) o1[0];
List<Message> deps = (List<Message>) o1[1];
l.setData(doc.toString().getBytes());
Long mainId = Ebean.createSqlQuery("select nextval('message_seq') as seq, currval('message_seq')").findUnique().getLong("seq");
l.setId(mainId);
l.save();
in.close();
/**
* update deps
*/
if(!deps.isEmpty()) {
Logger.debug(deps+"");
Logger.info("DEPENDENCIES count: "+deps.size());
if(comet != null) comet.sendMessage("DEPENDENCIES count: "+deps.size());
String docString = doc.toString();
Message main = Message.find.byId(mainId);
int i = 0;
for(Message d: deps) {
d.setParent(main);
Long dId = Ebean.createSqlQuery("select nextval('message_seq') as seq, currval('message_seq')").findUnique().getLong("seq");
d.setId(dId);
d.save();
docString = docString.replaceAll("##"+i+"##", "/open/"+dId);
i++;
}
// update main
main.setData(docString.getBytes());
main.update();
}
} else {
in = new FileInputStream(f);
l.setData(IOUtils.toByteArray(in));
l.save();
in.close();
}
Logger.debug(f.getAbsolutePath() + (f.delete() ? " deleted":" not deleted"));
}
// lista powiazanych plikow, plik zrodlowy bedzie musial miec zmienione odnosniki
private static List<Message> parse(File f, String sourceUrlString) {
return null;
}
/**
* [0] - content (OutputDocument)
* [1] - deps
* @param f
* @param sourceUrlString
* @param comet
* @return
*/
private static Object[] process(File f, String sourceUrlString, Comet comet) {
List<Message> deps = new ArrayList<Message>();
try {
final URL sourceUrl=new URL(sourceUrlString);
Source source = new Source(f);
OutputDocument outputDocument = new OutputDocument(source);
StringBuilder sb=new StringBuilder();
int cssCount = 0;
int scriptCount = 0;
int imgCount = 0;
int depsCount = 0;
List all = source.getAllStartTags();
int k = 0;
for (Iterator i=all.iterator(); i.hasNext();) {
sb=new StringBuilder();
StartTag startTag=(StartTag)i.next();
//Logger.info(startTag.getName());
/**
* replace <link rel="stylesheet" href="<path>" .../>
* with <style type="text/css"> code </style>
*/
if(startTag.getName().equalsIgnoreCase("link")) {
Attributes attributes=startTag.getAttributes();
String rel=attributes.getValue("rel");
if (!"stylesheet".equalsIgnoreCase(rel)) continue;
String href=attributes.getValue("href");
if (href==null) continue;
String styleSheetContent;
try {
/*
styleSheetContent = Util.getString(new InputStreamReader(new URL(sourceUrl,href).openStream()));
styleSheetContent = processCss(styleSheetContent, new URL(new URL(sourceUrlString),href), comet);
*/
Message m = downloadFile(new URL(sourceUrl,href).toString());
- if(!m.getContentEncoding().equals("gzip")) {
+ if(m.getContentEncoding() == null || !m.getContentEncoding().equals("gzip")) {
styleSheetContent = Util.getString(new InputStreamReader(new ByteArrayInputStream(m.getData())));
styleSheetContent = processCss(styleSheetContent, new URL(new URL(sourceUrlString),href), comet);
m.setData(styleSheetContent.getBytes());
}
deps.add(m);
outputDocument.replace(attributes.get("href"), "href=\"##"+depsCount++ +"##\"");
Logger.info("REPLACED css: "+href);
if(comet != null) if(comet != null) comet.sendMessage("REPLACED css: "+href);
cssCount++;
} catch (Exception ex) {
Logger.error(ex.toString());
continue; // don't convert if URL is invalid
}
/*
sb.setLength(0);
sb.append("<style");
Attribute typeAttribute=attributes.get("type");
if (typeAttribute!=null) sb.append(' ').append(typeAttribute);
sb.append(">\n").append(styleSheetContent).append("\n</style>");
outputDocument.replace(startTag,sb);
*/
}
/**
* replace <img src="<path>" .../>
* with base64 <img src="data:image/jpg;base64,..."/>
*/
if(startTag.getName().equalsIgnoreCase("img")) {
Attributes attributes=startTag.getAttributes();
final String src=attributes.getValue("src");
if (src==null) continue;
// Logger.info("img: "+src);
// toBase64(src);
String photoUrl = (src.startsWith("http") ? new URL(src) : new URL(sourceUrl,src)).toString();
Message m = downloadFile(photoUrl);
deps.add(m);
outputDocument.replace(attributes.get("src"), "src=\"##"+depsCount++ +"##\"");
/**
* Lazy Load Plugin for jQuery
*/
final String src1=attributes.getValue("data-original");
if(src1 != null) {
String photoUrl1 = (src1.startsWith("http") ? new URL(src1) : new URL(sourceUrl,src1)).toString();
Message m1 = downloadFile(photoUrl1);
deps.add(m1);
outputDocument.replace(attributes.get("data-original"), "data-original=\"##"+depsCount++ +"##\"");
}
/*
outputDocument.replace(attributes, new HashMap<String, String>(){{
// put("src","http://www.copywriting.pl/wp-content/uploads/2011/09/udana-nazwa.jpg");
put("src",toBase64(src.startsWith("http") ? new URL(src) : new URL(sourceUrl, src)));
}});
*/
Logger.info("REPLACED img src: "+src);
if(comet != null) if(comet != null) comet.sendMessage("REPLACED img src: "+src);
imgCount++;
}
/**
* replace <script src="<path>" .../>
* with <script> js code </script>
*/
if(startTag.getName().equalsIgnoreCase("script")) {
Attributes attributes=startTag.getAttributes();
String src=attributes.getValue("src");
if (src==null) continue;
// String jsText;
try {
Logger.info(new URL(sourceUrl,src).toString());
if(comet != null) if(comet != null) comet.sendMessage(new URL(sourceUrl,src).toString());
// jsText = Util.getString(new InputStreamReader(new URL(sourceUrl,src).openStream()));
Message m = downloadFile(new URL(sourceUrl,src).toString());
deps.add(m);
outputDocument.replace(attributes.get("src"), "src=\"##"+depsCount++ +"##\"");
Logger.info("REPLACED js: "+src);
if(comet != null) comet.sendMessage("REPLACED js: "+src);
scriptCount++;
} catch (Exception ex) {
Logger.error(ex.toString());
continue; // don't convert if URL is invalid
}
/*
sb.setLength(0);
// sb.append("<!-- "+new URL(sourceUrl,src).toString()+" -->\n");
sb.append("<script");
Attribute typeAttribute=attributes.get("type");
if (typeAttribute!=null) sb.append(' ').append(typeAttribute);
sb.append(">\n").append(jsText).append("\n</script>");
outputDocument.replace(startTag,sb);
*/
}
}
Logger.info("REPLACED css count: "+cssCount);
Logger.info("REPLACED img src count: "+imgCount);
Logger.info("REPLACED script count: "+scriptCount);
if(comet != null) {
comet.sendMessage("REPLACED css count: "+cssCount);
comet.sendMessage("REPLACED img src count: "+imgCount);
comet.sendMessage("REPLACED script count: "+scriptCount);
}
return new Object[]{outputDocument, deps};
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* replace all url() with base64
* @param input
* @param comet
* @return
*/
private static String processCss(String input, URL baseUrl, Comet comet) {
//StringBuffer sb = new StringBuffer(input.length());
StringBuffer sb = new StringBuffer();
// (url\s{0,}\(\s{0,}['"]{0,1})([^\)'"]*)(['"]{0,1}\))
String regex = "(url\\s{0,}\\(\\s{0,}['\"]{0,1})([^\\'\")]*)(['\"]{0,1}\\))";
// input.replaceAll(regex, "$1"+"URL"+"$2$3");
// return input;
Pattern p = Pattern.compile(regex, Pattern.DOTALL);
Matcher m = p.matcher(input);
while(m.find()) {
try {
URL url;
if(m.group(2).startsWith("http")) {
url = new URL(m.group(2));
} else if(m.group(2).startsWith("data:")) {
url = null;
} else {
url = new URL(baseUrl, m.group(2));
}
if(url != null) {
Logger.info(m.group() + " => " + url.toString());
if(comet != null) comet.sendMessage(m.group() + " => " + url.toString());
try {
String b64 = toBase64(url);
m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1)+b64+m.group(3)));
} catch (IOException e) {
Logger.error(e.toString());
}
}
} catch (MalformedURLException e) {
Logger.error(e.toString());
}
}
m.appendTail(sb);
return sb.toString();
}
public static Result open(Long id) {
Message m = Ebean.find(Message.class, id);//Message.find.byId(id);
if(m == null) {
return badRequest("no data");
}
try {
response().setContentType(m.getContentType());
if(m.getContentEncoding() != null) {
response().setHeader(CONTENT_ENCODING, m.getContentEncoding());
}
// response().setHeader("Content-Disposition", "inline; filename=\"myfile.txt\"");
return m.getData() != null ? ok(IOUtils.toBufferedInputStream(new ByteArrayInputStream(m.getData()))) : ok("no data");
} catch (IOException e) {
e.printStackTrace();
}
return badRequest("no data");
}
/**
* test Comet socket
* @return
*/
public static Result comet() {
Comet comet = new Comet("parent.log") {
public void onConnected() {
int i = 0;
while(1 == 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
sendMessage("comet message "+i++);
}
//close();
}
@Override
public void onDisconnected(Callback0 callback) {
sendMessage("disconnect");
close();
}
};
// otwiera socket (nieskonczony response)
return ok(comet);
}
}
| true | true | private static Object[] process(File f, String sourceUrlString, Comet comet) {
List<Message> deps = new ArrayList<Message>();
try {
final URL sourceUrl=new URL(sourceUrlString);
Source source = new Source(f);
OutputDocument outputDocument = new OutputDocument(source);
StringBuilder sb=new StringBuilder();
int cssCount = 0;
int scriptCount = 0;
int imgCount = 0;
int depsCount = 0;
List all = source.getAllStartTags();
int k = 0;
for (Iterator i=all.iterator(); i.hasNext();) {
sb=new StringBuilder();
StartTag startTag=(StartTag)i.next();
//Logger.info(startTag.getName());
/**
* replace <link rel="stylesheet" href="<path>" .../>
* with <style type="text/css"> code </style>
*/
if(startTag.getName().equalsIgnoreCase("link")) {
Attributes attributes=startTag.getAttributes();
String rel=attributes.getValue("rel");
if (!"stylesheet".equalsIgnoreCase(rel)) continue;
String href=attributes.getValue("href");
if (href==null) continue;
String styleSheetContent;
try {
/*
styleSheetContent = Util.getString(new InputStreamReader(new URL(sourceUrl,href).openStream()));
styleSheetContent = processCss(styleSheetContent, new URL(new URL(sourceUrlString),href), comet);
*/
Message m = downloadFile(new URL(sourceUrl,href).toString());
if(!m.getContentEncoding().equals("gzip")) {
styleSheetContent = Util.getString(new InputStreamReader(new ByteArrayInputStream(m.getData())));
styleSheetContent = processCss(styleSheetContent, new URL(new URL(sourceUrlString),href), comet);
m.setData(styleSheetContent.getBytes());
}
deps.add(m);
outputDocument.replace(attributes.get("href"), "href=\"##"+depsCount++ +"##\"");
Logger.info("REPLACED css: "+href);
if(comet != null) if(comet != null) comet.sendMessage("REPLACED css: "+href);
cssCount++;
} catch (Exception ex) {
Logger.error(ex.toString());
continue; // don't convert if URL is invalid
}
/*
sb.setLength(0);
sb.append("<style");
Attribute typeAttribute=attributes.get("type");
if (typeAttribute!=null) sb.append(' ').append(typeAttribute);
sb.append(">\n").append(styleSheetContent).append("\n</style>");
outputDocument.replace(startTag,sb);
*/
}
/**
* replace <img src="<path>" .../>
* with base64 <img src="data:image/jpg;base64,..."/>
*/
if(startTag.getName().equalsIgnoreCase("img")) {
Attributes attributes=startTag.getAttributes();
final String src=attributes.getValue("src");
if (src==null) continue;
// Logger.info("img: "+src);
// toBase64(src);
String photoUrl = (src.startsWith("http") ? new URL(src) : new URL(sourceUrl,src)).toString();
Message m = downloadFile(photoUrl);
deps.add(m);
outputDocument.replace(attributes.get("src"), "src=\"##"+depsCount++ +"##\"");
/**
* Lazy Load Plugin for jQuery
*/
final String src1=attributes.getValue("data-original");
if(src1 != null) {
String photoUrl1 = (src1.startsWith("http") ? new URL(src1) : new URL(sourceUrl,src1)).toString();
Message m1 = downloadFile(photoUrl1);
deps.add(m1);
outputDocument.replace(attributes.get("data-original"), "data-original=\"##"+depsCount++ +"##\"");
}
/*
outputDocument.replace(attributes, new HashMap<String, String>(){{
// put("src","http://www.copywriting.pl/wp-content/uploads/2011/09/udana-nazwa.jpg");
put("src",toBase64(src.startsWith("http") ? new URL(src) : new URL(sourceUrl, src)));
}});
*/
Logger.info("REPLACED img src: "+src);
if(comet != null) if(comet != null) comet.sendMessage("REPLACED img src: "+src);
imgCount++;
}
/**
* replace <script src="<path>" .../>
* with <script> js code </script>
*/
if(startTag.getName().equalsIgnoreCase("script")) {
Attributes attributes=startTag.getAttributes();
String src=attributes.getValue("src");
if (src==null) continue;
// String jsText;
try {
Logger.info(new URL(sourceUrl,src).toString());
if(comet != null) if(comet != null) comet.sendMessage(new URL(sourceUrl,src).toString());
// jsText = Util.getString(new InputStreamReader(new URL(sourceUrl,src).openStream()));
Message m = downloadFile(new URL(sourceUrl,src).toString());
deps.add(m);
outputDocument.replace(attributes.get("src"), "src=\"##"+depsCount++ +"##\"");
Logger.info("REPLACED js: "+src);
if(comet != null) comet.sendMessage("REPLACED js: "+src);
scriptCount++;
} catch (Exception ex) {
Logger.error(ex.toString());
continue; // don't convert if URL is invalid
}
/*
sb.setLength(0);
// sb.append("<!-- "+new URL(sourceUrl,src).toString()+" -->\n");
sb.append("<script");
Attribute typeAttribute=attributes.get("type");
if (typeAttribute!=null) sb.append(' ').append(typeAttribute);
sb.append(">\n").append(jsText).append("\n</script>");
outputDocument.replace(startTag,sb);
*/
}
}
Logger.info("REPLACED css count: "+cssCount);
Logger.info("REPLACED img src count: "+imgCount);
Logger.info("REPLACED script count: "+scriptCount);
if(comet != null) {
comet.sendMessage("REPLACED css count: "+cssCount);
comet.sendMessage("REPLACED img src count: "+imgCount);
comet.sendMessage("REPLACED script count: "+scriptCount);
}
return new Object[]{outputDocument, deps};
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
| private static Object[] process(File f, String sourceUrlString, Comet comet) {
List<Message> deps = new ArrayList<Message>();
try {
final URL sourceUrl=new URL(sourceUrlString);
Source source = new Source(f);
OutputDocument outputDocument = new OutputDocument(source);
StringBuilder sb=new StringBuilder();
int cssCount = 0;
int scriptCount = 0;
int imgCount = 0;
int depsCount = 0;
List all = source.getAllStartTags();
int k = 0;
for (Iterator i=all.iterator(); i.hasNext();) {
sb=new StringBuilder();
StartTag startTag=(StartTag)i.next();
//Logger.info(startTag.getName());
/**
* replace <link rel="stylesheet" href="<path>" .../>
* with <style type="text/css"> code </style>
*/
if(startTag.getName().equalsIgnoreCase("link")) {
Attributes attributes=startTag.getAttributes();
String rel=attributes.getValue("rel");
if (!"stylesheet".equalsIgnoreCase(rel)) continue;
String href=attributes.getValue("href");
if (href==null) continue;
String styleSheetContent;
try {
/*
styleSheetContent = Util.getString(new InputStreamReader(new URL(sourceUrl,href).openStream()));
styleSheetContent = processCss(styleSheetContent, new URL(new URL(sourceUrlString),href), comet);
*/
Message m = downloadFile(new URL(sourceUrl,href).toString());
if(m.getContentEncoding() == null || !m.getContentEncoding().equals("gzip")) {
styleSheetContent = Util.getString(new InputStreamReader(new ByteArrayInputStream(m.getData())));
styleSheetContent = processCss(styleSheetContent, new URL(new URL(sourceUrlString),href), comet);
m.setData(styleSheetContent.getBytes());
}
deps.add(m);
outputDocument.replace(attributes.get("href"), "href=\"##"+depsCount++ +"##\"");
Logger.info("REPLACED css: "+href);
if(comet != null) if(comet != null) comet.sendMessage("REPLACED css: "+href);
cssCount++;
} catch (Exception ex) {
Logger.error(ex.toString());
continue; // don't convert if URL is invalid
}
/*
sb.setLength(0);
sb.append("<style");
Attribute typeAttribute=attributes.get("type");
if (typeAttribute!=null) sb.append(' ').append(typeAttribute);
sb.append(">\n").append(styleSheetContent).append("\n</style>");
outputDocument.replace(startTag,sb);
*/
}
/**
* replace <img src="<path>" .../>
* with base64 <img src="data:image/jpg;base64,..."/>
*/
if(startTag.getName().equalsIgnoreCase("img")) {
Attributes attributes=startTag.getAttributes();
final String src=attributes.getValue("src");
if (src==null) continue;
// Logger.info("img: "+src);
// toBase64(src);
String photoUrl = (src.startsWith("http") ? new URL(src) : new URL(sourceUrl,src)).toString();
Message m = downloadFile(photoUrl);
deps.add(m);
outputDocument.replace(attributes.get("src"), "src=\"##"+depsCount++ +"##\"");
/**
* Lazy Load Plugin for jQuery
*/
final String src1=attributes.getValue("data-original");
if(src1 != null) {
String photoUrl1 = (src1.startsWith("http") ? new URL(src1) : new URL(sourceUrl,src1)).toString();
Message m1 = downloadFile(photoUrl1);
deps.add(m1);
outputDocument.replace(attributes.get("data-original"), "data-original=\"##"+depsCount++ +"##\"");
}
/*
outputDocument.replace(attributes, new HashMap<String, String>(){{
// put("src","http://www.copywriting.pl/wp-content/uploads/2011/09/udana-nazwa.jpg");
put("src",toBase64(src.startsWith("http") ? new URL(src) : new URL(sourceUrl, src)));
}});
*/
Logger.info("REPLACED img src: "+src);
if(comet != null) if(comet != null) comet.sendMessage("REPLACED img src: "+src);
imgCount++;
}
/**
* replace <script src="<path>" .../>
* with <script> js code </script>
*/
if(startTag.getName().equalsIgnoreCase("script")) {
Attributes attributes=startTag.getAttributes();
String src=attributes.getValue("src");
if (src==null) continue;
// String jsText;
try {
Logger.info(new URL(sourceUrl,src).toString());
if(comet != null) if(comet != null) comet.sendMessage(new URL(sourceUrl,src).toString());
// jsText = Util.getString(new InputStreamReader(new URL(sourceUrl,src).openStream()));
Message m = downloadFile(new URL(sourceUrl,src).toString());
deps.add(m);
outputDocument.replace(attributes.get("src"), "src=\"##"+depsCount++ +"##\"");
Logger.info("REPLACED js: "+src);
if(comet != null) comet.sendMessage("REPLACED js: "+src);
scriptCount++;
} catch (Exception ex) {
Logger.error(ex.toString());
continue; // don't convert if URL is invalid
}
/*
sb.setLength(0);
// sb.append("<!-- "+new URL(sourceUrl,src).toString()+" -->\n");
sb.append("<script");
Attribute typeAttribute=attributes.get("type");
if (typeAttribute!=null) sb.append(' ').append(typeAttribute);
sb.append(">\n").append(jsText).append("\n</script>");
outputDocument.replace(startTag,sb);
*/
}
}
Logger.info("REPLACED css count: "+cssCount);
Logger.info("REPLACED img src count: "+imgCount);
Logger.info("REPLACED script count: "+scriptCount);
if(comet != null) {
comet.sendMessage("REPLACED css count: "+cssCount);
comet.sendMessage("REPLACED img src count: "+imgCount);
comet.sendMessage("REPLACED script count: "+scriptCount);
}
return new Object[]{outputDocument, deps};
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
|
diff --git a/Lab3/src/utils/DNAUtil.java b/Lab3/src/utils/DNAUtil.java
index 9d38066..df3b217 100644
--- a/Lab3/src/utils/DNAUtil.java
+++ b/Lab3/src/utils/DNAUtil.java
@@ -1,347 +1,347 @@
package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import model.Gene;
public class DNAUtil {
public static double avgCDSSpan = 0;
public static double avgCDSSize = 0;
public static double avgExonSize = 0;
public static double avgIntronSize = 0;
public static double avgIntergenicSize = 0;
public static int totalNucleotides = 0;
public static int numGenes = 0;
public static int totalCDSActual = 0;
public static double totalT = 0;
// Static methods again works for me
public static String calculateResults(String filepath) throws Exception {
avgCDSSize = 0;
avgCDSSpan = 0;
avgExonSize = 0;
avgIntronSize = 0;
avgIntergenicSize = 0;
totalNucleotides = 0;
numGenes = 0;
totalCDSActual = 0;
totalT = 0;
// Name of the gene to all of the attributes of it
Map<String, List<Gene>> genes = new HashMap<String, List<Gene>>();
readFile(filepath, genes);
calculateGeneContentAndDensity(genes);
return displayInfo(genes);
}
private static String displayInfo(Map<String, List<Gene>> genes) {
String rtn = "";
DecimalFormat df = new DecimalFormat("#.##");
// for(String name : genes.keySet()) {
// rtn += (name + " " + genes.get(name).size() + "\n");
// }
rtn += "Gene Content:\n";
rtn += "a) " + df.format(avgCDSSpan) + "\tAverage CDS Span \n";
rtn += "b) " + df.format(avgCDSSize) + "\tAverage CDS Size \n";
rtn += "c) " + df.format(avgExonSize) + "\tAverage Exon Size \n";
rtn += "d) " + df.format(avgIntronSize) + "\tAverage Intron Size \n";
rtn += "e) " + df.format(avgIntergenicSize)
+ "\tAverage Intergenic Region Size \n";
rtn += "\n2. Gene Density:\n";
rtn += "a) " + df.format(numGenes * avgCDSSpan)
+ "\tNumber of Genes * Average CDS Span\n";
rtn += "b) " + df.format(numGenes * avgCDSSize)
+ "\tNumber of Genes * Average CDS Size\n";
rtn += "c) "
+ df.format((double) totalCDSActual / totalT)
+ "\tTotal CDS Size (combining isoforms) / number of nucleotides\n";
rtn += "d) "
+ df.format((double) numGenes / (totalNucleotides / 1000.0))
+ "\tNumber of Genes per KBPairs\n";
rtn += "e) " + df.format((totalNucleotides / 1000.0) / numGenes)
+ "\tKBPairs / Number of Genes \n";
return rtn;
}
private static void readFile(String filepath, Map<String, List<Gene>> genes)
throws Exception {
// Set up the file reader
File f = new File(filepath);
FileReader in = new FileReader(f);
BufferedReader reader = new BufferedReader(in);
String line = null;
do {
line = reader.readLine();
if (line != null) {
// Break the line apart by the tabs
String[] tokens = line.split("\t");
// Create a new Gene to save the parts
Gene g = new Gene();
// Set all the normal stuff
g.setChromosomeName(tokens[0]);
g.setSource(tokens[1]);
if (!tokens[2].equals("mRNA") && !tokens[2].equals("CDS")) {
continue;
}
g.setFeature(tokens[2]);
g.setStart(Integer.parseInt(tokens[3]));
g.setStop(Integer.parseInt(tokens[4]));
g.setScore(tokens[5].equals(".") ? 0 : Double
.parseDouble(tokens[5]));
g.setForwardStrand(tokens[6].equals("+") ? true : false);
g.setFrame(tokens[7].equals(".") ? 0 : Integer
.parseInt(tokens[7]));
String[] attributes = tokens[8].split(";");
// Save all attributes
for (String s : attributes) {
s = s.trim();
String[] pair = s.split(" ");
String key = pair[0];
String val = pair[1];
if (key.equals("gene_id")) {
g.setName(val.replace("\"", ""));
g.addAttribute(key, val.replace("\"", ""));
} else {
g.addAttribute(key, val.replace("\"", ""));
}
}
// Update start or stop based on + and - values
if (g.getFeature().equals("mRNA")) {
if (g.isForwardStrand()) {
g.setStop(g.getStop() + 3);
} else {
g.setStart(g.getStart() - 3);
}
}
// The gene is finished reading save it to the gene map
if (genes.get(g.getName()) == null) {
List<Gene> temp = new ArrayList<Gene>();
temp.add(g);
genes.put(g.getName(), temp);
} else {
genes.get(g.getName()).add(g);
}
}
} while (line != null);
// All done
reader.close();
}
private static void calculateGeneContentAndDensity(
Map<String, List<Gene>> genes) {
List<Gene> gList;
int mRNATotalSize = 0;
int mRNACount = 0;
Map<String, Double> averageCDSSizes = new HashMap<String, Double>();
Map<String, Double> averageExonSizes = new HashMap<String, Double>();
Map<String, AttributeInfo> isoforms = new HashMap<String, AttributeInfo>();
Map<String, AttributeInfo> geneInfos = new HashMap<String, AttributeInfo>();
int totalCDS = 0;
int totalIntergenicRegionSize = 0;
List<Gene> mRNAs = new ArrayList<Gene>();
boolean foundRNA = false;
// Lazy flag ... haha
boolean first = true;
int maxEndPos = 0;
int smallestStartPos = 0;
List<IntegerPair> cdsRegions = new ArrayList<IntegerPair>();
for (String name : genes.keySet()) {
gList = genes.get(name);
foundRNA = false;
for (Gene g : gList) {
// Average CDS Span
if (g.getFeature().equals("mRNA")) {
if (!foundRNA) {
mRNAs.add(g);
foundRNA = true;
}
mRNACount++;
mRNATotalSize += g.getStop() - g.getStart();
} else if (g.getFeature().equals("CDS")) {
totalCDS++;
cdsRegions.add(new IntegerPair(g.getStart(), g.getStop()));
// Average CDS size for all isoforms
String transcriptID = g.getAttributes()
.get("transcript_id");
if (isoforms.containsKey(transcriptID)) {
isoforms.get(transcriptID).add(
g.getStop() - g.getStart());
} else {
isoforms.put(transcriptID, new AttributeInfo(
transcriptID, g.getStop() - g.getStart()));
}
// Average Exon Size for each gene that is a CDS
String geneID = g.getAttributes().get("gene_id");
if (geneInfos.containsKey(geneID)) {
geneInfos.get(geneID).add(g.getStop() - g.getStart());
} else {
geneInfos.put(
geneID,
new AttributeInfo(geneID, g.getStop()
- g.getStart()));
}
}
if (first) {
maxEndPos = g.getStop();
smallestStartPos = g.getStart();
} else {
maxEndPos = (g.getStop() > maxEndPos) ? g.getStop()
: maxEndPos;
smallestStartPos = (g.getStart() < smallestStartPos) ? g
.getStart() : smallestStartPos;
}
}
}
// actual total cds size
Collections.sort(cdsRegions, new Comparator<IntegerPair>() {
@Override
public int compare(IntegerPair o1, IntegerPair o2) {
if (o1.start < o2.start) {
return -1;
} else if (o1.start > o2.start) {
return 1;
} else {
return 0;
}
}
});
// find and combine overlapping regions
IntegerPair curVal = cdsRegions.size() > 0 ? cdsRegions.get(0) : null;
- int cdsMin = curVal.start;
- int cdsMax = curVal.stop;
+ int cdsMin = curVal != null ? curVal.start : 0;
+ int cdsMax = curVal != null ? curVal.stop : 0;
Iterator<IntegerPair> iter = cdsRegions.iterator();
while (iter.hasNext()) {
IntegerPair temp = iter.next();
while(temp.start <= curVal.stop && iter.hasNext()) {
if(temp.stop > curVal.stop) {
curVal.stop = temp.stop;
}
temp = iter.next();
}
totalCDSActual += (curVal.stop - curVal.start) + 1;
if(curVal.start < cdsMin) {
cdsMin = curVal.start;
}
if(curVal.stop > cdsMax) {
cdsMax = curVal.stop;
}
curVal = temp;
}
totalT = cdsMax - cdsMin + 1;
// Average intergenic region size
Collections.sort(mRNAs, new Comparator<Gene>() {
@Override
public int compare(Gene o1, Gene o2) {
if (o1.getStart() < o2.getStart()) {
return -1;
} else if (o1.getStart() > o2.getStart()) {
return 1;
} else {
return 0;
}
}
});
int lastStop = -1;
for (Gene rna : mRNAs) {
if (lastStop < 0) {
lastStop = rna.getStop();
} else {
totalIntergenicRegionSize += rna.getStart() - lastStop;
lastStop = rna.getStop();
}
}
if (mRNAs.size() == 1) {
avgIntergenicSize = 0;
} else {
avgIntergenicSize = totalIntergenicRegionSize / (mRNAs.size() - 1);
}
// Average CDS Span
avgCDSSpan = (double) mRNATotalSize / mRNACount;
// Find average CDS size per isoform
for (String name : isoforms.keySet()) {
AttributeInfo iso = isoforms.get(name);
averageCDSSizes.put(iso.id, (double) iso.totalSize / iso.count);
}
// Find average of all isoform CDS size averages
for (String name : averageCDSSizes.keySet()) {
avgCDSSize += averageCDSSizes.get(name);
}
// Average CDS size for all isoforms
avgCDSSize /= isoforms.keySet().size();
// Average Exon Size for each gene
for (String name : geneInfos.keySet()) {
AttributeInfo geneInfo = geneInfos.get(name);
averageExonSizes.put(geneInfo.id, (double) geneInfo.totalSize
/ geneInfo.count);
}
// Find average of all Gene Exon size averages
for (String name : averageExonSizes.keySet()) {
avgExonSize += averageExonSizes.get(name);
}
// Average Exon Size for all genes
avgExonSize /= geneInfos.keySet().size();
// Average Intron Size
avgIntronSize = (avgCDSSpan - avgCDSSize) / (totalCDS - 1);
// Number of genes
numGenes = geneInfos.keySet().size();
// Finding highest Nucleotide number
totalNucleotides = maxEndPos - smallestStartPos;
}
}
| true | true | private static void calculateGeneContentAndDensity(
Map<String, List<Gene>> genes) {
List<Gene> gList;
int mRNATotalSize = 0;
int mRNACount = 0;
Map<String, Double> averageCDSSizes = new HashMap<String, Double>();
Map<String, Double> averageExonSizes = new HashMap<String, Double>();
Map<String, AttributeInfo> isoforms = new HashMap<String, AttributeInfo>();
Map<String, AttributeInfo> geneInfos = new HashMap<String, AttributeInfo>();
int totalCDS = 0;
int totalIntergenicRegionSize = 0;
List<Gene> mRNAs = new ArrayList<Gene>();
boolean foundRNA = false;
// Lazy flag ... haha
boolean first = true;
int maxEndPos = 0;
int smallestStartPos = 0;
List<IntegerPair> cdsRegions = new ArrayList<IntegerPair>();
for (String name : genes.keySet()) {
gList = genes.get(name);
foundRNA = false;
for (Gene g : gList) {
// Average CDS Span
if (g.getFeature().equals("mRNA")) {
if (!foundRNA) {
mRNAs.add(g);
foundRNA = true;
}
mRNACount++;
mRNATotalSize += g.getStop() - g.getStart();
} else if (g.getFeature().equals("CDS")) {
totalCDS++;
cdsRegions.add(new IntegerPair(g.getStart(), g.getStop()));
// Average CDS size for all isoforms
String transcriptID = g.getAttributes()
.get("transcript_id");
if (isoforms.containsKey(transcriptID)) {
isoforms.get(transcriptID).add(
g.getStop() - g.getStart());
} else {
isoforms.put(transcriptID, new AttributeInfo(
transcriptID, g.getStop() - g.getStart()));
}
// Average Exon Size for each gene that is a CDS
String geneID = g.getAttributes().get("gene_id");
if (geneInfos.containsKey(geneID)) {
geneInfos.get(geneID).add(g.getStop() - g.getStart());
} else {
geneInfos.put(
geneID,
new AttributeInfo(geneID, g.getStop()
- g.getStart()));
}
}
if (first) {
maxEndPos = g.getStop();
smallestStartPos = g.getStart();
} else {
maxEndPos = (g.getStop() > maxEndPos) ? g.getStop()
: maxEndPos;
smallestStartPos = (g.getStart() < smallestStartPos) ? g
.getStart() : smallestStartPos;
}
}
}
// actual total cds size
Collections.sort(cdsRegions, new Comparator<IntegerPair>() {
@Override
public int compare(IntegerPair o1, IntegerPair o2) {
if (o1.start < o2.start) {
return -1;
} else if (o1.start > o2.start) {
return 1;
} else {
return 0;
}
}
});
// find and combine overlapping regions
IntegerPair curVal = cdsRegions.size() > 0 ? cdsRegions.get(0) : null;
int cdsMin = curVal.start;
int cdsMax = curVal.stop;
Iterator<IntegerPair> iter = cdsRegions.iterator();
while (iter.hasNext()) {
IntegerPair temp = iter.next();
while(temp.start <= curVal.stop && iter.hasNext()) {
if(temp.stop > curVal.stop) {
curVal.stop = temp.stop;
}
temp = iter.next();
}
totalCDSActual += (curVal.stop - curVal.start) + 1;
if(curVal.start < cdsMin) {
cdsMin = curVal.start;
}
if(curVal.stop > cdsMax) {
cdsMax = curVal.stop;
}
curVal = temp;
}
totalT = cdsMax - cdsMin + 1;
// Average intergenic region size
Collections.sort(mRNAs, new Comparator<Gene>() {
@Override
public int compare(Gene o1, Gene o2) {
if (o1.getStart() < o2.getStart()) {
return -1;
} else if (o1.getStart() > o2.getStart()) {
return 1;
} else {
return 0;
}
}
});
int lastStop = -1;
for (Gene rna : mRNAs) {
if (lastStop < 0) {
lastStop = rna.getStop();
} else {
totalIntergenicRegionSize += rna.getStart() - lastStop;
lastStop = rna.getStop();
}
}
if (mRNAs.size() == 1) {
avgIntergenicSize = 0;
} else {
avgIntergenicSize = totalIntergenicRegionSize / (mRNAs.size() - 1);
}
// Average CDS Span
avgCDSSpan = (double) mRNATotalSize / mRNACount;
// Find average CDS size per isoform
for (String name : isoforms.keySet()) {
AttributeInfo iso = isoforms.get(name);
averageCDSSizes.put(iso.id, (double) iso.totalSize / iso.count);
}
// Find average of all isoform CDS size averages
for (String name : averageCDSSizes.keySet()) {
avgCDSSize += averageCDSSizes.get(name);
}
// Average CDS size for all isoforms
avgCDSSize /= isoforms.keySet().size();
// Average Exon Size for each gene
for (String name : geneInfos.keySet()) {
AttributeInfo geneInfo = geneInfos.get(name);
averageExonSizes.put(geneInfo.id, (double) geneInfo.totalSize
/ geneInfo.count);
}
// Find average of all Gene Exon size averages
for (String name : averageExonSizes.keySet()) {
avgExonSize += averageExonSizes.get(name);
}
// Average Exon Size for all genes
avgExonSize /= geneInfos.keySet().size();
// Average Intron Size
avgIntronSize = (avgCDSSpan - avgCDSSize) / (totalCDS - 1);
// Number of genes
numGenes = geneInfos.keySet().size();
// Finding highest Nucleotide number
totalNucleotides = maxEndPos - smallestStartPos;
}
| private static void calculateGeneContentAndDensity(
Map<String, List<Gene>> genes) {
List<Gene> gList;
int mRNATotalSize = 0;
int mRNACount = 0;
Map<String, Double> averageCDSSizes = new HashMap<String, Double>();
Map<String, Double> averageExonSizes = new HashMap<String, Double>();
Map<String, AttributeInfo> isoforms = new HashMap<String, AttributeInfo>();
Map<String, AttributeInfo> geneInfos = new HashMap<String, AttributeInfo>();
int totalCDS = 0;
int totalIntergenicRegionSize = 0;
List<Gene> mRNAs = new ArrayList<Gene>();
boolean foundRNA = false;
// Lazy flag ... haha
boolean first = true;
int maxEndPos = 0;
int smallestStartPos = 0;
List<IntegerPair> cdsRegions = new ArrayList<IntegerPair>();
for (String name : genes.keySet()) {
gList = genes.get(name);
foundRNA = false;
for (Gene g : gList) {
// Average CDS Span
if (g.getFeature().equals("mRNA")) {
if (!foundRNA) {
mRNAs.add(g);
foundRNA = true;
}
mRNACount++;
mRNATotalSize += g.getStop() - g.getStart();
} else if (g.getFeature().equals("CDS")) {
totalCDS++;
cdsRegions.add(new IntegerPair(g.getStart(), g.getStop()));
// Average CDS size for all isoforms
String transcriptID = g.getAttributes()
.get("transcript_id");
if (isoforms.containsKey(transcriptID)) {
isoforms.get(transcriptID).add(
g.getStop() - g.getStart());
} else {
isoforms.put(transcriptID, new AttributeInfo(
transcriptID, g.getStop() - g.getStart()));
}
// Average Exon Size for each gene that is a CDS
String geneID = g.getAttributes().get("gene_id");
if (geneInfos.containsKey(geneID)) {
geneInfos.get(geneID).add(g.getStop() - g.getStart());
} else {
geneInfos.put(
geneID,
new AttributeInfo(geneID, g.getStop()
- g.getStart()));
}
}
if (first) {
maxEndPos = g.getStop();
smallestStartPos = g.getStart();
} else {
maxEndPos = (g.getStop() > maxEndPos) ? g.getStop()
: maxEndPos;
smallestStartPos = (g.getStart() < smallestStartPos) ? g
.getStart() : smallestStartPos;
}
}
}
// actual total cds size
Collections.sort(cdsRegions, new Comparator<IntegerPair>() {
@Override
public int compare(IntegerPair o1, IntegerPair o2) {
if (o1.start < o2.start) {
return -1;
} else if (o1.start > o2.start) {
return 1;
} else {
return 0;
}
}
});
// find and combine overlapping regions
IntegerPair curVal = cdsRegions.size() > 0 ? cdsRegions.get(0) : null;
int cdsMin = curVal != null ? curVal.start : 0;
int cdsMax = curVal != null ? curVal.stop : 0;
Iterator<IntegerPair> iter = cdsRegions.iterator();
while (iter.hasNext()) {
IntegerPair temp = iter.next();
while(temp.start <= curVal.stop && iter.hasNext()) {
if(temp.stop > curVal.stop) {
curVal.stop = temp.stop;
}
temp = iter.next();
}
totalCDSActual += (curVal.stop - curVal.start) + 1;
if(curVal.start < cdsMin) {
cdsMin = curVal.start;
}
if(curVal.stop > cdsMax) {
cdsMax = curVal.stop;
}
curVal = temp;
}
totalT = cdsMax - cdsMin + 1;
// Average intergenic region size
Collections.sort(mRNAs, new Comparator<Gene>() {
@Override
public int compare(Gene o1, Gene o2) {
if (o1.getStart() < o2.getStart()) {
return -1;
} else if (o1.getStart() > o2.getStart()) {
return 1;
} else {
return 0;
}
}
});
int lastStop = -1;
for (Gene rna : mRNAs) {
if (lastStop < 0) {
lastStop = rna.getStop();
} else {
totalIntergenicRegionSize += rna.getStart() - lastStop;
lastStop = rna.getStop();
}
}
if (mRNAs.size() == 1) {
avgIntergenicSize = 0;
} else {
avgIntergenicSize = totalIntergenicRegionSize / (mRNAs.size() - 1);
}
// Average CDS Span
avgCDSSpan = (double) mRNATotalSize / mRNACount;
// Find average CDS size per isoform
for (String name : isoforms.keySet()) {
AttributeInfo iso = isoforms.get(name);
averageCDSSizes.put(iso.id, (double) iso.totalSize / iso.count);
}
// Find average of all isoform CDS size averages
for (String name : averageCDSSizes.keySet()) {
avgCDSSize += averageCDSSizes.get(name);
}
// Average CDS size for all isoforms
avgCDSSize /= isoforms.keySet().size();
// Average Exon Size for each gene
for (String name : geneInfos.keySet()) {
AttributeInfo geneInfo = geneInfos.get(name);
averageExonSizes.put(geneInfo.id, (double) geneInfo.totalSize
/ geneInfo.count);
}
// Find average of all Gene Exon size averages
for (String name : averageExonSizes.keySet()) {
avgExonSize += averageExonSizes.get(name);
}
// Average Exon Size for all genes
avgExonSize /= geneInfos.keySet().size();
// Average Intron Size
avgIntronSize = (avgCDSSpan - avgCDSSize) / (totalCDS - 1);
// Number of genes
numGenes = geneInfos.keySet().size();
// Finding highest Nucleotide number
totalNucleotides = maxEndPos - smallestStartPos;
}
|
diff --git a/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/transaction/AbstractTitanTx.java b/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/transaction/AbstractTitanTx.java
index 928177187..2a844a1a7 100644
--- a/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/transaction/AbstractTitanTx.java
+++ b/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/transaction/AbstractTitanTx.java
@@ -1,538 +1,538 @@
package com.thinkaurelius.titan.graphdb.transaction;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.thinkaurelius.titan.core.InvalidElementException;
import com.thinkaurelius.titan.core.TitanEdge;
import com.thinkaurelius.titan.core.TitanException;
import com.thinkaurelius.titan.core.TitanKey;
import com.thinkaurelius.titan.core.TitanLabel;
import com.thinkaurelius.titan.core.TitanProperty;
import com.thinkaurelius.titan.core.TitanQuery;
import com.thinkaurelius.titan.core.TitanRelation;
import com.thinkaurelius.titan.core.TitanType;
import com.thinkaurelius.titan.core.TitanVertex;
import com.thinkaurelius.titan.core.TypeMaker;
import com.thinkaurelius.titan.graphdb.blueprints.TitanBlueprintsTransaction;
import com.thinkaurelius.titan.graphdb.database.InternalTitanGraph;
import com.thinkaurelius.titan.graphdb.idmanagement.IDInspector;
import com.thinkaurelius.titan.graphdb.query.SimpleTitanQuery;
import com.thinkaurelius.titan.graphdb.relations.AttributeUtil;
import com.thinkaurelius.titan.graphdb.relations.InternalRelation;
import com.thinkaurelius.titan.graphdb.relations.factory.RelationFactory;
import com.thinkaurelius.titan.graphdb.types.InternalTitanType;
import com.thinkaurelius.titan.graphdb.types.manager.TypeManager;
import com.thinkaurelius.titan.graphdb.types.system.SystemKey;
import com.thinkaurelius.titan.graphdb.types.system.SystemType;
import com.thinkaurelius.titan.graphdb.util.VertexCentricEdgeIterable;
import com.thinkaurelius.titan.graphdb.vertices.InternalTitanVertex;
import com.thinkaurelius.titan.graphdb.vertices.factory.VertexFactory;
import com.thinkaurelius.titan.util.datastructures.Factory;
import com.thinkaurelius.titan.util.datastructures.IterablesUtil;
import com.thinkaurelius.titan.util.datastructures.Maps;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.util.PropertyFilteredIterable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public abstract class AbstractTitanTx extends TitanBlueprintsTransaction implements InternalTitanTransaction {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(AbstractTitanTx.class);
protected InternalTitanGraph graphdb;
protected final TypeManager etManager;
protected final VertexFactory vertexFactory;
protected final RelationFactory edgeFactory;
private final ConcurrentMap<TitanKey, ConcurrentMap<Object, TitanVertex>> keyIndex;
private final Lock keyedPropertyCreateLock;
private final ConcurrentMap<TitanKey, Multimap<Object, TitanVertex>> attributeIndex;
private final Optional<Set<InternalTitanVertex>> newVertices;
private VertexCache vertexCache;
private boolean isOpen;
private final TransactionConfig config;
public AbstractTitanTx(InternalTitanGraph g, VertexFactory vertexFac, RelationFactory edgeFac,
TypeManager etManage, TransactionConfig config) {
graphdb = g;
etManager = etManage;
vertexFactory = vertexFac;
edgeFactory = edgeFac;
edgeFactory.setTransaction(this);
this.config = config;
isOpen = true;
if (!config.isReadOnly() && config.hasMaintainNewVertices()) {
newVertices = Optional.of(Collections.newSetFromMap(new ConcurrentHashMap<InternalTitanVertex, Boolean>(10,
0.75f, 2)));
} else {
newVertices = Optional.absent();
}
vertexCache = new StandardVertexCache();
keyIndex = new ConcurrentHashMap<TitanKey, ConcurrentMap<Object, TitanVertex>>(20, 0.75f, 2);
attributeIndex = new ConcurrentHashMap<TitanKey, Multimap<Object, TitanVertex>>(20, 0.75f, 2);
keyedPropertyCreateLock = new ReentrantLock();
}
protected final void verifyWriteAccess(TitanVertex... vertices) {
if (config.isReadOnly())
throw new UnsupportedOperationException("Cannot create new entities in read-only transaction");
verifyAccess(vertices);
}
@Override
public final void verifyAccess(TitanVertex... vertices) {
verifyOpen();
for (TitanVertex v : vertices) {
if (!(v instanceof SystemType) && !this.equals(((InternalTitanVertex) v).getTransaction()))
throw new IllegalArgumentException("The vertex or type is not associated with this transaction [" + v + "]");
if (!v.isAvailable())
throw new IllegalArgumentException("The vertex or type is now longer available [" + v + "]");
}
}
private final void verifyOpen() {
if (isClosed())
throw TitanException.transactionNotOpenException();
}
/*
* ------------------------------------ TitanVertex and TitanRelation creation ------------------------------------
*/
@Override
public void registerNewEntity(InternalTitanVertex n) {
assert (!(n instanceof InternalRelation) || !((InternalRelation) n).isInline());
assert n.isNew();
assert !n.hasID();
boolean isNode = !(n instanceof InternalRelation);
if (config.hasAssignIDsImmediately()) {
graphdb.assignID(n);
if (isNode)
vertexCache.add(n, n.getID());
}
if (isNode && newVertices.isPresent()) {
newVertices.get().add(n);
}
}
@Override
public TitanVertex addVertex() {
verifyWriteAccess();
InternalTitanVertex n = vertexFactory.createNew(this);
return n;
}
@Override
public boolean containsVertex(long id) {
verifyOpen();
if (vertexCache.contains(id) && !vertexCache.get(id).isRemoved())
return true;
else
return false;
}
@Override
public TitanVertex getVertex(long id) {
verifyOpen();
if (getTxConfiguration().hasVerifyNodeExistence() && !containsVertex(id))
return null;
return getExistingVertex(id);
}
@Override
public InternalTitanVertex getExistingVertex(long id) {
return getExisting(id);
}
private InternalTitanVertex getExisting(long id) {
synchronized (vertexCache) {
InternalTitanVertex vertex = vertexCache.get(id);
if (vertex == null) {
IDInspector idspec = graphdb.getIDInspector();
if (idspec.isEdgeTypeID(id)) {
vertex = etManager.getType(id, this);
} else if (graphdb.isReferenceVertexID(id)) {
throw new UnsupportedOperationException("Reference vertices are currently not supported");
} else if (idspec.isNodeID(id)) {
vertex = vertexFactory.createExisting(this, id);
} else
throw new IllegalArgumentException("ID could not be recognized");
vertexCache.add(vertex, id);
} else if (vertex.isRemoved()) throw new IllegalArgumentException("Vertex has been removed for id: " + id);
return vertex;
}
}
public boolean isDeletedVertex(long id) {
InternalTitanVertex vertex = vertexCache.get(id);
return vertex!=null && vertex.isRemoved();
}
@Override
public void deleteVertex(InternalTitanVertex n) {
verifyWriteAccess(n);
if (n.hasID()) {
assert vertexCache.contains(n.getID());
}
if (n.isNew() && newVertices.isPresent()) {
assert newVertices.get().contains(n);
newVertices.get().remove(n);
}
}
@Override
public TitanProperty addProperty(TitanVertex vertex, TitanKey key, Object attribute) {
verifyWriteAccess(vertex, key);
// Check that attribute of keyed propertyType is unique and lock if so
final boolean isUniqueKey = key.isUnique() && !(vertex instanceof TitanRelation);
if (isUniqueKey)
keyedPropertyCreateLock.lock();
InternalRelation e = null;
try {
if (isUniqueKey && config.hasVerifyKeyUniqueness() && getVertex(key, attribute) != null) {
throw new InvalidElementException(
"The specified attribute is already used for the given property key: " + attribute, vertex);
}
e = edgeFactory.createNewProperty(key, (InternalTitanVertex) vertex, attribute);
addedRelation(e);
} finally {
if (isUniqueKey)
keyedPropertyCreateLock.unlock();
}
Preconditions.checkNotNull(e);
return (TitanProperty) e;
}
@Override
public TitanProperty addProperty(TitanVertex vertex, String key, Object attribute) {
return addProperty(vertex, getPropertyKey(key), attribute);
}
@Override
public TitanEdge addEdge(TitanVertex outVertex, TitanVertex inVertex, TitanLabel label) {
verifyWriteAccess(outVertex, inVertex, label);
InternalRelation e = edgeFactory.createNewRelationship(label, (InternalTitanVertex) outVertex, (InternalTitanVertex) inVertex);
addedRelation(e);
return (TitanEdge) e;
}
@Override
public TitanEdge addEdge(TitanVertex outVertex, TitanVertex inVertex, String label) {
return addEdge(outVertex, inVertex, getEdgeLabel(label));
}
@Override
public TypeMaker makeType() {
verifyWriteAccess();
return etManager.getTypeMaker(this);
}
@Override
public boolean containsType(String name) {
verifyOpen();
if (keyIndex.containsKey(SystemKey.TypeName) && keyIndex.get(SystemKey.TypeName).containsKey(name)) {
return true;
} else {
return etManager.containsType(name, this);
}
}
@Override
public TitanType getType(String name) {
verifyOpen();
TitanType et = null;
if (keyIndex.containsKey(SystemKey.TypeName)) {
Map<Object, TitanVertex> subindex = keyIndex.get(SystemKey.TypeName);
et = (TitanType) subindex.get(name);
}
if (et == null) {
// Second, check TypeManager
InternalTitanType eti = etManager.getType(name, this);
if (eti != null)
vertexCache.add(eti, eti.getID());
et = eti;
}
return et;
}
@Override
public TitanKey getPropertyKey(String name) {
TitanType et = getType(name);
if (et == null) {
return config.getAutoEdgeTypeMaker().makeKey(name, makeType());
} else if (et.isPropertyKey()) {
return (TitanKey) et;
} else
throw new IllegalArgumentException("The type of given name is not a key: " + name);
}
@Override
public TitanLabel getEdgeLabel(String name) {
TitanType et = getType(name);
if (et == null) {
return config.getAutoEdgeTypeMaker().makeLabel(name, makeType());
} else if (et.isEdgeLabel()) {
return (TitanLabel) et;
} else
throw new IllegalArgumentException("The type of given name is not a label: " + name);
}
@Override
public void addedRelation(InternalRelation relation) {
verifyWriteAccess();
Preconditions.checkArgument(relation.isNew());
}
@Override
public void deletedRelation(InternalRelation relation) {
verifyWriteAccess();
if (relation.isProperty() && !relation.isRemoved() && !relation.isInline()) {
TitanProperty prop = (TitanProperty) relation;
if (prop.getPropertyKey().hasIndex()) {
removeKeyFromIndex(prop);
}
}
}
@Override
public TitanQuery query(InternalTitanVertex n) {
return new SimpleTitanQuery(n);
}
@Override
public TitanQuery query(long nodeid) {
return new SimpleTitanQuery((InternalTitanVertex) getVertex(nodeid));
}
@Override
public Iterable<Vertex> getVertices() {
if (newVertices.isPresent())
return (Iterable) Iterables.filter(newVertices.get(), new Predicate<InternalTitanVertex>() {
@Override
public boolean apply(@Nullable InternalTitanVertex internalTitanVertex) {
return !(internalTitanVertex instanceof TitanType);
}
});
else
return IterablesUtil.emptyIterable();
}
@Override
public Iterable<Edge> getEdges() {
return new VertexCentricEdgeIterable(getVertices());
}
@Override
public void loadedRelation(InternalRelation relation) {
if (relation.isProperty() && !relation.isInline()) {
TitanProperty prop = (TitanProperty) relation;
if (prop.getPropertyKey().hasIndex()) {
addProperty2Index(prop);
}
}
}
/*
* ----------------------------------------------- Index Handling ----------------------------------------------
*/
private void addProperty2Index(TitanProperty property) {
addProperty2Index(property.getPropertyKey(), property.getAttribute(), property.getVertex());
}
private static Factory<ConcurrentMap<Object, TitanVertex>> keyIndexFactory = new Factory<ConcurrentMap<Object, TitanVertex>>() {
@Override
public ConcurrentMap<Object, TitanVertex> create() {
return new ConcurrentHashMap<Object, TitanVertex>(10, 0.75f, 4);
}
};
private static Factory<Multimap<Object, TitanVertex>> attributeIndexFactory = new Factory<Multimap<Object, TitanVertex>>() {
@Override
public Multimap<Object, TitanVertex> create() {
Multimap<Object, TitanVertex> map = ArrayListMultimap.create(10, 20);
return map;
// return Multimaps.synchronizedSetMultimap(map);
}
};
protected void addProperty2Index(TitanKey key, Object att, TitanVertex vertex) {
Preconditions.checkArgument(key.hasIndex());
if (key.isUnique()) {
// TODO ignore NO-ENTRTY
ConcurrentMap<Object, TitanVertex> subindex = Maps.putIfAbsent(keyIndex, key, keyIndexFactory);
TitanVertex oth = subindex.putIfAbsent(att, vertex);
if (oth != null && !oth.equals(vertex)) {
throw new IllegalArgumentException("The value is already used by another vertex and the key is unique");
}
} else {
Multimap<Object, TitanVertex> subindex = Maps.putIfAbsent(attributeIndex, key, attributeIndexFactory);
subindex.put(att, vertex);
}
}
private void removeKeyFromIndex(TitanProperty property) {
Preconditions.checkArgument(property.getPropertyKey().hasIndex());
TitanKey type = property.getPropertyKey();
if (type.isUnique()) {
Map<Object, TitanVertex> subindex = keyIndex.get(type);
Preconditions.checkNotNull(subindex);
TitanVertex n = subindex.remove(property.getAttribute());
assert n != null && n.equals(property.getVertex());
// TODO Set to NO-ENTRY node object
} else {
boolean hasIdenticalProperty = false;
for (TitanProperty p2 : property.getVertex().getProperties(type)) {
if (!p2.equals(property) && p2.getAttribute().equals(property.getAttribute())) {
hasIdenticalProperty = true;
break;
}
}
if (!hasIdenticalProperty) {
Multimap<Object, TitanVertex> subindex = attributeIndex.get(type);
Preconditions.checkNotNull(subindex);
boolean removed = subindex.remove(property.getAttribute(), property.getVertex());
assert removed;
}
}
}
// #### Keyed Properties #####
@Override
public TitanVertex getVertex(TitanKey key, Object value) {
verifyAccess(key);
Preconditions.checkNotNull(key);
Preconditions.checkArgument(key.isUnique(), "Key is not declared unique");
value = AttributeUtil.prepareAttribute(value, key.getDataType());
if (!keyIndex.containsKey(key)) {
return null;
} else {
// TODO: check for NO-ENTRY and return null
Map<Object, TitanVertex> subindex = keyIndex.get(key);
return subindex.get(value);
}
}
@Override
public TitanVertex getVertex(String type, Object value) {
if (!containsType(type))
return null;
return getVertex(getPropertyKey(type), value);
}
// #### General Indexed Properties #####
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Iterable<Vertex> getVertices(String key, Object attribute) {
Preconditions.checkNotNull(key);
if (!containsType(key))
return ImmutableSet.of();
TitanKey tkey = getPropertyKey(key);
return (Iterable) getVertices(tkey, attribute);
// return new PropertyFilteredIterable<Vertex>(key,attribute,getVertices());
}
@Override
public Iterable<TitanVertex> getVertices(final TitanKey key, Object attribute) {
verifyAccess(key);
Preconditions.checkNotNull(key);
- attribute = AttributeUtil.prepareAttribute(attribute, key.getDataType());
- if (key.hasIndex()) {
+ if (attribute!=null) attribute = AttributeUtil.prepareAttribute(attribute, key.getDataType());
+ if (key.hasIndex() && attribute!=null) {
// First, get stuff from disk
long[] nodeids = getVertexIDsFromDisk(key, attribute);
Set<TitanVertex> vertices = new HashSet<TitanVertex>(nodeids.length);
for (int i = 0; i < nodeids.length; i++) {
if (!isDeletedVertex(nodeids[i])) {
vertices.add(getExistingVertex(nodeids[i]));
}
}
// Next, the in-memory stuff
Multimap<Object, TitanVertex> attrSubindex = attributeIndex.get(key);
if (attrSubindex != null) {
vertices.addAll(attrSubindex.get(attribute));
}
Map<Object, TitanVertex> keySubindex = keyIndex.get(key);
if (keySubindex != null) {
TitanVertex vertex = keySubindex.get(attribute);
if (vertex != null) {
vertices.add(vertex);
}
}
return vertices;
} else {
log.warn("getVertices is invoked with a non-indexed key [" + key.getName() + "] which requires a full database scan. Create key-indexes for better performance.");
return Iterables.filter(new PropertyFilteredIterable<Vertex>(key.getName(), attribute, this.getVertices()), TitanVertex.class);
}
}
/*
* --------------------------------------------- Transaction Handling ---------------------------------------------
*/
private void close() {
vertexCache.close();
keyIndex.clear();
isOpen = false;
}
@Override
public synchronized void commit() {
close();
}
@Override
public synchronized void rollback() {
close();
}
@Override
public boolean isOpen() {
return isOpen;
}
@Override
public boolean isClosed() {
return !isOpen;
}
@Override
public TransactionConfig getTxConfiguration() {
return config;
}
}
| true | true | public Iterable<TitanVertex> getVertices(final TitanKey key, Object attribute) {
verifyAccess(key);
Preconditions.checkNotNull(key);
attribute = AttributeUtil.prepareAttribute(attribute, key.getDataType());
if (key.hasIndex()) {
// First, get stuff from disk
long[] nodeids = getVertexIDsFromDisk(key, attribute);
Set<TitanVertex> vertices = new HashSet<TitanVertex>(nodeids.length);
for (int i = 0; i < nodeids.length; i++) {
if (!isDeletedVertex(nodeids[i])) {
vertices.add(getExistingVertex(nodeids[i]));
}
}
// Next, the in-memory stuff
Multimap<Object, TitanVertex> attrSubindex = attributeIndex.get(key);
if (attrSubindex != null) {
vertices.addAll(attrSubindex.get(attribute));
}
Map<Object, TitanVertex> keySubindex = keyIndex.get(key);
if (keySubindex != null) {
TitanVertex vertex = keySubindex.get(attribute);
if (vertex != null) {
vertices.add(vertex);
}
}
return vertices;
} else {
log.warn("getVertices is invoked with a non-indexed key [" + key.getName() + "] which requires a full database scan. Create key-indexes for better performance.");
return Iterables.filter(new PropertyFilteredIterable<Vertex>(key.getName(), attribute, this.getVertices()), TitanVertex.class);
}
}
| public Iterable<TitanVertex> getVertices(final TitanKey key, Object attribute) {
verifyAccess(key);
Preconditions.checkNotNull(key);
if (attribute!=null) attribute = AttributeUtil.prepareAttribute(attribute, key.getDataType());
if (key.hasIndex() && attribute!=null) {
// First, get stuff from disk
long[] nodeids = getVertexIDsFromDisk(key, attribute);
Set<TitanVertex> vertices = new HashSet<TitanVertex>(nodeids.length);
for (int i = 0; i < nodeids.length; i++) {
if (!isDeletedVertex(nodeids[i])) {
vertices.add(getExistingVertex(nodeids[i]));
}
}
// Next, the in-memory stuff
Multimap<Object, TitanVertex> attrSubindex = attributeIndex.get(key);
if (attrSubindex != null) {
vertices.addAll(attrSubindex.get(attribute));
}
Map<Object, TitanVertex> keySubindex = keyIndex.get(key);
if (keySubindex != null) {
TitanVertex vertex = keySubindex.get(attribute);
if (vertex != null) {
vertices.add(vertex);
}
}
return vertices;
} else {
log.warn("getVertices is invoked with a non-indexed key [" + key.getName() + "] which requires a full database scan. Create key-indexes for better performance.");
return Iterables.filter(new PropertyFilteredIterable<Vertex>(key.getName(), attribute, this.getVertices()), TitanVertex.class);
}
}
|
diff --git a/src/main/java/org/agilewiki/jasocket/jid/agent/EvalAgent.java b/src/main/java/org/agilewiki/jasocket/jid/agent/EvalAgent.java
index 601745c..252eeed 100644
--- a/src/main/java/org/agilewiki/jasocket/jid/agent/EvalAgent.java
+++ b/src/main/java/org/agilewiki/jasocket/jid/agent/EvalAgent.java
@@ -1,61 +1,61 @@
/*
* Copyright 2012 Bill La Forge
*
* This file is part of AgileWiki and is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License (LGPL) as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
* 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
* or navigate to the following url http://www.gnu.org/licenses/lgpl-2.1.txt
*
* Note however that only Scala, Java and JavaScript files are being covered by LGPL.
* All other files are covered by the Common Public License (CPL).
* A copy of this license is also included and can be
* found as well at http://www.opensource.org/licenses/cpl1.0.txt
*/
package org.agilewiki.jasocket.jid.agent;
import org.agilewiki.jactor.RP;
import org.agilewiki.jactor.factory.JAFactory;
import org.agilewiki.jasocket.commands.Command;
import org.agilewiki.jasocket.commands.CommandAgent;
import org.agilewiki.jasocket.commands.CommandStringAgent;
import org.slf4j.LoggerFactory;
public class EvalAgent extends CommandStringAgent {
@Override
protected void process(RP rp) throws Exception {
if (!isLocal()) {
LoggerFactory.getLogger(EvalAgent.class).
- info("from " + agentChannel().remoteAddress + ">" + getArgString() + "\n>");
+ info("from " + agentChannel().remoteAddress + ">" + getArgString());
}
String in = getArgString().trim();
int i = in.indexOf(' ');
String rem = "";
if (i > -1) {
rem = in.substring(i + 1);
in = in.substring(0, i);
}
rem = rem.trim();
Command cmd = getCommand(in);
if (cmd == null) {
println("No such command: " + in + ". (Use the help command for a list of commands.)");
rp.processResponse(out);
return;
}
String type = cmd.type();
CommandAgent agent = (CommandAgent)
JAFactory.newActor(this, type, getMailboxFactory().createAsyncMailbox(), agentChannelManager());
agent.setArgString(rem);
StartAgent.req.send(this, agent, rp);
}
}
| true | true | protected void process(RP rp) throws Exception {
if (!isLocal()) {
LoggerFactory.getLogger(EvalAgent.class).
info("from " + agentChannel().remoteAddress + ">" + getArgString() + "\n>");
}
String in = getArgString().trim();
int i = in.indexOf(' ');
String rem = "";
if (i > -1) {
rem = in.substring(i + 1);
in = in.substring(0, i);
}
rem = rem.trim();
Command cmd = getCommand(in);
if (cmd == null) {
println("No such command: " + in + ". (Use the help command for a list of commands.)");
rp.processResponse(out);
return;
}
String type = cmd.type();
CommandAgent agent = (CommandAgent)
JAFactory.newActor(this, type, getMailboxFactory().createAsyncMailbox(), agentChannelManager());
agent.setArgString(rem);
StartAgent.req.send(this, agent, rp);
}
| protected void process(RP rp) throws Exception {
if (!isLocal()) {
LoggerFactory.getLogger(EvalAgent.class).
info("from " + agentChannel().remoteAddress + ">" + getArgString());
}
String in = getArgString().trim();
int i = in.indexOf(' ');
String rem = "";
if (i > -1) {
rem = in.substring(i + 1);
in = in.substring(0, i);
}
rem = rem.trim();
Command cmd = getCommand(in);
if (cmd == null) {
println("No such command: " + in + ". (Use the help command for a list of commands.)");
rp.processResponse(out);
return;
}
String type = cmd.type();
CommandAgent agent = (CommandAgent)
JAFactory.newActor(this, type, getMailboxFactory().createAsyncMailbox(), agentChannelManager());
agent.setArgString(rem);
StartAgent.req.send(this, agent, rp);
}
|
diff --git a/src/chvck/colourMate/activities/CompareColours.java b/src/chvck/colourMate/activities/CompareColours.java
index cfa1179..a658caa 100644
--- a/src/chvck/colourMate/activities/CompareColours.java
+++ b/src/chvck/colourMate/activities/CompareColours.java
@@ -1,60 +1,65 @@
package chvck.colourMate.activities;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import chvck.colourMate.R;
public class CompareColours extends ColourActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.compare);
ImageView origColourView = (ImageView) findViewById(R.id.originalColourView);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll_compare);
Bundle extras = getIntent().getExtras();
int[] newColours = extras.getIntArray("colours");
final int origColour = extras.getInt("origColour");
- setViewColour(origColourView, origColour);
+ setViewColour(origColourView, origColour);
+ origColourView.setOnClickListener(new OnClickListener() {
+ public void onClick(View v) {
+ use(origColour);
+ }
+ });
//ll.addView(origColourView);
for (final int newColour : newColours) {
ImageView imageView = new ImageView(this);
setViewColour(imageView, newColour);
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
use(newColour);
}
});
ll.addView(imageView);
}
}
private void setViewColour(ImageView view, int colour) {
view.setBackgroundColor(colour);
Drawable backgroundRes = view.getBackground();
Drawable drawableRes = this.getResources().getDrawable(R.drawable.white_background);
Drawable[] drawableLayers = { backgroundRes, drawableRes };
LayerDrawable ld = new LayerDrawable(drawableLayers);
view.setBackgroundDrawable(ld);
}
private void use(int colour) {
Intent intent = new Intent();
intent.setClass(this, chvck.colourMate.activities.SelectedColour.class);
intent.putExtra("colour", colour);
startActivityForResult(intent, 0);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.compare);
ImageView origColourView = (ImageView) findViewById(R.id.originalColourView);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll_compare);
Bundle extras = getIntent().getExtras();
int[] newColours = extras.getIntArray("colours");
final int origColour = extras.getInt("origColour");
setViewColour(origColourView, origColour);
//ll.addView(origColourView);
for (final int newColour : newColours) {
ImageView imageView = new ImageView(this);
setViewColour(imageView, newColour);
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
use(newColour);
}
});
ll.addView(imageView);
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.compare);
ImageView origColourView = (ImageView) findViewById(R.id.originalColourView);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll_compare);
Bundle extras = getIntent().getExtras();
int[] newColours = extras.getIntArray("colours");
final int origColour = extras.getInt("origColour");
setViewColour(origColourView, origColour);
origColourView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
use(origColour);
}
});
//ll.addView(origColourView);
for (final int newColour : newColours) {
ImageView imageView = new ImageView(this);
setViewColour(imageView, newColour);
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
use(newColour);
}
});
ll.addView(imageView);
}
}
|
diff --git a/src/com/dmdirc/updater/Update.java b/src/com/dmdirc/updater/Update.java
index 441f7865a..bade7d0d1 100644
--- a/src/com/dmdirc/updater/Update.java
+++ b/src/com/dmdirc/updater/Update.java
@@ -1,222 +1,226 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.updater;
import com.dmdirc.Main;
import com.dmdirc.interfaces.UpdateListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.util.DownloadListener;
import com.dmdirc.util.Downloader;
import com.dmdirc.util.WeakList;
import java.io.IOException;
import java.util.List;
/**
* Represents a single available update for some component.
*
* @author chris
*/
public final class Update implements DownloadListener {
/** Update component. */
private final UpdateComponent component;
/** Remote version name. */
private final String versionName;
/** Update url. */
private final String url;
/** The progress of the current stage. */
private float progress;
/** A list of registered update listeners. */
private final List<UpdateListener> listeners
= new WeakList<UpdateListener>();
/** Our current status. */
private UpdateStatus status = UpdateStatus.PENDING;
/**
* Creates a new instance of Update, with details from the specified line.
*
* @param updateInfo An update information line from the update server
*/
public Update(final String updateInfo) {
// outofdate client STABLE 20071007 0.5.1 file
final String[] parts = updateInfo.split(" ");
if (parts.length == 6) {
component = UpdateChecker.findComponent(parts[1]);
versionName = parts[4];
url = parts[5];
} else {
component = null;
versionName = null;
url = null;
Logger.appError(ErrorLevel.LOW,
"Invalid update line received from server: ",
new UnsupportedOperationException("line: " + updateInfo));
}
}
/**
* Retrieves the component that this update is for.
*
* @return The component of this update
*/
public UpdateComponent getComponent() {
return component;
}
/**
* Returns the remote version of the component that's available.
*
* @return The remote version number
*/
public String getRemoteVersion() {
return versionName;
}
/**
* Returns the URL where the new update may be downloaded.
*
* @return The URL of the update
*/
public String getUrl() {
return url;
}
/**
* Retrieves the status of this update.
*
* @return This update's status
*/
public UpdateStatus getStatus() {
return status;
}
/**
* Sets the status of this update, and notifies all listeners of the change.
*
* @param newStatus This update's new status
*/
protected void setStatus(final UpdateStatus newStatus) {
status = newStatus;
progress = 0;
for (UpdateListener listener : listeners) {
listener.updateStatusChange(this, status);
}
}
/**
* Removes the specified update listener.
*
* @param o The update listener to remove
*/
public void removeUpdateListener(final Object o) {
listeners.remove(o);
}
/**
* Adds the specified update listener.
*
* @param e The update listener to add
*/
public void addUpdateListener(final UpdateListener e) {
listeners.add(e);
}
/**
* Makes this update download and install itself.
*/
public void doUpdate() {
new Thread(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final String path = Main.getConfigDir() + "update.tmp."
+ Math.round(Math.random() * 1000);
setStatus(UpdateStatus.DOWNLOADING);
try {
Downloader.downloadPage(getUrl(), path, Update.this);
} catch (IOException ex) {
setStatus(UpdateStatus.ERROR);
Logger.userError(ErrorLevel.MEDIUM, "Error when updating component "
+ component.getName(), ex);
return;
}
setStatus(UpdateStatus.INSTALLING);
try {
final boolean restart = getComponent().doInstall(path);
if (restart) {
setStatus(UpdateStatus.RESTART_NEEDED);
UpdateChecker.removeComponent(getComponent().getName());
} else {
setStatus(UpdateStatus.INSTALLED);
}
+ } catch (IOException ex) {
+ setStatus(UpdateStatus.ERROR);
+ Logger.userError(ErrorLevel.MEDIUM,
+ "I/O error when updating component " + component.getName(), ex);
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
Logger.appError(ErrorLevel.MEDIUM,
"Error when updating component " + component.getName(), ex);
}
}
}, "Update thread").start();
}
/** {@inheritDoc} */
@Override
public void downloadProgress(final float percent) {
progress = percent;
for (UpdateListener listener : listeners) {
listener.updateProgressChange(this, percent);
}
}
/**
* Retrieves the current progress of the current state of this update.
*
* @return The percentage of the current stage that has been completed
*/
public float getProgress() {
return progress;
}
/** {@inheritDoc} */
@Override
public void setIndeterminate(boolean indeterminate) {
//TODO
}
}
| true | true | public void doUpdate() {
new Thread(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final String path = Main.getConfigDir() + "update.tmp."
+ Math.round(Math.random() * 1000);
setStatus(UpdateStatus.DOWNLOADING);
try {
Downloader.downloadPage(getUrl(), path, Update.this);
} catch (IOException ex) {
setStatus(UpdateStatus.ERROR);
Logger.userError(ErrorLevel.MEDIUM, "Error when updating component "
+ component.getName(), ex);
return;
}
setStatus(UpdateStatus.INSTALLING);
try {
final boolean restart = getComponent().doInstall(path);
if (restart) {
setStatus(UpdateStatus.RESTART_NEEDED);
UpdateChecker.removeComponent(getComponent().getName());
} else {
setStatus(UpdateStatus.INSTALLED);
}
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
Logger.appError(ErrorLevel.MEDIUM,
"Error when updating component " + component.getName(), ex);
}
}
}, "Update thread").start();
}
| public void doUpdate() {
new Thread(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final String path = Main.getConfigDir() + "update.tmp."
+ Math.round(Math.random() * 1000);
setStatus(UpdateStatus.DOWNLOADING);
try {
Downloader.downloadPage(getUrl(), path, Update.this);
} catch (IOException ex) {
setStatus(UpdateStatus.ERROR);
Logger.userError(ErrorLevel.MEDIUM, "Error when updating component "
+ component.getName(), ex);
return;
}
setStatus(UpdateStatus.INSTALLING);
try {
final boolean restart = getComponent().doInstall(path);
if (restart) {
setStatus(UpdateStatus.RESTART_NEEDED);
UpdateChecker.removeComponent(getComponent().getName());
} else {
setStatus(UpdateStatus.INSTALLED);
}
} catch (IOException ex) {
setStatus(UpdateStatus.ERROR);
Logger.userError(ErrorLevel.MEDIUM,
"I/O error when updating component " + component.getName(), ex);
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
Logger.appError(ErrorLevel.MEDIUM,
"Error when updating component " + component.getName(), ex);
}
}
}, "Update thread").start();
}
|
diff --git a/src/api/org/openmrs/module/ModuleUtil.java b/src/api/org/openmrs/module/ModuleUtil.java
index 54ac5b86..978c4807 100644
--- a/src/api/org/openmrs/module/ModuleUtil.java
+++ b/src/api/org/openmrs/module/ModuleUtil.java
@@ -1,567 +1,565 @@
/**
* 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.module;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.AdministrationService;
import org.openmrs.api.context.Context;
import org.openmrs.api.context.ServiceContext;
import org.openmrs.util.OpenmrsClassLoader;
import org.openmrs.util.OpenmrsUtil;
import org.springframework.context.support.AbstractRefreshableApplicationContext;
/**
* Utility methods for working and manipulating modules
*/
public class ModuleUtil {
private static Log log = LogFactory.getLog(ModuleUtil.class);
/**
* Start up the module system with the given properties.
*
* @param props Properties (OpenMRS runtime properties)
*/
public static void startup(Properties props) {
String moduleListString = props.getProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD);
if (moduleListString == null || moduleListString.length() == 0) {
// Attempt to get all of the modules from the modules folder
// and store them in the modules list
log.debug("Starting all modules");
ModuleFactory.loadModules();
}
else {
// use the list of modules and load only those
log.debug("Starting all modules in this list: " + moduleListString);
String[] moduleArray = moduleListString.split(" ");
List<File> modulesToLoad = new Vector<File>();
for (String modulePath : moduleArray) {
if (modulePath != null && modulePath.length() > 0) {
File file = new File(modulePath);
if (file.exists())
modulesToLoad.add(file);
else {
// try to load the file from the classpath
InputStream stream = ModuleUtil.class.getClassLoader().getResourceAsStream(modulePath);
// expand the classpath-found file to a temporary location
if (stream != null) {
try {
// get and make a temp directory if necessary
String tmpDir = System.getProperty("java.io.tmpdir");
- File tmpDirFile = new File(tmpDir, "openmrs-mod-startup");
- tmpDirFile.mkdirs();
+ File expandedFile = File.createTempFile(file.getName() + "-", ".omod", new File(tmpDir));
// pull the name from the absolute path load attempt
- File expandedFile = new File(tmpDirFile, file.getName());
FileOutputStream outStream = new FileOutputStream(expandedFile, false);
// do the actual file copying
OpenmrsUtil.copyFile(stream, outStream);
// add the freshly expanded file to the list of modules we're going to start up
modulesToLoad.add(expandedFile);
expandedFile.deleteOnExit();
}
catch (IOException io) {
log.error("Unable to expand classpath found module: " + modulePath, io);
}
}
else
log.error("Unable to load module at path: " + modulePath + " because no file exists there and it is not found on the classpath. (absolute path tried: " + file.getAbsolutePath() + ")");
}
}
}
ModuleFactory.loadModules(modulesToLoad);
}
// start all of the modules we just loaded
ModuleFactory.startModules();
if (log.isDebugEnabled()) {
Collection<Module> modules = ModuleFactory.getStartedModules();
if (modules == null || modules.size() == 0)
log.debug("No modules loaded");
else
log.debug("Found and loaded " + modules.size() + " module(s)");
}
}
/**
* Stops the module system by calling stopModule for all
* modules that are currently started
*/
public static void shutdown() {
List<Module> modules = new Vector<Module>();
modules.addAll(ModuleFactory.getStartedModules());
for (Module mod : modules) {
if (log.isDebugEnabled())
log.debug("stopping module: " + mod.getModuleId());
if (mod.isStarted())
ModuleFactory.stopModule(mod, true);
}
log.debug("done shutting down modules");
}
/**
* Add the <code>inputStream</code> as a file in the modules repository
*
* @param stream InputStream to load
* @return filename String of the file's name of the stream
*/
public static File insertModuleFile(InputStream inputStream, String filename) {
File folder = getModuleRepository();
// check if module filename is already loaded
if (OpenmrsUtil.folderContains(folder, filename))
throw new ModuleException(filename
+ " is already associated with a loaded module.");
File file = new File(folder.getAbsolutePath() + File.separator
+ filename);
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
OpenmrsUtil.copyFile(inputStream, outputStream);
} catch (FileNotFoundException e) {
throw new ModuleException("Can't create module file for "
+ filename, e);
} catch (IOException e) {
throw new ModuleException("Can't create module file for "
+ filename, e);
}
finally {
try { inputStream.close(); } catch (Exception e) { /* pass */ }
try { outputStream.close();} catch (Exception e) { /* pass */ }
}
return file;
}
/**
* Compares <code>version</code> to <code>value</code>
* version and value are strings like w.x.y.z
*
* Returns <code>0</code> if either <code>version</code> or
* <code>value</code> is null.
*
* @param version String like w.x.y.z
* @param value String like w.x.y.z
* @return the value <code>0</code> if <code>version</code> is
* equal to the argument <code>value</code>; a value less than
* <code>0</code> if <code>version</code> is numerically less
* than the argument <code>value</code>; and a value greater
* than <code>0</code> if <code>version</code> is numerically
* greater than the argument <code>value</code>
*/
public static int compareVersion(String version, String value) {
try {
if (version == null || value == null)
return 0;
List<String> versions = new Vector<String>();
List<String> values = new Vector<String>();
Collections.addAll(versions, version.split("\\."));
Collections.addAll(values, value.split("\\."));
// match the sizes of the lists
while (versions.size() < values.size()) {
versions.add("0");
}
while (values.size() < versions.size()) {
values.add("0");
}
for (int x = 0; x < versions.size(); x++) {
String verNum = versions.get(x).trim();
String valNum = values.get(x).trim();
Integer ver = new Integer(verNum == "" ? "0" : verNum);
Integer val = new Integer(valNum == "" ? "0" : valNum);
int ret = ver.compareTo(val);
if (ret != 0)
return ret;
}
} catch (NumberFormatException e) {
log.error("Error while converting a version/value to an integer: " + version + "/" + value, e);
}
// default return value if an error occurs or elements are equal
return 0;
}
/**
* Gets the folder where modules are stored. ModuleExceptions are thrown on
* errors
*
* @return folder containing modules
*/
public static File getModuleRepository() {
AdministrationService as = Context.getAdministrationService();
String folderName = as.getGlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT);
// try to load the repository folder straight away.
File folder = new File(folderName);
// if the property wasn't a full path already, assume it was intended to be a folder in the
// application directory
if (!folder.exists()) {
folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName);
}
// now create the modules folder if it doesn't exist
if (!folder.exists()) {
log.warn("Module repository " + folder.getAbsolutePath() + " doesn't exist. Creating directories now.");
folder.mkdirs();
}
if (!folder.isDirectory())
throw new ModuleException("Module repository is not a directory at: "
+ folder.getAbsolutePath());
return folder;
}
/**
* Utility method to convert a {@link File} object to a local URL.
*
* @param file
* a file object
* @return absolute URL that points to the given file
* @throws MalformedURLException
* if file can't be represented as URL for some reason
*/
public static URL file2url(final File file) throws MalformedURLException {
if (file == null)
return null;
try {
return file.getCanonicalFile().toURI().toURL();
} catch (MalformedURLException mue) {
throw mue;
} catch (IOException ioe) {
throw new MalformedURLException("Cannot convert: " + file.getName()
+ " to url");
} catch (NoSuchMethodError nsme) {
throw new MalformedURLException("Cannot convert: " + file.getName()
+ " to url");
}
}
/**
* Expand the given <code>fileToExpand</code> jar to the
* <code>tmpModuleFile<code> directory
*
* If <code>name</code> is null, the entire jar is expanded.
* If<code>name</code> is not null, then only that path/file is expanded.
*
* @param fileToExpand file pointing at a .jar
* @param tmpModuleDir directory in which to place the files
* @param name filename inside of the jar to look for and expand
* @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir
* relating to <code>name</code>. if false will start directory structure at <code>name</code>
*/
@SuppressWarnings("unchecked")
public static void expandJar(File fileToExpand, File tmpModuleDir,
String name, boolean keepFullPath) throws IOException {
JarFile jarFile = null;
InputStream input = null;
String docBase = tmpModuleDir.getAbsolutePath();
try {
jarFile = new JarFile(fileToExpand);
Enumeration jarEntries = jarFile.entries();
boolean foundName = (name == null);
// loop over all of the elements looking for the match to 'name'
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
if (name == null || jarEntry.getName().startsWith(name)) {
String entryName = jarEntry.getName();
// trim out the name path from the name of the new file
if (keepFullPath == false && name != null)
entryName = entryName.replaceFirst(name, "");
// if it has a slash, it's in a directory
int last = entryName.lastIndexOf('/');
if (last >= 0) {
File parent = new File(docBase, entryName.substring(0,
last));
parent.mkdirs();
log.debug("Creating parent dirs: "
+ parent.getAbsolutePath());
}
// we don't want to "expand" directories or empty names
if (entryName.endsWith("/") || entryName.equals("")) {
continue;
}
input = jarFile.getInputStream(jarEntry);
expand(input, docBase, entryName);
input.close();
input = null;
foundName = true;
}
}
if (!foundName)
log.debug("Unable to find: " + name + " in file "
+ fileToExpand.getAbsolutePath());
} catch (IOException e) {
log.warn("Unable to delete tmpModuleFile on error", e);
throw e;
} finally {
try { input.close(); } catch (Exception e) { /* pass */ }
try { jarFile.close(); } catch (Exception e) { /* pass */ }
}
}
/**
* Expand the given file in the given stream to a location (fileDir/name)
*
* The <code>input</code> InputStream is not closed in this method
*
* @param input stream to read from
* @param fileDir directory to copy to
* @param name file/directory within the <code>fileDir</code> to which we expand <code>input</code>
*
* @return File the file created by the expansion.
*
* @throws IOException if an error occurred while copying
*/
private static File expand(InputStream input, String fileDir, String name)
throws IOException {
if (log.isDebugEnabled())
log.debug("expanding: " + name);
File file = new File(fileDir, name);
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
OpenmrsUtil.copyFile(input, outStream);
} finally {
try { outStream.close(); } catch (Exception e) { /* pass */ }
}
return file;
}
/**
* Downloads the contents of a URL and copies them to a string (Borrowed
* from oreilly)
*
* @param URL
* @return InputStream of contents
*/
public static InputStream getURLStream(URL url) {
InputStream in = null;
try {
URLConnection uc = url.openConnection();
uc.setDefaultUseCaches(false);
uc.setUseCaches(false);
uc.setRequestProperty("Cache-Control", "max-age=0,no-cache");
uc.setRequestProperty("Pragma", "no-cache");
// uc.setRequestProperty("Cache-Control","no-cache");
log.error("Logging an attempt to connect to: " + url);
in = uc.getInputStream();
} catch (IOException io) {
log.warn("io while reading: " + url, io);
}
return in;
}
/**
* Downloads the contents of a URL and copies them to a string (Borrowed
* from oreilly)
*
* @param URL
* @return String contents of the URL
*/
public static String getURL(URL url) {
InputStream in = null;
OutputStream out = null;
String output = "";
try {
in = getURLStream(url);
if (in == null) // skip this module if updateURL is not defined
return "";
out = new ByteArrayOutputStream();
OpenmrsUtil.copyFile(in, out);
output = out.toString();
} catch (IOException io) {
log.warn("io while reading: " + url, io);
} finally {
try { in.close(); } catch (Exception e) { /* pass */ }
try { out.close(); } catch (Exception e) { /* pass */ }
}
return output;
}
/**
* Iterates over the modules and checks each update.rdf file for an update
*
* @returns true/false whether an update was found for one of the modules
* @throws ModuleException
*/
public static Boolean checkForModuleUpdates() throws ModuleException {
Boolean updateFound = false;
for (Module mod : ModuleFactory.getLoadedModules()) {
String updateURL = mod.getUpdateURL();
if (updateURL != null && !updateURL.equals("")) {
try {
// get the contents pointed to by the url
URL url = new URL(updateURL);
if (!url.toString().endsWith(ModuleConstants.UPDATE_FILE_NAME)) {
log.warn("Illegal url: " + url);
continue;
}
String content = getURL(url);
// skip empty or invalid updates
if (content.equals(""))
continue;
// process and parse the contents
UpdateFileParser parser = new UpdateFileParser(content);
parser.parse();
log.debug("Update for mod: " + mod.getModuleId() + " compareVersion result: " + compareVersion(mod.getVersion(), parser.getCurrentVersion()));
// check the udpate.rdf version against the installed version
if (compareVersion(mod.getVersion(), parser.getCurrentVersion()) < 0) {
if (mod.getModuleId().equals(parser.getModuleId())) {
mod.setDownloadURL(parser.getDownloadURL());
mod.setUpdateVersion(parser.getCurrentVersion());
updateFound = true;
}
else
log.warn("Module id does not match in update.rdf:" + parser.getModuleId());
}
else {
mod.setDownloadURL(null);
mod.setUpdateVersion(null);
}
}
catch (ModuleException e) {
log.warn("Unable to get updates from update.xml", e);
}
catch (MalformedURLException e) {
log.warn("Unable to form a URL object out of: " + updateURL, e);
}
}
}
return updateFound;
}
/**
* @return true/false whether the 'allow upload' or 'allow web admin' property has been turned on
*/
public static Boolean allowAdmin() {
Properties properties = Context.getRuntimeProperties();
String prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_UPLOAD, null);
if (prop == null)
prop = properties.getProperty(ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN, "false");
return "true".equals(prop);
}
/**
* Refreshes the given application context "properly" in OpenMRS. Will first shut down
* the Context and destroy the classloader, then will refresh and set everything
* back up again
*
* @param ctx Spring application context that needs refreshing
* @return AbstractRefreshableApplicationContext the newly refreshed application context
*/
public static AbstractRefreshableApplicationContext refreshApplicationContext(AbstractRefreshableApplicationContext ctx) {
OpenmrsClassLoader.saveState();
ServiceContext.destroyInstance();
try {
ctx.stop();
ctx.close();
}
catch (Exception e) {
log.warn("Exception while stopping and closing context: ", e);
// Spring seems to be trying to refresh the context instead of /just/ stopping
// pass
}
OpenmrsClassLoader.destroyInstance();
ctx.setClassLoader(OpenmrsClassLoader.getInstance());
Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
ServiceContext.getInstance().startRefreshingContext();
try {
ctx.refresh();
}
finally {
ServiceContext.getInstance().doneRefreshingContext();
}
ctx.setClassLoader(OpenmrsClassLoader.getInstance());
Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
OpenmrsClassLoader.restoreState();
// reload the advice points that were lost when refreshing Spring
if (log.isDebugEnabled())
log.debug("Reloading advice for all started modules: " + ModuleFactory.getStartedModules().size());
for (Module module : ModuleFactory.getStartedModules()) {
ModuleFactory.loadAdvice(module);
}
return ctx;
}
}
| false | true | public static void startup(Properties props) {
String moduleListString = props.getProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD);
if (moduleListString == null || moduleListString.length() == 0) {
// Attempt to get all of the modules from the modules folder
// and store them in the modules list
log.debug("Starting all modules");
ModuleFactory.loadModules();
}
else {
// use the list of modules and load only those
log.debug("Starting all modules in this list: " + moduleListString);
String[] moduleArray = moduleListString.split(" ");
List<File> modulesToLoad = new Vector<File>();
for (String modulePath : moduleArray) {
if (modulePath != null && modulePath.length() > 0) {
File file = new File(modulePath);
if (file.exists())
modulesToLoad.add(file);
else {
// try to load the file from the classpath
InputStream stream = ModuleUtil.class.getClassLoader().getResourceAsStream(modulePath);
// expand the classpath-found file to a temporary location
if (stream != null) {
try {
// get and make a temp directory if necessary
String tmpDir = System.getProperty("java.io.tmpdir");
File tmpDirFile = new File(tmpDir, "openmrs-mod-startup");
tmpDirFile.mkdirs();
// pull the name from the absolute path load attempt
File expandedFile = new File(tmpDirFile, file.getName());
FileOutputStream outStream = new FileOutputStream(expandedFile, false);
// do the actual file copying
OpenmrsUtil.copyFile(stream, outStream);
// add the freshly expanded file to the list of modules we're going to start up
modulesToLoad.add(expandedFile);
expandedFile.deleteOnExit();
}
catch (IOException io) {
log.error("Unable to expand classpath found module: " + modulePath, io);
}
}
else
log.error("Unable to load module at path: " + modulePath + " because no file exists there and it is not found on the classpath. (absolute path tried: " + file.getAbsolutePath() + ")");
}
}
}
ModuleFactory.loadModules(modulesToLoad);
}
// start all of the modules we just loaded
ModuleFactory.startModules();
if (log.isDebugEnabled()) {
Collection<Module> modules = ModuleFactory.getStartedModules();
if (modules == null || modules.size() == 0)
log.debug("No modules loaded");
else
log.debug("Found and loaded " + modules.size() + " module(s)");
}
}
| public static void startup(Properties props) {
String moduleListString = props.getProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD);
if (moduleListString == null || moduleListString.length() == 0) {
// Attempt to get all of the modules from the modules folder
// and store them in the modules list
log.debug("Starting all modules");
ModuleFactory.loadModules();
}
else {
// use the list of modules and load only those
log.debug("Starting all modules in this list: " + moduleListString);
String[] moduleArray = moduleListString.split(" ");
List<File> modulesToLoad = new Vector<File>();
for (String modulePath : moduleArray) {
if (modulePath != null && modulePath.length() > 0) {
File file = new File(modulePath);
if (file.exists())
modulesToLoad.add(file);
else {
// try to load the file from the classpath
InputStream stream = ModuleUtil.class.getClassLoader().getResourceAsStream(modulePath);
// expand the classpath-found file to a temporary location
if (stream != null) {
try {
// get and make a temp directory if necessary
String tmpDir = System.getProperty("java.io.tmpdir");
File expandedFile = File.createTempFile(file.getName() + "-", ".omod", new File(tmpDir));
// pull the name from the absolute path load attempt
FileOutputStream outStream = new FileOutputStream(expandedFile, false);
// do the actual file copying
OpenmrsUtil.copyFile(stream, outStream);
// add the freshly expanded file to the list of modules we're going to start up
modulesToLoad.add(expandedFile);
expandedFile.deleteOnExit();
}
catch (IOException io) {
log.error("Unable to expand classpath found module: " + modulePath, io);
}
}
else
log.error("Unable to load module at path: " + modulePath + " because no file exists there and it is not found on the classpath. (absolute path tried: " + file.getAbsolutePath() + ")");
}
}
}
ModuleFactory.loadModules(modulesToLoad);
}
// start all of the modules we just loaded
ModuleFactory.startModules();
if (log.isDebugEnabled()) {
Collection<Module> modules = ModuleFactory.getStartedModules();
if (modules == null || modules.size() == 0)
log.debug("No modules loaded");
else
log.debug("Found and loaded " + modules.size() + " module(s)");
}
}
|
diff --git a/src/org/apache/xalan/templates/FuncFormatNumb.java b/src/org/apache/xalan/templates/FuncFormatNumb.java
index 4e2e6ce9..b1df0c9a 100644
--- a/src/org/apache/xalan/templates/FuncFormatNumb.java
+++ b/src/org/apache/xalan/templates/FuncFormatNumb.java
@@ -1,220 +1,220 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 "Xalan" 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, Lotus
* Development Corporation., http://www.lotus.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xalan.templates;
import java.util.Vector;
import org.apache.xml.utils.QName;
import org.apache.xpath.functions.Function;
import org.apache.xpath.functions.Function3Args;
import org.apache.xpath.XPathContext;
import org.apache.xpath.objects.XObject;
import org.apache.xpath.objects.XString;
import org.apache.xpath.XPath;
import org.apache.xpath.Expression;
import org.apache.xpath.functions.WrongNumberArgsException;
import org.apache.xalan.res.XSLMessages;
import org.apache.xalan.res.XSLTErrorResources;
import org.w3c.dom.Node;
import javax.xml.transform.TransformerException;
import javax.xml.transform.ErrorListener;
import org.apache.xml.utils.SAXSourceLocator;
/**
* <meta name="usage" content="advanced"/>
* Execute the FormatNumber() function.
*/
public class FuncFormatNumb extends Function3Args
{
/**
* Execute the function. The function must return
* a valid object.
* @param xctxt The current execution context.
* @return A valid XObject.
*
* @throws javax.xml.transform.TransformerException
*/
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
{
// A bit of an ugly hack to get our context.
ElemTemplateElement templElem =
(ElemTemplateElement) xctxt.getNamespaceContext();
StylesheetRoot ss = templElem.getStylesheetRoot();
java.text.DecimalFormat formatter = null;
java.text.DecimalFormatSymbols dfs = null;
double num = getArg0().execute(xctxt).num();
String patternStr = getArg1().execute(xctxt).str();
// TODO: what should be the behavior here??
if (patternStr.indexOf(0x00A4) > 0)
ss.error(XSLTErrorResources.ER_CURRENCY_SIGN_ILLEGAL); // currency sign not allowed
// this third argument is not a locale name. It is the name of a
// decimal-format declared in the stylesheet!(xsl:decimal-format
try
{
Expression arg2Expr = getArg2();
if (null != arg2Expr)
{
String dfName = arg2Expr.execute(xctxt).str();
QName qname = new QName(dfName, xctxt.getNamespaceContext());
dfs = ss.getDecimalFormatComposed(qname);
if (null == dfs)
{
warn(xctxt, XSLTErrorResources.WG_NO_DECIMALFORMAT_DECLARATION,
new Object[]{ dfName }); //"not found!!!
//formatter = new java.text.DecimalFormat(patternStr);
}
else
{
//formatter = new java.text.DecimalFormat(patternStr, dfs);
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
formatter.applyLocalizedPattern(patternStr);
}
}
//else
if (null == formatter)
{
// look for a possible default decimal-format
if (ss.getDecimalFormatCount() > 0)
dfs = ss.getDecimalFormatComposed(new QName(""));
if (dfs != null)
{
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
formatter.applyLocalizedPattern(patternStr);
}
else
{
- dfs = new java.text.DecimalFormatSymbols();
+ dfs = new java.text.DecimalFormatSymbols(java.util.Locale.US);
dfs.setInfinity(Constants.ATTRVAL_INFINITY);
dfs.setNaN(Constants.ATTRVAL_NAN);
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
if (null != patternStr)
formatter.applyLocalizedPattern(patternStr);
}
}
return new XString(formatter.format(num));
}
catch (Exception iae)
{
templElem.error(XSLTErrorResources.ER_MALFORMED_FORMAT_STRING,
new Object[]{ patternStr });
return XString.EMPTYSTRING;
//throw new XSLProcessorException(iae);
}
}
/**
* Warn the user of a problem.
*
* @param xctxt The XPath runtime state.
* @param msg Warning message code
* @param args Arguments to be used in warning message
* @throws XSLProcessorException thrown if the active ProblemListener and XPathContext decide
* the error condition is severe enough to halt processing.
*
* @throws javax.xml.transform.TransformerException
*/
public void warn(XPathContext xctxt, int msg, Object args[])
throws javax.xml.transform.TransformerException
{
String formattedMsg = XSLMessages.createWarning(msg, args);
ErrorListener errHandler = xctxt.getErrorListener();
errHandler.warning(new TransformerException(formattedMsg,
(SAXSourceLocator)xctxt.getSAXLocator()));
}
/**
* Overide the superclass method to allow one or two arguments.
*
*
* @param argNum Number of arguments passed in
*
* @throws WrongNumberArgsException
*/
public void checkNumberArgs(int argNum) throws WrongNumberArgsException
{
if ((argNum > 3) || (argNum < 2))
throw new WrongNumberArgsException(XSLMessages.createMessage(XSLTErrorResources.ER_TWO_OR_THREE, null)); //"2 or 3");
}
}
| true | true | public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
{
// A bit of an ugly hack to get our context.
ElemTemplateElement templElem =
(ElemTemplateElement) xctxt.getNamespaceContext();
StylesheetRoot ss = templElem.getStylesheetRoot();
java.text.DecimalFormat formatter = null;
java.text.DecimalFormatSymbols dfs = null;
double num = getArg0().execute(xctxt).num();
String patternStr = getArg1().execute(xctxt).str();
// TODO: what should be the behavior here??
if (patternStr.indexOf(0x00A4) > 0)
ss.error(XSLTErrorResources.ER_CURRENCY_SIGN_ILLEGAL); // currency sign not allowed
// this third argument is not a locale name. It is the name of a
// decimal-format declared in the stylesheet!(xsl:decimal-format
try
{
Expression arg2Expr = getArg2();
if (null != arg2Expr)
{
String dfName = arg2Expr.execute(xctxt).str();
QName qname = new QName(dfName, xctxt.getNamespaceContext());
dfs = ss.getDecimalFormatComposed(qname);
if (null == dfs)
{
warn(xctxt, XSLTErrorResources.WG_NO_DECIMALFORMAT_DECLARATION,
new Object[]{ dfName }); //"not found!!!
//formatter = new java.text.DecimalFormat(patternStr);
}
else
{
//formatter = new java.text.DecimalFormat(patternStr, dfs);
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
formatter.applyLocalizedPattern(patternStr);
}
}
//else
if (null == formatter)
{
// look for a possible default decimal-format
if (ss.getDecimalFormatCount() > 0)
dfs = ss.getDecimalFormatComposed(new QName(""));
if (dfs != null)
{
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
formatter.applyLocalizedPattern(patternStr);
}
else
{
dfs = new java.text.DecimalFormatSymbols();
dfs.setInfinity(Constants.ATTRVAL_INFINITY);
dfs.setNaN(Constants.ATTRVAL_NAN);
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
if (null != patternStr)
formatter.applyLocalizedPattern(patternStr);
}
}
return new XString(formatter.format(num));
}
catch (Exception iae)
{
templElem.error(XSLTErrorResources.ER_MALFORMED_FORMAT_STRING,
new Object[]{ patternStr });
return XString.EMPTYSTRING;
//throw new XSLProcessorException(iae);
}
}
| public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
{
// A bit of an ugly hack to get our context.
ElemTemplateElement templElem =
(ElemTemplateElement) xctxt.getNamespaceContext();
StylesheetRoot ss = templElem.getStylesheetRoot();
java.text.DecimalFormat formatter = null;
java.text.DecimalFormatSymbols dfs = null;
double num = getArg0().execute(xctxt).num();
String patternStr = getArg1().execute(xctxt).str();
// TODO: what should be the behavior here??
if (patternStr.indexOf(0x00A4) > 0)
ss.error(XSLTErrorResources.ER_CURRENCY_SIGN_ILLEGAL); // currency sign not allowed
// this third argument is not a locale name. It is the name of a
// decimal-format declared in the stylesheet!(xsl:decimal-format
try
{
Expression arg2Expr = getArg2();
if (null != arg2Expr)
{
String dfName = arg2Expr.execute(xctxt).str();
QName qname = new QName(dfName, xctxt.getNamespaceContext());
dfs = ss.getDecimalFormatComposed(qname);
if (null == dfs)
{
warn(xctxt, XSLTErrorResources.WG_NO_DECIMALFORMAT_DECLARATION,
new Object[]{ dfName }); //"not found!!!
//formatter = new java.text.DecimalFormat(patternStr);
}
else
{
//formatter = new java.text.DecimalFormat(patternStr, dfs);
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
formatter.applyLocalizedPattern(patternStr);
}
}
//else
if (null == formatter)
{
// look for a possible default decimal-format
if (ss.getDecimalFormatCount() > 0)
dfs = ss.getDecimalFormatComposed(new QName(""));
if (dfs != null)
{
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
formatter.applyLocalizedPattern(patternStr);
}
else
{
dfs = new java.text.DecimalFormatSymbols(java.util.Locale.US);
dfs.setInfinity(Constants.ATTRVAL_INFINITY);
dfs.setNaN(Constants.ATTRVAL_NAN);
formatter = new java.text.DecimalFormat();
formatter.setDecimalFormatSymbols(dfs);
if (null != patternStr)
formatter.applyLocalizedPattern(patternStr);
}
}
return new XString(formatter.format(num));
}
catch (Exception iae)
{
templElem.error(XSLTErrorResources.ER_MALFORMED_FORMAT_STRING,
new Object[]{ patternStr });
return XString.EMPTYSTRING;
//throw new XSLProcessorException(iae);
}
}
|
diff --git a/clients/android/NewsBlur/src/com/newsblur/activity/Reading.java b/clients/android/NewsBlur/src/com/newsblur/activity/Reading.java
index 17d69a870..4fe4657a1 100644
--- a/clients/android/NewsBlur/src/com/newsblur/activity/Reading.java
+++ b/clients/android/NewsBlur/src/com/newsblur/activity/Reading.java
@@ -1,538 +1,543 @@
package com.newsblur.activity;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.newsblur.R;
import com.newsblur.activity.Main;
import com.newsblur.domain.Story;
import com.newsblur.domain.UserDetails;
import com.newsblur.fragment.ReadingItemFragment;
import com.newsblur.fragment.ShareDialogFragment;
import com.newsblur.fragment.SyncUpdateFragment;
import com.newsblur.fragment.TextSizeDialogFragment;
import com.newsblur.network.APIManager;
import com.newsblur.util.AppConstants;
import com.newsblur.util.FeedUtils;
import com.newsblur.util.PrefConstants;
import com.newsblur.util.PrefsUtils;
import com.newsblur.util.UIUtils;
import com.newsblur.util.ViewUtils;
import com.newsblur.view.NonfocusScrollview.ScrollChangeListener;
public abstract class Reading extends NbFragmentActivity implements OnPageChangeListener, SyncUpdateFragment.SyncUpdateFragmentInterface, OnSeekBarChangeListener, ScrollChangeListener {
public static final String EXTRA_FEED = "feed_selected";
public static final String EXTRA_POSITION = "feed_position";
public static final String EXTRA_USERID = "user_id";
public static final String EXTRA_USERNAME = "username";
public static final String EXTRA_FOLDERNAME = "foldername";
public static final String EXTRA_FEED_IDS = "feed_ids";
private static final String TEXT_SIZE = "textsize";
private static final int OVERLAY_RANGE_TOP_DP = 45;
private static final int OVERLAY_RANGE_BOT_DP = 60;
/** The longest time (in seconds) the UI will wait for API pages to load while
searching for the next unread story. */
private static final long UNREAD_SEARCH_LOAD_WAIT_SECONDS = 30;
private final Object UNREAD_SEARCH_MUTEX = new Object();
private CountDownLatch unreadSearchLatch;
protected int passedPosition;
protected int currentState;
protected ViewPager pager;
protected Button overlayLeft, overlayRight;
protected ProgressBar overlayProgress;
protected FragmentManager fragmentManager;
protected ReadingAdapter readingAdapter;
protected ContentResolver contentResolver;
private APIManager apiManager;
protected SyncUpdateFragment syncFragment;
protected Cursor stories;
private boolean noMoreApiPages;
protected volatile boolean requestedPage; // set high iff a syncservice request for stories is already in flight
private int currentApiPage = 0;
private Set<Story> storiesToMarkAsRead;
// unread counts for the circular progress overlay. set to nonzero to activate the progress indicator overlay
protected int startingUnreadCount = 0;
protected int currentUnreadCount = 0;
// A list of stories we have marked as read during this reading session. Needed to help keep track of unread
// counts since it would be too costly to query and update the DB on every page change.
private Set<Story> storiesAlreadySeen;
private float overlayRangeTopPx;
private float overlayRangeBotPx;
private List<Story> pageHistory;
@Override
protected void onCreate(Bundle savedInstanceBundle) {
requestWindowFeature(Window.FEATURE_PROGRESS);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceBundle);
setContentView(R.layout.activity_reading);
this.overlayLeft = (Button) findViewById(R.id.reading_overlay_left);
this.overlayRight = (Button) findViewById(R.id.reading_overlay_right);
this.overlayProgress = (ProgressBar) findViewById(R.id.reading_overlay_progress);
fragmentManager = getSupportFragmentManager();
storiesToMarkAsRead = new HashSet<Story>();
storiesAlreadySeen = new HashSet<Story>();
passedPosition = getIntent().getIntExtra(EXTRA_POSITION, 0);
currentState = getIntent().getIntExtra(ItemsList.EXTRA_STATE, 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contentResolver = getContentResolver();
this.apiManager = new APIManager(this);
// this value is expensive to compute but doesn't change during a single runtime
this.overlayRangeTopPx = (float) UIUtils.convertDPsToPixels(this, OVERLAY_RANGE_TOP_DP);
this.overlayRangeBotPx = (float) UIUtils.convertDPsToPixels(this, OVERLAY_RANGE_BOT_DP);
this.pageHistory = new ArrayList<Story>();
}
/**
* Sets up the local pager widget. Should be called from onCreate() after both the cursor and
* adapter are created.
*/
protected void setupPager() {
syncFragment = (SyncUpdateFragment) fragmentManager.findFragmentByTag(SyncUpdateFragment.TAG);
if (syncFragment == null) {
syncFragment = new SyncUpdateFragment();
fragmentManager.beginTransaction().add(syncFragment, SyncUpdateFragment.TAG).commit();
}
pager = (ViewPager) findViewById(R.id.reading_pager);
pager.setPageMargin(UIUtils.convertDPsToPixels(getApplicationContext(), 1));
pager.setPageMarginDrawable(R.drawable.divider_light);
pager.setOnPageChangeListener(this);
pager.setAdapter(readingAdapter);
pager.setCurrentItem(passedPosition);
// setCurrentItem sometimes fails to pass the first page to the callback, so call it manually
// for the first one.
this.onPageSelected(passedPosition);
this.enableOverlays();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.reading, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int currentItem = pager.getCurrentItem();
Story story = readingAdapter.getStory(currentItem);
UserDetails user = PrefsUtils.getUserDetails(this);
if (item.getItemId() == android.R.id.home) {
finish();
return true;
} else if (item.getItemId() == R.id.menu_reading_original) {
if (story != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(story.permalink));
startActivity(i);
}
return true;
} else if (item.getItemId() == R.id.menu_reading_sharenewsblur) {
if (story != null) {
ReadingItemFragment currentFragment = (ReadingItemFragment) readingAdapter.instantiateItem(pager, currentItem);
DialogFragment newFragment = ShareDialogFragment.newInstance(currentFragment, story, currentFragment.previouslySavedShareText);
newFragment.show(getSupportFragmentManager(), "dialog");
}
return true;
} else if (item.getItemId() == R.id.menu_shared) {
FeedUtils.shareStory(story, this);
return true;
} else if (item.getItemId() == R.id.menu_textsize) {
float currentValue = getSharedPreferences(PrefConstants.PREFERENCES, 0).getFloat(PrefConstants.PREFERENCE_TEXT_SIZE, 0.5f);
TextSizeDialogFragment textSize = TextSizeDialogFragment.newInstance(currentValue);
textSize.show(getSupportFragmentManager(), TEXT_SIZE);
return true;
} else if (item.getItemId() == R.id.menu_reading_save) {
FeedUtils.saveStory(story, Reading.this, apiManager);
return true;
} else if (item.getItemId() == R.id.menu_reading_markunread) {
this.markStoryUnread(story);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
// interface OnPageChangeListener
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int position) {
Story story = readingAdapter.getStory(position);
if (story != null) {
synchronized (this.pageHistory) {
// if the history is just starting out or the last entry in it isn't this page, add this page
if ((this.pageHistory.size() < 1) || (!story.equals(this.pageHistory.get(this.pageHistory.size()-1)))) {
this.pageHistory.add(story);
}
}
addStoryToMarkAsRead(story);
checkStoryCount(position);
}
this.enableOverlays();
}
// interface ScrollChangeListener
@Override
public void scrollChanged(int hPos, int vPos, int currentWidth, int currentHeight) {
int scrollMax = currentHeight - findViewById(android.R.id.content).getMeasuredHeight();
int posFromBot = (scrollMax - vPos);
float newAlpha = 0.0f;
if ((vPos < this.overlayRangeTopPx) && (posFromBot < this.overlayRangeBotPx)) {
// if we have a super-tiny scroll window such that we never leave either top or bottom,
// just leave us at full alpha.
newAlpha = 1.0f;
} else if (vPos < this.overlayRangeTopPx) {
float delta = this.overlayRangeTopPx - ((float) vPos);
newAlpha = delta / this.overlayRangeTopPx;
} else if (posFromBot < this.overlayRangeBotPx) {
float delta = this.overlayRangeBotPx - ((float) posFromBot);
newAlpha = delta / this.overlayRangeBotPx;
}
this.setOverlayAlpha(newAlpha);
}
private void setOverlayAlpha(float a) {
UIUtils.setViewAlpha(this.overlayLeft, a);
UIUtils.setViewAlpha(this.overlayRight, a);
UIUtils.setViewAlpha(this.overlayProgress, a);
}
/**
* Check and correct the display status of the overlays. Call this any time
* an event happens that might change our list position.
*/
private void enableOverlays() {
this.overlayLeft.setEnabled(this.getLastReadPosition(false) != -1);
this.overlayRight.setText((this.currentUnreadCount > 0) ? R.string.overlay_next : R.string.overlay_done);
this.overlayRight.setBackgroundResource((this.currentUnreadCount > 0) ? R.drawable.selector_overlay_bg_right : R.drawable.overlay_right_done);
if (this.startingUnreadCount == 0 ) {
// sessions with no unreads just show a full progress bar
this.overlayProgress.setMax(1);
this.overlayProgress.setProgress(1);
} else {
int unreadProgress = this.startingUnreadCount - this.currentUnreadCount;
this.overlayProgress.setMax(this.startingUnreadCount);
this.overlayProgress.setProgress(unreadProgress);
}
this.overlayProgress.invalidate();
this.setOverlayAlpha(1.0f);
}
@Override
public void updateAfterSync() {
this.requestedPage = false;
updateSyncStatus(false);
stories.requery();
readingAdapter.notifyDataSetChanged();
this.enableOverlays();
checkStoryCount(pager.getCurrentItem());
if (this.unreadSearchLatch != null) {
this.unreadSearchLatch.countDown();
}
}
@Override
public void updatePartialSync() {
stories.requery();
readingAdapter.notifyDataSetChanged();
this.enableOverlays();
checkStoryCount(pager.getCurrentItem());
if (this.unreadSearchLatch != null) {
this.unreadSearchLatch.countDown();
}
}
/**
* Lets us know that there are no more pages of stories to load, ever, and will cause
* us to stop requesting them.
*/
@Override
public void setNothingMoreToUpdate() {
this.noMoreApiPages = true;
if (this.unreadSearchLatch !=null) {
this.unreadSearchLatch.countDown();
}
}
/**
* While navigating the story list and at the specified position, see if it is possible
* and desirable to start loading more stories in the background. Note that if a load
* is triggered, this method will be called again by the callback to ensure another
* load is not needed and all latches are tripped.
*/
private void checkStoryCount(int position) {
// if the pager is at or near the number of stories loaded, check for more unless we know we are at the end of the list
if (((position + 2) >= stories.getCount()) && !noMoreApiPages && !requestedPage) {
currentApiPage += 1;
requestedPage = true;
triggerRefresh(currentApiPage);
}
}
@Override
public void updateSyncStatus(final boolean syncRunning) {
runOnUiThread(new Runnable() {
public void run() {
setSupportProgressBarIndeterminateVisibility(syncRunning);
}
});
}
public abstract void triggerRefresh(int page);
@Override
protected void onPause() {
flushStoriesMarkedRead();
super.onPause();
}
/**
* Log a story as having been read. The local DB and remote server will be updated
* batch-wise when the activity pauses.
*/
protected void addStoryToMarkAsRead(Story story) {
if (story == null) return;
if (story.read) return;
synchronized (this.storiesToMarkAsRead) {
this.storiesToMarkAsRead.add(story);
}
// flush immediately if the batch reaches a sufficient size
if (this.storiesToMarkAsRead.size() >= AppConstants.MAX_MARK_READ_BATCH) {
flushStoriesMarkedRead();
}
if (!this.storiesAlreadySeen.contains(story)) {
// only decrement the cached story count if the story wasn't already read
this.storiesAlreadySeen.add(story);
this.currentUnreadCount--;
}
this.enableOverlays();
}
private void flushStoriesMarkedRead() {
synchronized(this.storiesToMarkAsRead) {
if (this.storiesToMarkAsRead.size() > 0) {
FeedUtils.markStoriesAsRead(this.storiesToMarkAsRead, this);
this.storiesToMarkAsRead.clear();
}
}
}
private void markStoryUnread(Story story) {
// first, ensure the story isn't queued up to be marked as read
this.storiesToMarkAsRead.remove(story);
// next, call the API to un-mark it as read, just in case we missed the batch
// operation, or it was read long before now.
FeedUtils.markStoryUnread(story, Reading.this, this.apiManager);
this.currentUnreadCount++;
this.storiesAlreadySeen.remove(story);
this.enableOverlays();
}
// NB: this callback is for the text size slider
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
getSharedPreferences(PrefConstants.PREFERENCES, 0).edit().putFloat(PrefConstants.PREFERENCE_TEXT_SIZE, (float) progress / AppConstants.FONT_SIZE_INCREMENT_FACTOR).commit();
Intent data = new Intent(ReadingItemFragment.TEXT_SIZE_CHANGED);
data.putExtra(ReadingItemFragment.TEXT_SIZE_VALUE, (float) progress / AppConstants.FONT_SIZE_INCREMENT_FACTOR);
sendBroadcast(data);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
/**
* Click handler for the righthand overlay nav button.
*/
public void overlayRight(View v) {
if (this.currentUnreadCount == 0) {
// if there are no unread stories, go back to the feed list
Intent i = new Intent(this, Main.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
} else {
// if there are unreads, go to the next one
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
nextUnread();
return null;
}
}.execute();
//}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
/**
* Search our set of stories for the next unread one. This requires some heavy
* cooperation with the way stories are automatically loaded in the background
* as we walk through the list.
*/
private void nextUnread() {
synchronized (UNREAD_SEARCH_MUTEX) {
int candidate = 0;
boolean unreadFound = false;
+ boolean error = false;
unreadSearch:while (!unreadFound) {
Story story = readingAdapter.getStory(candidate);
if (story == null) {
if (this.noMoreApiPages) {
// this is odd. if there were no unreads, how was the button even enabled?
Log.e(this.getClass().getName(), "Ran out of stories while looking for unreads.");
- Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
} else {
if ((candidate == pager.getCurrentItem()) || (story.read) || (this.storiesAlreadySeen.contains(story))) {
candidate++;
continue unreadSearch;
} else {
unreadFound = true;
break unreadSearch;
}
}
// if we didn't find a story trigger a check to see if there are any more to search before proceeding
this.unreadSearchLatch = new CountDownLatch(1);
this.checkStoryCount(candidate+1);
try {
boolean unlatched = this.unreadSearchLatch.await(UNREAD_SEARCH_LOAD_WAIT_SECONDS, TimeUnit.SECONDS);
if (unlatched) {
continue unreadSearch;
} else {
Log.e(this.getClass().getName(), "Timed out waiting for next API page while looking for unreads.");
- Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
} catch (InterruptedException ie) {
Log.e(this.getClass().getName(), "Interrupted waiting for next API page while looking for unreads.");
- Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
}
+ if (error) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ Toast.makeText(Reading.this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
+ }
+ });
+ }
if (unreadFound) {
final int page = candidate;
runOnUiThread(new Runnable() {
public void run() {
pager.setCurrentItem(page, true);
}
});
}
}
}
/**
* Click handler for the lefthand overlay nav button.
*/
public void overlayLeft(View v) {
int targetPosition = this.getLastReadPosition(true);
if (targetPosition != -1) {
pager.setCurrentItem(targetPosition, true);
} else {
Log.e(this.getClass().getName(), "reading history contained item not found in cursor.");
}
}
/**
* Get the pager position of the last story read during this activity or -1 if there is nothing
* in the history.
*
* @param trimHistory optionally trim the history of the currently displayed page iff the
* back button has been pressed.
*/
private int getLastReadPosition(boolean trimHistory) {
synchronized (this.pageHistory) {
// the last item is always the currently shown page, do not count it
if (this.pageHistory.size() < 2) {
return -1;
}
Story targetStory = this.pageHistory.get(this.pageHistory.size()-2);
int targetPosition = this.readingAdapter.getPosition(targetStory);
if (trimHistory && (targetPosition != -1)) {
this.pageHistory.remove(this.pageHistory.size()-1);
}
return targetPosition;
}
}
/**
* Click handler for the progress indicator on the righthand overlay nav button.
*/
public void overlayCount(View v) {
String unreadText = getString((this.currentUnreadCount == 1) ? R.string.overlay_count_toast_1 : R.string.overlay_count_toast_N);
Toast.makeText(this, String.format(unreadText, this.currentUnreadCount), Toast.LENGTH_SHORT).show();
}
}
| false | true | private void nextUnread() {
synchronized (UNREAD_SEARCH_MUTEX) {
int candidate = 0;
boolean unreadFound = false;
unreadSearch:while (!unreadFound) {
Story story = readingAdapter.getStory(candidate);
if (story == null) {
if (this.noMoreApiPages) {
// this is odd. if there were no unreads, how was the button even enabled?
Log.e(this.getClass().getName(), "Ran out of stories while looking for unreads.");
Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
} else {
if ((candidate == pager.getCurrentItem()) || (story.read) || (this.storiesAlreadySeen.contains(story))) {
candidate++;
continue unreadSearch;
} else {
unreadFound = true;
break unreadSearch;
}
}
// if we didn't find a story trigger a check to see if there are any more to search before proceeding
this.unreadSearchLatch = new CountDownLatch(1);
this.checkStoryCount(candidate+1);
try {
boolean unlatched = this.unreadSearchLatch.await(UNREAD_SEARCH_LOAD_WAIT_SECONDS, TimeUnit.SECONDS);
if (unlatched) {
continue unreadSearch;
} else {
Log.e(this.getClass().getName(), "Timed out waiting for next API page while looking for unreads.");
Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
} catch (InterruptedException ie) {
Log.e(this.getClass().getName(), "Interrupted waiting for next API page while looking for unreads.");
Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
}
if (unreadFound) {
final int page = candidate;
runOnUiThread(new Runnable() {
public void run() {
pager.setCurrentItem(page, true);
}
});
}
}
}
| private void nextUnread() {
synchronized (UNREAD_SEARCH_MUTEX) {
int candidate = 0;
boolean unreadFound = false;
boolean error = false;
unreadSearch:while (!unreadFound) {
Story story = readingAdapter.getStory(candidate);
if (story == null) {
if (this.noMoreApiPages) {
// this is odd. if there were no unreads, how was the button even enabled?
Log.e(this.getClass().getName(), "Ran out of stories while looking for unreads.");
break unreadSearch;
}
} else {
if ((candidate == pager.getCurrentItem()) || (story.read) || (this.storiesAlreadySeen.contains(story))) {
candidate++;
continue unreadSearch;
} else {
unreadFound = true;
break unreadSearch;
}
}
// if we didn't find a story trigger a check to see if there are any more to search before proceeding
this.unreadSearchLatch = new CountDownLatch(1);
this.checkStoryCount(candidate+1);
try {
boolean unlatched = this.unreadSearchLatch.await(UNREAD_SEARCH_LOAD_WAIT_SECONDS, TimeUnit.SECONDS);
if (unlatched) {
continue unreadSearch;
} else {
Log.e(this.getClass().getName(), "Timed out waiting for next API page while looking for unreads.");
break unreadSearch;
}
} catch (InterruptedException ie) {
Log.e(this.getClass().getName(), "Interrupted waiting for next API page while looking for unreads.");
break unreadSearch;
}
}
if (error) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Reading.this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
}
});
}
if (unreadFound) {
final int page = candidate;
runOnUiThread(new Runnable() {
public void run() {
pager.setCurrentItem(page, true);
}
});
}
}
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/BrowserInfo.java b/src/com/itmill/toolkit/terminal/gwt/client/BrowserInfo.java
index 63805fd62..d62a4a657 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/BrowserInfo.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/BrowserInfo.java
@@ -1,141 +1,141 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client;
/**
* Class used to query information about web browser.
*
* Browser details are detected only once and those are stored in this singleton
* class.
*
*/
public class BrowserInfo {
private static BrowserInfo instance;
/**
* Singleton method to get BrowserInfo object.
*
* @return instance of BrowserInfo object
*/
public static BrowserInfo get() {
if (instance == null) {
instance = new BrowserInfo();
}
return instance;
}
private boolean isGecko;
private boolean isAppleWebKit;
private boolean isSafari;
private boolean isOpera;
private boolean isIE;
private float ieVersion = -1;
private float geckoVersion = -1;
private float appleWebKitVersion = -1;
private BrowserInfo() {
try {
String ua = getBrowserString().toLowerCase();
// browser engine name
- isGecko = ua.indexOf("gecko") != -1 && ua.indexOf("safari") == -1;
+ isGecko = ua.indexOf("gecko") != -1 && ua.indexOf("webkit") == -1;
isAppleWebKit = ua.indexOf("applewebkit") != -1;
// browser name
isSafari = ua.indexOf("safari") != -1;
isOpera = ua.indexOf("opera") != -1;
isIE = ua.indexOf("msie") != -1 && !isOpera
&& (ua.indexOf("webtv") == -1);
if (isGecko) {
String tmp = ua.substring(ua.indexOf("rv:") + 3);
tmp = tmp.replaceFirst("(\\.[0-9]+).+", "$1");
geckoVersion = Float.parseFloat(tmp);
}
if (isAppleWebKit) {
String tmp = ua.substring(ua.indexOf("webkit/") + 7);
tmp = tmp.replaceFirst("([0-9]+)[^0-9].+", "$1");
appleWebKitVersion = Float.parseFloat(tmp);
}
if (isIE) {
String ieVersionString = ua.substring(ua.indexOf("msie ") + 5);
ieVersionString = ieVersionString.substring(0, ieVersionString
.indexOf(";"));
ieVersion = Float.parseFloat(ieVersionString);
}
} catch (Exception e) {
e.printStackTrace();
ApplicationConnection.getConsole().error(e.getMessage());
}
}
public boolean isIE() {
return isIE;
}
public boolean isSafari() {
return isSafari;
}
public boolean isIE6() {
return isIE && ieVersion == 6;
}
public boolean isIE7() {
return isIE && ieVersion == 7;
}
public boolean isGecko() {
return isGecko;
}
public boolean isFF2() {
return isGecko && geckoVersion == 1.8;
}
public boolean isFF3() {
return isGecko && geckoVersion == 1.9;
}
public float getGeckoVersion() {
return geckoVersion;
}
public float getWebkitVersion() {
return appleWebKitVersion;
}
public float getIEVersion() {
return ieVersion;
}
public boolean isOpera() {
return isOpera;
}
public native static String getBrowserString()
/*-{
return $wnd.navigator.userAgent;
}-*/;
public static void test() {
Console c = ApplicationConnection.getConsole();
c.log("getBrowserString() " + getBrowserString());
c.log("isIE() " + get().isIE());
c.log("isIE6() " + get().isIE6());
c.log("isIE7() " + get().isIE7());
c.log("isFF2() " + get().isFF2());
c.log("isSafari() " + get().isSafari());
c.log("getGeckoVersion() " + get().getGeckoVersion());
c.log("getWebkitVersion() " + get().getWebkitVersion());
c.log("getIEVersion() " + get().getIEVersion());
c.log("isIE() " + get().isIE());
c.log("isIE() " + get().isIE());
}
}
| true | true | private BrowserInfo() {
try {
String ua = getBrowserString().toLowerCase();
// browser engine name
isGecko = ua.indexOf("gecko") != -1 && ua.indexOf("safari") == -1;
isAppleWebKit = ua.indexOf("applewebkit") != -1;
// browser name
isSafari = ua.indexOf("safari") != -1;
isOpera = ua.indexOf("opera") != -1;
isIE = ua.indexOf("msie") != -1 && !isOpera
&& (ua.indexOf("webtv") == -1);
if (isGecko) {
String tmp = ua.substring(ua.indexOf("rv:") + 3);
tmp = tmp.replaceFirst("(\\.[0-9]+).+", "$1");
geckoVersion = Float.parseFloat(tmp);
}
if (isAppleWebKit) {
String tmp = ua.substring(ua.indexOf("webkit/") + 7);
tmp = tmp.replaceFirst("([0-9]+)[^0-9].+", "$1");
appleWebKitVersion = Float.parseFloat(tmp);
}
if (isIE) {
String ieVersionString = ua.substring(ua.indexOf("msie ") + 5);
ieVersionString = ieVersionString.substring(0, ieVersionString
.indexOf(";"));
ieVersion = Float.parseFloat(ieVersionString);
}
} catch (Exception e) {
e.printStackTrace();
ApplicationConnection.getConsole().error(e.getMessage());
}
}
| private BrowserInfo() {
try {
String ua = getBrowserString().toLowerCase();
// browser engine name
isGecko = ua.indexOf("gecko") != -1 && ua.indexOf("webkit") == -1;
isAppleWebKit = ua.indexOf("applewebkit") != -1;
// browser name
isSafari = ua.indexOf("safari") != -1;
isOpera = ua.indexOf("opera") != -1;
isIE = ua.indexOf("msie") != -1 && !isOpera
&& (ua.indexOf("webtv") == -1);
if (isGecko) {
String tmp = ua.substring(ua.indexOf("rv:") + 3);
tmp = tmp.replaceFirst("(\\.[0-9]+).+", "$1");
geckoVersion = Float.parseFloat(tmp);
}
if (isAppleWebKit) {
String tmp = ua.substring(ua.indexOf("webkit/") + 7);
tmp = tmp.replaceFirst("([0-9]+)[^0-9].+", "$1");
appleWebKitVersion = Float.parseFloat(tmp);
}
if (isIE) {
String ieVersionString = ua.substring(ua.indexOf("msie ") + 5);
ieVersionString = ieVersionString.substring(0, ieVersionString
.indexOf(";"));
ieVersion = Float.parseFloat(ieVersionString);
}
} catch (Exception e) {
e.printStackTrace();
ApplicationConnection.getConsole().error(e.getMessage());
}
}
|
diff --git a/library/src/org/whispersystems/textsecure/storage/SessionRecordV2.java b/library/src/org/whispersystems/textsecure/storage/SessionRecordV2.java
index 6a0fdb6ce..e4c5ba39f 100644
--- a/library/src/org/whispersystems/textsecure/storage/SessionRecordV2.java
+++ b/library/src/org/whispersystems/textsecure/storage/SessionRecordV2.java
@@ -1,569 +1,569 @@
/**
* Copyright (C) 2013 Open Whisper Systems
*
* 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
* (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 org.whispersystems.textsecure.storage;
import android.content.Context;
import android.util.Log;
import android.util.Pair;
import com.google.protobuf.ByteString;
import org.whispersystems.textsecure.crypto.IdentityKey;
import org.whispersystems.textsecure.crypto.IdentityKeyPair;
import org.whispersystems.textsecure.crypto.InvalidKeyException;
import org.whispersystems.textsecure.crypto.InvalidMessageException;
import org.whispersystems.textsecure.crypto.MasterCipher;
import org.whispersystems.textsecure.crypto.MasterSecret;
import org.whispersystems.textsecure.crypto.ecc.Curve;
import org.whispersystems.textsecure.crypto.ecc.ECKeyPair;
import org.whispersystems.textsecure.crypto.ecc.ECPrivateKey;
import org.whispersystems.textsecure.crypto.ecc.ECPublicKey;
import org.whispersystems.textsecure.crypto.ratchet.ChainKey;
import org.whispersystems.textsecure.crypto.ratchet.MessageKeys;
import org.whispersystems.textsecure.crypto.ratchet.RootKey;
import org.whispersystems.textsecure.storage.StorageProtos.SessionStructure.Chain;
import org.whispersystems.textsecure.storage.StorageProtos.SessionStructure.PendingKeyExchange;
import org.whispersystems.textsecure.storage.StorageProtos.SessionStructure.PendingPreKey;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.crypto.spec.SecretKeySpec;
/**
* A disk record representing a current session.
*
* @author Moxie Marlinspike
*/
public class SessionRecordV2 extends Record {
private static final Object FILE_LOCK = new Object();
private static final int CURRENT_VERSION = 1;
private final MasterSecret masterSecret;
private StorageProtos.SessionStructure sessionStructure =
StorageProtos.SessionStructure.newBuilder().build();
public SessionRecordV2(Context context, MasterSecret masterSecret, RecipientDevice peer) {
this(context, masterSecret, peer.getRecipientId(), peer.getDeviceId());
}
public SessionRecordV2(Context context, MasterSecret masterSecret, long recipientId, int deviceId) {
super(context, SESSIONS_DIRECTORY_V2, getRecordName(recipientId, deviceId));
this.masterSecret = masterSecret;
loadData();
}
private static String getRecordName(long recipientId, int deviceId) {
return recipientId + (deviceId == RecipientDevice.DEFAULT_DEVICE_ID ? "" : "." + deviceId);
}
public static List<Integer> getSessionSubDevices(Context context, CanonicalRecipient recipient) {
List<Integer> results = new LinkedList<Integer>();
File parent = getParentDirectory(context, SESSIONS_DIRECTORY_V2);
String[] children = parent.list();
if (children == null) return results;
for (String child : children) {
try {
String[] parts = child.split("[.]", 2);
long sessionRecipientId = Long.parseLong(parts[0]);
if (sessionRecipientId == recipient.getRecipientId() && parts.length > 1) {
results.add(Integer.parseInt(parts[1]));
}
} catch (NumberFormatException e) {
Log.w("SessionRecordV2", e);
}
}
return results;
}
public static void deleteAll(Context context, CanonicalRecipient recipient) {
List<Integer> devices = getSessionSubDevices(context, recipient);
delete(context, SESSIONS_DIRECTORY_V2, getRecordName(recipient.getRecipientId(),
RecipientDevice.DEFAULT_DEVICE_ID));
for (int device : devices) {
delete(context, SESSIONS_DIRECTORY_V2, getRecordName(recipient.getRecipientId(), device));
}
}
public static void delete(Context context, RecipientDevice recipientDevice) {
delete(context, SESSIONS_DIRECTORY_V2, getRecordName(recipientDevice.getRecipientId(),
recipientDevice.getDeviceId()));
}
public static boolean hasSession(Context context, MasterSecret masterSecret,
RecipientDevice recipient)
{
return hasSession(context, masterSecret, recipient.getRecipientId(), recipient.getDeviceId());
}
public static boolean hasSession(Context context, MasterSecret masterSecret,
long recipientId, int deviceId)
{
return hasRecord(context, SESSIONS_DIRECTORY_V2, getRecordName(recipientId, deviceId)) &&
new SessionRecordV2(context, masterSecret, recipientId, deviceId).hasSenderChain();
}
public void clear() {
this.sessionStructure = StorageProtos.SessionStructure.newBuilder().build();
}
public void setSessionVersion(int version) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setSessionVersion(version)
.build();
}
public int getSessionVersion() {
return this.sessionStructure.getSessionVersion();
}
public void setRemoteIdentityKey(IdentityKey identityKey) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setRemoteIdentityPublic(ByteString.copyFrom(identityKey.serialize()))
.build();
}
public void setLocalIdentityKey(IdentityKey identityKey) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setLocalIdentityPublic(ByteString.copyFrom(identityKey.serialize()))
.build();
}
public IdentityKey getRemoteIdentityKey() {
try {
if (!this.sessionStructure.hasRemoteIdentityPublic()) {
return null;
}
return new IdentityKey(this.sessionStructure.getRemoteIdentityPublic().toByteArray(), 0);
} catch (InvalidKeyException e) {
Log.w("SessionRecordV2", e);
return null;
}
}
public IdentityKey getLocalIdentityKey() {
try {
return new IdentityKey(this.sessionStructure.getLocalIdentityPublic().toByteArray(), 0);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public int getPreviousCounter() {
return sessionStructure.getPreviousCounter();
}
public void setPreviousCounter(int previousCounter) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setPreviousCounter(previousCounter)
.build();
}
public RootKey getRootKey() {
return new RootKey(this.sessionStructure.getRootKey().toByteArray());
}
public void setRootKey(RootKey rootKey) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setRootKey(ByteString.copyFrom(rootKey.getKeyBytes()))
.build();
}
public ECPublicKey getSenderEphemeral() {
try {
return Curve.decodePoint(sessionStructure.getSenderChain().getSenderEphemeral().toByteArray(), 0);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public ECKeyPair getSenderEphemeralPair() {
ECPublicKey publicKey = getSenderEphemeral();
ECPrivateKey privateKey = Curve.decodePrivatePoint(publicKey.getType(),
sessionStructure.getSenderChain()
.getSenderEphemeralPrivate()
.toByteArray());
return new ECKeyPair(publicKey, privateKey);
}
public boolean hasReceiverChain(ECPublicKey senderEphemeral) {
return getReceiverChain(senderEphemeral) != null;
}
public boolean hasSenderChain() {
return sessionStructure.hasSenderChain();
}
private Pair<Chain,Integer> getReceiverChain(ECPublicKey senderEphemeral) {
List<Chain> receiverChains = sessionStructure.getReceiverChainsList();
int index = 0;
for (Chain receiverChain : receiverChains) {
try {
ECPublicKey chainSenderEphemeral = Curve.decodePoint(receiverChain.getSenderEphemeral().toByteArray(), 0);
if (chainSenderEphemeral.equals(senderEphemeral)) {
return new Pair<Chain,Integer>(receiverChain,index);
}
} catch (InvalidKeyException e) {
Log.w("SessionRecordV2", e);
}
index++;
}
return null;
}
public ChainKey getReceiverChainKey(ECPublicKey senderEphemeral) {
Pair<Chain,Integer> receiverChainAndIndex = getReceiverChain(senderEphemeral);
Chain receiverChain = receiverChainAndIndex.first;
if (receiverChain == null) {
return null;
} else {
return new ChainKey(receiverChain.getChainKey().getKey().toByteArray(),
receiverChain.getChainKey().getIndex());
}
}
public void addReceiverChain(ECPublicKey senderEphemeral, ChainKey chainKey) {
Chain.ChainKey chainKeyStructure = Chain.ChainKey.newBuilder()
.setKey(ByteString.copyFrom(chainKey.getKey()))
.setIndex(chainKey.getIndex())
.build();
Chain chain = Chain.newBuilder()
.setChainKey(chainKeyStructure)
.setSenderEphemeral(ByteString.copyFrom(senderEphemeral.serialize()))
.build();
this.sessionStructure = this.sessionStructure.toBuilder().addReceiverChains(chain).build();
if (this.sessionStructure.getReceiverChainsList().size() > 5) {
this.sessionStructure = this.sessionStructure.toBuilder()
.removeReceiverChains(0)
.build();
}
}
public void setSenderChain(ECKeyPair senderEphemeralPair, ChainKey chainKey) {
Chain.ChainKey chainKeyStructure = Chain.ChainKey.newBuilder()
.setKey(ByteString.copyFrom(chainKey.getKey()))
.setIndex(chainKey.getIndex())
.build();
Chain senderChain = Chain.newBuilder()
.setSenderEphemeral(ByteString.copyFrom(senderEphemeralPair.getPublicKey().serialize()))
.setSenderEphemeralPrivate(ByteString.copyFrom(senderEphemeralPair.getPrivateKey().serialize()))
.setChainKey(chainKeyStructure)
.build();
this.sessionStructure = this.sessionStructure.toBuilder().setSenderChain(senderChain).build();
}
public ChainKey getSenderChainKey() {
Chain.ChainKey chainKeyStructure = sessionStructure.getSenderChain().getChainKey();
return new ChainKey(chainKeyStructure.getKey().toByteArray(), chainKeyStructure.getIndex());
}
public void setSenderChainKey(ChainKey nextChainKey) {
Chain.ChainKey chainKey = Chain.ChainKey.newBuilder()
.setKey(ByteString.copyFrom(nextChainKey.getKey()))
.setIndex(nextChainKey.getIndex())
.build();
Chain chain = sessionStructure.getSenderChain().toBuilder()
.setChainKey(chainKey).build();
this.sessionStructure = this.sessionStructure.toBuilder().setSenderChain(chain).build();
}
public boolean hasMessageKeys(ECPublicKey senderEphemeral, int counter) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first;
if (chain == null) {
return false;
}
List<Chain.MessageKey> messageKeyList = chain.getMessageKeysList();
for (Chain.MessageKey messageKey : messageKeyList) {
if (messageKey.getIndex() == counter) {
return true;
}
}
return false;
}
public MessageKeys removeMessageKeys(ECPublicKey senderEphemeral, int counter) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first;
if (chain == null) {
return null;
}
- List<Chain.MessageKey> messageKeyList = chain.getMessageKeysList();
+ List<Chain.MessageKey> messageKeyList = new LinkedList<Chain.MessageKey>(chain.getMessageKeysList());
Iterator<Chain.MessageKey> messageKeyIterator = messageKeyList.iterator();
MessageKeys result = null;
while (messageKeyIterator.hasNext()) {
Chain.MessageKey messageKey = messageKeyIterator.next();
if (messageKey.getIndex() == counter) {
result = new MessageKeys(new SecretKeySpec(messageKey.getCipherKey().toByteArray(), "AES"),
new SecretKeySpec(messageKey.getMacKey().toByteArray(), "HmacSHA256"),
messageKey.getIndex());
messageKeyIterator.remove();
break;
}
}
Chain updatedChain = chain.toBuilder().clearMessageKeys()
.addAllMessageKeys(messageKeyList)
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setReceiverChains(chainAndIndex.second, updatedChain)
.build();
return result;
}
public void setMessageKeys(ECPublicKey senderEphemeral, MessageKeys messageKeys) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first;
Chain.MessageKey messageKeyStructure = Chain.MessageKey.newBuilder()
.setCipherKey(ByteString.copyFrom(messageKeys.getCipherKey().getEncoded()))
.setMacKey(ByteString.copyFrom(messageKeys.getMacKey().getEncoded()))
.setIndex(messageKeys.getCounter())
.build();
Chain updatedChain = chain.toBuilder()
.addMessageKeys(messageKeyStructure)
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setReceiverChains(chainAndIndex.second, updatedChain)
.build();
}
public void setReceiverChainKey(ECPublicKey senderEphemeral, ChainKey chainKey) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first;
Chain.ChainKey chainKeyStructure = Chain.ChainKey.newBuilder()
.setKey(ByteString.copyFrom(chainKey.getKey()))
.setIndex(chainKey.getIndex())
.build();
Chain updatedChain = chain.toBuilder().setChainKey(chainKeyStructure).build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setReceiverChains(chainAndIndex.second, updatedChain)
.build();
}
public void setPendingKeyExchange(int sequence,
ECKeyPair ourBaseKey,
ECKeyPair ourEphemeralKey,
IdentityKeyPair ourIdentityKey)
{
PendingKeyExchange structure =
PendingKeyExchange.newBuilder()
.setSequence(sequence)
.setLocalBaseKey(ByteString.copyFrom(ourBaseKey.getPublicKey().serialize()))
.setLocalBaseKeyPrivate(ByteString.copyFrom(ourBaseKey.getPrivateKey().serialize()))
.setLocalEphemeralKey(ByteString.copyFrom(ourEphemeralKey.getPublicKey().serialize()))
.setLocalEphemeralKeyPrivate(ByteString.copyFrom(ourEphemeralKey.getPrivateKey().serialize()))
.setLocalIdentityKey(ByteString.copyFrom(ourIdentityKey.getPublicKey().serialize()))
.setLocalIdentityKeyPrivate(ByteString.copyFrom(ourIdentityKey.getPrivateKey().serialize()))
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setPendingKeyExchange(structure)
.build();
}
public int getPendingKeyExchangeSequence() {
return sessionStructure.getPendingKeyExchange().getSequence();
}
public ECKeyPair getPendingKeyExchangeBaseKey() throws InvalidKeyException {
ECPublicKey publicKey = Curve.decodePoint(sessionStructure.getPendingKeyExchange()
.getLocalBaseKey().toByteArray(), 0);
ECPrivateKey privateKey = Curve.decodePrivatePoint(publicKey.getType(),
sessionStructure.getPendingKeyExchange()
.getLocalBaseKeyPrivate()
.toByteArray());
return new ECKeyPair(publicKey, privateKey);
}
public ECKeyPair getPendingKeyExchangeEphemeralKey() throws InvalidKeyException {
ECPublicKey publicKey = Curve.decodePoint(sessionStructure.getPendingKeyExchange()
.getLocalEphemeralKey().toByteArray(), 0);
ECPrivateKey privateKey = Curve.decodePrivatePoint(publicKey.getType(),
sessionStructure.getPendingKeyExchange()
.getLocalEphemeralKeyPrivate()
.toByteArray());
return new ECKeyPair(publicKey, privateKey);
}
public IdentityKeyPair getPendingKeyExchangeIdentityKey() throws InvalidKeyException {
IdentityKey publicKey = new IdentityKey(sessionStructure.getPendingKeyExchange()
.getLocalIdentityKey().toByteArray(), 0);
ECPrivateKey privateKey = Curve.decodePrivatePoint(publicKey.getPublicKey().getType(),
sessionStructure.getPendingKeyExchange()
.getLocalIdentityKeyPrivate()
.toByteArray());
return new IdentityKeyPair(publicKey, privateKey);
}
public boolean hasPendingKeyExchange() {
return sessionStructure.hasPendingKeyExchange();
}
public void setPendingPreKey(int preKeyId, ECPublicKey baseKey) {
PendingPreKey pending = PendingPreKey.newBuilder()
.setPreKeyId(preKeyId)
.setBaseKey(ByteString.copyFrom(baseKey.serialize()))
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setPendingPreKey(pending)
.build();
}
public boolean hasPendingPreKey() {
return this.sessionStructure.hasPendingPreKey();
}
public Pair<Integer, ECPublicKey> getPendingPreKey() {
try {
return new Pair<Integer, ECPublicKey>(sessionStructure.getPendingPreKey().getPreKeyId(),
Curve.decodePoint(sessionStructure.getPendingPreKey()
.getBaseKey()
.toByteArray(), 0));
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public void clearPendingPreKey() {
this.sessionStructure = this.sessionStructure.toBuilder()
.clearPendingPreKey()
.build();
}
public void setRemoteRegistrationId(int registrationId) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setRemoteRegistrationId(registrationId)
.build();
}
public int getRemoteRegistrationId() {
return this.sessionStructure.getRemoteRegistrationId();
}
public void setLocalRegistrationId(int registrationId) {
this.sessionStructure = this.sessionStructure.toBuilder()
.setLocalRegistrationId(registrationId)
.build();
}
public int getLocalRegistrationId() {
return this.sessionStructure.getLocalRegistrationId();
}
public void save() {
synchronized (FILE_LOCK) {
try {
RandomAccessFile file = openRandomAccessFile();
FileChannel out = file.getChannel();
out.position(0);
MasterCipher cipher = new MasterCipher(masterSecret);
writeInteger(CURRENT_VERSION, out);
writeBlob(cipher.encryptBytes(sessionStructure.toByteArray()), out);
out.truncate(out.position());
file.close();
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe);
}
}
}
private void loadData() {
synchronized (FILE_LOCK) {
try {
FileInputStream in = this.openInputStream();
int versionMarker = readInteger(in);
if (versionMarker > CURRENT_VERSION) {
throw new AssertionError("Unknown version: " + versionMarker);
}
MasterCipher cipher = new MasterCipher(masterSecret);
byte[] encryptedBlob = readBlob(in);
this.sessionStructure = StorageProtos.SessionStructure
.parseFrom(cipher.decryptBytes(encryptedBlob));
in.close();
} catch (FileNotFoundException e) {
Log.w("SessionRecordV2", "No session information found.");
// XXX
} catch (IOException ioe) {
Log.w("SessionRecordV2", ioe);
// XXX
} catch (InvalidMessageException e) {
Log.w("SessionRecordV2", e);
}
}
}
}
| true | true | public MessageKeys removeMessageKeys(ECPublicKey senderEphemeral, int counter) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first;
if (chain == null) {
return null;
}
List<Chain.MessageKey> messageKeyList = chain.getMessageKeysList();
Iterator<Chain.MessageKey> messageKeyIterator = messageKeyList.iterator();
MessageKeys result = null;
while (messageKeyIterator.hasNext()) {
Chain.MessageKey messageKey = messageKeyIterator.next();
if (messageKey.getIndex() == counter) {
result = new MessageKeys(new SecretKeySpec(messageKey.getCipherKey().toByteArray(), "AES"),
new SecretKeySpec(messageKey.getMacKey().toByteArray(), "HmacSHA256"),
messageKey.getIndex());
messageKeyIterator.remove();
break;
}
}
Chain updatedChain = chain.toBuilder().clearMessageKeys()
.addAllMessageKeys(messageKeyList)
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setReceiverChains(chainAndIndex.second, updatedChain)
.build();
return result;
}
| public MessageKeys removeMessageKeys(ECPublicKey senderEphemeral, int counter) {
Pair<Chain,Integer> chainAndIndex = getReceiverChain(senderEphemeral);
Chain chain = chainAndIndex.first;
if (chain == null) {
return null;
}
List<Chain.MessageKey> messageKeyList = new LinkedList<Chain.MessageKey>(chain.getMessageKeysList());
Iterator<Chain.MessageKey> messageKeyIterator = messageKeyList.iterator();
MessageKeys result = null;
while (messageKeyIterator.hasNext()) {
Chain.MessageKey messageKey = messageKeyIterator.next();
if (messageKey.getIndex() == counter) {
result = new MessageKeys(new SecretKeySpec(messageKey.getCipherKey().toByteArray(), "AES"),
new SecretKeySpec(messageKey.getMacKey().toByteArray(), "HmacSHA256"),
messageKey.getIndex());
messageKeyIterator.remove();
break;
}
}
Chain updatedChain = chain.toBuilder().clearMessageKeys()
.addAllMessageKeys(messageKeyList)
.build();
this.sessionStructure = this.sessionStructure.toBuilder()
.setReceiverChains(chainAndIndex.second, updatedChain)
.build();
return result;
}
|
diff --git a/Osm2GpsMid/FBrowser/de/ueller/osm/fBrowser/SingleTile.java b/Osm2GpsMid/FBrowser/de/ueller/osm/fBrowser/SingleTile.java
index e4232a6b..15fbcfc2 100644
--- a/Osm2GpsMid/FBrowser/de/ueller/osm/fBrowser/SingleTile.java
+++ b/Osm2GpsMid/FBrowser/de/ueller/osm/fBrowser/SingleTile.java
@@ -1,168 +1,168 @@
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* Copyright (c) 2008 Kai Krueger apm at users dot sourceforge dot net
* See Copying
*/
package de.ueller.osm.fBrowser;
import java.awt.Graphics;
import java.awt.Point;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.tree.TreeNode;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import de.ueller.osmToGpsMid.Constants;
public class SingleTile extends Tile{
public static final byte STATE_NOTLOAD = 0;
public static final byte STATE_LOADSTARTED = 1;
public static final byte STATE_LOADREADY = 2;
private static final byte STATE_CLEANUP = 3;
// Node[] nodes;
public short[] nodeLat;
public short[] nodeLon;
public int[] nameIdx;
public byte[] type;
// Way[][] ways;
// byte state = 0;
//
// boolean abortPainting = false;
public final byte zl;
private final String root;
SingleTile(DataInputStream dis, int deep, byte zl,String root) throws IOException {
// logger.debug("load " + deep + ":ST Nr=" + fileId);
this.zl = zl;
this.root = root;
minLat = dis.readFloat();
minLon = dis.readFloat();
maxLat = dis.readFloat();
maxLon = dis.readFloat();
fileId = (short) dis.readInt();
readContent();
// logger.debug("ready " + deep + ":ST Nr=" + fileId);
}
private void readContent() throws IOException{
String fn = root+"/t" + zl + fileId + ".d";
System.out.println("read " + fn);
FileInputStream f=new FileInputStream(fn);
DataInputStream ds = new DataInputStream(f);
if (ds.readByte()!=0x54) {
throw new IOException("not a MapMid-file");
}
centerLat = ds.readFloat();
centerLon = ds.readFloat();
int nodeCount=ds.readShort();
short[] radlat = new short[nodeCount];
short[] radlon = new short[nodeCount];
int iNodeCount=ds.readShort();
System.out.println("nodes total: " + nodeCount + " interestNode: " + iNodeCount);
int[] nameIdx=new int[iNodeCount];
for (int i = 0; i < iNodeCount; i++) {
nameIdx[i] = -1;
}
byte[] type = new byte[iNodeCount];
for (int i=0; i< nodeCount;i++){
// System.out.println("read coord :"+i+"("+nodeCount+")"+"("+iNodeCount+")");
byte flag = ds.readByte();
radlat[i] = ds.readShort();
radlon[i] = ds.readShort();
- if (i < iNodeCount){
+// if (i < iNodeCount){
if ((flag & Constants.NODE_MASK_NAME) > 0){
if ((flag & Constants.NODE_MASK_NAMEHIGH) > 0) {
nameIdx[i]=ds.readInt();
} else {
nameIdx[i]=ds.readShort();
}
type[i]=ds.readByte();
}
- }
+// }
}
nodeLat=radlat;
nodeLon=radlon;
}
public String toString() {
return "Map " + zl + "-" + fileId;
}
/* (non-Javadoc)
* @see javax.swing.tree.TreeNode#getChildCount()
*/
@Override
public int getChildCount() {
return 0;
}
/* (non-Javadoc)
* @see javax.swing.tree.TreeNode#getChildAt(int)
*/
@Override
public TreeNode getChildAt(int childIndex) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.openstreetmap.gui.jmapviewer.interfaces.MapMarkerArea#getLat()
*/
@Override
public double getLat() {
return (minLat+maxLat)/2*f;
}
/* (non-Javadoc)
* @see org.openstreetmap.gui.jmapviewer.interfaces.MapMarkerArea#getLon()
*/
@Override
public double getLon() {
return (minLon+maxLon)/2*f;
}
/* (non-Javadoc)
* @see org.openstreetmap.gui.jmapviewer.interfaces.MapMarkerArea#paint(java.awt.Graphics, org.openstreetmap.gui.jmapviewer.JMapViewer)
*/
@Override
public void paint(Graphics g, JMapViewer map) {
System.out.println("draw "+this);
for (int i=0;i<nodeLat.length;i++){
float x = centerLat+nodeLat[i]*FIXPT_MULT_INV;
float y = centerLon+nodeLon[i]*FIXPT_MULT_INV;
// System.out.println("draw " + i + " "+ x + "/" + y);
Point tl = map.getMapPosition(x*f, y*f, false);
g.fillOval(tl.x - 2, tl.y - 2, 5, 5);
}
}
}
| false | true | private void readContent() throws IOException{
String fn = root+"/t" + zl + fileId + ".d";
System.out.println("read " + fn);
FileInputStream f=new FileInputStream(fn);
DataInputStream ds = new DataInputStream(f);
if (ds.readByte()!=0x54) {
throw new IOException("not a MapMid-file");
}
centerLat = ds.readFloat();
centerLon = ds.readFloat();
int nodeCount=ds.readShort();
short[] radlat = new short[nodeCount];
short[] radlon = new short[nodeCount];
int iNodeCount=ds.readShort();
System.out.println("nodes total: " + nodeCount + " interestNode: " + iNodeCount);
int[] nameIdx=new int[iNodeCount];
for (int i = 0; i < iNodeCount; i++) {
nameIdx[i] = -1;
}
byte[] type = new byte[iNodeCount];
for (int i=0; i< nodeCount;i++){
// System.out.println("read coord :"+i+"("+nodeCount+")"+"("+iNodeCount+")");
byte flag = ds.readByte();
radlat[i] = ds.readShort();
radlon[i] = ds.readShort();
if (i < iNodeCount){
if ((flag & Constants.NODE_MASK_NAME) > 0){
if ((flag & Constants.NODE_MASK_NAMEHIGH) > 0) {
nameIdx[i]=ds.readInt();
} else {
nameIdx[i]=ds.readShort();
}
type[i]=ds.readByte();
}
}
}
nodeLat=radlat;
nodeLon=radlon;
}
| private void readContent() throws IOException{
String fn = root+"/t" + zl + fileId + ".d";
System.out.println("read " + fn);
FileInputStream f=new FileInputStream(fn);
DataInputStream ds = new DataInputStream(f);
if (ds.readByte()!=0x54) {
throw new IOException("not a MapMid-file");
}
centerLat = ds.readFloat();
centerLon = ds.readFloat();
int nodeCount=ds.readShort();
short[] radlat = new short[nodeCount];
short[] radlon = new short[nodeCount];
int iNodeCount=ds.readShort();
System.out.println("nodes total: " + nodeCount + " interestNode: " + iNodeCount);
int[] nameIdx=new int[iNodeCount];
for (int i = 0; i < iNodeCount; i++) {
nameIdx[i] = -1;
}
byte[] type = new byte[iNodeCount];
for (int i=0; i< nodeCount;i++){
// System.out.println("read coord :"+i+"("+nodeCount+")"+"("+iNodeCount+")");
byte flag = ds.readByte();
radlat[i] = ds.readShort();
radlon[i] = ds.readShort();
// if (i < iNodeCount){
if ((flag & Constants.NODE_MASK_NAME) > 0){
if ((flag & Constants.NODE_MASK_NAMEHIGH) > 0) {
nameIdx[i]=ds.readInt();
} else {
nameIdx[i]=ds.readShort();
}
type[i]=ds.readByte();
}
// }
}
nodeLat=radlat;
nodeLon=radlon;
}
|
diff --git a/js/src/main/java/org/obiba/magma/js/methods/TextMethods.java b/js/src/main/java/org/obiba/magma/js/methods/TextMethods.java
index e1d9fdf1..9dbdbac2 100644
--- a/js/src/main/java/org/obiba/magma/js/methods/TextMethods.java
+++ b/js/src/main/java/org/obiba/magma/js/methods/TextMethods.java
@@ -1,203 +1,205 @@
package org.obiba.magma.js.methods;
import java.util.ArrayList;
import java.util.List;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.RegExpProxy;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.obiba.magma.Value;
import org.obiba.magma.ValueType;
import org.obiba.magma.js.MagmaJsEvaluationRuntimeException;
import org.obiba.magma.js.ScriptableValue;
import org.obiba.magma.type.BooleanType;
import org.obiba.magma.type.TextType;
/**
* Methods of the {@code ScriptableValue} javascript class that returns {@code ScriptableValue} of {@code BooleanType}
*/
public class TextMethods {
/**
* <pre>
* $('TextVar').trim()
* </pre>
*/
public static ScriptableValue trim(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
ScriptableValue sv = (ScriptableValue) thisObj;
if(sv.getValue().isNull()) {
return new ScriptableValue(thisObj, TextType.get().nullValue());
}
String stringValue = sv.getValue().toString();
return new ScriptableValue(thisObj, TextType.get().valueOf(stringValue.trim()));
}
/**
* <pre>
* $('TextVar').replace('regex', '$1')
* </pre>
* @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace
*/
public static ScriptableValue replace(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
ScriptableValue sv = (ScriptableValue) thisObj;
if(sv.getValue().isNull()) {
return new ScriptableValue(thisObj, TextType.get().nullValue());
}
String stringValue = sv.getValue().toString();
// Delegate to Javascript's String.replace method
String result = (String) ScriptRuntime.checkRegExpProxy(ctx).action(ctx, thisObj, ScriptRuntime.toObject(ctx, thisObj, stringValue), args, RegExpProxy.RA_REPLACE);
return new ScriptableValue(thisObj, TextType.get().valueOf(result));
}
/**
* <pre>
* $('TextVar').matches('regex1', 'regex2', ...)
* </pre>
*/
public static ScriptableValue matches(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
ScriptableValue sv = (ScriptableValue) thisObj;
if(sv.getValue().isNull()) {
return new ScriptableValue(thisObj, TextType.get().nullValue());
}
String stringValue = sv.getValue().toString();
// Delegate to Javascript's String.replace method
boolean matches = false;
for(Object arg : args) {
Object result = ScriptRuntime.checkRegExpProxy(ctx).action(ctx, thisObj, ScriptRuntime.toObject(ctx, thisObj, stringValue), new Object[] { arg }, RegExpProxy.RA_MATCH);
if(result != null) {
matches = true;
}
}
return new ScriptableValue(thisObj, BooleanType.get().valueOf(matches));
}
/**
* Returns a new {@link ScriptableValue} of {@link TextType} combining the String value of this value with the String
* values of the parameters parameters.
*
* <pre>
* $('TextVar').concat($('TextVar'))
* $('Var').concat($('Var'))
* $('Var').concat('SomeValue')
* </pre>
*/
public static ScriptableValue concat(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
ScriptableValue sv = (ScriptableValue) thisObj;
StringBuilder sb = new StringBuilder();
sb.append(sv.toString());
if(args != null) {
for(Object arg : args) {
if(arg instanceof ScriptableValue) {
arg = arg.toString();
}
sb.append(arg);
}
}
return new ScriptableValue(thisObj, TextType.get().valueOf(sb.toString()));
}
/**
* Categorise values of a variable. That is, lookup the current value in an association table and return the
* associated value. When the current value is not found in the association table, the method returns a null value.
*
* <pre>
* $('SMOKE').map({'NO':0, 'YES':1, 'DNK':8888, 'PNA':9999})
*
* $('SMOKE_ONSET').map(
* {'AGE':$('SMOKE_ONSET_AGE'),
* 'YEAR':$('SMOKE_ONSET_YEAR').minus($('BIRTH_DATE').year()),
* 'DNK':8888,
* 'PNA':9999})
*
* // Works for sequences also (FRENCH,ENGLISH --> 0,1)
* $('LANGUAGES_SPOKEN').map({'FRENCH':0, 'ENGLISH':1});
*
* // Can execute function to calculate lookup value
* $('BMI_DIAG').map(
* {'OVERW': function(value) {
* // 'OVERW' is passed in as the method's parameter
* var computedValue = 2*2; // some complex computation...
* return comuptedValue;
* },
* 'NORMW': 0
* }
* </pre>
* @param ctx
* @param thisObj
* @param args
* @param funObj
* @return
*/
public static ScriptableValue map(Context ctx, Scriptable thisObj, Object[] args, Function funObj) {
if(args == null || args.length < 1 || args[0] instanceof NativeObject == false) {
throw new MagmaJsEvaluationRuntimeException("illegal arguments to map()");
}
ScriptableValue sv = (ScriptableValue) thisObj;
NativeObject valueMap = (NativeObject) args[0];
// This could be determined by looking at the mapped values (if all ints, then 'integer', else 'text', etc.)
ValueType returnType = TextType.get();
Value currentValue = sv.getValue();
if(currentValue.isSequence()) {
List<Value> newValues = new ArrayList<Value>();
for(Value value : currentValue.asSequence().getValue()) {
newValues.add(lookupValue(ctx, thisObj, value, returnType, valueMap));
}
return new ScriptableValue(thisObj, returnType.sequenceOf(newValues));
} else {
return new ScriptableValue(thisObj, returnType.valueOf(lookupValue(ctx, thisObj, currentValue, returnType, valueMap)));
}
}
/**
* Lookup {@code value} in {@code valueMap} and return the mapped value of type {@code returnType}
*
* @param ctx
* @param thisObj
* @param value
* @param returnType
* @param valueMap
* @return
*/
private static Value lookupValue(Context ctx, Scriptable thisObj, Value value, ValueType returnType, NativeObject valueMap) {
Object newValue = null;
if(value.getValueType().isNumeric()) {
newValue = valueMap.get(((Number) value.getValue()).intValue(), null);
} else {
newValue = valueMap.get((String) value.toString(), null);
}
if(newValue == null || newValue == NativeObject.NOT_FOUND) {
return returnType.nullValue();
}
if(newValue instanceof Function) {
Function valueFunction = (Function) newValue;
Object evaluatedValue = valueFunction.call(ctx, thisObj, thisObj, new Object[] { new ScriptableValue(thisObj, value) });
if(evaluatedValue instanceof ScriptableValue) {
newValue = ((ScriptableValue) evaluatedValue).getValue().getValue();
} else {
newValue = evaluatedValue;
}
} else if(newValue instanceof Double) {
// HACK: for rhino bug 448499: https://bugzilla.mozilla.org/show_bug.cgi?id=448499
if(((Double) newValue).doubleValue() == 1.0d) {
newValue = (int) 1;
+ } else if(((Double) newValue).doubleValue() == 0.0d) {
+ newValue = (int) 0;
}
}
return returnType.valueOf(newValue);
}
}
| true | true | private static Value lookupValue(Context ctx, Scriptable thisObj, Value value, ValueType returnType, NativeObject valueMap) {
Object newValue = null;
if(value.getValueType().isNumeric()) {
newValue = valueMap.get(((Number) value.getValue()).intValue(), null);
} else {
newValue = valueMap.get((String) value.toString(), null);
}
if(newValue == null || newValue == NativeObject.NOT_FOUND) {
return returnType.nullValue();
}
if(newValue instanceof Function) {
Function valueFunction = (Function) newValue;
Object evaluatedValue = valueFunction.call(ctx, thisObj, thisObj, new Object[] { new ScriptableValue(thisObj, value) });
if(evaluatedValue instanceof ScriptableValue) {
newValue = ((ScriptableValue) evaluatedValue).getValue().getValue();
} else {
newValue = evaluatedValue;
}
} else if(newValue instanceof Double) {
// HACK: for rhino bug 448499: https://bugzilla.mozilla.org/show_bug.cgi?id=448499
if(((Double) newValue).doubleValue() == 1.0d) {
newValue = (int) 1;
}
}
return returnType.valueOf(newValue);
}
| private static Value lookupValue(Context ctx, Scriptable thisObj, Value value, ValueType returnType, NativeObject valueMap) {
Object newValue = null;
if(value.getValueType().isNumeric()) {
newValue = valueMap.get(((Number) value.getValue()).intValue(), null);
} else {
newValue = valueMap.get((String) value.toString(), null);
}
if(newValue == null || newValue == NativeObject.NOT_FOUND) {
return returnType.nullValue();
}
if(newValue instanceof Function) {
Function valueFunction = (Function) newValue;
Object evaluatedValue = valueFunction.call(ctx, thisObj, thisObj, new Object[] { new ScriptableValue(thisObj, value) });
if(evaluatedValue instanceof ScriptableValue) {
newValue = ((ScriptableValue) evaluatedValue).getValue().getValue();
} else {
newValue = evaluatedValue;
}
} else if(newValue instanceof Double) {
// HACK: for rhino bug 448499: https://bugzilla.mozilla.org/show_bug.cgi?id=448499
if(((Double) newValue).doubleValue() == 1.0d) {
newValue = (int) 1;
} else if(((Double) newValue).doubleValue() == 0.0d) {
newValue = (int) 0;
}
}
return returnType.valueOf(newValue);
}
|
diff --git a/bpel-compiler/src/test/java/org/apache/ode/bpel/compiler_2_0/GoodCompileTest.java b/bpel-compiler/src/test/java/org/apache/ode/bpel/compiler_2_0/GoodCompileTest.java
index ae183b82..83417409 100644
--- a/bpel-compiler/src/test/java/org/apache/ode/bpel/compiler_2_0/GoodCompileTest.java
+++ b/bpel-compiler/src/test/java/org/apache/ode/bpel/compiler_2_0/GoodCompileTest.java
@@ -1,81 +1,81 @@
/*
* 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.ode.bpel.compiler_2_0;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* A series of BPEL 2.0 compilation test.
*/
public class GoodCompileTest extends TestCase {
public static Test suite() throws Exception {
TestSuite suite = new TestSuite();
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign8-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign9-2.0.bpel"));
- // suite.addTest(new GoodCompileTCase("/2.0/good/AsyncProcess/AsyncProcess2.bpel"));
+ suite.addTest(new GoodCompileTCase("/2.0/good/AsyncProcess/AsyncProcess2.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/compensation/comp1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/compensation/comp2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/rethrow/Rethrow1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/rethrow/Rethrow2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/wait/Wait1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/wait/Wait2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/while/While1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableProperty1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData1-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData2-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData3-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData4-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableProperty1-xp2.0.bpel"));
return suite;
}
}
| true | true | public static Test suite() throws Exception {
TestSuite suite = new TestSuite();
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign8-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign9-2.0.bpel"));
// suite.addTest(new GoodCompileTCase("/2.0/good/AsyncProcess/AsyncProcess2.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/compensation/comp1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/compensation/comp2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/rethrow/Rethrow1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/rethrow/Rethrow2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/wait/Wait1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/wait/Wait2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/while/While1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableProperty1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData1-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData2-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData3-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData4-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableProperty1-xp2.0.bpel"));
return suite;
}
| public static Test suite() throws Exception {
TestSuite suite = new TestSuite();
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign8-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/assign/Assign9-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/AsyncProcess/AsyncProcess2.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/compensation/comp1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/compensation/comp2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/flow/flow7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/if/If3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/pick/Pick6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/rethrow/Rethrow1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/rethrow/Rethrow2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw5-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw6-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/throw/Throw7-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/wait/Wait1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/wait/Wait2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/while/While1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData2-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData3-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableData4-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath10-func/GetVariableProperty1-2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData1-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData2-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData3-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableData4-xp2.0.bpel"));
suite.addTest(new GoodCompileTCase("/2.0/good/xpath20-func/GetVariableProperty1-xp2.0.bpel"));
return suite;
}
|
diff --git a/src/com/zemariamm/appirater/AppirateUtils.java b/src/com/zemariamm/appirater/AppirateUtils.java
index 916ec67..9f185d9 100644
--- a/src/com/zemariamm/appirater/AppirateUtils.java
+++ b/src/com/zemariamm/appirater/AppirateUtils.java
@@ -1,123 +1,123 @@
package com.zemariamm.appirater;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class AppirateUtils {
public static final int SHOW_APPIRATER = 4;
public static final String DB_PREFERENCES="DB_APPIRATER";
private static SharedPreferences getPreferences(Context context) {
int mode = Activity.MODE_PRIVATE;
return context.getSharedPreferences(DB_PREFERENCES, mode);
}
private static boolean isNeverShowAppirater(Context context){
SharedPreferences prefs = AppirateUtils.getPreferences(context);
return prefs.getBoolean("neverrate", false);
}
public static void markNeverRate(Context context) {
SharedPreferences.Editor editor = AppirateUtils.getPreferences(context).edit();
editor.putBoolean("neverrate", true);
editor.commit();
}
private static int getTimesOpened(Context context)
{
SharedPreferences prefs = AppirateUtils.getPreferences(context);
int times = prefs.getInt("times", 0);
times++;
//Log.d("Hooligans AppiraterUtils"," ******************************************* Current number: " + times);
SharedPreferences.Editor editor = AppirateUtils.getPreferences(context).edit();
editor.putInt("times", times);
editor.commit();
return times;
}
private static int getShowAppirater(Context context) {
int default_times = AppirateUtils.SHOW_APPIRATER;
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
Bundle aBundle=ai.metaData;
default_times = aBundle.getInt("appirater");
// no divide by zero!
if (default_times == 0)
default_times = AppirateUtils.SHOW_APPIRATER;
}
catch (Exception e) {
e.printStackTrace();
}
return default_times;
}
public static boolean shouldAppirater(Context context) {
int times = AppirateUtils.getTimesOpened(context);
boolean shouldShow = false;
if (times % getShowAppirater(context) == 0)
{
shouldShow = true;
}
if (AppirateUtils.isNeverShowAppirater(context))
{
//Log.d("Hooligans AppiraterUtils"," ******************************************* He once clicked NEVER RATE THIS APP or ALREADY Rated it");
shouldShow = false;
}
return shouldShow;
}
public static void appiraterDialog(final Context context,final AppiraterBase parent) {
AlertDialog.Builder builderInvite = new AlertDialog.Builder(context);
//String appName = context.getResources().getString(R.string.app_name);
String packageName = "";
String appName = "" ;
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
packageName = info.packageName;
appName = context.getResources().getString(info.applicationInfo.labelRes);
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("Appirater","PackageName: " + packageName);
final String marketLink = "market://details?id=" + packageName;
- String title = context.getString(R.string.appirate_utils_message_before_appname) + appName + context.getString(R.string.appirate_utils_message_after_appname);
+ String title = context.getString(R.string.appirate_utils_message_before_appname) + " " + appName + context.getString(R.string.appirate_utils_message_after_appname);
builderInvite.setMessage(title);
builderInvite.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parent.processRate();
AppirateUtils.markNeverRate(context);
Uri uri = Uri.parse(marketLink);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
dialog.dismiss();
}
}).setNeutralButton("Remind me later", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
parent.processRemindMe();
dialog.dismiss();
}
}).setNegativeButton("No, Thanks", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AppirateUtils.markNeverRate(context);
parent.processNever();
dialog.cancel();
}
});
builderInvite.create().show();
}
}
| true | true | public static void appiraterDialog(final Context context,final AppiraterBase parent) {
AlertDialog.Builder builderInvite = new AlertDialog.Builder(context);
//String appName = context.getResources().getString(R.string.app_name);
String packageName = "";
String appName = "" ;
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
packageName = info.packageName;
appName = context.getResources().getString(info.applicationInfo.labelRes);
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("Appirater","PackageName: " + packageName);
final String marketLink = "market://details?id=" + packageName;
String title = context.getString(R.string.appirate_utils_message_before_appname) + appName + context.getString(R.string.appirate_utils_message_after_appname);
builderInvite.setMessage(title);
builderInvite.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parent.processRate();
AppirateUtils.markNeverRate(context);
Uri uri = Uri.parse(marketLink);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
dialog.dismiss();
}
}).setNeutralButton("Remind me later", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
parent.processRemindMe();
dialog.dismiss();
}
}).setNegativeButton("No, Thanks", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AppirateUtils.markNeverRate(context);
parent.processNever();
dialog.cancel();
}
});
builderInvite.create().show();
}
| public static void appiraterDialog(final Context context,final AppiraterBase parent) {
AlertDialog.Builder builderInvite = new AlertDialog.Builder(context);
//String appName = context.getResources().getString(R.string.app_name);
String packageName = "";
String appName = "" ;
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
packageName = info.packageName;
appName = context.getResources().getString(info.applicationInfo.labelRes);
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("Appirater","PackageName: " + packageName);
final String marketLink = "market://details?id=" + packageName;
String title = context.getString(R.string.appirate_utils_message_before_appname) + " " + appName + context.getString(R.string.appirate_utils_message_after_appname);
builderInvite.setMessage(title);
builderInvite.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
parent.processRate();
AppirateUtils.markNeverRate(context);
Uri uri = Uri.parse(marketLink);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
dialog.dismiss();
}
}).setNeutralButton("Remind me later", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
parent.processRemindMe();
dialog.dismiss();
}
}).setNegativeButton("No, Thanks", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AppirateUtils.markNeverRate(context);
parent.processNever();
dialog.cancel();
}
});
builderInvite.create().show();
}
|
diff --git a/src/java/org/infoglue/cms/applications/structuretool/actions/CreatePageTemplateAction.java b/src/java/org/infoglue/cms/applications/structuretool/actions/CreatePageTemplateAction.java
index 0e402e8a9..8250cd85f 100755
--- a/src/java/org/infoglue/cms/applications/structuretool/actions/CreatePageTemplateAction.java
+++ b/src/java/org/infoglue/cms/applications/structuretool/actions/CreatePageTemplateAction.java
@@ -1,311 +1,313 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* 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. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including 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 org.infoglue.cms.applications.structuretool.actions;
import org.infoglue.cms.entities.content.ContentVO;
import org.infoglue.cms.entities.content.ContentVersionVO;
import org.infoglue.cms.entities.content.DigitalAssetVO;
import org.infoglue.cms.entities.management.ContentTypeDefinitionVO;
import org.infoglue.cms.entities.management.RepositoryVO;
import org.infoglue.cms.exception.Bug;
import org.infoglue.cms.exception.ConstraintException;
import org.infoglue.cms.exception.SystemException;
import org.infoglue.cms.applications.common.VisualFormatter;
import org.infoglue.cms.applications.common.actions.InfoGlueAbstractAction;
import org.infoglue.cms.applications.contenttool.actions.ViewContentTreeActionInterface;
import org.infoglue.cms.util.CmsPropertyHandler;
import org.infoglue.cms.util.ConstraintExceptionBuffer;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentController;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentControllerProxy;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController;
import org.infoglue.cms.controllers.kernel.impl.simple.DigitalAssetController;
import org.infoglue.cms.controllers.kernel.impl.simple.LanguageController;
import org.infoglue.cms.controllers.kernel.impl.simple.RepositoryController;
import org.infoglue.cms.util.CmsLogger;
import webwork.action.Action;
import webwork.action.ActionContext;
import webwork.multipart.MultiPartRequestWrapper;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
/**
* This action represents the CreatePageTemplate Usecase.
*/
public class CreatePageTemplateAction extends InfoGlueAbstractAction implements ViewContentTreeActionInterface
{
//Used by the tree only
private List repositories;
private Integer contentId;
private String tree;
private String hideLeafs;
private Integer parentContentId;
private Integer repositoryId;
private ConstraintExceptionBuffer ceb;
private Integer siteNodeId;
private String name;
private String returnAddress;
public String doInput() throws Exception
{
this.repositories = RepositoryController.getController().getAuthorizedRepositoryVOList(this.getInfoGluePrincipal());
return Action.INPUT;
}
public String doExecute() throws Exception
{
CmsLogger.logInfo("contentId:" + contentId);
CmsLogger.logInfo("parentContentId:" + parentContentId);
CmsLogger.logInfo("repositoryId:" + repositoryId);
CmsLogger.logInfo("siteNodeId:" + siteNodeId);
CmsLogger.logInfo("name:" + name);
ContentTypeDefinitionVO contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName("PageTemplate");
+ if(contentTypeDefinitionVO == null)
+ throw new SystemException("The system does not have the content type named 'PageTemplate' which is required for this operation.");
ContentVO contentVO = new ContentVO();
contentVO.setCreatorName(this.getInfoGluePrincipal().getName());
contentVO.setIsBranch(new Boolean(false));
contentVO.setName(name);
contentVO.setRepositoryId(this.repositoryId);
contentVO = ContentControllerProxy.getController().create(parentContentId, contentTypeDefinitionVO.getId(), this.repositoryId, contentVO);
String componentStructure = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><components></components>";
ContentVO metaInfoContentVO = ContentController.getContentController().getContentVOWithId(this.contentId);
Integer originalMetaInfoMasterLanguageId = LanguageController.getController().getMasterLanguage(metaInfoContentVO.getRepositoryId()).getId();
Integer destinationMasterLanguageId = LanguageController.getController().getMasterLanguage(this.repositoryId).getId();
ContentVersionVO originalContentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(this.contentId, originalMetaInfoMasterLanguageId);
CmsLogger.logInfo("originalMetaInfoMasterLanguageId:" + originalMetaInfoMasterLanguageId);
CmsLogger.logInfo("contentId:" + contentId);
CmsLogger.logInfo("originalContentVersionVO:" + originalContentVersionVO);
componentStructure = ContentVersionController.getContentVersionController().getAttributeValue(originalContentVersionVO.getId(), "ComponentStructure", false);
CmsLogger.logInfo("componentStructure:" + componentStructure);
//Create initial content version also... in masterlanguage
String versionValue = "<?xml version='1.0' encoding='UTF-8'?><article xmlns=\"x-schema:ArticleSchema.xml\"><attributes><Name><![CDATA[" + this.name + "]]></Name><ComponentStructure><![CDATA[" + componentStructure + "]]></ComponentStructure></attributes></article>";
ContentVersionVO contentVersionVO = new ContentVersionVO();
contentVersionVO.setVersionComment("Saved page template");
contentVersionVO.setVersionModifier(this.getInfoGluePrincipal().getName());
contentVersionVO.setVersionValue(versionValue);
ContentVersionVO newContentVersion = ContentVersionController.getContentVersionController().create(contentVO.getId(), destinationMasterLanguageId, contentVersionVO, null);
InputStream is = null;
File file = null;
try
{
MultiPartRequestWrapper mpr = ActionContext.getContext().getMultiPartRequest();
CmsLogger.logInfo("mpr:" + mpr);
if(mpr != null)
{
Enumeration names = mpr.getFileNames();
while (names.hasMoreElements())
{
String name = (String)names.nextElement();
String contentType = mpr.getContentType(name);
String fileSystemName = mpr.getFilesystemName(name);
CmsLogger.logInfo("name:" + name);
CmsLogger.logInfo("contentType:" + contentType);
CmsLogger.logInfo("fileSystemName:" + fileSystemName);
file = mpr.getFile(name);
String fileName = fileSystemName;
fileName = new VisualFormatter().replaceNonAscii(fileName, '_');
String tempFileName = "tmp_" + System.currentTimeMillis() + "_" + fileName;
String filePath = CmsPropertyHandler.getProperty("digitalAssetPath");
fileSystemName = filePath + File.separator + tempFileName;
DigitalAssetVO newAsset = new DigitalAssetVO();
newAsset.setAssetContentType(contentType);
newAsset.setAssetKey("thumbnail");
newAsset.setAssetFileName(fileName);
newAsset.setAssetFilePath(filePath);
newAsset.setAssetFileSize(new Integer(new Long(file.length()).intValue()));
is = new FileInputStream(file);
DigitalAssetController.create(newAsset, is, newContentVersion.getContentVersionId());
}
}
else
{
CmsLogger.logSevere("File upload failed for some reason.");
}
}
catch (Exception e)
{
CmsLogger.logSevere("An error occurred when we tried to upload a new asset:" + e.getMessage(), e);
}
finally
{
try
{
is.close();
file.delete();
}
catch(Exception e){}
}
return Action.SUCCESS;
}
public Integer getTopRepositoryId() throws ConstraintException, SystemException, Bug
{
List repositories = RepositoryController.getController().getAuthorizedRepositoryVOList(this.getInfoGluePrincipal());
Integer topRepositoryId = null;
if (repositoryId != null)
topRepositoryId = repositoryId;
if(repositories.size() > 0)
{
topRepositoryId = ((RepositoryVO)repositories.get(0)).getRepositoryId();
}
return topRepositoryId;
}
public void setHideLeafs(String hideLeafs)
{
this.hideLeafs = hideLeafs;
}
public String getHideLeafs()
{
return this.hideLeafs;
}
public String getTree()
{
return tree;
}
public void setTree(String tree)
{
this.tree = tree;
}
public void setParentContentId(Integer parentContentId)
{
this.parentContentId = parentContentId;
}
public Integer getParentContentId()
{
return this.parentContentId;
}
public List getRepositories()
{
return this.repositories;
}
public void setRepositoryId(Integer repositoryId)
{
this.repositoryId = repositoryId;
}
public Integer getRepositoryId()
{
try
{
if(this.repositoryId == null)
{
this.repositoryId = (Integer)getHttpSession().getAttribute("repositoryId");
if(this.repositoryId == null)
{
this.repositoryId = getTopRepositoryId();
getHttpSession().setAttribute("repositoryId", this.repositoryId);
}
}
}
catch(Exception e)
{
}
return repositoryId;
}
public void setContentId(Integer contentId)
{
this.contentId = contentId;
}
public Integer getContentId()
{
return this.contentId;
}
public String getReturnAddress()
{
return returnAddress;
}
public void setReturnAddress(String string)
{
returnAddress = string;
}
public Integer getSiteNodeId()
{
return siteNodeId;
}
public void setSiteNodeId(Integer siteNodeId)
{
this.siteNodeId = siteNodeId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
| true | true | public String doExecute() throws Exception
{
CmsLogger.logInfo("contentId:" + contentId);
CmsLogger.logInfo("parentContentId:" + parentContentId);
CmsLogger.logInfo("repositoryId:" + repositoryId);
CmsLogger.logInfo("siteNodeId:" + siteNodeId);
CmsLogger.logInfo("name:" + name);
ContentTypeDefinitionVO contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName("PageTemplate");
ContentVO contentVO = new ContentVO();
contentVO.setCreatorName(this.getInfoGluePrincipal().getName());
contentVO.setIsBranch(new Boolean(false));
contentVO.setName(name);
contentVO.setRepositoryId(this.repositoryId);
contentVO = ContentControllerProxy.getController().create(parentContentId, contentTypeDefinitionVO.getId(), this.repositoryId, contentVO);
String componentStructure = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><components></components>";
ContentVO metaInfoContentVO = ContentController.getContentController().getContentVOWithId(this.contentId);
Integer originalMetaInfoMasterLanguageId = LanguageController.getController().getMasterLanguage(metaInfoContentVO.getRepositoryId()).getId();
Integer destinationMasterLanguageId = LanguageController.getController().getMasterLanguage(this.repositoryId).getId();
ContentVersionVO originalContentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(this.contentId, originalMetaInfoMasterLanguageId);
CmsLogger.logInfo("originalMetaInfoMasterLanguageId:" + originalMetaInfoMasterLanguageId);
CmsLogger.logInfo("contentId:" + contentId);
CmsLogger.logInfo("originalContentVersionVO:" + originalContentVersionVO);
componentStructure = ContentVersionController.getContentVersionController().getAttributeValue(originalContentVersionVO.getId(), "ComponentStructure", false);
CmsLogger.logInfo("componentStructure:" + componentStructure);
//Create initial content version also... in masterlanguage
String versionValue = "<?xml version='1.0' encoding='UTF-8'?><article xmlns=\"x-schema:ArticleSchema.xml\"><attributes><Name><![CDATA[" + this.name + "]]></Name><ComponentStructure><![CDATA[" + componentStructure + "]]></ComponentStructure></attributes></article>";
ContentVersionVO contentVersionVO = new ContentVersionVO();
contentVersionVO.setVersionComment("Saved page template");
contentVersionVO.setVersionModifier(this.getInfoGluePrincipal().getName());
contentVersionVO.setVersionValue(versionValue);
ContentVersionVO newContentVersion = ContentVersionController.getContentVersionController().create(contentVO.getId(), destinationMasterLanguageId, contentVersionVO, null);
InputStream is = null;
File file = null;
try
{
MultiPartRequestWrapper mpr = ActionContext.getContext().getMultiPartRequest();
CmsLogger.logInfo("mpr:" + mpr);
if(mpr != null)
{
Enumeration names = mpr.getFileNames();
while (names.hasMoreElements())
{
String name = (String)names.nextElement();
String contentType = mpr.getContentType(name);
String fileSystemName = mpr.getFilesystemName(name);
CmsLogger.logInfo("name:" + name);
CmsLogger.logInfo("contentType:" + contentType);
CmsLogger.logInfo("fileSystemName:" + fileSystemName);
file = mpr.getFile(name);
String fileName = fileSystemName;
fileName = new VisualFormatter().replaceNonAscii(fileName, '_');
String tempFileName = "tmp_" + System.currentTimeMillis() + "_" + fileName;
String filePath = CmsPropertyHandler.getProperty("digitalAssetPath");
fileSystemName = filePath + File.separator + tempFileName;
DigitalAssetVO newAsset = new DigitalAssetVO();
newAsset.setAssetContentType(contentType);
newAsset.setAssetKey("thumbnail");
newAsset.setAssetFileName(fileName);
newAsset.setAssetFilePath(filePath);
newAsset.setAssetFileSize(new Integer(new Long(file.length()).intValue()));
is = new FileInputStream(file);
DigitalAssetController.create(newAsset, is, newContentVersion.getContentVersionId());
}
}
else
{
CmsLogger.logSevere("File upload failed for some reason.");
}
}
catch (Exception e)
{
CmsLogger.logSevere("An error occurred when we tried to upload a new asset:" + e.getMessage(), e);
}
finally
{
try
{
is.close();
file.delete();
}
catch(Exception e){}
}
return Action.SUCCESS;
}
| public String doExecute() throws Exception
{
CmsLogger.logInfo("contentId:" + contentId);
CmsLogger.logInfo("parentContentId:" + parentContentId);
CmsLogger.logInfo("repositoryId:" + repositoryId);
CmsLogger.logInfo("siteNodeId:" + siteNodeId);
CmsLogger.logInfo("name:" + name);
ContentTypeDefinitionVO contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName("PageTemplate");
if(contentTypeDefinitionVO == null)
throw new SystemException("The system does not have the content type named 'PageTemplate' which is required for this operation.");
ContentVO contentVO = new ContentVO();
contentVO.setCreatorName(this.getInfoGluePrincipal().getName());
contentVO.setIsBranch(new Boolean(false));
contentVO.setName(name);
contentVO.setRepositoryId(this.repositoryId);
contentVO = ContentControllerProxy.getController().create(parentContentId, contentTypeDefinitionVO.getId(), this.repositoryId, contentVO);
String componentStructure = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><components></components>";
ContentVO metaInfoContentVO = ContentController.getContentController().getContentVOWithId(this.contentId);
Integer originalMetaInfoMasterLanguageId = LanguageController.getController().getMasterLanguage(metaInfoContentVO.getRepositoryId()).getId();
Integer destinationMasterLanguageId = LanguageController.getController().getMasterLanguage(this.repositoryId).getId();
ContentVersionVO originalContentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(this.contentId, originalMetaInfoMasterLanguageId);
CmsLogger.logInfo("originalMetaInfoMasterLanguageId:" + originalMetaInfoMasterLanguageId);
CmsLogger.logInfo("contentId:" + contentId);
CmsLogger.logInfo("originalContentVersionVO:" + originalContentVersionVO);
componentStructure = ContentVersionController.getContentVersionController().getAttributeValue(originalContentVersionVO.getId(), "ComponentStructure", false);
CmsLogger.logInfo("componentStructure:" + componentStructure);
//Create initial content version also... in masterlanguage
String versionValue = "<?xml version='1.0' encoding='UTF-8'?><article xmlns=\"x-schema:ArticleSchema.xml\"><attributes><Name><![CDATA[" + this.name + "]]></Name><ComponentStructure><![CDATA[" + componentStructure + "]]></ComponentStructure></attributes></article>";
ContentVersionVO contentVersionVO = new ContentVersionVO();
contentVersionVO.setVersionComment("Saved page template");
contentVersionVO.setVersionModifier(this.getInfoGluePrincipal().getName());
contentVersionVO.setVersionValue(versionValue);
ContentVersionVO newContentVersion = ContentVersionController.getContentVersionController().create(contentVO.getId(), destinationMasterLanguageId, contentVersionVO, null);
InputStream is = null;
File file = null;
try
{
MultiPartRequestWrapper mpr = ActionContext.getContext().getMultiPartRequest();
CmsLogger.logInfo("mpr:" + mpr);
if(mpr != null)
{
Enumeration names = mpr.getFileNames();
while (names.hasMoreElements())
{
String name = (String)names.nextElement();
String contentType = mpr.getContentType(name);
String fileSystemName = mpr.getFilesystemName(name);
CmsLogger.logInfo("name:" + name);
CmsLogger.logInfo("contentType:" + contentType);
CmsLogger.logInfo("fileSystemName:" + fileSystemName);
file = mpr.getFile(name);
String fileName = fileSystemName;
fileName = new VisualFormatter().replaceNonAscii(fileName, '_');
String tempFileName = "tmp_" + System.currentTimeMillis() + "_" + fileName;
String filePath = CmsPropertyHandler.getProperty("digitalAssetPath");
fileSystemName = filePath + File.separator + tempFileName;
DigitalAssetVO newAsset = new DigitalAssetVO();
newAsset.setAssetContentType(contentType);
newAsset.setAssetKey("thumbnail");
newAsset.setAssetFileName(fileName);
newAsset.setAssetFilePath(filePath);
newAsset.setAssetFileSize(new Integer(new Long(file.length()).intValue()));
is = new FileInputStream(file);
DigitalAssetController.create(newAsset, is, newContentVersion.getContentVersionId());
}
}
else
{
CmsLogger.logSevere("File upload failed for some reason.");
}
}
catch (Exception e)
{
CmsLogger.logSevere("An error occurred when we tried to upload a new asset:" + e.getMessage(), e);
}
finally
{
try
{
is.close();
file.delete();
}
catch(Exception e){}
}
return Action.SUCCESS;
}
|
diff --git a/src/main/java/org/jbei/ice/web/utils/WebUtils.java b/src/main/java/org/jbei/ice/web/utils/WebUtils.java
index b061f4731..559b868a3 100644
--- a/src/main/java/org/jbei/ice/web/utils/WebUtils.java
+++ b/src/main/java/org/jbei/ice/web/utils/WebUtils.java
@@ -1,151 +1,163 @@
package org.jbei.ice.web.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.wicket.PageParameters;
import org.apache.wicket.protocol.http.WebRequestCycle;
import org.jbei.ice.lib.managers.EntryManager;
import org.jbei.ice.lib.managers.ManagerException;
import org.jbei.ice.lib.models.Entry;
import org.jbei.ice.web.pages.EntryViewPage;
public class WebUtils {
public static String makeEntryLink(JbeiLink jbeiLink) {
String result = null;
CharSequence relativePath = WebRequestCycle.get().urlFor(EntryViewPage.class,
new PageParameters());
int id = 0;
try {
// BUG fails on 4008!
Entry entry = EntryManager.getByPartNumber(jbeiLink.getPartNumber());
if (entry != null) {
id = entry.getId();
}
} catch (ManagerException e) {
e.printStackTrace();
}
String descriptiveLabel = "";
if (jbeiLink.getDescriptiveLabel() == null) {
} else if (jbeiLink.getDescriptiveLabel().equals("")) {
} else {
descriptiveLabel = jbeiLink.getDescriptiveLabel();
}
result = "<a href=" + relativePath + "/" + id + ">" + descriptiveLabel + "</a>";
return result;
}
public static String makeEntryLink(int id) {
String result = null;
CharSequence relativePath = WebRequestCycle.get().urlFor(EntryViewPage.class,
new PageParameters());
// TODO this is not very elegant at all. Is there a better way than to generate <a> tag manually?
try {
result = "<a href=" + relativePath.toString() + "/" + id + ">"
+ EntryManager.get(id).getOnePartNumber().getPartNumber() + "</a>";
} catch (ManagerException e) {
e.printStackTrace();
}
return result;
}
public static String parseJbeiLinks(String text) {
String result = null;
return result;
}
public static String makeEntryLinks(Collection<? extends Entry> entries) {
String result = "";
for (Entry entry : entries) {
result = result + makeEntryLink(entry.getId()) + " ";
}
return result;
}
public static String jbeiLinkifyText(String text) {
Pattern basicJbeiPattern = Pattern.compile("\\[\\[jbei:.*?\\]\\]");
Pattern partNumberPattern = Pattern.compile("\\[\\[jbei:(.*)\\]\\]");
Pattern descriptivePattern = Pattern.compile("\\[\\[jbei:(.*)\\|(.*)\\]\\]");
+ if (text == null) {
+ return text;
+ }
Matcher basicJbeiMatcher = basicJbeiPattern.matcher(text);
ArrayList<JbeiLink> jbeiLinks = new ArrayList<JbeiLink>();
ArrayList<Integer> starts = new ArrayList<Integer>();
ArrayList<Integer> ends = new ArrayList<Integer>();
while (basicJbeiMatcher.find()) {
String partNumber = null;
String descriptive = null;
Matcher partNumberMatcher = partNumberPattern.matcher(basicJbeiMatcher.group());
Matcher descriptivePatternMatcher = descriptivePattern
.matcher(basicJbeiMatcher.group());
if (descriptivePatternMatcher.find()) {
partNumber = descriptivePatternMatcher.group(1).trim();
descriptive = descriptivePatternMatcher.group(2).trim();
} else if (partNumberMatcher.find()) {
partNumber = partNumberMatcher.group(1).trim();
}
if (partNumber != null) {
- jbeiLinks.add(new JbeiLink(partNumber, descriptive));
- starts.add(basicJbeiMatcher.start());
- ends.add(basicJbeiMatcher.end());
+ Entry entry = null;
+ try {
+ entry = EntryManager.getByPartNumber(partNumber);
+ } catch (ManagerException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if (entry != null) {
+ jbeiLinks.add(new JbeiLink(partNumber, descriptive));
+ starts.add(basicJbeiMatcher.start());
+ ends.add(basicJbeiMatcher.end());
+ }
}
}
String newText = new String(text);
for (int i = jbeiLinks.size() - 1; i > -1; i = i - 1) {
String before = newText.substring(0, starts.get(i));
String after = newText.substring(ends.get(i));
newText = before + makeEntryLink(jbeiLinks.get(i)) + after;
}
return newText;
}
public static class JbeiLink {
private String descriptiveLabel = "";
private String partNumber = "";
public JbeiLink(String partNumber, String descriptiveLabel) {
this.partNumber = partNumber;
this.descriptiveLabel = descriptiveLabel;
}
public void setDescriptiveLabel(String descriptiveLabel) {
this.descriptiveLabel = descriptiveLabel;
}
public String getDescriptiveLabel() {
return descriptiveLabel;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartNumber() {
return partNumber;
}
}
}
| false | true | public static String jbeiLinkifyText(String text) {
Pattern basicJbeiPattern = Pattern.compile("\\[\\[jbei:.*?\\]\\]");
Pattern partNumberPattern = Pattern.compile("\\[\\[jbei:(.*)\\]\\]");
Pattern descriptivePattern = Pattern.compile("\\[\\[jbei:(.*)\\|(.*)\\]\\]");
Matcher basicJbeiMatcher = basicJbeiPattern.matcher(text);
ArrayList<JbeiLink> jbeiLinks = new ArrayList<JbeiLink>();
ArrayList<Integer> starts = new ArrayList<Integer>();
ArrayList<Integer> ends = new ArrayList<Integer>();
while (basicJbeiMatcher.find()) {
String partNumber = null;
String descriptive = null;
Matcher partNumberMatcher = partNumberPattern.matcher(basicJbeiMatcher.group());
Matcher descriptivePatternMatcher = descriptivePattern
.matcher(basicJbeiMatcher.group());
if (descriptivePatternMatcher.find()) {
partNumber = descriptivePatternMatcher.group(1).trim();
descriptive = descriptivePatternMatcher.group(2).trim();
} else if (partNumberMatcher.find()) {
partNumber = partNumberMatcher.group(1).trim();
}
if (partNumber != null) {
jbeiLinks.add(new JbeiLink(partNumber, descriptive));
starts.add(basicJbeiMatcher.start());
ends.add(basicJbeiMatcher.end());
}
}
String newText = new String(text);
for (int i = jbeiLinks.size() - 1; i > -1; i = i - 1) {
String before = newText.substring(0, starts.get(i));
String after = newText.substring(ends.get(i));
newText = before + makeEntryLink(jbeiLinks.get(i)) + after;
}
return newText;
}
| public static String jbeiLinkifyText(String text) {
Pattern basicJbeiPattern = Pattern.compile("\\[\\[jbei:.*?\\]\\]");
Pattern partNumberPattern = Pattern.compile("\\[\\[jbei:(.*)\\]\\]");
Pattern descriptivePattern = Pattern.compile("\\[\\[jbei:(.*)\\|(.*)\\]\\]");
if (text == null) {
return text;
}
Matcher basicJbeiMatcher = basicJbeiPattern.matcher(text);
ArrayList<JbeiLink> jbeiLinks = new ArrayList<JbeiLink>();
ArrayList<Integer> starts = new ArrayList<Integer>();
ArrayList<Integer> ends = new ArrayList<Integer>();
while (basicJbeiMatcher.find()) {
String partNumber = null;
String descriptive = null;
Matcher partNumberMatcher = partNumberPattern.matcher(basicJbeiMatcher.group());
Matcher descriptivePatternMatcher = descriptivePattern
.matcher(basicJbeiMatcher.group());
if (descriptivePatternMatcher.find()) {
partNumber = descriptivePatternMatcher.group(1).trim();
descriptive = descriptivePatternMatcher.group(2).trim();
} else if (partNumberMatcher.find()) {
partNumber = partNumberMatcher.group(1).trim();
}
if (partNumber != null) {
Entry entry = null;
try {
entry = EntryManager.getByPartNumber(partNumber);
} catch (ManagerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (entry != null) {
jbeiLinks.add(new JbeiLink(partNumber, descriptive));
starts.add(basicJbeiMatcher.start());
ends.add(basicJbeiMatcher.end());
}
}
}
String newText = new String(text);
for (int i = jbeiLinks.size() - 1; i > -1; i = i - 1) {
String before = newText.substring(0, starts.get(i));
String after = newText.substring(ends.get(i));
newText = before + makeEntryLink(jbeiLinks.get(i)) + after;
}
return newText;
}
|
diff --git a/src/org/jacorb/idl/StructType.java b/src/org/jacorb/idl/StructType.java
index 2727d637e..4db26e31a 100644
--- a/src/org/jacorb/idl/StructType.java
+++ b/src/org/jacorb/idl/StructType.java
@@ -1,673 +1,673 @@
package org.jacorb.idl;
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2003 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
import java.io.File;
import java.io.PrintWriter;
import java.util.*;
/**
* @author Gerald Brose
* @version $Id$
*/
public class StructType
extends TypeDeclaration
implements Scope
{
private boolean written = false;
public boolean exc;
public MemberList memberlist = null;
private boolean parsed = false;
private ScopeData scopeData;
public StructType(int num)
{
super(num);
pack_name = "";
}
public void setScopeData(ScopeData data)
{
scopeData = data;
}
public ScopeData getScopeData()
{
return scopeData;
}
/**
* @return true if this struct represents an IDL exception
*/
public boolean isException()
{
return exc;
}
public Object clone()
{
StructType st = new StructType(new_num());
st.pack_name = this.pack_name;
st.name = this.name;
st.memberlist = this.memberlist;
st.included = this.included;
st.token = this.token;
st.exc = this.exc;
st.scopeData = this.scopeData;
st.enclosing_symbol = this.enclosing_symbol;
return st;
}
public TypeDeclaration declaration()
{
return this;
};
public String typeName()
{
if (typeName == null)
setPrintPhaseNames();
return typeName;
}
/**
* get this types's mapped Java name
*/
public String getJavaTypeName()
{
if (typeName == null)
setPrintPhaseNames();
return typeName;
}
/**
* get this symbol's IDL type name
*/
public String getIDLTypeName()
{
return getJavaTypeName(); // TODO
}
public boolean basic()
{
return false;
}
public void set_memberlist(MemberList m)
{
m.setContainingType(this);
memberlist = m;
memberlist.setPackage(name);
if (memberlist != null)
memberlist.setEnclosingSymbol(this);
}
public void set_included(boolean i)
{
included = i;
}
public void setPackage(String s)
{
s = parser.pack_replace(s);
if (pack_name.length() > 0)
pack_name = s + "." + pack_name;
else
pack_name = s;
if (memberlist != null)
memberlist.setPackage(s);
}
public void setEnclosingSymbol(IdlSymbol s)
{
if (enclosing_symbol != null && enclosing_symbol != s)
{
System.err.println("was " + enclosing_symbol.getClass().getName() +
" now: " + s.getClass().getName());
throw new RuntimeException("Compiler Error: trying to reassign container for " + name);
}
enclosing_symbol = s;
if (memberlist != null)
memberlist.setEnclosingSymbol(this);
}
public String toString()
{
return typeName();
}
public void parse()
{
boolean justAnotherOne = false;
if (parsed)
{
// there are occasions where the compiler may try to parse
// a struct type spec for a second time, viz if the struct is
// referred to through a scoped name in another struct member.
// that's not a problem, but we have to skip parsing again!
// (Gerald: introduced together with the fix for bug #84).
return;
}
if (logger.isDebugEnabled())
logger.debug("Parsing Struct " + name);
escapeName();
ConstrTypeSpec ctspec = new ConstrTypeSpec(new_num());
try
{
// important: typeName must be set _before_ a new scope is introduced,
// otherwise the typeName for this struct class will be the same
// as the package name for the new pseudo scope!
ScopedName.definePseudoScope(full_name());
ctspec.c_type_spec = this;
NameTable.define(full_name(), "type-struct");
TypeMap.typedef(full_name(), ctspec);
}
catch (NameAlreadyDefined nad)
{
if (exc)
{
parser.error("Struct " + getJavaTypeName() + " already defined", token);
}
else
{
if (parser.get_pending (full_name ()) != null)
{
if (memberlist != null)
{
justAnotherOne = true;
}
if (!full_name().equals("org.omg.CORBA.TypeCode") && memberlist != null)
{
TypeMap.replaceForwardDeclaration(full_name(), ctspec);
}
}
else
{
parser.error("Struct " + getJavaTypeName() + " already defined", token);
}
}
}
if (memberlist != null)
{
ScopedName.addRecursionScope(getJavaTypeName());
memberlist.parse();
ScopedName.removeRecursionScope(getJavaTypeName());
if (exc == false)
{
NameTable.parsed_interfaces.put(full_name(), "");
parser.remove_pending(full_name());
}
}
else if (!justAnotherOne && exc == false)
{
// i am forward declared, must set myself as
// pending further parsing
parser.set_pending(full_name());
}
parsed = true;
}
public String className()
{
String fullName = getJavaTypeName();
if (fullName.indexOf('.') > 0)
{
return fullName.substring(fullName.lastIndexOf('.') + 1);
}
else
{
return fullName;
}
}
public String printReadExpression(String Streamname)
{
return toString() + "Helper.read(" + Streamname + ")";
}
public String printWriteStatement(String var_name, String streamname)
{
return toString() + "Helper.write(" + streamname + "," + var_name + ");";
}
public String holderName()
{
return getJavaTypeName() + "Holder";
}
/**
* @return a string for an expression of type TypeCode that
* describes this type
*/
public String getTypeCodeExpression()
{
return full_name() + "Helper.type()";
}
public String getTypeCodeExpression(Set knownTypes)
{
if (knownTypes.contains(this))
{
return this.getRecursiveTypeCodeExpression();
}
else
{
return this.getTypeCodeExpression();
}
}
private void printClassComment(String className, PrintWriter ps)
{
ps.println("/**");
ps.println(" *\tGenerated from IDL definition of " +
(exc ? "exception " : "struct ") + "\"" +
className + "\"");
ps.println(" *\t@author JacORB IDL compiler ");
ps.println(" */\n");
}
private void printHolderClass(String className, PrintWriter ps)
{
if (parser.checkJdk14 && pack_name.equals(""))
parser.fatal_error
("No package defined for " + className + " - illegal in JDK1.4", token);
if (!pack_name.equals(""))
ps.println("package " + pack_name + ";");
printImport(ps);
printClassComment(className, ps);
ps.println("public" + parser.getFinalString() + " class " + className + "Holder");
ps.println("\timplements org.omg.CORBA.portable.Streamable");
ps.println("{");
ps.println("\tpublic " + getJavaTypeName() + " value;\n");
ps.println("\tpublic " + className + "Holder ()");
ps.println("\t{");
ps.println("\t}");
ps.println("\tpublic " + className + "Holder(final " + getJavaTypeName() + " initial)");
ps.println("\t{");
ps.println("\t\tvalue = initial;");
ps.println("\t}");
ps.println("\tpublic org.omg.CORBA.TypeCode _type ()");
ps.println("\t{");
ps.println("\t\treturn " + getJavaTypeName() + "Helper.type ();");
ps.println("\t}");
ps.println("\tpublic void _read(final org.omg.CORBA.portable.InputStream _in)");
ps.println("\t{");
ps.println("\t\tvalue = " + getJavaTypeName() + "Helper.read(_in);");
ps.println("\t}");
ps.println("\tpublic void _write(final org.omg.CORBA.portable.OutputStream _out)");
ps.println("\t{");
ps.println("\t\t" + getJavaTypeName() + "Helper.write(_out, value);");
ps.println("\t}");
ps.println("}");
}
private void printHelperClass(String className, PrintWriter ps)
{
if (parser.checkJdk14 && pack_name.equals(""))
parser.fatal_error
("No package defined for " + className + " - illegal in JDK1.4", token);
if (!pack_name.equals(""))
ps.println("package " + pack_name + ";\n");
printImport(ps);
printClassComment(className, ps);
ps.println("public" + parser.getFinalString() + " class " + className + "Helper");
ps.println("{");
ps.println("\tprivate static org.omg.CORBA.TypeCode _type = null;");
/* type() method */
ps.println("\tpublic static org.omg.CORBA.TypeCode type ()");
ps.println("\t{");
ps.println("\t\tif (_type == null)");
ps.println("\t\t{");
StringBuffer sb = new StringBuffer();
sb.append("org.omg.CORBA.ORB.init().create_" +
(exc ? "exception" : "struct") + "_tc(" +
getJavaTypeName() + "Helper.id(),\"" + className() + "\",");
if (memberlist != null)
{
sb.append("new org.omg.CORBA.StructMember[]{");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
sb.append("new org.omg.CORBA.StructMember(\"" + d.name() + "\", ");
sb.append(m.type_spec.typeSpec().getTypeCodeExpression());
sb.append(", null)");
if (e.hasMoreElements())
sb.append(",");
}
sb.append("}");
}
else
{
sb.append("new org.omg.CORBA.StructMember[0]");
}
sb.append(")");
ps.println("\t\t\t_type = " + sb.toString() + ";");
ps.println("\t\t}");
ps.println("\t\treturn _type;");
ps.println("\t}\n");
String type = getJavaTypeName();
TypeSpec.printInsertExtractMethods(ps, type);
printIdMethod(ps); // inherited from IdlSymbol
/* read */
ps.println("\tpublic static " + type +
" read (final org.omg.CORBA.portable.InputStream in)");
ps.println("\t{");
ps.println("\t\t" + type + " result = new " + type + "();");
if (exc)
{
ps.println("\t\tif (!in.read_string().equals(id())) throw new org.omg.CORBA.MARSHAL(\"wrong id\");");
}
if (memberlist != null)
{
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.println("\t\t" + m.type_spec.typeSpec().printReadStatement("result." + d.name(), "in"));
}
}
ps.println("\t\treturn result;");
ps.println("\t}");
/* write */
ps.println("\tpublic static void write (final org.omg.CORBA.portable.OutputStream out, final " + type + " s)");
ps.println("\t{");
if (exc)
{
ps.println("\t\tout.write_string(id());");
}
if (memberlist != null)
{
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.println("\t\t" + m.type_spec.typeSpec().printWriteStatement("s." + d.name(), "out"));
}
}
ps.println("\t}");
ps.println("}");
}
private void printStructClass(String className, PrintWriter ps)
{
if (parser.checkJdk14 && pack_name.equals(""))
parser.fatal_error
("No package defined for " + className + " - illegal in JDK1.4", token);
String fullClassName = className;
if (!pack_name.equals(""))
{
fullClassName = pack_name + "." + className;
ps.println("package " + pack_name + ";");
}
printImport(ps);
printClassComment(className, ps);
ps.println("public" + parser.getFinalString() + " class " + className);
if (exc)
ps.println("\textends org.omg.CORBA.UserException");
else
ps.println("\timplements org.omg.CORBA.portable.IDLEntity");
ps.println("{");
// print an empty constructor
if (exc)
{
ps.println("\tpublic " + className + "()");
ps.println("\t{");
ps.println("\t\tsuper(" + fullClassName + "Helper.id());");
ps.println("\t}");
ps.println();
if (memberlist == null)
{
ps.println("\tpublic " + className + "(String value)");
ps.println("\t{");
ps.println("\t\tsuper(value);");
ps.println("\t}");
}
}
else
{
ps.println("\tpublic " + className + "(){}");
}
if (memberlist != null)
{
// print member declarations
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
((Member)e.nextElement()).member_print(ps, "\tpublic ");
ps.println();
}
// print a constructor for class member initialization
if (exc)
{
// print a constructor for class member initialization with additional first string parameter
ps.print("\tpublic " + className + "(");
ps.print("java.lang.String _reason,");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print(m.type_spec.toString() + " " + d.toString());
if (e.hasMoreElements())
ps.print(", ");
}
ps.println(")");
ps.println("\t{");
ps.println("\t\tsuper(" + fullClassName + "Helper.id()+\"\"+_reason);");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print("\t\tthis.");
ps.print(d.name());
ps.print(" = ");
ps.println(d.name() + ";");
}
ps.println("\t}");
}
ps.print("\tpublic " + className + "(");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
- ps.print(m.type_spec.getJavaTypeName() + " " + d.name());
+ ps.print(m.type_spec.toString() + " " + d.name());
if (e.hasMoreElements())
ps.print(", ");
}
ps.println(")");
ps.println("\t{");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print("\t\tthis.");
ps.print(d.name());
ps.print(" = ");
ps.println(d.name() + ";");
}
ps.println("\t}");
}
ps.println("}");
}
/**
* Generates code from this AST class
*
* @param ps not used, the necessary output streams to classes
* that receive code (e.g., helper and holder classes for the
* IDL/Java mapping, are created inside this method.
*/
public void print(PrintWriter ps)
{
setPrintPhaseNames();
if (!parsed)
{
throw new ParseException ("Unparsed Struct!");
}
// no code generation for included definitions
if (included && !generateIncluded())
{
return;
}
// only generate code once
if (!written)
{
// guard against recursive entries, which can happen due to
// containments, e.g., an alias within an interface that refers
// back to the interface
written = true;
try
{
String className = className();
String path = parser.out_dir + fileSeparator +
pack_name.replace('.', fileSeparator);
File dir = new File(path);
if (!dir.exists())
{
if (!dir.mkdirs())
{
org.jacorb.idl.parser.fatal_error("Unable to create " + path, null);
}
}
String fname = className + ".java";
File f = new File(dir, fname);
if (GlobalInputStream.isMoreRecentThan(f))
{
// print the mapped java class
PrintWriter printWriter = new PrintWriter(new java.io.FileWriter(f));
printStructClass(className, printWriter);
printWriter.close();
}
fname = className + "Holder.java";
f = new File(dir, fname);
if (GlobalInputStream.isMoreRecentThan(f))
{
// print the mapped holder class
PrintWriter printWriter = new PrintWriter(new java.io.FileWriter(f));
printHolderClass(className, printWriter);
printWriter.close();
}
fname = className + "Helper.java";
f = new File(dir, fname);
if (GlobalInputStream.isMoreRecentThan(f))
{
// print the mapped helper class
PrintWriter printWriter = new PrintWriter(new java.io.FileWriter(f));
printHelperClass(className, printWriter);
printWriter.close();
}
// written = true;
}
catch (java.io.IOException i)
{
System.err.println("File IO error");
i.printStackTrace();
}
}
}
public void accept(IDLTreeVisitor visitor)
{
visitor.visitStruct(this);
}
}
| true | true | private void printStructClass(String className, PrintWriter ps)
{
if (parser.checkJdk14 && pack_name.equals(""))
parser.fatal_error
("No package defined for " + className + " - illegal in JDK1.4", token);
String fullClassName = className;
if (!pack_name.equals(""))
{
fullClassName = pack_name + "." + className;
ps.println("package " + pack_name + ";");
}
printImport(ps);
printClassComment(className, ps);
ps.println("public" + parser.getFinalString() + " class " + className);
if (exc)
ps.println("\textends org.omg.CORBA.UserException");
else
ps.println("\timplements org.omg.CORBA.portable.IDLEntity");
ps.println("{");
// print an empty constructor
if (exc)
{
ps.println("\tpublic " + className + "()");
ps.println("\t{");
ps.println("\t\tsuper(" + fullClassName + "Helper.id());");
ps.println("\t}");
ps.println();
if (memberlist == null)
{
ps.println("\tpublic " + className + "(String value)");
ps.println("\t{");
ps.println("\t\tsuper(value);");
ps.println("\t}");
}
}
else
{
ps.println("\tpublic " + className + "(){}");
}
if (memberlist != null)
{
// print member declarations
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
((Member)e.nextElement()).member_print(ps, "\tpublic ");
ps.println();
}
// print a constructor for class member initialization
if (exc)
{
// print a constructor for class member initialization with additional first string parameter
ps.print("\tpublic " + className + "(");
ps.print("java.lang.String _reason,");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print(m.type_spec.toString() + " " + d.toString());
if (e.hasMoreElements())
ps.print(", ");
}
ps.println(")");
ps.println("\t{");
ps.println("\t\tsuper(" + fullClassName + "Helper.id()+\"\"+_reason);");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print("\t\tthis.");
ps.print(d.name());
ps.print(" = ");
ps.println(d.name() + ";");
}
ps.println("\t}");
}
ps.print("\tpublic " + className + "(");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print(m.type_spec.getJavaTypeName() + " " + d.name());
if (e.hasMoreElements())
ps.print(", ");
}
ps.println(")");
ps.println("\t{");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print("\t\tthis.");
ps.print(d.name());
ps.print(" = ");
ps.println(d.name() + ";");
}
ps.println("\t}");
}
ps.println("}");
}
| private void printStructClass(String className, PrintWriter ps)
{
if (parser.checkJdk14 && pack_name.equals(""))
parser.fatal_error
("No package defined for " + className + " - illegal in JDK1.4", token);
String fullClassName = className;
if (!pack_name.equals(""))
{
fullClassName = pack_name + "." + className;
ps.println("package " + pack_name + ";");
}
printImport(ps);
printClassComment(className, ps);
ps.println("public" + parser.getFinalString() + " class " + className);
if (exc)
ps.println("\textends org.omg.CORBA.UserException");
else
ps.println("\timplements org.omg.CORBA.portable.IDLEntity");
ps.println("{");
// print an empty constructor
if (exc)
{
ps.println("\tpublic " + className + "()");
ps.println("\t{");
ps.println("\t\tsuper(" + fullClassName + "Helper.id());");
ps.println("\t}");
ps.println();
if (memberlist == null)
{
ps.println("\tpublic " + className + "(String value)");
ps.println("\t{");
ps.println("\t\tsuper(value);");
ps.println("\t}");
}
}
else
{
ps.println("\tpublic " + className + "(){}");
}
if (memberlist != null)
{
// print member declarations
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
((Member)e.nextElement()).member_print(ps, "\tpublic ");
ps.println();
}
// print a constructor for class member initialization
if (exc)
{
// print a constructor for class member initialization with additional first string parameter
ps.print("\tpublic " + className + "(");
ps.print("java.lang.String _reason,");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print(m.type_spec.toString() + " " + d.toString());
if (e.hasMoreElements())
ps.print(", ");
}
ps.println(")");
ps.println("\t{");
ps.println("\t\tsuper(" + fullClassName + "Helper.id()+\"\"+_reason);");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print("\t\tthis.");
ps.print(d.name());
ps.print(" = ");
ps.println(d.name() + ";");
}
ps.println("\t}");
}
ps.print("\tpublic " + className + "(");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print(m.type_spec.toString() + " " + d.name());
if (e.hasMoreElements())
ps.print(", ");
}
ps.println(")");
ps.println("\t{");
for (Enumeration e = memberlist.v.elements(); e.hasMoreElements();)
{
Member m = (Member)e.nextElement();
Declarator d = m.declarator;
ps.print("\t\tthis.");
ps.print(d.name());
ps.print(" = ");
ps.println(d.name() + ";");
}
ps.println("\t}");
}
ps.println("}");
}
|
diff --git a/dspace/src/org/dspace/search/Harvest.java b/dspace/src/org/dspace/search/Harvest.java
index 6497ab13f..2b0c8cd9d 100644
--- a/dspace/src/org/dspace/search/Harvest.java
+++ b/dspace/src/org/dspace/search/Harvest.java
@@ -1,406 +1,406 @@
/*
* Harvest.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - 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.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS 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 COPYRIGHT
* HOLDERS OR 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.
*/
package org.dspace.search;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
import org.dspace.storage.rdbms.TableRowIterator;
/**
* Utility class for extracting information about items, possibly just within a
* certain community or collection, that have been created, modified or
* withdrawn within a particular range of dates.
*
* @author Robert Tansley
* @version $Revision$
*/
public class Harvest
{
/** log4j logger */
private static Logger log = Logger.getLogger(Harvest.class);
/**
* Obtain information about items that have been created, modified or
* withdrawn within a given date range. You can also specify 'offset' and
* 'limit' so that a big harvest can be split up into smaller sections.
* <P>
* Note that dates are passed in the standard ISO8601 format used by DSpace
* (and OAI-PMH).
* <P>
* FIXME: Assumes all in_archive items have public metadata
*
* @param context
* DSpace context
* @param scope
* a Collection, Community, or <code>null</code> indicating the scope is
* all of DSpace
* @param startDate
* start of date range, or <code>null</code>
* @param endDate
* end of date range, or <code>null</code>
* @param offset
* for a partial harvest, the point in the overall list of
* matching items to start at. 0 means just start at the
* beginning.
* @param limit
* the number of matching items to return in a partial harvest.
* Specify 0 to return the whole list (or the rest of the list if
* an offset was specified.)
* @param items
* if <code>true</code> the <code>item</code> field of each
* <code>HarvestedItemInfo</code> object is filled out
* @param collections
* if <code>true</code> the <code>collectionHandles</code>
* field of each <code>HarvestedItemInfo</code> object is
* filled out
* @param withdrawn
* If <code>true</code>, information about withdrawn items is
* included
* @return List of <code>HarvestedItemInfo</code> objects
* @throws SQLException
*/
public static List harvest(Context context, DSpaceObject scope,
String startDate, String endDate, int offset, int limit,
boolean items, boolean collections, boolean withdrawn)
throws SQLException
{
// Put together our query. Note there is no need for an
// "in_archive=true" condition, we are using the existence of
// Handles as our 'existence criterion'.
String query = "SELECT handle.handle, handle.resource_id, item.withdrawn, item.last_modified FROM handle, item";
// We are building a complex query that may contain a variable
// about of input data points. To accomidate this while still
// providing type safty we build a list of parameters to be
// plugged into the query at the database level.
List parameters = new ArrayList();
if (scope != null)
{
if (scope.getType() == Constants.COLLECTION)
{
query += ", collection2item";
}
else if (scope.getType() == Constants.COMMUNITY)
{
query += ", community2item";
}
}
query += " WHERE handle.resource_type_id=" + Constants.ITEM + " AND handle.resource_id=item.item_id ";
if (scope != null)
{
if (scope.getType() == Constants.COLLECTION)
{
query += " AND collection2item.collection_id= ? " +
" AND collection2item.item_id=handle.resource_id ";
parameters.add(new Integer(scope.getID()));
}
else if (scope.getType() == Constants.COMMUNITY)
{
query += " AND community2item.community_id= ? " +
" AND community2item.item_id=handle.resource_id";
parameters.add(new Integer(scope.getID()));
}
}
if (startDate != null)
{
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
startDate = oracleTimeStampFormat(startDate);
query += " AND item.last_modified >= " +
oracleTimeStampFunction(startDate);
parameters.add(startDate);
}
else //postgres
{
query = query + " AND item.last_modified >= ? ";
parameters.add(startDate);
}
}
if (endDate != null)
{
/*
* If the end date has seconds precision, e.g.:
*
* 2004-04-29T13:45:43Z
*
* we need to add 999 milliseconds to this. This is because SQL
* TIMESTAMPs have millisecond precision, and so might have a value:
*
* 2004-04-29T13:45:43.952Z
*
* and so <= '2004-04-29T13:45:43Z' would not pick this up. Reading
* things out of the database, TIMESTAMPs are rounded down, so the
* above value would be read as '2004-04-29T13:45:43Z', and
* therefore a caller would expect <= '2004-04-29T13:45:43Z' to
* include that value.
*
* Got that? ;-)
*/
if (endDate.length() == 20)
{
endDate = endDate.substring(0, 19) + ".999Z";
}
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
endDate = oracleTimeStampFormat(endDate);
- query += " AND item.last_modified <= ? " +
+ query += " AND item.last_modified <= " +
oracleTimeStampFunction(endDate);
parameters.add(endDate);
}
else //postgres
{
query += " AND item.last_modified <= ? ";
parameters.add(endDate);
}
}
if (withdrawn == false)
{
// Exclude withdrawn items
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
query += " AND withdrawn=0 ";
}
else
{
// postgres uses booleans
query += " AND withdrawn=false ";
}
}
// Order by item ID, so that for a given harvest the order will be
// consistent. This is so that big harvests can be broken up into
// several smaller operations (e.g. for OAI resumption tokens.)
query += " ORDER BY handle.resource_id";
log.debug(LogManager.getHeader(context, "harvest SQL", query));
// Execute
Object[] parametersArray = parameters.toArray();
TableRowIterator tri = DatabaseManager.query(context, query, parametersArray);
List infoObjects = new LinkedList();
int index = 0;
// Process results of query into HarvestedItemInfo objects
while (tri.hasNext())
{
TableRow row = tri.next();
/*
* This conditional ensures that we only process items within any
* constraints specified by 'offset' and 'limit' parameters.
*/
if ((index >= offset)
&& ((limit == 0) || (index < (offset + limit))))
{
HarvestedItemInfo itemInfo = new HarvestedItemInfo();
itemInfo.context = context;
itemInfo.handle = row.getStringColumn("handle");
itemInfo.itemID = row.getIntColumn("resource_id");
itemInfo.datestamp = row.getDateColumn("last_modified");
itemInfo.withdrawn = row.getBooleanColumn("withdrawn");
if (collections)
{
fillCollections(context, itemInfo);
}
if (items)
{
// Get the item
itemInfo.item = Item.find(context, itemInfo.itemID);
}
infoObjects.add(itemInfo);
}
index++;
}
tri.close();
return infoObjects;
}
/**
* Get harvested item info for a single item. <code>item</code> field in
* returned <code>HarvestedItemInfo</code> object is always filled out.
*
* @param context
* DSpace context
* @param handle
* Prefix-less Handle of item
* @param collections
* if <code>true</code> the <code>collectionHandles</code>
* field of the <code>HarvestedItemInfo</code> object is filled
* out
*
* @return <code>HarvestedItemInfo</code> object for the single item, or
* <code>null</code>
* @throws SQLException
*/
public static HarvestedItemInfo getSingle(Context context, String handle,
boolean collections) throws SQLException
{
// FIXME: Assume Handle is item
Item i = (Item) HandleManager.resolveToObject(context, handle);
if (i == null)
{
return null;
}
// Fill out OAI info item object
HarvestedItemInfo itemInfo = new HarvestedItemInfo();
itemInfo.context = context;
itemInfo.item = i;
itemInfo.handle = handle;
itemInfo.withdrawn = i.isWithdrawn();
itemInfo.datestamp = i.getLastModified();
itemInfo.itemID = i.getID();
// Get the sets
if (collections)
{
fillCollections(context, itemInfo);
}
return itemInfo;
}
/**
* Fill out the containers field of the HarvestedItemInfo object
*
* @param context
* DSpace context
* @param itemInfo
* HarvestedItemInfo object to fill out
* @throws SQLException
*/
private static void fillCollections(Context context,
HarvestedItemInfo itemInfo) throws SQLException
{
// Get the collection Handles from DB
TableRowIterator colRows = DatabaseManager.query(context,
"SELECT handle.handle FROM handle, collection2item WHERE handle.resource_type_id= ? " +
"AND collection2item.collection_id=handle.resource_id AND collection2item.item_id = ? ",
Constants.COLLECTION, itemInfo.itemID);
// Chuck 'em in the itemInfo object
itemInfo.collectionHandles = new LinkedList();
while (colRows.hasNext())
{
TableRow r = colRows.next();
itemInfo.collectionHandles.add(r.getStringColumn("handle"));
}
}
/**
* Create an oracle to_timestamp function for the given iso date. It must be
* an ISO 8601-stlye string.
*
* Since the date could be a possible sql injection attack vector instead
* of placing the value inside the query a place holder will be used. The
* caller must ensure that the isoDateString parameter is bound to the query
* for the approprate substitution.
*
* @param isoDateString
* @return The oracle to_timestamp function.
*/
private static String oracleTimeStampFunction(String isoDateString)
{
if (isoDateString.length() == 19 )
{
return "TO_TIMESTAMP( ? ,'YYYY-MM-DD\"T\"HH24:MI:SS')";
} else if (isoDateString.length() > 19)
{
return "TO_TIMESTAMP( ? ,'YYYY-MM-DD\"T\"HH24:MI:SS.FF\"Z\"')";
} else
{
throw new IllegalArgumentException("argument does not seem to be in the expected ISO 8601 format");
}
}
/**
* Format the isoDateString according to oracles needs. The input should be ISO-85601 style.
*
* @param isoDateString
* @return a datastring format better suited to oracles needs.
*/
private static String oracleTimeStampFormat(String isoDateString)
{
if (isoDateString.length() == 10)
{
return isoDateString + "T00:00:00";
}
else
{
return isoDateString;
}
}
}
| true | true | public static List harvest(Context context, DSpaceObject scope,
String startDate, String endDate, int offset, int limit,
boolean items, boolean collections, boolean withdrawn)
throws SQLException
{
// Put together our query. Note there is no need for an
// "in_archive=true" condition, we are using the existence of
// Handles as our 'existence criterion'.
String query = "SELECT handle.handle, handle.resource_id, item.withdrawn, item.last_modified FROM handle, item";
// We are building a complex query that may contain a variable
// about of input data points. To accomidate this while still
// providing type safty we build a list of parameters to be
// plugged into the query at the database level.
List parameters = new ArrayList();
if (scope != null)
{
if (scope.getType() == Constants.COLLECTION)
{
query += ", collection2item";
}
else if (scope.getType() == Constants.COMMUNITY)
{
query += ", community2item";
}
}
query += " WHERE handle.resource_type_id=" + Constants.ITEM + " AND handle.resource_id=item.item_id ";
if (scope != null)
{
if (scope.getType() == Constants.COLLECTION)
{
query += " AND collection2item.collection_id= ? " +
" AND collection2item.item_id=handle.resource_id ";
parameters.add(new Integer(scope.getID()));
}
else if (scope.getType() == Constants.COMMUNITY)
{
query += " AND community2item.community_id= ? " +
" AND community2item.item_id=handle.resource_id";
parameters.add(new Integer(scope.getID()));
}
}
if (startDate != null)
{
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
startDate = oracleTimeStampFormat(startDate);
query += " AND item.last_modified >= " +
oracleTimeStampFunction(startDate);
parameters.add(startDate);
}
else //postgres
{
query = query + " AND item.last_modified >= ? ";
parameters.add(startDate);
}
}
if (endDate != null)
{
/*
* If the end date has seconds precision, e.g.:
*
* 2004-04-29T13:45:43Z
*
* we need to add 999 milliseconds to this. This is because SQL
* TIMESTAMPs have millisecond precision, and so might have a value:
*
* 2004-04-29T13:45:43.952Z
*
* and so <= '2004-04-29T13:45:43Z' would not pick this up. Reading
* things out of the database, TIMESTAMPs are rounded down, so the
* above value would be read as '2004-04-29T13:45:43Z', and
* therefore a caller would expect <= '2004-04-29T13:45:43Z' to
* include that value.
*
* Got that? ;-)
*/
if (endDate.length() == 20)
{
endDate = endDate.substring(0, 19) + ".999Z";
}
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
endDate = oracleTimeStampFormat(endDate);
query += " AND item.last_modified <= ? " +
oracleTimeStampFunction(endDate);
parameters.add(endDate);
}
else //postgres
{
query += " AND item.last_modified <= ? ";
parameters.add(endDate);
}
}
if (withdrawn == false)
{
// Exclude withdrawn items
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
query += " AND withdrawn=0 ";
}
else
{
// postgres uses booleans
query += " AND withdrawn=false ";
}
}
// Order by item ID, so that for a given harvest the order will be
// consistent. This is so that big harvests can be broken up into
// several smaller operations (e.g. for OAI resumption tokens.)
query += " ORDER BY handle.resource_id";
log.debug(LogManager.getHeader(context, "harvest SQL", query));
// Execute
Object[] parametersArray = parameters.toArray();
TableRowIterator tri = DatabaseManager.query(context, query, parametersArray);
List infoObjects = new LinkedList();
int index = 0;
// Process results of query into HarvestedItemInfo objects
while (tri.hasNext())
{
TableRow row = tri.next();
/*
* This conditional ensures that we only process items within any
* constraints specified by 'offset' and 'limit' parameters.
*/
if ((index >= offset)
&& ((limit == 0) || (index < (offset + limit))))
{
HarvestedItemInfo itemInfo = new HarvestedItemInfo();
itemInfo.context = context;
itemInfo.handle = row.getStringColumn("handle");
itemInfo.itemID = row.getIntColumn("resource_id");
itemInfo.datestamp = row.getDateColumn("last_modified");
itemInfo.withdrawn = row.getBooleanColumn("withdrawn");
if (collections)
{
fillCollections(context, itemInfo);
}
if (items)
{
// Get the item
itemInfo.item = Item.find(context, itemInfo.itemID);
}
infoObjects.add(itemInfo);
}
index++;
}
tri.close();
return infoObjects;
}
| public static List harvest(Context context, DSpaceObject scope,
String startDate, String endDate, int offset, int limit,
boolean items, boolean collections, boolean withdrawn)
throws SQLException
{
// Put together our query. Note there is no need for an
// "in_archive=true" condition, we are using the existence of
// Handles as our 'existence criterion'.
String query = "SELECT handle.handle, handle.resource_id, item.withdrawn, item.last_modified FROM handle, item";
// We are building a complex query that may contain a variable
// about of input data points. To accomidate this while still
// providing type safty we build a list of parameters to be
// plugged into the query at the database level.
List parameters = new ArrayList();
if (scope != null)
{
if (scope.getType() == Constants.COLLECTION)
{
query += ", collection2item";
}
else if (scope.getType() == Constants.COMMUNITY)
{
query += ", community2item";
}
}
query += " WHERE handle.resource_type_id=" + Constants.ITEM + " AND handle.resource_id=item.item_id ";
if (scope != null)
{
if (scope.getType() == Constants.COLLECTION)
{
query += " AND collection2item.collection_id= ? " +
" AND collection2item.item_id=handle.resource_id ";
parameters.add(new Integer(scope.getID()));
}
else if (scope.getType() == Constants.COMMUNITY)
{
query += " AND community2item.community_id= ? " +
" AND community2item.item_id=handle.resource_id";
parameters.add(new Integer(scope.getID()));
}
}
if (startDate != null)
{
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
startDate = oracleTimeStampFormat(startDate);
query += " AND item.last_modified >= " +
oracleTimeStampFunction(startDate);
parameters.add(startDate);
}
else //postgres
{
query = query + " AND item.last_modified >= ? ";
parameters.add(startDate);
}
}
if (endDate != null)
{
/*
* If the end date has seconds precision, e.g.:
*
* 2004-04-29T13:45:43Z
*
* we need to add 999 milliseconds to this. This is because SQL
* TIMESTAMPs have millisecond precision, and so might have a value:
*
* 2004-04-29T13:45:43.952Z
*
* and so <= '2004-04-29T13:45:43Z' would not pick this up. Reading
* things out of the database, TIMESTAMPs are rounded down, so the
* above value would be read as '2004-04-29T13:45:43Z', and
* therefore a caller would expect <= '2004-04-29T13:45:43Z' to
* include that value.
*
* Got that? ;-)
*/
if (endDate.length() == 20)
{
endDate = endDate.substring(0, 19) + ".999Z";
}
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
endDate = oracleTimeStampFormat(endDate);
query += " AND item.last_modified <= " +
oracleTimeStampFunction(endDate);
parameters.add(endDate);
}
else //postgres
{
query += " AND item.last_modified <= ? ";
parameters.add(endDate);
}
}
if (withdrawn == false)
{
// Exclude withdrawn items
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
query += " AND withdrawn=0 ";
}
else
{
// postgres uses booleans
query += " AND withdrawn=false ";
}
}
// Order by item ID, so that for a given harvest the order will be
// consistent. This is so that big harvests can be broken up into
// several smaller operations (e.g. for OAI resumption tokens.)
query += " ORDER BY handle.resource_id";
log.debug(LogManager.getHeader(context, "harvest SQL", query));
// Execute
Object[] parametersArray = parameters.toArray();
TableRowIterator tri = DatabaseManager.query(context, query, parametersArray);
List infoObjects = new LinkedList();
int index = 0;
// Process results of query into HarvestedItemInfo objects
while (tri.hasNext())
{
TableRow row = tri.next();
/*
* This conditional ensures that we only process items within any
* constraints specified by 'offset' and 'limit' parameters.
*/
if ((index >= offset)
&& ((limit == 0) || (index < (offset + limit))))
{
HarvestedItemInfo itemInfo = new HarvestedItemInfo();
itemInfo.context = context;
itemInfo.handle = row.getStringColumn("handle");
itemInfo.itemID = row.getIntColumn("resource_id");
itemInfo.datestamp = row.getDateColumn("last_modified");
itemInfo.withdrawn = row.getBooleanColumn("withdrawn");
if (collections)
{
fillCollections(context, itemInfo);
}
if (items)
{
// Get the item
itemInfo.item = Item.find(context, itemInfo.itemID);
}
infoObjects.add(itemInfo);
}
index++;
}
tri.close();
return infoObjects;
}
|
diff --git a/src/org/rascalmpl/semantics/dynamic/ShellCommand.java b/src/org/rascalmpl/semantics/dynamic/ShellCommand.java
index d921143ea0..55585438af 100644
--- a/src/org/rascalmpl/semantics/dynamic/ShellCommand.java
+++ b/src/org/rascalmpl/semantics/dynamic/ShellCommand.java
@@ -1,148 +1,148 @@
/*******************************************************************************
* Copyright (c) 2009-2011 CWI
* 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:
* * Jurgen J. Vinju - [email protected] - CWI
* * Mark Hills - [email protected] (CWI)
* * Arnold Lankamp - [email protected]
*******************************************************************************/
package org.rascalmpl.semantics.dynamic;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IValue;
import org.rascalmpl.ast.Expression;
import org.rascalmpl.ast.QualifiedName;
import org.rascalmpl.interpreter.Evaluator;
import org.rascalmpl.interpreter.control_exceptions.QuitException;
import org.rascalmpl.interpreter.env.ModuleEnvironment;
import org.rascalmpl.interpreter.result.Result;
public abstract class ShellCommand extends org.rascalmpl.ast.ShellCommand {
static public class Edit extends org.rascalmpl.ast.ShellCommand.Edit {
public Edit(IConstructor __param1, QualifiedName __param2) {
super(__param1, __param2);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
return org.rascalmpl.interpreter.result.ResultFactory.nothing();
}
}
static public class Help extends org.rascalmpl.ast.ShellCommand.Help {
public Help(IConstructor __param1) {
super(__param1);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
__eval.setCurrentAST(this);
__eval.printHelpMessage(__eval.getStdOut());
return org.rascalmpl.interpreter.result.ResultFactory.nothing();
}
}
static public class History extends org.rascalmpl.ast.ShellCommand.History {
public History(IConstructor __param1) {
super(__param1);
}
}
static public class ListDeclarations extends
org.rascalmpl.ast.ShellCommand.ListDeclarations {
public ListDeclarations(IConstructor __param1) {
super(__param1);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
return org.rascalmpl.interpreter.result.ResultFactory.nothing();
}
}
static public class Quit extends org.rascalmpl.ast.ShellCommand.Quit {
public Quit(IConstructor __param1) {
super(__param1);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
throw new QuitException();
}
}
static public class SetOption extends
org.rascalmpl.ast.ShellCommand.SetOption {
public SetOption(IConstructor __param1, QualifiedName __param2,
Expression __param3) {
super(__param1, __param2, __param3);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
- String name = "rascal.config." + this.getName().toString();
+ String name = "rascal." + this.getName().toString();
String value = this.getExpression().interpret(__eval).getValue()
.toString();
java.lang.System.setProperty(name, value);
__eval.updateProperties();
return org.rascalmpl.interpreter.result.ResultFactory.nothing();
}
}
static public class Test extends org.rascalmpl.ast.ShellCommand.Test {
public Test(IConstructor __param1) {
super(__param1);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
return org.rascalmpl.interpreter.result.ResultFactory.bool(__eval.runTests(__eval.getMonitor()), __eval);
}
}
static public class Unimport extends
org.rascalmpl.ast.ShellCommand.Unimport {
public Unimport(IConstructor __param1, QualifiedName __param2) {
super(__param1, __param2);
}
@Override
public Result<IValue> interpret(Evaluator __eval) {
((ModuleEnvironment) __eval.getCurrentEnvt().getRoot())
.unImport(this.getName().toString());
return org.rascalmpl.interpreter.result.ResultFactory.nothing();
}
}
public ShellCommand(IConstructor __param1) {
super(__param1);
}
}
| true | true | public Result<IValue> interpret(Evaluator __eval) {
String name = "rascal.config." + this.getName().toString();
String value = this.getExpression().interpret(__eval).getValue()
.toString();
java.lang.System.setProperty(name, value);
__eval.updateProperties();
return org.rascalmpl.interpreter.result.ResultFactory.nothing();
}
| public Result<IValue> interpret(Evaluator __eval) {
String name = "rascal." + this.getName().toString();
String value = this.getExpression().interpret(__eval).getValue()
.toString();
java.lang.System.setProperty(name, value);
__eval.updateProperties();
return org.rascalmpl.interpreter.result.ResultFactory.nothing();
}
|
diff --git a/src/com/android/ficus/zipper/ZipperAdapter.java b/src/com/android/ficus/zipper/ZipperAdapter.java
index f064793..c69da31 100644
--- a/src/com/android/ficus/zipper/ZipperAdapter.java
+++ b/src/com/android/ficus/zipper/ZipperAdapter.java
@@ -1,109 +1,109 @@
/*
* Copyright (C) 2011 Ficus Kirkpatrick
*
* 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.ficus.zipper;
import com.android.ficus.zipper.ClipperzCard.ClipperzField;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.List;
/**
* An ExpandableListAdapter that exposes each {@link ClipperzCard} as a group,
* with each underlying field as a child of the group.
*/
public class ZipperAdapter extends BaseExpandableListAdapter {
private final Context mContext;
private final List<ClipperzCard> mCards;
public ZipperAdapter(Context context, List<ClipperzCard> cards) {
mContext = context;
mCards = cards;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return mCards.get(groupPosition).fields.get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return groupPosition * 1000 + childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.field_view, null);
}
ClipperzField field = mCards.get(groupPosition).fields.get(childPosition);
String text = field.name + ": ";
// TODO: Add an option for showing/hiding passwords?
- text = field.hidden ? mContext.getString(R.string.hidden): field.value;
+ text += field.hidden ? mContext.getString(R.string.hidden): field.value;
TextView fieldView = (TextView) convertView.findViewById(R.id.field_text);
fieldView.setText(text);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return mCards.get(groupPosition).fields.size();
}
@Override
public Object getGroup(int groupPosition) {
return mCards.get(groupPosition);
}
@Override
public int getGroupCount() {
return mCards.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.card_view, null);
}
TextView label = (TextView) convertView.findViewById(R.id.label);
label.setText(mCards.get(groupPosition).label);
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
| true | true | public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.field_view, null);
}
ClipperzField field = mCards.get(groupPosition).fields.get(childPosition);
String text = field.name + ": ";
// TODO: Add an option for showing/hiding passwords?
text = field.hidden ? mContext.getString(R.string.hidden): field.value;
TextView fieldView = (TextView) convertView.findViewById(R.id.field_text);
fieldView.setText(text);
return convertView;
}
| public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.field_view, null);
}
ClipperzField field = mCards.get(groupPosition).fields.get(childPosition);
String text = field.name + ": ";
// TODO: Add an option for showing/hiding passwords?
text += field.hidden ? mContext.getString(R.string.hidden): field.value;
TextView fieldView = (TextView) convertView.findViewById(R.id.field_text);
fieldView.setText(text);
return convertView;
}
|
diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java
index 1aa515b..c228e1c 100644
--- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java
+++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java
@@ -1,708 +1,708 @@
/**
* Copyright (C) 2009-2013 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.openstack.nova.os.network;
import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudErrorType;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.OperationNotSupportedException;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.network.AbstractFirewallSupport;
import org.dasein.cloud.network.Direction;
import org.dasein.cloud.network.Firewall;
import org.dasein.cloud.network.FirewallCreateOptions;
import org.dasein.cloud.network.FirewallRule;
import org.dasein.cloud.network.Permission;
import org.dasein.cloud.network.Protocol;
import org.dasein.cloud.network.RuleTarget;
import org.dasein.cloud.network.RuleTargetType;
import org.dasein.cloud.openstack.nova.os.NovaException;
import org.dasein.cloud.openstack.nova.os.NovaMethod;
import org.dasein.cloud.openstack.nova.os.NovaOpenStack;
import org.dasein.cloud.util.APITrace;
import org.dasein.util.CalendarWrapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
/**
* Support for OpenStack security groups.
* @author George Reese ([email protected])
* @since 2011.10
* @version 2011.10
* @version 2012.04.1 Added some intelligence around features Rackspace does not support
* @version 2013.04 Added API tracing
*/
public class NovaSecurityGroup extends AbstractFirewallSupport {
static private final Logger logger = NovaOpenStack.getLogger(NovaSecurityGroup.class, "std");
NovaSecurityGroup(NovaOpenStack cloud) {
super(cloud);
}
private @Nonnull String getTenantId() throws CloudException, InternalException {
return ((NovaOpenStack)getProvider()).getAuthenticationContext().getTenantId();
}
@Override
public @Nonnull String authorize(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull RuleTarget sourceEndpoint, @Nonnull Protocol protocol, @Nonnull RuleTarget destinationEndpoint, int beginPort, int endPort, @Nonnegative int precedence) throws CloudException, InternalException {
APITrace.begin(getProvider(), "Firewall.authorize");
try {
if( direction.equals(Direction.EGRESS) ) {
throw new OperationNotSupportedException(getProvider().getCloudName() + " does not support egress rules.");
}
HashMap<String,Object> wrapper = new HashMap<String,Object>();
HashMap<String,Object> json = new HashMap<String,Object>();
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
json.put("ip_protocol", protocol.name().toLowerCase());
json.put("from_port", beginPort);
json.put("to_port", endPort);
json.put("parent_group_id", firewallId);
switch( sourceEndpoint.getRuleTargetType() ) {
case CIDR: json.put("cidr", sourceEndpoint.getCidr()); break;
case VLAN: throw new OperationNotSupportedException("Cannot target VLANs with firewall rules");
case VM: throw new OperationNotSupportedException("Cannot target virtual machines with firewall rules");
case GLOBAL:
Firewall targetGroup = getFirewall(sourceEndpoint.getProviderFirewallId());
if( targetGroup == null ) {
throw new CloudException("No such source endpoint firewall: " + sourceEndpoint.getProviderFirewallId());
}
json.put("group_id", targetGroup.getProviderFirewallId());
break;
}
wrapper.put("security_group_rule", json);
JSONObject result = method.postServers("/os-security-group-rules", null, new JSONObject(wrapper), false);
if( result != null && result.has("security_group_rule") ) {
try {
JSONObject rule = result.getJSONObject("security_group_rule");
return rule.getString("id");
}
catch( JSONException e ) {
logger.error("Invalid JSON returned from rule creation: " + e.getMessage());
throw new CloudException(e);
}
}
logger.error("authorize(): No firewall rule was created by the create attempt, and no error was returned");
throw new CloudException("No firewall rule was created");
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String create(@Nonnull FirewallCreateOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.create");
try {
if( options.getProviderVlanId() != null ) {
throw new OperationNotSupportedException("Creating IP addresses in VLANs is not supported");
}
HashMap<String,Object> wrapper = new HashMap<String,Object>();
HashMap<String,Object> json = new HashMap<String,Object>();
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
json.put("name", options.getName());
json.put("description", options.getDescription());
wrapper.put("security_group", json);
JSONObject result = method.postServers("/os-security-groups", null, new JSONObject(wrapper), false);
if( result != null && result.has("security_group") ) {
try {
JSONObject ob = result.getJSONObject("security_group");
Firewall fw = toFirewall(ob);
if( fw != null ) {
String id = fw.getProviderFirewallId();
if( id != null ) {
return id;
}
}
}
catch( JSONException e ) {
logger.error("create(): Unable to understand create response: " + e.getMessage());
e.printStackTrace();
throw new CloudException(e);
}
}
logger.error("create(): No firewall was created by the create attempt, and no error was returned");
throw new CloudException("No firewall was created");
}
finally {
APITrace.end();
}
}
@Override
public void delete(@Nonnull String firewallId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.delete");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR;
do {
try {
method.deleteServers("/os-security-groups", firewallId);
return;
}
catch( NovaException e ) {
if( e.getHttpCode() != HttpStatus.SC_CONFLICT ) {
throw e;
}
}
try { Thread.sleep(CalendarWrapper.MINUTE); }
catch( InterruptedException e ) { /* ignore */ }
} while( System.currentTimeMillis() < timeout );
}
finally {
APITrace.end();
}
}
@Override
public @Nullable Firewall getFirewall(@Nonnull String firewallId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.getFirewall");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/os-security-groups", firewallId, false);
if( ob == null ) {
return null;
}
try {
if( ob.has("security_group") ) {
JSONObject json = ob.getJSONObject("security_group");
Firewall fw = toFirewall(json);
if( fw != null ) {
return fw;
}
}
}
catch( JSONException e ) {
logger.error("getRule(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security group");
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String getProviderTermForFirewall(@Nonnull Locale locale) {
return "security group";
}
@Override
public @Nonnull Collection<FirewallRule> getRules(@Nonnull String firewallId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.getRules");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/os-security-groups", firewallId, false);
if( ob == null ) {
return null;
}
try {
if( ob.has("security_group") ) {
JSONObject json = ob.getJSONObject("security_group");
if( !json.has("rules") ) {
return Collections.emptyList();
}
ArrayList<FirewallRule> rules = new ArrayList<FirewallRule>();
JSONArray arr = json.getJSONArray("rules");
Iterable<Firewall> myFirewalls = null;
for( int i=0; i<arr.length(); i++ ) {
JSONObject rule = arr.getJSONObject(i);
int startPort = -1, endPort = -1;
Protocol protocol = null;
String ruleId = null;
if( rule.has("id") ) {
ruleId = rule.getString("id");
}
if( ruleId == null ) {
continue;
}
RuleTarget sourceEndpoint = null;
if( rule.has("ip_range") ) {
JSONObject range = rule.getJSONObject("ip_range");
if( range.has("cidr") ) {
sourceEndpoint = RuleTarget.getCIDR(range.getString("cidr"));
}
}
if( rule.has("group") ) {
JSONObject g = rule.getJSONObject("group");
String id = (g.has("id") ? g.getString("id") : null);
if( id != null ) {
sourceEndpoint = RuleTarget.getGlobal(id);
}
else {
String o = (g.has("tenant_id") ? g.getString("tenant_id") : null);
if( getTenantId().equals(o) ) {
String n = (g.has("name") ? g.getString("name") : null);
if( n != null ) {
if( myFirewalls == null ) {
myFirewalls = list();
}
for( Firewall fw : myFirewalls ) {
if( fw.getName().equals(n) ) {
sourceEndpoint = RuleTarget.getGlobal(fw.getProviderFirewallId());
break;
}
}
}
}
}
}
if( sourceEndpoint == null ) {
continue;
}
if( rule.has("from_port") ) {
startPort = rule.getInt("from_port");
}
if( rule.has("to_port") ) {
endPort = rule.getInt("to_port");
}
if( startPort == -1 && endPort != -1 ) {
startPort = endPort;
}
else if( endPort == -1 && startPort != -1 ) {
endPort = startPort;
}
if( startPort > endPort ) {
int s = startPort;
startPort = endPort;
endPort = s;
}
if( rule.has("ip_protocol") ) {
String p = null;
if( !rule.isNull("ip_protocol") ) {
- rule.getString("ip_protocol");
+ p = rule.getString("ip_protocol");
}
if( p == null || p.equalsIgnoreCase("null") ) {
protocol = Protocol.ANY;
}
else {
protocol = Protocol.valueOf(p.toUpperCase());
}
}
if( protocol == null ) {
protocol = Protocol.TCP;
}
rules.add(FirewallRule.getInstance(ruleId, firewallId, sourceEndpoint, Direction.INGRESS, protocol, Permission.ALLOW, RuleTarget.getGlobal(firewallId), startPort, endPort));
}
return rules;
}
}
catch( JSONException e ) {
logger.error("getRules(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups");
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Requirement identifyPrecedenceRequirement(boolean inVlan) throws InternalException, CloudException {
return Requirement.NONE;
}
private boolean verifySupport() throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.verifySupport");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
try {
method.getServers("/os-security-groups", null, false);
return true;
}
catch( CloudException e ) {
if( e.getHttpCode() == 404 ) {
return false;
}
throw e;
}
}
finally {
APITrace.end();
}
}
@SuppressWarnings("SimplifiableIfStatement")
@Override
public boolean isSubscribed() throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.isSubscribed");
try {
if( ((NovaOpenStack)getProvider()).getMajorVersion() > 1 && ((NovaOpenStack)getProvider()).getComputeServices().getVirtualMachineSupport().isSubscribed() ) {
return verifySupport();
}
if( ((NovaOpenStack)getProvider()).getMajorVersion() == 1 && ((NovaOpenStack)getProvider()).getMinorVersion() >= 1 && ((NovaOpenStack)getProvider()).getComputeServices().getVirtualMachineSupport().isSubscribed() ) {
return verifySupport();
}
return false;
}
finally {
APITrace.end();
}
}
@Override
public boolean isZeroPrecedenceHighest() throws InternalException, CloudException {
return true; // nonsense since no precedence is supported
}
@Override
public @Nonnull Collection<Firewall> list() throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.list");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/os-security-groups", null, false);
ArrayList<Firewall> firewalls = new ArrayList<Firewall>();
try {
if( ob != null && ob.has("security_groups") ) {
JSONArray list = ob.getJSONArray("security_groups");
for( int i=0; i<list.length(); i++ ) {
JSONObject json = list.getJSONObject(i);
Firewall fw = toFirewall(json);
if( fw != null ) {
firewalls.add(fw);
}
}
}
}
catch( JSONException e ) {
logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace();
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups in " + ob.toString());
}
return firewalls;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<ResourceStatus> listFirewallStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.listFirewallStatus");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/os-security-groups", null, false);
ArrayList<ResourceStatus> firewalls = new ArrayList<ResourceStatus>();
try {
if( ob != null && ob.has("security_groups") ) {
JSONArray list = ob.getJSONArray("security_groups");
for( int i=0; i<list.length(); i++ ) {
JSONObject json = list.getJSONObject(i);
try {
ResourceStatus fw = toStatus(json);
if( fw != null ) {
firewalls.add(fw);
}
}
catch( JSONException e ) {
throw new CloudException("Invalid JSON from cloud: " + e.getMessage());
}
}
}
}
catch( JSONException e ) {
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups in " + ob.toString());
}
return firewalls;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<RuleTargetType> listSupportedDestinationTypes(boolean inVlan) throws InternalException, CloudException {
if( inVlan ) {
return Collections.emptyList();
}
return Collections.singletonList(RuleTargetType.GLOBAL);
}
@Override
public @Nonnull Iterable<Direction> listSupportedDirections(boolean inVlan) throws InternalException, CloudException {
if( inVlan ) {
return Collections.emptyList();
}
return Collections.singletonList(Direction.INGRESS);
}
@Override
public @Nonnull Iterable<Permission> listSupportedPermissions(boolean inVlan) throws InternalException, CloudException {
if( inVlan ) {
return Collections.emptyList();
}
return Collections.singletonList(Permission.ALLOW);
}
@Override
public @Nonnull Iterable<RuleTargetType> listSupportedSourceTypes(boolean inVlan) throws InternalException, CloudException {
if( inVlan ) {
return Collections.emptyList();
}
ArrayList<RuleTargetType> list= new ArrayList<RuleTargetType>();
list.add(RuleTargetType.CIDR);
list.add(RuleTargetType.GLOBAL);
return list;
}
@Override
public void revoke(@Nonnull String providerFirewallRuleId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.revoke");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR;
do {
try {
method.deleteServers("/os-security-group-rules", providerFirewallRuleId);
return;
}
catch( NovaException e ) {
if( e.getHttpCode() != HttpStatus.SC_CONFLICT ) {
throw e;
}
}
try { Thread.sleep(CalendarWrapper.MINUTE); }
catch( InterruptedException e ) { /* ignore */ }
} while( System.currentTimeMillis() < timeout );
}
finally {
APITrace.end();
}
}
@Override
@Deprecated
public void revoke(@Nonnull String firewallId, @Nonnull String cidr, @Nonnull Protocol protocol, int beginPort, int endPort) throws CloudException, InternalException {
revoke(firewallId, Direction.INGRESS, Permission.ALLOW, cidr, protocol, RuleTarget.getGlobal(firewallId), beginPort, endPort);
}
@Override
@Deprecated
public void revoke(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull String cidr, @Nonnull Protocol protocol, int beginPort, int endPort) throws CloudException, InternalException {
revoke(firewallId, direction, Permission.ALLOW, cidr, protocol, RuleTarget.getGlobal(firewallId), beginPort, endPort);
}
@Override
@Deprecated
public void revoke(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull String source, @Nonnull Protocol protocol, int beginPort, int endPort) throws CloudException, InternalException {
revoke(firewallId, direction, permission, source, protocol, RuleTarget.getGlobal(firewallId), beginPort, endPort);
}
@Override
public void revoke(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull String source, @Nonnull Protocol protocol, @Nonnull RuleTarget target, int beginPort, int endPort) throws CloudException, InternalException {
APITrace.begin(getProvider(), "Firewall.revoke");
try {
if( direction.equals(Direction.EGRESS) ) {
throw new OperationNotSupportedException(getProvider().getCloudName() + " does not support egress rules.");
}
FirewallRule targetRule = null;
for( FirewallRule rule : getRules(firewallId) ) {
RuleTarget t = rule.getSourceEndpoint();
if( t.getRuleTargetType().equals(RuleTargetType.CIDR) && source.equals(t.getCidr()) ) {
RuleTarget rt = rule.getDestinationEndpoint();
if( target.getRuleTargetType().equals(rt.getRuleTargetType()) ) {
boolean matches = false;
switch( rt.getRuleTargetType() ) {
case CIDR:
//noinspection ConstantConditions
matches = target.getCidr().equals(rt.getCidr());
break;
case GLOBAL:
//noinspection ConstantConditions
matches = target.getProviderFirewallId().equals(rt.getProviderFirewallId());
break;
case VLAN:
//noinspection ConstantConditions
matches = target.getProviderVlanId().equals(rt.getProviderVlanId());
break;
case VM:
//noinspection ConstantConditions
matches = target.getProviderVirtualMachineId().equals(rt.getProviderVirtualMachineId());
break;
}
if( matches && rule.getProtocol().equals(protocol) && rule.getPermission().equals(permission) && rule.getDirection().equals(direction) ) {
if( rule.getStartPort() == beginPort && rule.getEndPort() == endPort ) {
targetRule = rule;
break;
}
}
}
}
else if( t.getRuleTargetType().equals(RuleTargetType.GLOBAL) && source.equals(t.getProviderFirewallId()) ) {
RuleTarget rt = rule.getDestinationEndpoint();
if( target.getRuleTargetType().equals(rt.getRuleTargetType()) ) {
boolean matches = false;
switch( rt.getRuleTargetType() ) {
case CIDR:
//noinspection ConstantConditions
matches = target.getCidr().equals(rt.getCidr());
break;
case GLOBAL:
//noinspection ConstantConditions
matches = target.getProviderFirewallId().equals(rt.getProviderFirewallId());
break;
case VLAN:
//noinspection ConstantConditions
matches = target.getProviderVlanId().equals(rt.getProviderVlanId());
break;
case VM:
//noinspection ConstantConditions
matches = target.getProviderVirtualMachineId().equals(rt.getProviderVirtualMachineId());
break;
}
if( matches && rule.getProtocol().equals(protocol) && rule.getPermission().equals(permission) && rule.getDirection().equals(direction) ) {
if( rule.getStartPort() == beginPort && rule.getEndPort() == endPort ) {
targetRule = rule;
break;
}
}
}
}
}
if( targetRule == null ) {
throw new CloudException("No such firewall rule");
}
revoke(targetRule.getProviderRuleId());
}
finally {
APITrace.end();
}
}
@Override
public boolean supportsRules(@Nonnull Direction direction, @Nonnull Permission permission, boolean inVlan) throws CloudException, InternalException {
return (!inVlan && Direction.INGRESS.equals(direction) && Permission.ALLOW.equals(permission));
}
@Override
public boolean supportsFirewallSources() throws CloudException, InternalException {
return true;
}
private @Nullable Firewall toFirewall(@Nonnull JSONObject json) throws CloudException, InternalException {
try {
Firewall fw = new Firewall();
String id = null, name = null;
fw.setActive(true);
fw.setAvailable(true);
fw.setProviderVlanId(null);
String regionId = getContext().getRegionId();
fw.setRegionId(regionId == null ? "" : regionId);
if( json.has("id") ) {
id = json.getString("id");
}
if( json.has("name") ) {
name = json.getString("name");
}
if( json.has("description") ) {
fw.setDescription(json.getString("description"));
}
if( id == null ) {
return null;
}
fw.setProviderFirewallId(id);
if( name == null ) {
name = id;
}
fw.setName(name);
if( fw.getDescription() == null ) {
fw.setDescription(name);
}
return fw;
}
catch( JSONException e ) {
throw new InternalException(e);
}
}
private @Nullable ResourceStatus toStatus(@Nonnull JSONObject json) throws JSONException {
String id = null;
if( json.has("id") ) {
id = json.getString("id");
}
if( id == null ) {
return null;
}
return new ResourceStatus(id, true);
}
}
| true | true | public @Nonnull Collection<FirewallRule> getRules(@Nonnull String firewallId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.getRules");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/os-security-groups", firewallId, false);
if( ob == null ) {
return null;
}
try {
if( ob.has("security_group") ) {
JSONObject json = ob.getJSONObject("security_group");
if( !json.has("rules") ) {
return Collections.emptyList();
}
ArrayList<FirewallRule> rules = new ArrayList<FirewallRule>();
JSONArray arr = json.getJSONArray("rules");
Iterable<Firewall> myFirewalls = null;
for( int i=0; i<arr.length(); i++ ) {
JSONObject rule = arr.getJSONObject(i);
int startPort = -1, endPort = -1;
Protocol protocol = null;
String ruleId = null;
if( rule.has("id") ) {
ruleId = rule.getString("id");
}
if( ruleId == null ) {
continue;
}
RuleTarget sourceEndpoint = null;
if( rule.has("ip_range") ) {
JSONObject range = rule.getJSONObject("ip_range");
if( range.has("cidr") ) {
sourceEndpoint = RuleTarget.getCIDR(range.getString("cidr"));
}
}
if( rule.has("group") ) {
JSONObject g = rule.getJSONObject("group");
String id = (g.has("id") ? g.getString("id") : null);
if( id != null ) {
sourceEndpoint = RuleTarget.getGlobal(id);
}
else {
String o = (g.has("tenant_id") ? g.getString("tenant_id") : null);
if( getTenantId().equals(o) ) {
String n = (g.has("name") ? g.getString("name") : null);
if( n != null ) {
if( myFirewalls == null ) {
myFirewalls = list();
}
for( Firewall fw : myFirewalls ) {
if( fw.getName().equals(n) ) {
sourceEndpoint = RuleTarget.getGlobal(fw.getProviderFirewallId());
break;
}
}
}
}
}
}
if( sourceEndpoint == null ) {
continue;
}
if( rule.has("from_port") ) {
startPort = rule.getInt("from_port");
}
if( rule.has("to_port") ) {
endPort = rule.getInt("to_port");
}
if( startPort == -1 && endPort != -1 ) {
startPort = endPort;
}
else if( endPort == -1 && startPort != -1 ) {
endPort = startPort;
}
if( startPort > endPort ) {
int s = startPort;
startPort = endPort;
endPort = s;
}
if( rule.has("ip_protocol") ) {
String p = null;
if( !rule.isNull("ip_protocol") ) {
rule.getString("ip_protocol");
}
if( p == null || p.equalsIgnoreCase("null") ) {
protocol = Protocol.ANY;
}
else {
protocol = Protocol.valueOf(p.toUpperCase());
}
}
if( protocol == null ) {
protocol = Protocol.TCP;
}
rules.add(FirewallRule.getInstance(ruleId, firewallId, sourceEndpoint, Direction.INGRESS, protocol, Permission.ALLOW, RuleTarget.getGlobal(firewallId), startPort, endPort));
}
return rules;
}
}
catch( JSONException e ) {
logger.error("getRules(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups");
}
return null;
}
finally {
APITrace.end();
}
}
| public @Nonnull Collection<FirewallRule> getRules(@Nonnull String firewallId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Firewall.getRules");
try {
NovaMethod method = new NovaMethod((NovaOpenStack)getProvider());
JSONObject ob = method.getServers("/os-security-groups", firewallId, false);
if( ob == null ) {
return null;
}
try {
if( ob.has("security_group") ) {
JSONObject json = ob.getJSONObject("security_group");
if( !json.has("rules") ) {
return Collections.emptyList();
}
ArrayList<FirewallRule> rules = new ArrayList<FirewallRule>();
JSONArray arr = json.getJSONArray("rules");
Iterable<Firewall> myFirewalls = null;
for( int i=0; i<arr.length(); i++ ) {
JSONObject rule = arr.getJSONObject(i);
int startPort = -1, endPort = -1;
Protocol protocol = null;
String ruleId = null;
if( rule.has("id") ) {
ruleId = rule.getString("id");
}
if( ruleId == null ) {
continue;
}
RuleTarget sourceEndpoint = null;
if( rule.has("ip_range") ) {
JSONObject range = rule.getJSONObject("ip_range");
if( range.has("cidr") ) {
sourceEndpoint = RuleTarget.getCIDR(range.getString("cidr"));
}
}
if( rule.has("group") ) {
JSONObject g = rule.getJSONObject("group");
String id = (g.has("id") ? g.getString("id") : null);
if( id != null ) {
sourceEndpoint = RuleTarget.getGlobal(id);
}
else {
String o = (g.has("tenant_id") ? g.getString("tenant_id") : null);
if( getTenantId().equals(o) ) {
String n = (g.has("name") ? g.getString("name") : null);
if( n != null ) {
if( myFirewalls == null ) {
myFirewalls = list();
}
for( Firewall fw : myFirewalls ) {
if( fw.getName().equals(n) ) {
sourceEndpoint = RuleTarget.getGlobal(fw.getProviderFirewallId());
break;
}
}
}
}
}
}
if( sourceEndpoint == null ) {
continue;
}
if( rule.has("from_port") ) {
startPort = rule.getInt("from_port");
}
if( rule.has("to_port") ) {
endPort = rule.getInt("to_port");
}
if( startPort == -1 && endPort != -1 ) {
startPort = endPort;
}
else if( endPort == -1 && startPort != -1 ) {
endPort = startPort;
}
if( startPort > endPort ) {
int s = startPort;
startPort = endPort;
endPort = s;
}
if( rule.has("ip_protocol") ) {
String p = null;
if( !rule.isNull("ip_protocol") ) {
p = rule.getString("ip_protocol");
}
if( p == null || p.equalsIgnoreCase("null") ) {
protocol = Protocol.ANY;
}
else {
protocol = Protocol.valueOf(p.toUpperCase());
}
}
if( protocol == null ) {
protocol = Protocol.TCP;
}
rules.add(FirewallRule.getInstance(ruleId, firewallId, sourceEndpoint, Direction.INGRESS, protocol, Permission.ALLOW, RuleTarget.getGlobal(firewallId), startPort, endPort));
}
return rules;
}
}
catch( JSONException e ) {
logger.error("getRules(): Unable to identify expected values in JSON: " + e.getMessage());
throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups");
}
return null;
}
finally {
APITrace.end();
}
}
|
diff --git a/src/schedule/ScheduleHeuristic.java b/src/schedule/ScheduleHeuristic.java
index 4201fd4..a3b660d 100644
--- a/src/schedule/ScheduleHeuristic.java
+++ b/src/schedule/ScheduleHeuristic.java
@@ -1,77 +1,77 @@
package src.schedule;
import java.util.ArrayList;
import java.util.List;
import src.optimizer.Heuristic;
public class ScheduleHeuristic implements Heuristic<Schedule> {
public Integer getByeWeekValue(Schedule evolvable) {
Integer value = 0;
List<Week> weeks = evolvable.getWeeks();
for(int i = 0; i < weeks.size(); i++) {
if(i >= 4 && i <= 11) {
continue;
}
Week w = weeks.get(i);
for(int j = 0; j < Week.DAYS_PER_WEEK; j++) {
Day day = w.getDay(j);
List<NFLEvent> events = day.getEvents();
for(NFLEvent event : events) {
if(event.getHome().equalsIgnoreCase("BYE")
|| event.getAway().equalsIgnoreCase("BYE")) {
value += 1;
}
}
}
}
return value;
}
@Override
public Integer getValue(Schedule evolvable) {
Integer value = 0;
for(Week w : evolvable.getWeeks()) {
Integer weekValue = 0;
// Everything is on Day 0 for now.
Day day = w.getDay(0);
List<String> teams = new ArrayList<String>();
for(NFLEvent e : day.getEvents()) {
teams.add(e.getAway());
teams.add(e.getHome());
}
for(int i = 0; i < teams.size(); i++) {
String team = teams.get(i);
if(!team.equals("BYE") && !teams.subList(0, i).contains(team)) {
//System.out.println("Team: " + team + " occurs " + occurences(team, teams) + " times.");
weekValue += (1 - occurences(team, teams));
}
}
- //System.out.println("Value for week: " + weekValue);
+ System.out.println("Value for week: " + weekValue);
value += weekValue;
}
//value += 0 - this.getByeWeekValue(evolvable);
return value;
}
public Integer occurences(String find, List<String> list) {
Integer value = 0;
for(String v : list) {
if(v.equals(find)) {
value += 1;
}
}
return value;
}
}
| true | true | public Integer getValue(Schedule evolvable) {
Integer value = 0;
for(Week w : evolvable.getWeeks()) {
Integer weekValue = 0;
// Everything is on Day 0 for now.
Day day = w.getDay(0);
List<String> teams = new ArrayList<String>();
for(NFLEvent e : day.getEvents()) {
teams.add(e.getAway());
teams.add(e.getHome());
}
for(int i = 0; i < teams.size(); i++) {
String team = teams.get(i);
if(!team.equals("BYE") && !teams.subList(0, i).contains(team)) {
//System.out.println("Team: " + team + " occurs " + occurences(team, teams) + " times.");
weekValue += (1 - occurences(team, teams));
}
}
//System.out.println("Value for week: " + weekValue);
value += weekValue;
}
//value += 0 - this.getByeWeekValue(evolvable);
return value;
}
| public Integer getValue(Schedule evolvable) {
Integer value = 0;
for(Week w : evolvable.getWeeks()) {
Integer weekValue = 0;
// Everything is on Day 0 for now.
Day day = w.getDay(0);
List<String> teams = new ArrayList<String>();
for(NFLEvent e : day.getEvents()) {
teams.add(e.getAway());
teams.add(e.getHome());
}
for(int i = 0; i < teams.size(); i++) {
String team = teams.get(i);
if(!team.equals("BYE") && !teams.subList(0, i).contains(team)) {
//System.out.println("Team: " + team + " occurs " + occurences(team, teams) + " times.");
weekValue += (1 - occurences(team, teams));
}
}
System.out.println("Value for week: " + weekValue);
value += weekValue;
}
//value += 0 - this.getByeWeekValue(evolvable);
return value;
}
|
diff --git a/jboss-5/src/main/java/org/mobicents/ha/javax/sip/cache/SIPDialogCacheData.java b/jboss-5/src/main/java/org/mobicents/ha/javax/sip/cache/SIPDialogCacheData.java
index d8d0359..d176147 100644
--- a/jboss-5/src/main/java/org/mobicents/ha/javax/sip/cache/SIPDialogCacheData.java
+++ b/jboss-5/src/main/java/org/mobicents/ha/javax/sip/cache/SIPDialogCacheData.java
@@ -1,271 +1,273 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.ha.javax.sip.cache;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.SipProviderImpl;
import gov.nist.javax.sip.message.SIPResponse;
import gov.nist.javax.sip.stack.AbstractHASipDialog;
import gov.nist.javax.sip.stack.SIPDialog;
import java.text.ParseException;
import java.util.Map;
import java.util.Map.Entry;
import javax.sip.PeerUnavailableException;
import javax.sip.SipFactory;
import javax.sip.address.Address;
import javax.sip.header.ContactHeader;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.TransactionManager;
import org.jboss.cache.Cache;
import org.jboss.cache.CacheException;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.mobicents.cache.CacheData;
import org.mobicents.cache.MobicentsCache;
import org.mobicents.ha.javax.sip.ClusteredSipStack;
import org.mobicents.ha.javax.sip.HASipDialog;
import org.mobicents.ha.javax.sip.HASipDialogFactory;
/**
* @author [email protected]
* @author martins
*
*/
public class SIPDialogCacheData extends CacheData {
private static final String APPDATA = "APPDATA";
private ClusteredSipStack clusteredSipStack;
public SIPDialogCacheData(Fqn nodeFqn, MobicentsCache mobicentsCache, ClusteredSipStack clusteredSipStack) {
super(nodeFqn, mobicentsCache);
this.clusteredSipStack = clusteredSipStack;
}
public SIPDialog getSIPDialog(String dialogId) throws SipCacheException {
HASipDialog haSipDialog = null;
final Cache jbossCache = getMobicentsCache().getJBossCache();
final boolean isBuddyReplicationEnabled = jbossCache.getConfiguration().getBuddyReplicationConfig().isEnabled();
TransactionManager transactionManager = null;
if(isBuddyReplicationEnabled) {
transactionManager = jbossCache.getConfiguration().getRuntimeConfig().getTransactionManager();
}
boolean doTx = false;
try {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager :" + transactionManager);
}
if(transactionManager != null && transactionManager.getTransaction() == null) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager begin transaction");
}
transactionManager.begin();
doTx = true;
}
+ // Issue 1517 : http://code.google.com/p/mobicents/issues/detail?id=1517
+ // Adding code to handle Buddy replication to force data gravitation
if(isBuddyReplicationEnabled) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("forcing data gravitation since buddy replication is enabled");
}
jbossCache.getInvocationContext().getOptionOverrides().setForceDataGravitation(true);
}
final Node<String,Object> childNode = getNode().getChild(dialogId);
if(childNode != null) {
try {
final Map<String, Object> dialogMetaData = childNode.getData();
final Object dialogAppData = childNode.get(APPDATA);
haSipDialog = createDialog(dialogId, dialogMetaData, dialogAppData);
} catch (CacheException e) {
throw new SipCacheException("A problem occured while retrieving the following dialog " + dialogId + " from the TreeCache", e);
}
}
} catch (Exception ex) {
try {
// Let's set it no matter what.
transactionManager.setRollbackOnly();
} catch (Exception exn) {
clusteredSipStack.getStackLogger().logError("Problem rolling back session mgmt transaction",
exn);
}
} finally {
if (doTx) {
try {
if (transactionManager.getTransaction().getStatus() != Status.STATUS_MARKED_ROLLBACK) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager committing transaction");
}
transactionManager.commit();
} else {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("endBatch(): rolling back batch");
}
transactionManager.rollback();
}
} catch (RollbackException re) {
// Do nothing here since cache may rollback automatically.
clusteredSipStack.getStackLogger().logWarning("endBatch(): rolling back transaction with exception: "
+ re);
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
throw new RuntimeException(
"endTransaction(): Caught Exception ending batch: ",
e);
}
}
}
return (SIPDialog) haSipDialog;
}
/*
* (non-Javadoc)
* @see org.mobicents.ha.javax.sip.cache.SipCache#updateDialog(gov.nist.javax.sip.stack.SIPDialog)
*/
public void updateSIPDialog(SIPDialog sipDialog) throws SipCacheException {
final String dialogId = sipDialog.getDialogId();
final Node<String,Object> childNode = getNode().getChild(dialogId);
if(childNode != null) {
try {
final Map<String, Object> dialogMetaData = childNode.getData();
final HASipDialog haSipDialog = (HASipDialog) sipDialog;
final Object dialogAppData = childNode.get(APPDATA);
updateDialog(haSipDialog, dialogMetaData, dialogAppData);
} catch (CacheException e) {
throw new SipCacheException("A problem occured while retrieving the following dialog " + dialogId + " from the TreeCache", e);
}
}
}
public HASipDialog createDialog(String dialogId, Map<String, Object> dialogMetaData, Object dialogAppData) throws SipCacheException {
HASipDialog haSipDialog = null;
if(dialogMetaData != null) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("sipStack " + this + " dialog " + dialogId + " is present in the distributed cache, recreating it locally");
}
final String lastResponseStringified = (String) dialogMetaData.get(AbstractHASipDialog.LAST_RESPONSE);
try {
final SIPResponse lastResponse = (SIPResponse) SipFactory.getInstance().createMessageFactory().createResponse(lastResponseStringified);
haSipDialog = HASipDialogFactory.createHASipDialog(clusteredSipStack.getReplicationStrategy(), (SipProviderImpl)clusteredSipStack.getSipProviders().next(), lastResponse);
haSipDialog.setDialogId(dialogId);
updateDialogMetaData(dialogMetaData, dialogAppData, haSipDialog);
// setLastResponse won't be called on recreation since version will be null on recreation
haSipDialog.setLastResponse(lastResponse);
if(haSipDialog.isServer()) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("HA SIP Dialog " + haSipDialog.isServer() + " switching parties on recreation");
}
Address remoteParty = haSipDialog.getLocalParty();
Address localParty = haSipDialog.getRemoteParty();
haSipDialog.setLocalPartyInternal(localParty);
haSipDialog.setRemotePartyInternal(remoteParty);
}
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("HA SIP Dialog " + dialogId + " localTag = " + haSipDialog.getLocalTag());
clusteredSipStack.getStackLogger().logDebug("HA SIP Dialog " + dialogId + " remoteTag = " + haSipDialog.getRemoteTag());
clusteredSipStack.getStackLogger().logDebug("HA SIP Dialog " + dialogId + " localParty = " + haSipDialog.getLocalParty());
clusteredSipStack.getStackLogger().logDebug("HA SIP Dialog " + dialogId + " remoteParty = " + haSipDialog.getRemoteParty());
}
} catch (PeerUnavailableException e) {
throw new SipCacheException("A problem occured while retrieving the following dialog " + dialogId + " from the TreeCache", e);
} catch (ParseException e) {
throw new SipCacheException("A problem occured while retrieving the following dialog " + dialogId + " from the TreeCache", e);
}
}
return haSipDialog;
}
public void updateDialog(HASipDialog haSipDialog, Map<String, Object> dialogMetaData,
Object dialogAppData) throws SipCacheException {
if(dialogMetaData != null) {
final long currentVersion = haSipDialog.getVersion();
final Long cacheVersion = ((Long)dialogMetaData.get(AbstractHASipDialog.VERSION));
if(cacheVersion != null && currentVersion < cacheVersion.longValue()) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("HA SIP Dialog " + haSipDialog + " with dialogId " + haSipDialog.getDialogIdToReplicate() + " is older " + currentVersion + " than the one in the cache " + cacheVersion + " updating it");
}
try {
final String lastResponseStringified = (String) dialogMetaData.get(AbstractHASipDialog.LAST_RESPONSE);
final SIPResponse lastResponse = (SIPResponse) SipFactory.getInstance().createMessageFactory().createResponse(lastResponseStringified);
haSipDialog.setLastResponse(lastResponse);
updateDialogMetaData(dialogMetaData, dialogAppData, haSipDialog);
} catch (PeerUnavailableException e) {
throw new SipCacheException("A problem occured while retrieving the following dialog " + haSipDialog.getDialogIdToReplicate() + " from the TreeCache", e);
} catch (ParseException e) {
throw new SipCacheException("A problem occured while retrieving the following dialog " + haSipDialog.getDialogIdToReplicate() + " from the TreeCache", e);
}
} else {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("HA SIP Dialog " + haSipDialog + " with dialogId " + haSipDialog.getDialogIdToReplicate() + " is not older " + currentVersion + " than the one in the cache " + cacheVersion + ", not updating it");
}
}
}
}
/**
* Update the haSipDialog passed in param with the dialogMetaData and app meta data
* @param dialogMetaData
* @param dialogAppData
* @param haSipDialog
* @throws ParseException
* @throws PeerUnavailableException
*/
private void updateDialogMetaData(Map<String, Object> dialogMetaData, Object dialogAppData, HASipDialog haSipDialog) throws ParseException,
PeerUnavailableException {
haSipDialog.setMetaDataToReplicate(dialogMetaData);
haSipDialog.setApplicationDataToReplicate(dialogAppData);
final String contactStringified = (String) dialogMetaData.get(AbstractHASipDialog.CONTACT_HEADER);
if(contactStringified != null) {
Address contactAddress = SipFactory.getInstance().createAddressFactory().createAddress(contactStringified);
ContactHeader contactHeader = SipFactory.getInstance().createHeaderFactory().createContactHeader(contactAddress);
haSipDialog.setContactHeader(contactHeader);
}
}
public void putSIPDialog(SIPDialog dialog) throws SipCacheException {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logStackTrace();
}
final HASipDialog haSipDialog = (HASipDialog) dialog;
final String dialogId = haSipDialog.getDialogIdToReplicate();
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("put HA SIP Dialog " + dialog + " with dialog " + dialogId);
}
final Node childNode = getNode().addChild(Fqn.fromElements(dialogId));
for (Entry<String, Object> metaData : haSipDialog.getMetaDataToReplicate().entrySet()) {
childNode.put(metaData.getKey(), metaData.getValue());
}
final Object dialogAppData = haSipDialog.getApplicationDataToReplicate();
if(dialogAppData != null) {
childNode.put(APPDATA, dialogAppData);
}
}
public boolean removeSIPDialog(String dialogId) {
return getNode().removeChild(dialogId);
}
}
| true | true | public SIPDialog getSIPDialog(String dialogId) throws SipCacheException {
HASipDialog haSipDialog = null;
final Cache jbossCache = getMobicentsCache().getJBossCache();
final boolean isBuddyReplicationEnabled = jbossCache.getConfiguration().getBuddyReplicationConfig().isEnabled();
TransactionManager transactionManager = null;
if(isBuddyReplicationEnabled) {
transactionManager = jbossCache.getConfiguration().getRuntimeConfig().getTransactionManager();
}
boolean doTx = false;
try {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager :" + transactionManager);
}
if(transactionManager != null && transactionManager.getTransaction() == null) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager begin transaction");
}
transactionManager.begin();
doTx = true;
}
if(isBuddyReplicationEnabled) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("forcing data gravitation since buddy replication is enabled");
}
jbossCache.getInvocationContext().getOptionOverrides().setForceDataGravitation(true);
}
final Node<String,Object> childNode = getNode().getChild(dialogId);
if(childNode != null) {
try {
final Map<String, Object> dialogMetaData = childNode.getData();
final Object dialogAppData = childNode.get(APPDATA);
haSipDialog = createDialog(dialogId, dialogMetaData, dialogAppData);
} catch (CacheException e) {
throw new SipCacheException("A problem occured while retrieving the following dialog " + dialogId + " from the TreeCache", e);
}
}
} catch (Exception ex) {
try {
// Let's set it no matter what.
transactionManager.setRollbackOnly();
} catch (Exception exn) {
clusteredSipStack.getStackLogger().logError("Problem rolling back session mgmt transaction",
exn);
}
} finally {
if (doTx) {
try {
if (transactionManager.getTransaction().getStatus() != Status.STATUS_MARKED_ROLLBACK) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager committing transaction");
}
transactionManager.commit();
} else {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("endBatch(): rolling back batch");
}
transactionManager.rollback();
}
} catch (RollbackException re) {
// Do nothing here since cache may rollback automatically.
clusteredSipStack.getStackLogger().logWarning("endBatch(): rolling back transaction with exception: "
+ re);
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
throw new RuntimeException(
"endTransaction(): Caught Exception ending batch: ",
e);
}
}
}
return (SIPDialog) haSipDialog;
}
| public SIPDialog getSIPDialog(String dialogId) throws SipCacheException {
HASipDialog haSipDialog = null;
final Cache jbossCache = getMobicentsCache().getJBossCache();
final boolean isBuddyReplicationEnabled = jbossCache.getConfiguration().getBuddyReplicationConfig().isEnabled();
TransactionManager transactionManager = null;
if(isBuddyReplicationEnabled) {
transactionManager = jbossCache.getConfiguration().getRuntimeConfig().getTransactionManager();
}
boolean doTx = false;
try {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager :" + transactionManager);
}
if(transactionManager != null && transactionManager.getTransaction() == null) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager begin transaction");
}
transactionManager.begin();
doTx = true;
}
// Issue 1517 : http://code.google.com/p/mobicents/issues/detail?id=1517
// Adding code to handle Buddy replication to force data gravitation
if(isBuddyReplicationEnabled) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("forcing data gravitation since buddy replication is enabled");
}
jbossCache.getInvocationContext().getOptionOverrides().setForceDataGravitation(true);
}
final Node<String,Object> childNode = getNode().getChild(dialogId);
if(childNode != null) {
try {
final Map<String, Object> dialogMetaData = childNode.getData();
final Object dialogAppData = childNode.get(APPDATA);
haSipDialog = createDialog(dialogId, dialogMetaData, dialogAppData);
} catch (CacheException e) {
throw new SipCacheException("A problem occured while retrieving the following dialog " + dialogId + " from the TreeCache", e);
}
}
} catch (Exception ex) {
try {
// Let's set it no matter what.
transactionManager.setRollbackOnly();
} catch (Exception exn) {
clusteredSipStack.getStackLogger().logError("Problem rolling back session mgmt transaction",
exn);
}
} finally {
if (doTx) {
try {
if (transactionManager.getTransaction().getStatus() != Status.STATUS_MARKED_ROLLBACK) {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("transaction manager committing transaction");
}
transactionManager.commit();
} else {
if(clusteredSipStack.getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
clusteredSipStack.getStackLogger().logDebug("endBatch(): rolling back batch");
}
transactionManager.rollback();
}
} catch (RollbackException re) {
// Do nothing here since cache may rollback automatically.
clusteredSipStack.getStackLogger().logWarning("endBatch(): rolling back transaction with exception: "
+ re);
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
throw new RuntimeException(
"endTransaction(): Caught Exception ending batch: ",
e);
}
}
}
return (SIPDialog) haSipDialog;
}
|
diff --git a/services/bonita-scheduler/bonita-scheduler-quartz/src/main/java/org/bonitasoft/engine/scheduler/impl/JDBCJobListener.java b/services/bonita-scheduler/bonita-scheduler-quartz/src/main/java/org/bonitasoft/engine/scheduler/impl/JDBCJobListener.java
index af79ed693b..950610e01a 100644
--- a/services/bonita-scheduler/bonita-scheduler-quartz/src/main/java/org/bonitasoft/engine/scheduler/impl/JDBCJobListener.java
+++ b/services/bonita-scheduler/bonita-scheduler-quartz/src/main/java/org/bonitasoft/engine/scheduler/impl/JDBCJobListener.java
@@ -1,118 +1,118 @@
/**
* Copyright (C) 2013 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* 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.
* You should have received a copy of the GNU Lesser 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.
*
* @since 6.1
*/
package org.bonitasoft.engine.scheduler.impl;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.bonitasoft.engine.commons.exceptions.SBonitaException;
import org.bonitasoft.engine.incident.Incident;
import org.bonitasoft.engine.incident.IncidentService;
import org.bonitasoft.engine.persistence.FilterOption;
import org.bonitasoft.engine.persistence.QueryOptions;
import org.bonitasoft.engine.persistence.SBonitaSearchException;
import org.bonitasoft.engine.scheduler.JobService;
import org.bonitasoft.engine.scheduler.model.SJobDescriptor;
import org.bonitasoft.engine.scheduler.model.SJobLog;
import org.bonitasoft.engine.scheduler.model.impl.SJobLogImpl;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author Celine Souchet
* @author Matthieu Chaffotte
*/
public class JDBCJobListener extends AbstractJobListener {
private final JobService jobService;
private final IncidentService incidentService;
public JDBCJobListener(final JobService jobService, final IncidentService incidentService) {
super();
this.jobService = jobService;
this.incidentService = incidentService;
}
@Override
public String getName() {
return "JDBCJobListener";
}
@Override
public void jobToBeExecuted(final JobExecutionContext context) {
// nothing to do
}
@Override
public void jobExecutionVetoed(final JobExecutionContext context) {
// nothing to do
}
@Override
public void jobWasExecuted(final JobExecutionContext context, final JobExecutionException jobException) {
final JobDetail jobDetail = context.getJobDetail();
final Long jobDescriptorId = (Long) jobDetail.getJobDataMap().getWrappedMap().get("jobId");
try {
if (jobException != null) {
final List<SJobLog> jobLogs = getJobLogs(jobDescriptorId);
if (!jobLogs.isEmpty()) {
final SJobLogImpl jobLog = (SJobLogImpl) jobLogs.get(0);
jobLog.setLastMessage(getStackTrace(jobException));
jobLog.setLastUpdateDate(System.currentTimeMillis());
jobLog.setRetryNumber(jobLog.getRetryNumber() + 1);
} else {
final SJobLogImpl jobLog = new SJobLogImpl(jobDescriptorId);
jobLog.setLastMessage(getStackTrace(jobException));
jobLog.setRetryNumber(Long.valueOf(0));
jobLog.setLastUpdateDate(System.currentTimeMillis());
jobService.createJobLog(jobLog);
}
} else {
final List<SJobLog> jobLogs = getJobLogs(jobDescriptorId);
if (!jobLogs.isEmpty()) {
jobService.deleteJobLog(jobLogs.get(0));
}
final SJobDescriptor jobDescriptor = jobService.getJobDescriptor(jobDescriptorId);
if (!getSchedulerService().isStillScheduled(jobDescriptor)) {
getSchedulerService().delete(jobDescriptor.getJobName());
}
}
} catch (final SBonitaException sbe) {
- final Integer tenantId = (Integer) jobDetail.getJobDataMap().getWrappedMap().get("tenantId");
+ final Long tenantId = (Long) jobDetail.getJobDataMap().getWrappedMap().get("tenantId");
final Incident incident = new Incident("An exception occurs during the job execution of the job descriptor" + jobDescriptorId, "", jobException,
sbe);
incidentService.report(tenantId, incident);
}
}
private List<SJobLog> getJobLogs(final long jobDescriptorId) throws SBonitaSearchException {
final List<FilterOption> filters = new ArrayList<FilterOption>(2);
filters.add(new FilterOption(SJobLog.class, "jobDescriptorId", jobDescriptorId));
final QueryOptions options = new QueryOptions(0, 1, null, filters, null);
return jobService.searchJobLogs(options);
}
private String getStackTrace(final JobExecutionException jobException) {
final StringWriter exceptionWriter = new StringWriter();
jobException.printStackTrace(new PrintWriter(exceptionWriter));
return exceptionWriter.toString();
}
}
| true | true | public void jobWasExecuted(final JobExecutionContext context, final JobExecutionException jobException) {
final JobDetail jobDetail = context.getJobDetail();
final Long jobDescriptorId = (Long) jobDetail.getJobDataMap().getWrappedMap().get("jobId");
try {
if (jobException != null) {
final List<SJobLog> jobLogs = getJobLogs(jobDescriptorId);
if (!jobLogs.isEmpty()) {
final SJobLogImpl jobLog = (SJobLogImpl) jobLogs.get(0);
jobLog.setLastMessage(getStackTrace(jobException));
jobLog.setLastUpdateDate(System.currentTimeMillis());
jobLog.setRetryNumber(jobLog.getRetryNumber() + 1);
} else {
final SJobLogImpl jobLog = new SJobLogImpl(jobDescriptorId);
jobLog.setLastMessage(getStackTrace(jobException));
jobLog.setRetryNumber(Long.valueOf(0));
jobLog.setLastUpdateDate(System.currentTimeMillis());
jobService.createJobLog(jobLog);
}
} else {
final List<SJobLog> jobLogs = getJobLogs(jobDescriptorId);
if (!jobLogs.isEmpty()) {
jobService.deleteJobLog(jobLogs.get(0));
}
final SJobDescriptor jobDescriptor = jobService.getJobDescriptor(jobDescriptorId);
if (!getSchedulerService().isStillScheduled(jobDescriptor)) {
getSchedulerService().delete(jobDescriptor.getJobName());
}
}
} catch (final SBonitaException sbe) {
final Integer tenantId = (Integer) jobDetail.getJobDataMap().getWrappedMap().get("tenantId");
final Incident incident = new Incident("An exception occurs during the job execution of the job descriptor" + jobDescriptorId, "", jobException,
sbe);
incidentService.report(tenantId, incident);
}
}
| public void jobWasExecuted(final JobExecutionContext context, final JobExecutionException jobException) {
final JobDetail jobDetail = context.getJobDetail();
final Long jobDescriptorId = (Long) jobDetail.getJobDataMap().getWrappedMap().get("jobId");
try {
if (jobException != null) {
final List<SJobLog> jobLogs = getJobLogs(jobDescriptorId);
if (!jobLogs.isEmpty()) {
final SJobLogImpl jobLog = (SJobLogImpl) jobLogs.get(0);
jobLog.setLastMessage(getStackTrace(jobException));
jobLog.setLastUpdateDate(System.currentTimeMillis());
jobLog.setRetryNumber(jobLog.getRetryNumber() + 1);
} else {
final SJobLogImpl jobLog = new SJobLogImpl(jobDescriptorId);
jobLog.setLastMessage(getStackTrace(jobException));
jobLog.setRetryNumber(Long.valueOf(0));
jobLog.setLastUpdateDate(System.currentTimeMillis());
jobService.createJobLog(jobLog);
}
} else {
final List<SJobLog> jobLogs = getJobLogs(jobDescriptorId);
if (!jobLogs.isEmpty()) {
jobService.deleteJobLog(jobLogs.get(0));
}
final SJobDescriptor jobDescriptor = jobService.getJobDescriptor(jobDescriptorId);
if (!getSchedulerService().isStillScheduled(jobDescriptor)) {
getSchedulerService().delete(jobDescriptor.getJobName());
}
}
} catch (final SBonitaException sbe) {
final Long tenantId = (Long) jobDetail.getJobDataMap().getWrappedMap().get("tenantId");
final Incident incident = new Incident("An exception occurs during the job execution of the job descriptor" + jobDescriptorId, "", jobException,
sbe);
incidentService.report(tenantId, incident);
}
}
|
diff --git a/src/test/java/org/sonar/report/pdf/test/ReporterTest.java b/src/test/java/org/sonar/report/pdf/test/ReporterTest.java
index 40e7cfd..9db53b2 100644
--- a/src/test/java/org/sonar/report/pdf/test/ReporterTest.java
+++ b/src/test/java/org/sonar/report/pdf/test/ReporterTest.java
@@ -1,42 +1,42 @@
package org.sonar.report.pdf.test;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.sonar.report.pdf.PDFReporter;
import org.sonar.report.pdf.TeamWorkbookPDFReporter;
import org.testng.annotations.Test;
import com.lowagie.text.DocumentException;
import java.net.URL;
public class ReporterTest {
/**
* Build a PDF report for the Sonar project on "sonar.base.url" instance of Sonar. The property "sonar.base.url" is
* set in report.properties, this file will be provided by the artifact consumer.
*
* The key of the project is not place in properties, this is provided in execution time.
*/
@Test(enabled = true, groups = { "report" }, dependsOnGroups = { "metrics" })
public void getReportTest() throws DocumentException, IOException, org.dom4j.DocumentException {
URL resource = this.getClass().getClassLoader().getResource("report.properties");
Properties config = new Properties();
config.load(resource.openStream());
PDFReporter reporter = new TeamWorkbookPDFReporter(new URL(config.getProperty("sonar.base.url") + "/images/sonar.png"),
- "es.juntadeandalucia.copt.transportes:autoriza", config.getProperty("sonar.base.url"));
+ "org.codehaus.sonar:sonar", config.getProperty("sonar.base.url"));
ByteArrayOutputStream baos = reporter.getReport();
FileOutputStream fos = null;
fos = new FileOutputStream("target/testReport.pdf");
baos.writeTo(fos);
fos.flush();
fos.close();
}
}
| true | true | public void getReportTest() throws DocumentException, IOException, org.dom4j.DocumentException {
URL resource = this.getClass().getClassLoader().getResource("report.properties");
Properties config = new Properties();
config.load(resource.openStream());
PDFReporter reporter = new TeamWorkbookPDFReporter(new URL(config.getProperty("sonar.base.url") + "/images/sonar.png"),
"es.juntadeandalucia.copt.transportes:autoriza", config.getProperty("sonar.base.url"));
ByteArrayOutputStream baos = reporter.getReport();
FileOutputStream fos = null;
fos = new FileOutputStream("target/testReport.pdf");
baos.writeTo(fos);
fos.flush();
fos.close();
}
| public void getReportTest() throws DocumentException, IOException, org.dom4j.DocumentException {
URL resource = this.getClass().getClassLoader().getResource("report.properties");
Properties config = new Properties();
config.load(resource.openStream());
PDFReporter reporter = new TeamWorkbookPDFReporter(new URL(config.getProperty("sonar.base.url") + "/images/sonar.png"),
"org.codehaus.sonar:sonar", config.getProperty("sonar.base.url"));
ByteArrayOutputStream baos = reporter.getReport();
FileOutputStream fos = null;
fos = new FileOutputStream("target/testReport.pdf");
baos.writeTo(fos);
fos.flush();
fos.close();
}
|
diff --git a/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java b/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java
index 584be4b2e..1732e3f9b 100644
--- a/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java
+++ b/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java
@@ -1,2478 +1,2478 @@
/*
* Copyright 2010 Ning, Inc.
*
* Ning 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 com.ning.http.client.providers.netty;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHandler.STATE;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.Body;
import com.ning.http.client.BodyGenerator;
import com.ning.http.client.ConnectionsPool;
import com.ning.http.client.Cookie;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.MaxRedirectException;
import com.ning.http.client.PerRequestConfig;
import com.ning.http.client.ProgressAsyncHandler;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.RandomAccessBody;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.client.filter.FilterContext;
import com.ning.http.client.filter.FilterException;
import com.ning.http.client.filter.IOExceptionFilter;
import com.ning.http.client.filter.ResponseFilter;
import com.ning.http.client.generators.InputStreamBodyGenerator;
import com.ning.http.client.listener.TransferCompletionHandler;
import com.ning.http.client.ntlm.NTLMEngine;
import com.ning.http.client.ntlm.NTLMEngineException;
import com.ning.http.client.providers.netty.FeedableBodyGenerator.FeedListener;
import com.ning.http.client.providers.netty.spnego.SpnegoEngine;
import com.ning.http.client.websocket.WebSocketUpgradeHandler;
import com.ning.http.multipart.MultipartBody;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.util.AsyncHttpProviderUtils;
import com.ning.http.util.AuthenticatorUtils;
import com.ning.http.client.providers.netty.util.CleanupChannelGroup;
import com.ning.http.util.ProxyUtils;
import com.ning.http.util.SslUtils;
import com.ning.http.util.UTF8UrlEncoder;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferOutputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureProgressListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DefaultChannelFuture;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.FileRegion;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultCookie;
import org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder;
import org.jboss.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedFile;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.ning.http.util.AsyncHttpProviderUtils.DEFAULT_CHARSET;
import static org.jboss.netty.channel.Channels.pipeline;
public class NettyAsyncHttpProvider extends SimpleChannelUpstreamHandler implements AsyncHttpProvider {
private final static String WEBSOCKET_KEY = "Sec-WebSocket-Key";
private final static String HTTP_HANDLER = "httpHandler";
protected final static String SSL_HANDLER = "sslHandler";
private final static String HTTPS = "https";
private final static String HTTP = "http";
private static final String WEBSOCKET = "ws";
private static final String WEBSOCKET_SSL = "wss";
private final static Logger log = LoggerFactory.getLogger(NettyAsyncHttpProvider.class);
private final static Charset UTF8 = Charset.forName("UTF-8");
private final ClientBootstrap plainBootstrap;
private final ClientBootstrap secureBootstrap;
private final ClientBootstrap webSocketBootstrap;
private final ClientBootstrap secureWebSocketBootstrap;
private final static int MAX_BUFFERED_BYTES = 8192;
private final AsyncHttpClientConfig config;
private final AtomicBoolean isClose = new AtomicBoolean(false);
private final ClientSocketChannelFactory socketChannelFactory;
private final ChannelGroup openChannels = new
CleanupChannelGroup("asyncHttpClient") {
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if (removed && trackConnections) {
freeConnections.release();
}
return removed;
}
};
private final ConnectionsPool<String, Channel> connectionsPool;
private Semaphore freeConnections = null;
private final NettyAsyncHttpProviderConfig asyncHttpProviderConfig;
private boolean executeConnectAsync = true;
public static final ThreadLocal<Boolean> IN_IO_THREAD = new ThreadLocalBoolean();
private final boolean trackConnections;
private final boolean useRawUrl;
private final static NTLMEngine ntlmEngine = new NTLMEngine();
private final static SpnegoEngine spnegoEngine = new SpnegoEngine();
private final Protocol httpProtocol = new HttpProtocol();
private final Protocol webSocketProtocol = new WebSocketProtocol();
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
if (config.getAsyncHttpProviderConfig() != null
&& NettyAsyncHttpProviderConfig.class.isAssignableFrom(config.getAsyncHttpProviderConfig().getClass())) {
asyncHttpProviderConfig = NettyAsyncHttpProviderConfig.class.cast(config.getAsyncHttpProviderConfig());
} else {
asyncHttpProviderConfig = new NettyAsyncHttpProviderConfig();
}
if (asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.USE_BLOCKING_IO) != null) {
socketChannelFactory = new OioClientSocketChannelFactory(config.executorService());
} else {
ExecutorService e;
Object o = asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.BOSS_EXECUTOR_SERVICE);
if (o != null && ExecutorService.class.isAssignableFrom(o.getClass())) {
e = ExecutorService.class.cast(o);
} else {
e = Executors.newCachedThreadPool();
}
int numWorkers = config.getIoThreadMultiplier() * Runtime.getRuntime().availableProcessors();
log.debug("Number of application's worker threads is {}", numWorkers);
socketChannelFactory = new NioClientSocketChannelFactory(e, config.executorService(), numWorkers);
}
plainBootstrap = new ClientBootstrap(socketChannelFactory);
secureBootstrap = new ClientBootstrap(socketChannelFactory);
webSocketBootstrap = new ClientBootstrap(socketChannelFactory);
secureWebSocketBootstrap = new ClientBootstrap(socketChannelFactory);
configureNetty();
this.config = config;
// This is dangerous as we can't catch a wrong typed ConnectionsPool
ConnectionsPool<String, Channel> cp = (ConnectionsPool<String, Channel>) config.getConnectionsPool();
if (cp == null && config.getAllowPoolingConnection()) {
cp = new NettyConnectionsPool(this);
} else if (cp == null) {
cp = new NonConnectionsPool();
}
this.connectionsPool = cp;
if (config.getMaxTotalConnections() != -1) {
trackConnections = true;
freeConnections = new Semaphore(config.getMaxTotalConnections());
} else {
trackConnections = false;
}
useRawUrl = config.isUseRawUrl();
}
@Override
public String toString() {
return String.format("NettyAsyncHttpProvider:\n\t- maxConnections: %d\n\t- openChannels: %s\n\t- connectionPools: %s",
config.getMaxTotalConnections() - freeConnections.availablePermits(),
openChannels.toString(),
connectionsPool.toString());
}
void configureNetty() {
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
plainBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
plainBootstrap.setPipelineFactory(createPlainPipelineFactory());
DefaultChannelFuture.setUseDeadLockChecker(false);
if (asyncHttpProviderConfig != null) {
Object value = asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.EXECUTE_ASYNC_CONNECT);
if (value != null && Boolean.class.isAssignableFrom(value.getClass())) {
executeConnectAsync = Boolean.class.cast(value);
} else if (asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.DISABLE_NESTED_REQUEST) != null) {
DefaultChannelFuture.setUseDeadLockChecker(true);
}
}
webSocketBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast("ws-decoder", new HttpResponseDecoder());
pipeline.addLast("ws-encoder", new HttpRequestEncoder());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
}
protected ChannelPipelineFactory createPlainPipelineFactory() {
return new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast(HTTP_HANDLER, new HttpClientCodec());
if (config.getRequestCompressionLevel() > 0) {
pipeline.addLast("deflater", new HttpContentCompressor(config.getRequestCompressionLevel()));
}
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
};
}
void constructSSLPipeline(final NettyConnectListener<?> cl) {
secureBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast(HTTP_HANDLER, new HttpClientCodec());
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
secureWebSocketBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast("ws-decoder", new HttpResponseDecoder());
pipeline.addLast("ws-encoder", new HttpRequestEncoder());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
secureBootstrap.setOption(entry.getKey(), entry.getValue());
secureWebSocketBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
}
private Channel lookupInCache(URI uri) {
final Channel channel = connectionsPool.poll(AsyncHttpProviderUtils.getBaseUrl(uri));
if (channel != null) {
log.debug("Using cached Channel {}\n for uri {}\n", channel, uri);
try {
// Always make sure the channel who got cached support the proper protocol. It could
// only occurs when a HttpMethod.CONNECT is used agains a proxy that require upgrading from http to
// https.
return verifyChannelPipeline(channel, uri.getScheme());
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
}
}
return null;
}
private SSLEngine createSSLEngine() throws IOException, GeneralSecurityException {
SSLEngine sslEngine = config.getSSLEngineFactory().newSSLEngine();
if (sslEngine == null) {
sslEngine = SslUtils.getSSLEngine();
}
return sslEngine;
}
private Channel verifyChannelPipeline(Channel channel, String scheme) throws IOException, GeneralSecurityException {
if (channel.getPipeline().get(SSL_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
channel.getPipeline().remove(SSL_HANDLER);
} else if (channel.getPipeline().get(HTTP_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
return channel;
} else if (channel.getPipeline().get(SSL_HANDLER) == null && isSecure(scheme)) {
channel.getPipeline().addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
}
return channel;
}
protected final <T> void writeRequest(final Channel channel,
final AsyncHttpClientConfig config,
final NettyResponseFuture<T> future,
final HttpRequest nettyRequest) {
try {
/**
* If the channel is dead because it was pooled and the remote server decided to close it,
* we just let it go and the closeChannel do it's work.
*/
if (!channel.isOpen() || !channel.isConnected()) {
return;
}
Body body = null;
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
BodyGenerator bg = future.getRequest().getBodyGenerator();
if (bg != null) {
// Netty issue with chunking.
if (InputStreamBodyGenerator.class.isAssignableFrom(bg.getClass())) {
InputStreamBodyGenerator.class.cast(bg).patchNettyChunkingIssue(true);
}
try {
body = bg.createBody();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
long length = body.getContentLength();
if (length >= 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, length);
} else {
nettyRequest.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
}
} else {
body = null;
}
}
if (TransferCompletionHandler.class.isAssignableFrom(future.getAsyncHandler().getClass())) {
FluentCaseInsensitiveStringsMap h = new FluentCaseInsensitiveStringsMap();
for (String s : future.getNettyRequest().getHeaderNames()) {
for (String header : future.getNettyRequest().getHeaders(s)) {
h.add(s, header);
}
}
TransferCompletionHandler.class.cast(future.getAsyncHandler()).transferAdapter(
new NettyTransferAdapter(h, nettyRequest.getContent(), future.getRequest().getFile()));
}
// Leave it to true.
if (future.getAndSetWriteHeaders(true)) {
try {
channel.write(nettyRequest).addListener(new ProgressListener(true, future.getAsyncHandler(), future));
} catch (Throwable cause) {
log.debug(cause.getMessage(), cause);
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
}
if (future.getAndSetWriteBody(true)) {
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getFile() != null) {
final File file = future.getRequest().getFile();
long fileLength = 0;
final RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
fileLength = raf.length();
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) != null) {
writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
} else {
final FileRegion region = new OptimizedFileRegion(raf, 0, fileLength);
writeFuture = channel.write(region);
}
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future));
} catch (IOException ex) {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
throw ex;
}
} else if (body != null || future.getRequest().getParts() != null) {
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (future.getRequest().getParts() != null) {
String boundary = future.getNettyRequest().getHeader("Content-Type");
String length = future.getNettyRequest().getHeader("Content-Length");
body = new MultipartBody(future.getRequest().getParts(), boundary, length);
}
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) == null && (body instanceof RandomAccessBody)) {
BodyFileRegion bodyFileRegion = new BodyFileRegion((RandomAccessBody) body);
writeFuture = channel.write(bodyFileRegion);
} else {
BodyChunkedInput bodyChunkedInput = new BodyChunkedInput(body);
BodyGenerator bg = future.getRequest().getBodyGenerator();
if (bg instanceof FeedableBodyGenerator) {
((FeedableBodyGenerator)bg).setListener(new FeedListener() {
@Override public void onContentAdded() {
channel.getPipeline().get(ChunkedWriteHandler.class).resumeTransfer();
}
});
}
writeFuture = channel.write(bodyChunkedInput);
}
final Body b = body;
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future) {
public void operationComplete(ChannelFuture cf) {
try {
b.close();
} catch (IOException e) {
log.warn("Failed to close request body: {}", e.getMessage(), e);
}
super.operationComplete(cf);
}
});
}
}
}
} catch (Throwable ioe) {
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
}
try {
future.touch();
int delay = requestTimeout(config, future.getRequest().getPerRequestConfig());
if (delay != -1 && !future.isDone() && !future.isCancelled()) {
ReaperFuture reaperFuture = new ReaperFuture(future);
Future<?> scheduledFuture = config.reaper().scheduleAtFixedRate(reaperFuture, 0, delay, TimeUnit.MILLISECONDS);
reaperFuture.setScheduledFuture(scheduledFuture);
future.setReaperFuture(reaperFuture);
}
} catch (RejectedExecutionException ex) {
abort(future, ex);
}
}
private static boolean isProxyServer(AsyncHttpClientConfig config, Request request) {
return request.getProxyServer() != null || config.getProxyServer() != null;
}
protected final static HttpRequest buildRequest(AsyncHttpClientConfig config, Request request, URI uri,
boolean allowConnect, ChannelBuffer buffer) throws IOException {
String method = request.getMethod();
if (allowConnect && (isProxyServer(config, request) && isSecure(uri))) {
method = HttpMethod.CONNECT.toString();
}
return construct(config, request, new HttpMethod(method), uri, buffer);
}
private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer) throws IOException {
String host = AsyncHttpProviderUtils.getHost(uri);
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
StringBuilder path = null;
if (isProxyServer(config, request))
path = new StringBuilder(uri.toString());
else {
path = new StringBuilder(uri.getRawPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
}
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader("Origin", "http://" + uri.getHost() + ":"
+ (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader("Sec-WebSocket-Version", "13");
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else if (request.getVirtualHost() != null) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM")) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = spnegoEngine.generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
if (!avoidProxy) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
if (proxyServer.getNtlmDomain() != null && proxyServer.getNtlmDomain().length() > 0) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!(auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM"))) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(),
proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else {
nettyRequest.setHeader("User-Agent",
AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class,
config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
- if (!"GET".equals(reqType) && !"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
+ if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getStringData().getBytes(bodyCharset)));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (request.getParams() != null && !request.getParams().isEmpty()) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
public void close() {
isClose.set(true);
try {
connectionsPool.destroy();
openChannels.close();
for (Channel channel : openChannels) {
ChannelHandlerContext ctx = channel.getPipeline().getContext(NettyAsyncHttpProvider.class);
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.setReaperFuture(null);
}
}
config.executorService().shutdown();
config.reaper().shutdown();
socketChannelFactory.releaseExternalResources();
plainBootstrap.releaseExternalResources();
secureBootstrap.releaseExternalResources();
webSocketBootstrap.releaseExternalResources();
secureWebSocketBootstrap.releaseExternalResources();
} catch (Throwable t) {
log.warn("Unexpected error on close", t);
}
}
/* @Override */
public Response prepareResponse(final HttpResponseStatus status,
final HttpResponseHeaders headers,
final List<HttpResponseBodyPart> bodyParts) {
return new NettyResponse(status, headers, bodyParts);
}
/* @Override */
public <T> ListenableFuture<T> execute(Request request, final AsyncHandler<T> asyncHandler) throws IOException {
return doConnect(request, asyncHandler, null, true, executeConnectAsync, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, reclaimCache);
}
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f,
boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
if (isClose.get()) {
throw new IOException("Closed");
}
if (request.getUrl().startsWith(WEBSOCKET) && !validateWebSocketRequest(request, asyncHandler)) {
throw new IOException("WebSocket method must be a GET");
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
String requestUrl;
if (useRawUrl) {
requestUrl = request.getRawUrl();
} else {
requestUrl = request.getUrl();
}
URI uri = AsyncHttpProviderUtils.createUri(requestUrl);
Channel channel = null;
if (useCache) {
if (f != null && f.reuseChannel() && f.channel() != null) {
channel = f.channel();
} else {
channel = lookupInCache(uri);
}
}
ChannelBuffer bufferedBytes = null;
if (f != null && f.getRequest().getFile() == null &&
!f.getNettyRequest().getMethod().getName().equals(HttpMethod.CONNECT.getName())) {
bufferedBytes = f.getNettyRequest().getContent();
}
boolean useSSl = isSecure(uri) && proxyServer == null;
if (channel != null && channel.isOpen() && channel.isConnected()) {
HttpRequest nettyRequest = buildRequest(config, request, uri, f == null ? false : f.isConnectAllowed(), bufferedBytes);
if (f == null) {
f = newFuture(uri, request, asyncHandler, nettyRequest, config, this);
} else {
nettyRequest = buildRequest(config, request, uri, f.isConnectAllowed(), bufferedBytes);
f.setNettyRequest(nettyRequest);
}
f.setState(NettyResponseFuture.STATE.POOLED);
f.attachChannel(channel, false);
log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest);
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(f);
try {
writeRequest(channel, config, f, nettyRequest);
} catch (Exception ex) {
log.debug("writeRequest failure", ex);
if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) {
log.debug("SSLEngine failure", ex);
f = null;
} else {
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("doConnect.writeRequest()", t);
}
IOException ioe = new IOException(ex.getMessage());
ioe.initCause(ex);
throw ioe;
}
}
return f;
}
// Do not throw an exception when we need an extra connection for a redirect.
if (!reclaimCache && !connectionsPool.canCacheConnection()) {
IOException ex = new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()", t);
}
throw ex;
}
boolean acquiredConnection = false;
if (trackConnections) {
if (!reclaimCache) {
if (!freeConnections.tryAcquire()) {
IOException ex = new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()", t);
}
throw ex;
} else {
acquiredConnection = true;
}
}
}
NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri);
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost());
if (useSSl) {
constructSSLPipeline(c);
}
ChannelFuture channelFuture;
ClientBootstrap bootstrap = request.getUrl().startsWith(WEBSOCKET) ? (useSSl ? secureWebSocketBootstrap : webSocketBootstrap) : (useSSl ? secureBootstrap : plainBootstrap);
bootstrap.setOption("connectTimeoutMillis", config.getConnectionTimeoutInMs());
// Do no enable this with win.
if (System.getProperty("os.name").toLowerCase().indexOf("win") == -1) {
bootstrap.setOption("reuseAddress", asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.REUSE_ADDRESS));
}
try {
InetSocketAddress remoteAddress;
if (request.getInetAddress() != null) {
remoteAddress = new InetSocketAddress(request.getInetAddress(), AsyncHttpProviderUtils.getPort(uri));
} else if (proxyServer == null || avoidProxy) {
remoteAddress = new InetSocketAddress(AsyncHttpProviderUtils.getHost(uri), AsyncHttpProviderUtils.getPort(uri));
} else {
remoteAddress = new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort());
}
if(request.getLocalAddress() != null){
channelFuture = bootstrap.connect(remoteAddress, new InetSocketAddress(request.getLocalAddress(), 0));
}else{
channelFuture = bootstrap.connect(remoteAddress);
}
} catch (Throwable t) {
if (acquiredConnection) {
freeConnections.release();
}
abort(c.future(), t.getCause() == null ? t : t.getCause());
return c.future();
}
boolean directInvokation = true;
if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) {
directInvokation = false;
}
if (directInvokation && !asyncConnect && request.getFile() == null) {
int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE;
if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) {
if (acquiredConnection) {
freeConnections.release();
}
channelFuture.cancel();
abort(c.future(), new ConnectException(String.format("Connect operation to %s timeout %s", uri, timeOut)));
}
try {
c.operationComplete(channelFuture);
} catch (Exception e) {
if (acquiredConnection) {
freeConnections.release();
}
IOException ioe = new IOException(e.getMessage());
ioe.initCause(e);
try {
asyncHandler.onThrowable(ioe);
} catch (Throwable t) {
log.warn("c.operationComplete()", t);
}
throw ioe;
}
} else {
channelFuture.addListener(c);
}
log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel());
if (!c.future().isCancelled() || !c.future().isDone()) {
openChannels.add(channelFuture.getChannel());
c.future().attachChannel(channelFuture.getChannel(), false);
}
return c.future();
}
protected static int requestTimeout(AsyncHttpClientConfig config, PerRequestConfig perRequestConfig) {
int result;
if (perRequestConfig != null) {
int prRequestTimeout = perRequestConfig.getRequestTimeoutInMs();
result = (prRequestTimeout != 0 ? prRequestTimeout : config.getRequestTimeoutInMs());
} else {
result = config.getRequestTimeoutInMs();
}
return result;
}
private void closeChannel(final ChannelHandlerContext ctx) {
connectionsPool.removeAll(ctx.getChannel());
finishChannel(ctx);
}
private void finishChannel(final ChannelHandlerContext ctx) {
ctx.setAttachment(new DiscardEvent());
// The channel may have already been removed if a timeout occurred, and this method may be called just after.
if (ctx.getChannel() == null) {
return;
}
log.debug("Closing Channel {} ", ctx.getChannel());
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.debug("Error closing a connection", t);
}
if (ctx.getChannel() != null) {
openChannels.remove(ctx.getChannel());
}
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
//call super to reset the read timeout
super.messageReceived(ctx, e);
IN_IO_THREAD.set(Boolean.TRUE);
if (ctx.getAttachment() == null) {
log.debug("ChannelHandlerContext wasn't having any attachment");
}
if (ctx.getAttachment() instanceof DiscardEvent) {
return;
} else if (ctx.getAttachment() instanceof AsyncCallable) {
if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
} else {
return;
}
} else {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
ctx.setAttachment(new DiscardEvent());
return;
} else if (!(ctx.getAttachment() instanceof NettyResponseFuture<?>)) {
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.trace("Closing an orphan channel {}", ctx.getChannel());
}
return;
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.handle(ctx, e);
}
private Realm kerberosChallenge(List<String> proxyAuth,
Request request,
ProxyServer proxyServer,
FluentCaseInsensitiveStringsMap headers,
Realm realm,
NettyResponseFuture<?> future) throws NTLMEngineException {
URI uri = URI.create(request.getUrl());
String host = request.getVirtualHost() == null ? AsyncHttpProviderUtils.getHost(uri) : request.getVirtualHost();
String server = proxyServer == null ? host : proxyServer.getHost();
try {
String challengeHeader = spnegoEngine.generateToken(server);
headers.remove(HttpHeaders.Names.AUTHORIZATION);
headers.add(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
Realm.RealmBuilder realmBuilder;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
} else {
realmBuilder = new Realm.RealmBuilder();
}
return realmBuilder.setUri(uri.getPath())
.setMethodName(request.getMethod())
.setScheme(Realm.AuthScheme.KERBEROS)
.build();
} catch (Throwable throwable) {
if (proxyAuth.contains("NTLM")) {
return ntlmChallenge(proxyAuth, request, proxyServer, headers, realm, future);
}
abort(future, throwable);
return null;
}
}
private Realm ntlmChallenge(List<String> wwwAuth,
Request request,
ProxyServer proxyServer,
FluentCaseInsensitiveStringsMap headers,
Realm realm,
NettyResponseFuture<?> future) throws NTLMEngineException {
boolean useRealm = (proxyServer == null && realm != null);
String ntlmDomain = useRealm ? realm.getNtlmDomain() : proxyServer.getNtlmDomain();
String ntlmHost = useRealm ? realm.getNtlmHost() : proxyServer.getHost();
String principal = useRealm ? realm.getPrincipal() : proxyServer.getPrincipal();
String password = useRealm ? realm.getPassword() : proxyServer.getPassword();
Realm newRealm;
if (realm != null && !realm.isNtlmMessageType2Received()) {
String challengeHeader = ntlmEngine.generateType1Msg(ntlmDomain, ntlmHost);
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm).setScheme(realm.getAuthScheme())
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.setNtlmMessageType2Received(true)
.build();
future.getAndSetAuth(false);
} else {
headers.remove(HttpHeaders.Names.AUTHORIZATION);
if (wwwAuth.get(0).startsWith("NTLM ")) {
String serverChallenge = wwwAuth.get(0).trim().substring("NTLM ".length());
String challengeHeader = ntlmEngine.generateType3Msg(principal, password,
ntlmDomain, ntlmHost, serverChallenge);
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
}
Realm.RealmBuilder realmBuilder;
Realm.AuthScheme authScheme;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
authScheme = realm.getAuthScheme();
} else {
realmBuilder = new Realm.RealmBuilder();
authScheme = Realm.AuthScheme.NTLM;
}
newRealm = realmBuilder.setScheme(authScheme)
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.build();
}
return newRealm;
}
private Realm ntlmProxyChallenge(List<String> wwwAuth,
Request request,
ProxyServer proxyServer,
FluentCaseInsensitiveStringsMap headers,
Realm realm,
NettyResponseFuture<?> future) throws NTLMEngineException {
future.getAndSetAuth(false);
headers.remove(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (wwwAuth.get(0).startsWith("NTLM ")) {
String serverChallenge = wwwAuth.get(0).trim().substring("NTLM ".length());
String challengeHeader = ntlmEngine.generateType3Msg(proxyServer.getPrincipal(),
proxyServer.getPassword(),
proxyServer.getNtlmDomain(),
proxyServer.getHost(),
serverChallenge);
headers.add(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
Realm newRealm;
Realm.RealmBuilder realmBuilder;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
} else {
realmBuilder = new Realm.RealmBuilder();
}
newRealm = realmBuilder//.setScheme(realm.getAuthScheme())
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.build();
return newRealm;
}
private void drainChannel(final ChannelHandlerContext ctx, final NettyResponseFuture<?> future, final boolean keepAlive, final URI uri) {
ctx.setAttachment(new AsyncCallable(future) {
public Object call() throws Exception {
if (keepAlive && ctx.getChannel().isReadable() && connectionsPool.offer(AsyncHttpProviderUtils.getBaseUrl(uri), ctx.getChannel())) {
return null;
}
finishChannel(ctx);
return null;
}
@Override
public String toString() {
return String.format("Draining task for channel %s", ctx.getChannel());
}
});
}
private FilterContext handleIoException(FilterContext fc, NettyResponseFuture<?> future) {
for (IOExceptionFilter asyncFilter : config.getIOExceptionFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
return fc;
}
private void replayRequest(final NettyResponseFuture<?> future, FilterContext fc, HttpResponse response, ChannelHandlerContext ctx) throws IOException {
final Request newRequest = fc.getRequest();
future.setAsyncHandler(fc.getAsyncHandler());
future.setState(NettyResponseFuture.STATE.NEW);
future.touch();
log.debug("\n\nReplaying Request {}\n for Future {}\n", newRequest, future);
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
nextRequest(newRequest, future);
return;
}
private List<String> getAuthorizationToken(List<Entry<String, String>> list, String headerAuth) {
ArrayList<String> l = new ArrayList<String>();
for (Entry<String, String> e : list) {
if (e.getKey().equalsIgnoreCase(headerAuth)) {
l.add(e.getValue().trim());
}
}
return l;
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future) throws IOException {
nextRequest(request, future, true);
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future, final boolean useCache) throws IOException {
execute(request, future, useCache, true, true);
}
private void abort(NettyResponseFuture<?> future, Throwable t) {
Channel channel = future.channel();
if (channel != null && openChannels.contains(channel)) {
closeChannel(channel.getPipeline().getContext(NettyAsyncHttpProvider.class));
openChannels.remove(channel);
}
if (!future.isCancelled() && !future.isDone()) {
log.debug("Aborting Future {}\n", future);
log.debug(t.getMessage(), t);
}
future.abort(t);
}
private void upgradeProtocol(ChannelPipeline p, String scheme) throws IOException, GeneralSecurityException {
if (p.get(HTTP_HANDLER) != null) {
p.remove(HTTP_HANDLER);
}
if (isSecure(scheme)) {
if (p.get(SSL_HANDLER) == null) {
p.addFirst(HTTP_HANDLER, new HttpClientCodec());
p.addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
} else {
p.addAfter(SSL_HANDLER, HTTP_HANDLER, new HttpClientCodec());
}
} else {
p.addFirst(HTTP_HANDLER, new HttpClientCodec());
}
}
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (isClose.get()) {
return;
}
connectionsPool.removeAll(ctx.getChannel());
try {
super.channelClosed(ctx, e);
} catch (Exception ex) {
log.trace("super.channelClosed", ex);
}
log.debug("Channel Closed: {} with attachment {}", e.getChannel(), ctx.getAttachment());
if (ctx.getAttachment() instanceof AsyncCallable) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ctx.setAttachment(ac.future());
ac.call();
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
if (config.getIOExceptionFilters().size() > 0) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest() && !future.cannotBeReplay()) {
replayRequest(future, fc, null, ctx);
return;
}
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.onClose(ctx, e);
if (future != null && !future.isDone() && !future.isCancelled()) {
if (!remotelyClosed(ctx.getChannel(), future)) {
abort(future, new IOException("Remotely Closed " + ctx.getChannel()));
}
} else {
closeChannel(ctx);
}
}
}
protected boolean remotelyClosed(Channel channel, NettyResponseFuture<?> future) {
if (isClose.get()) {
return false;
}
connectionsPool.removeAll(channel);
if (future == null && channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment() != null
&& NettyResponseFuture.class.isAssignableFrom(
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment().getClass())) {
future = (NettyResponseFuture<?>)
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
}
if (future == null || future.cannotBeReplay()) {
log.debug("Unable to recover future {}\n", future);
return false;
}
future.setState(NettyResponseFuture.STATE.RECONNECTED);
future.getAndSetStatusReceived(false);
log.debug("Trying to recover request {}\n", future.getNettyRequest());
try {
nextRequest(future.getRequest(), future);
return true;
} catch (IOException iox) {
future.setState(NettyResponseFuture.STATE.CLOSED);
future.abort(iox);
log.error("Remotely Closed, unable to recover", iox);
}
return false;
}
private void markAsDone(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx) throws MalformedURLException {
// We need to make sure everything is OK before adding the connection back to the pool.
try {
future.done(null);
} catch (Throwable t) {
// Never propagate exception once we know we are done.
log.debug(t.getMessage(), t);
}
if (!future.getKeepAlive() || !ctx.getChannel().isReadable()) {
closeChannel(ctx);
}
}
private void finishUpdate(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx, boolean lastValidChunk) throws IOException {
if (lastValidChunk && future.getKeepAlive()) {
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
} else {
if (future.getKeepAlive() && ctx.getChannel().isReadable() &&
connectionsPool.offer(AsyncHttpProviderUtils.getBaseUrl(future.getURI()), ctx.getChannel())) {
markAsDone(future, ctx);
return;
}
finishChannel(ctx);
}
markAsDone(future, ctx);
}
private final boolean updateStatusAndInterrupt(AsyncHandler<?> handler, HttpResponseStatus c) throws Exception {
return handler.onStatusReceived(c) != STATE.CONTINUE;
}
private final boolean updateHeadersAndInterrupt(AsyncHandler<?> handler, HttpResponseHeaders c) throws Exception {
return handler.onHeadersReceived(c) != STATE.CONTINUE;
}
private final boolean updateBodyAndInterrupt(final NettyResponseFuture<?> future, AsyncHandler<?> handler, HttpResponseBodyPart c) throws Exception {
boolean state = handler.onBodyPartReceived(c) != STATE.CONTINUE;
if (c.closeUnderlyingConnection()) {
future.setKeepAlive(false);
}
return state;
}
//Simple marker for stopping publishing bytes.
final static class DiscardEvent {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
Channel channel = e.getChannel();
Throwable cause = e.getCause();
NettyResponseFuture<?> future = null;
/** Issue 81
if (e.getCause() != null && e.getCause().getClass().isAssignableFrom(PrematureChannelClosureException.class)) {
return;
}
*/
if (e.getCause() != null && e.getCause().getClass().getSimpleName().equals("PrematureChannelClosureException")) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Unexpected I/O exception on channel {}", channel, cause);
}
try {
if (cause != null && ClosedChannelException.class.isAssignableFrom(cause.getClass())) {
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
future = (NettyResponseFuture<?>) ctx.getAttachment();
future.attachChannel(null, false);
future.touch();
if (IOException.class.isAssignableFrom(cause.getClass())) {
if (config.getIOExceptionFilters().size() > 0) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, null, ctx);
return;
}
} else {
// Close the channel so the recovering can occurs.
try {
ctx.getChannel().close();
} catch (Throwable t) {
; // Swallow.
}
return;
}
}
if (abortOnReadCloseException(cause) || abortOnWriteCloseException(cause)) {
log.debug("Trying to recover from dead Channel: {}", channel);
return;
}
} else if (ctx.getAttachment() instanceof AsyncCallable) {
future = ((AsyncCallable) ctx.getAttachment()).future();
}
} catch (Throwable t) {
cause = t;
}
if (future != null) {
try {
log.debug("Was unable to recover Future: {}", future);
abort(future, cause);
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.onError(ctx, e);
closeChannel(ctx);
ctx.sendUpstream(e);
}
protected static boolean abortOnConnectCloseException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketChannelImpl")
&& element.getMethodName().equals("checkConnect")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnDisconnectException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("org.jboss.netty.handler.ssl.SslHandler")
&& element.getMethodName().equals("channelDisconnected")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnReadCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher")
&& element.getMethodName().equals("read")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
protected static boolean abortOnWriteCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher")
&& element.getMethodName().equals("write")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
private final static int computeAndSetContentLength(Request request, HttpRequest r) {
int length = (int) request.getContentLength();
if (length == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) {
length = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH));
}
if (length >= 0) {
r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
}
return length;
}
public static <T> NettyResponseFuture<T> newFuture(URI uri,
Request request,
AsyncHandler<T> asyncHandler,
HttpRequest nettyRequest,
AsyncHttpClientConfig config,
NettyAsyncHttpProvider provider) {
NettyResponseFuture<T> f = new NettyResponseFuture<T>(uri, request, asyncHandler, nettyRequest,
requestTimeout(config, request.getPerRequestConfig()), config.getIdleConnectionTimeoutInMs(), provider);
if (request.getHeaders().getFirstValue("Expect") != null
&& request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
f.getAndSetWriteBody(false);
}
return f;
}
private class ProgressListener implements ChannelFutureProgressListener {
private final boolean notifyHeaders;
private final AsyncHandler asyncHandler;
private final NettyResponseFuture<?> future;
public ProgressListener(boolean notifyHeaders, AsyncHandler asyncHandler, NettyResponseFuture<?> future) {
this.notifyHeaders = notifyHeaders;
this.asyncHandler = asyncHandler;
this.future = future;
}
public void operationComplete(ChannelFuture cf) {
// The write operation failed. If the channel was cached, it means it got asynchronously closed.
// Let's retry a second time.
Throwable cause = cf.getCause();
if (cause != null && future.getState() != NettyResponseFuture.STATE.NEW) {
if (IllegalStateException.class.isAssignableFrom(cause.getClass())) {
log.debug(cause.getMessage(), cause);
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
if (ClosedChannelException.class.isAssignableFrom(cause.getClass())
|| abortOnReadCloseException(cause)
|| abortOnWriteCloseException(cause)) {
if (log.isDebugEnabled()) {
log.debug(cf.getCause() == null ? "" : cf.getCause().getMessage(), cf.getCause());
}
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
} else {
future.abort(cause);
}
return;
}
future.touch();
/**
* We need to make sure we aren't in the middle of an authorization process before publishing events
* as we will re-publish again the same event after the authorization, causing unpredictable behavior.
*/
Realm realm = future.getRequest().getRealm() != null ? future.getRequest().getRealm() : NettyAsyncHttpProvider.this.getConfig().getRealm();
boolean startPublishing = future.isInAuth()
|| realm == null
|| realm.getUsePreemptiveAuth() == true;
if (startPublishing && ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
if (notifyHeaders) {
ProgressAsyncHandler.class.cast(asyncHandler).onHeaderWriteCompleted();
} else {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteCompleted();
}
}
}
public void operationProgressed(ChannelFuture cf, long amount, long current, long total) {
future.touch();
if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteProgress(amount, current, total);
}
}
}
/**
* Because some implementation of the ThreadSchedulingService do not clean up cancel task until they try to run
* them, we wrap the task with the future so the when the NettyResponseFuture cancel the reaper future
* this wrapper will release the references to the channel and the nettyResponseFuture immediately. Otherwise,
* the memory referenced this way will only be released after the request timeout period which can be arbitrary long.
*/
private final class ReaperFuture implements Future, Runnable {
private Future scheduledFuture;
private NettyResponseFuture<?> nettyResponseFuture;
public ReaperFuture(NettyResponseFuture<?> nettyResponseFuture) {
this.nettyResponseFuture = nettyResponseFuture;
}
public void setScheduledFuture(Future scheduledFuture) {
this.scheduledFuture = scheduledFuture;
}
/**
* @Override
*/
public boolean cancel(boolean mayInterruptIfRunning) {
nettyResponseFuture = null;
return scheduledFuture.cancel(mayInterruptIfRunning);
}
/**
* @Override
*/
public Object get() throws InterruptedException, ExecutionException {
return scheduledFuture.get();
}
/**
* @Override
*/
public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return scheduledFuture.get(timeout, unit);
}
/**
* @Override
*/
public boolean isCancelled() {
return scheduledFuture.isCancelled();
}
/**
* @Override
*/
public boolean isDone() {
return scheduledFuture.isDone();
}
/**
* @Override
*/
public synchronized void run() {
if (isClose.get()) {
cancel(true);
return;
}
if (nettyResponseFuture != null && nettyResponseFuture.hasExpired()
&& !nettyResponseFuture.isDone() && !nettyResponseFuture.isCancelled()) {
log.debug("Request Timeout expired for {}\n", nettyResponseFuture);
int requestTimeout = config.getRequestTimeoutInMs();
PerRequestConfig p = nettyResponseFuture.getRequest().getPerRequestConfig();
if (p != null && p.getRequestTimeoutInMs() != -1) {
requestTimeout = p.getRequestTimeoutInMs();
}
abort(nettyResponseFuture, new TimeoutException(String.format("No response received after %s", requestTimeout)));
nettyResponseFuture = null;
}
if (nettyResponseFuture == null || nettyResponseFuture.isDone() || nettyResponseFuture.isCancelled()) {
cancel(true);
}
}
}
private abstract class AsyncCallable implements Callable<Object> {
private final NettyResponseFuture<?> future;
public AsyncCallable(NettyResponseFuture<?> future) {
this.future = future;
}
abstract public Object call() throws Exception;
public NettyResponseFuture<?> future() {
return future;
}
}
public static class ThreadLocalBoolean extends ThreadLocal<Boolean> {
private final boolean defaultValue;
public ThreadLocalBoolean() {
this(false);
}
public ThreadLocalBoolean(boolean defaultValue) {
this.defaultValue = defaultValue;
}
@Override
protected Boolean initialValue() {
return defaultValue ? Boolean.TRUE : Boolean.FALSE;
}
}
public static class OptimizedFileRegion implements FileRegion {
private final FileChannel file;
private final RandomAccessFile raf;
private final long position;
private final long count;
private long byteWritten;
public OptimizedFileRegion(RandomAccessFile raf, long position, long count) {
this.raf = raf;
this.file = raf.getChannel();
this.position = position;
this.count = count;
}
public long getPosition() {
return position;
}
public long getCount() {
return count;
}
public long transferTo(WritableByteChannel target, long position) throws IOException {
long count = this.count - position;
if (count < 0 || position < 0) {
throw new IllegalArgumentException(
"position out of range: " + position +
" (expected: 0 - " + (this.count - 1) + ")");
}
if (count == 0) {
return 0L;
}
long bw = file.transferTo(this.position + position, count, target);
byteWritten += bw;
if (byteWritten == raf.length()) {
releaseExternalResources();
}
return bw;
}
public void releaseExternalResources() {
try {
file.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
try {
raf.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
}
}
private static class NettyTransferAdapter extends TransferCompletionHandler.TransferAdapter {
private final ChannelBuffer content;
private final FileInputStream file;
private int byteRead = 0;
public NettyTransferAdapter(FluentCaseInsensitiveStringsMap headers, ChannelBuffer content, File file) throws IOException {
super(headers);
this.content = content;
if (file != null) {
this.file = new FileInputStream(file);
} else {
this.file = null;
}
}
@Override
public void getBytes(byte[] bytes) {
if (content.writableBytes() != 0) {
content.getBytes(byteRead, bytes);
byteRead += bytes.length;
} else if (file != null) {
try {
byteRead += file.read(bytes);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
protected AsyncHttpClientConfig getConfig() {
return config;
}
private static class NonConnectionsPool implements ConnectionsPool<String, Channel> {
public boolean offer(String uri, Channel connection) {
return false;
}
public Channel poll(String uri) {
return null;
}
public boolean removeAll(Channel connection) {
return false;
}
public boolean canCacheConnection() {
return true;
}
public void destroy() {
}
}
private static final boolean validateWebSocketRequest(Request request, AsyncHandler<?> asyncHandler) {
if (request.getMethod() != "GET" || !WebSocketUpgradeHandler.class.isAssignableFrom(asyncHandler.getClass())) {
return false;
}
return true;
}
private boolean redirect(Request request,
NettyResponseFuture<?> future,
HttpResponse response,
final ChannelHandlerContext ctx) throws Exception {
int statusCode = response.getStatus().getCode();
boolean redirectEnabled = request.isRedirectOverrideSet() ? request.isRedirectEnabled() : config.isRedirectEnabled();
if (redirectEnabled && (statusCode == 302
|| statusCode == 301
|| statusCode == 303
|| statusCode == 307)) {
if (future.incrementAndGetCurrentRedirectCount() < config.getMaxRedirects()) {
// We must allow 401 handling again.
future.getAndSetAuth(false);
String location = response.getHeader(HttpHeaders.Names.LOCATION);
URI uri = AsyncHttpProviderUtils.getRedirectUri(future.getURI(), location);
boolean stripQueryString = config.isRemoveQueryParamOnRedirect();
if (!uri.toString().equals(future.getURI().toString())) {
final RequestBuilder nBuilder = stripQueryString ?
new RequestBuilder(future.getRequest()).setQueryParameters(null)
: new RequestBuilder(future.getRequest());
if (!(statusCode < 302 || statusCode > 303)
&& !(statusCode == 302
&& config.isStrict302Handling())) {
nBuilder.setMethod("GET");
}
final URI initialConnectionUri = future.getURI();
final boolean initialConnectionKeepAlive = future.getKeepAlive();
future.setURI(uri);
String newUrl = uri.toString();
if (request.getUrl().startsWith(WEBSOCKET)) {
newUrl = newUrl.replace(HTTP, WEBSOCKET);
}
log.debug("Redirecting to {}", newUrl);
for (String cookieStr : future.getHttpResponse().getHeaders(HttpHeaders.Names.SET_COOKIE)) {
Cookie c = AsyncHttpProviderUtils.parseCookie(cookieStr);
nBuilder.addOrReplaceCookie(c);
}
for (String cookieStr : future.getHttpResponse().getHeaders(HttpHeaders.Names.SET_COOKIE2)) {
Cookie c = AsyncHttpProviderUtils.parseCookie(cookieStr);
nBuilder.addOrReplaceCookie(c);
}
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
if (initialConnectionKeepAlive && ctx.getChannel().isReadable() &&
connectionsPool.offer(AsyncHttpProviderUtils.getBaseUrl(initialConnectionUri), ctx.getChannel())) {
return null;
}
finishChannel(ctx);
return null;
}
};
if (response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
nextRequest(nBuilder.setUrl(newUrl).build(), future);
return true;
}
} else {
throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects());
}
}
return false;
}
private final class HttpProtocol implements Protocol {
// @Override
public void handle(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
final NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
// The connect timeout occured.
if (future.isCancelled() || future.isDone()) {
finishChannel(ctx);
return;
}
HttpRequest nettyRequest = future.getNettyRequest();
AsyncHandler handler = future.getAsyncHandler();
Request request = future.getRequest();
HttpResponse response = null;
try {
if (e.getMessage() instanceof HttpResponse) {
response = (HttpResponse) e.getMessage();
log.debug("\n\nRequest {}\n\nResponse {}\n", nettyRequest, response);
// Required if there is some trailing headers.
future.setHttpResponse(response);
int statusCode = response.getStatus().getCode();
String ka = response.getHeader(HttpHeaders.Names.CONNECTION);
future.setKeepAlive(ka == null || ! ka.toLowerCase().equals("close"));
List<String> wwwAuth = getAuthorizationToken(response.getHeaders(), HttpHeaders.Names.WWW_AUTHENTICATE);
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
HttpResponseStatus status = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response, NettyAsyncHttpProvider.this);
FilterContext fc = new FilterContext.FilterContextBuilder()
.asyncHandler(handler)
.request(request)
.responseStatus(status)
.responseHeaders(responseHeaders)
.build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The handler may have been wrapped.
handler = fc.getAsyncHandler();
future.setAsyncHandler(handler);
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
Realm newRealm = null;
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
final FluentCaseInsensitiveStringsMap headers = request.getHeaders();
final RequestBuilder builder = new RequestBuilder(future.getRequest());
//if (realm != null && !future.getURI().getPath().equalsIgnoreCase(realm.getUri())) {
// builder.setUrl(future.getURI().toString());
//}
if (statusCode == 401
&& realm != null
&& wwwAuth.size() > 0
&& !future.getAndSetAuth(true)) {
future.setState(NettyResponseFuture.STATE.NEW);
// NTLM
if (!wwwAuth.contains("Kerberos") && (wwwAuth.contains("NTLM") || (wwwAuth.contains("Negotiate")))) {
newRealm = ntlmChallenge(wwwAuth, request, proxyServer, headers, realm, future);
// SPNEGO KERBEROS
} else if (wwwAuth.contains("Negotiate")) {
newRealm = kerberosChallenge(wwwAuth, request, proxyServer, headers, realm, future);
if (newRealm == null) return;
} else {
Realm.RealmBuilder realmBuilder;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm).setScheme(realm.getAuthScheme())
;
} else {
realmBuilder = new Realm.RealmBuilder();
}
newRealm = realmBuilder
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.setUsePreemptiveAuth(true)
.parseWWWAuthenticateHeader(wwwAuth.get(0))
.build();
}
final Realm nr = new Realm.RealmBuilder().clone(newRealm)
.setUri(URI.create(request.getUrl()).getPath()).build();
log.debug("Sending authentication to {}", request.getUrl());
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
nextRequest(builder.setHeaders(headers).setRealm(nr).build(), future);
return null;
}
};
if (future.getKeepAlive() && response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
return;
}
if (statusCode == 100) {
future.getAndSetWriteHeaders(false);
future.getAndSetWriteBody(true);
writeRequest(ctx.getChannel(), config, future, nettyRequest);
return;
}
List<String> proxyAuth = getAuthorizationToken(response.getHeaders(), HttpHeaders.Names.PROXY_AUTHENTICATE);
if (statusCode == 407
&& realm != null
&& proxyAuth.size() > 0
&& !future.getAndSetAuth(true)) {
log.debug("Sending proxy authentication to {}", request.getUrl());
future.setState(NettyResponseFuture.STATE.NEW);
if (!proxyAuth.contains("Kerberos") && (proxyAuth.get(0).contains("NTLM") || (proxyAuth.contains("Negotiate")))) {
newRealm = ntlmProxyChallenge(proxyAuth, request, proxyServer, headers, realm, future);
// SPNEGO KERBEROS
} else if (proxyAuth.contains("Negotiate")) {
newRealm = kerberosChallenge(proxyAuth, request, proxyServer, headers, realm, future);
if (newRealm == null) return;
} else {
newRealm = future.getRequest().getRealm();
}
Request req = builder.setHeaders(headers).setRealm(newRealm).build();
future.setReuseChannel(true);
future.setConnectAllowed(true);
nextRequest(req, future);
return;
}
if (future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)
&& statusCode == 200) {
log.debug("Connected to {}:{}", proxyServer.getHost(), proxyServer.getPort());
if (future.getKeepAlive()) {
future.attachChannel(ctx.getChannel(), true);
}
try {
log.debug("Connecting to proxy {} for scheme {}", proxyServer, request.getUrl());
upgradeProtocol(ctx.getChannel().getPipeline(), URI.create(request.getUrl()).getScheme());
} catch (Throwable ex) {
abort(future, ex);
}
Request req = builder.build();
future.setReuseChannel(true);
future.setConnectAllowed(false);
nextRequest(req, future);
return;
}
if (redirect(request, future, response, ctx)) return;
if (!future.getAndSetStatusReceived(true) && updateStatusAndInterrupt(handler, status)) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (updateHeadersAndInterrupt(handler, responseHeaders)) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (!response.isChunked()) {
if (response.getContent().readableBytes() != 0) {
updateBodyAndInterrupt(future, handler, new ResponseBodyPart(future.getURI(), response, NettyAsyncHttpProvider.this, true));
}
finishUpdate(future, ctx, false);
return;
}
if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
updateBodyAndInterrupt(future, handler, new ResponseBodyPart(future.getURI(), response, NettyAsyncHttpProvider.this, true));
markAsDone(future, ctx);
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
}
} else if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (handler != null) {
if (chunk.isLast() || updateBodyAndInterrupt(future, handler,
new ResponseBodyPart(future.getURI(), null, NettyAsyncHttpProvider.this, chunk, chunk.isLast()))) {
if (chunk instanceof DefaultHttpChunkTrailer) {
updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(),
future.getHttpResponse(), NettyAsyncHttpProvider.this, (HttpChunkTrailer) chunk));
}
finishUpdate(future, ctx, !chunk.isLast());
}
}
}
} catch (Exception t) {
if (IOException.class.isAssignableFrom(t.getClass()) && config.getIOExceptionFilters().size() > 0) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(IOException.class.cast(t)).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
}
try {
abort(future, t);
} finally {
finishUpdate(future, ctx, false);
throw t;
}
}
}
// @Override
public void onError(ChannelHandlerContext ctx, ExceptionEvent e) {
}
// @Override
public void onClose(ChannelHandlerContext ctx, ChannelStateEvent e) {
}
}
private final class WebSocketProtocol implements Protocol {
// @Override
public void handle(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
NettyResponseFuture future = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(future.getAsyncHandler());
Request request = future.getRequest();
if (e.getMessage() instanceof HttpResponse) {
HttpResponse response = (HttpResponse) e.getMessage();
HttpResponseStatus s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response, NettyAsyncHttpProvider.this);
FilterContext<?> fc = new FilterContext.FilterContextBuilder()
.asyncHandler(h)
.request(request)
.responseStatus(s)
.responseHeaders(responseHeaders)
.build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The handler may have been wrapped.
future.setAsyncHandler(fc.getAsyncHandler());
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
future.setHttpResponse(response);
if (redirect(request, future, response, ctx)) return;
final org.jboss.netty.handler.codec.http.HttpResponseStatus status =
new org.jboss.netty.handler.codec.http.HttpResponseStatus(101, "Web Socket Protocol Handshake");
final boolean validStatus = response.getStatus().equals(status);
final boolean validUpgrade = response.getHeader(HttpHeaders.Names.UPGRADE) != null;
String c = response.getHeader(HttpHeaders.Names.CONNECTION);
if (c == null) {
c = response.getHeader("connection");
}
final boolean validConnection = c == null ? false : c.equalsIgnoreCase(HttpHeaders.Values.UPGRADE);
s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
final boolean statusReceived = h.onStatusReceived(s) == STATE.UPGRADE;
if (!statusReceived) {
h.onClose(new NettyWebSocket(ctx.getChannel()), 1002, "Bad response status " + response.getStatus().getCode());
future.done(null);
return;
}
if (!validStatus || !validUpgrade || !validConnection) {
throw new IOException("Invalid handshake response");
}
String accept = response.getHeader("Sec-WebSocket-Accept");
String key = WebSocketUtil.getAcceptKey(future.getNettyRequest().getHeader(WEBSOCKET_KEY));
if (accept == null || !accept.equals(key)) {
throw new IOException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, key));
}
ctx.getPipeline().replace("ws-decoder", "ws-decoder", new WebSocket08FrameDecoder(false, false));
ctx.getPipeline().replace("ws-encoder", "ws-encoder", new WebSocket08FrameEncoder(true));
if (h.onHeadersReceived(responseHeaders) == STATE.CONTINUE) {
h.onSuccess(new NettyWebSocket(ctx.getChannel()));
}
future.done(null);
} else if (e.getMessage() instanceof WebSocketFrame) {
final WebSocketFrame frame = (WebSocketFrame) e.getMessage();
HttpChunk webSocketChunk = new HttpChunk() {
private ChannelBuffer content;
// @Override
public boolean isLast() {
return false;
}
// @Override
public ChannelBuffer getContent() {
return content;
}
// @Override
public void setContent(ChannelBuffer content) {
this.content = content;
}
};
if (frame.getBinaryData() != null) {
webSocketChunk.setContent(ChannelBuffers.wrappedBuffer(frame.getBinaryData()));
ResponseBodyPart rp = new ResponseBodyPart(future.getURI(), null, NettyAsyncHttpProvider.this, webSocketChunk, true);
h.onBodyPartReceived(rp);
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
webSocket.onMessage(rp.getBodyPartBytes());
webSocket.onTextMessage(frame.getBinaryData().toString(UTF8));
if (CloseWebSocketFrame.class.isAssignableFrom(frame.getClass())) {
try {
webSocket.onClose(CloseWebSocketFrame.class.cast(frame).getStatusCode(), CloseWebSocketFrame.class.cast(frame).getReasonText());
} catch (Throwable t) {
// Swallow any exception that may comes from a Netty version released before 3.4.0
log.trace("", t);
}
}
}
} else {
log.error("Invalid attachment {}", ctx.getAttachment());
}
}
//@Override
public void onError(ChannelHandlerContext ctx, ExceptionEvent e) {
try {
log.warn("onError {}", e);
if (ctx.getAttachment() == null || !NettyResponseFuture.class.isAssignableFrom(ctx.getAttachment().getClass())) {
return;
}
NettyResponseFuture<?> nettyResponse = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(nettyResponse.getAsyncHandler());
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
webSocket.onError(e.getCause());
webSocket.close();
} catch (Throwable t) {
log.error("onError", t);
}
}
//@Override
public void onClose(ChannelHandlerContext ctx, ChannelStateEvent e) {
log.trace("onClose {}", e);
if (ctx.getAttachment() == null || !NettyResponseFuture.class.isAssignableFrom(ctx.getAttachment().getClass())) {
return;
}
try {
NettyResponseFuture<?> nettyResponse = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(nettyResponse.getAsyncHandler());
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
webSocket.close();
} catch (Throwable t) {
log.error("onError", t);
}
}
}
private static boolean isWebSocket(URI uri) {
return WEBSOCKET.equalsIgnoreCase(uri.getScheme()) || WEBSOCKET_SSL.equalsIgnoreCase(uri.getScheme());
}
private static boolean isSecure(String scheme) {
return HTTPS.equalsIgnoreCase(scheme) || WEBSOCKET_SSL.equalsIgnoreCase(scheme);
}
private static boolean isSecure(URI uri) {
return isSecure(uri.getScheme());
}
}
| true | true | private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer) throws IOException {
String host = AsyncHttpProviderUtils.getHost(uri);
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
StringBuilder path = null;
if (isProxyServer(config, request))
path = new StringBuilder(uri.toString());
else {
path = new StringBuilder(uri.getRawPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
}
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader("Origin", "http://" + uri.getHost() + ":"
+ (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader("Sec-WebSocket-Version", "13");
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else if (request.getVirtualHost() != null) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM")) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = spnegoEngine.generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
if (!avoidProxy) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
if (proxyServer.getNtlmDomain() != null && proxyServer.getNtlmDomain().length() > 0) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!(auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM"))) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(),
proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else {
nettyRequest.setHeader("User-Agent",
AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class,
config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
if (!"GET".equals(reqType) && !"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getStringData().getBytes(bodyCharset)));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (request.getParams() != null && !request.getParams().isEmpty()) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
| private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer) throws IOException {
String host = AsyncHttpProviderUtils.getHost(uri);
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
StringBuilder path = null;
if (isProxyServer(config, request))
path = new StringBuilder(uri.toString());
else {
path = new StringBuilder(uri.getRawPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
}
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader("Origin", "http://" + uri.getHost() + ":"
+ (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader("Sec-WebSocket-Version", "13");
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else if (request.getVirtualHost() != null) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM")) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = spnegoEngine.generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
if (!avoidProxy) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
if (proxyServer.getNtlmDomain() != null && proxyServer.getNtlmDomain().length() > 0) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!(auth != null && auth.size() > 0 && auth.get(0).startsWith("NTLM"))) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(),
proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else {
nettyRequest.setHeader("User-Agent",
AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class,
config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getStringData().getBytes(bodyCharset)));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (request.getParams() != null && !request.getParams().isEmpty()) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
|
diff --git a/native/SalesforceSDK/src/com/salesforce/androidsdk/auth/AuthenticatorService.java b/native/SalesforceSDK/src/com/salesforce/androidsdk/auth/AuthenticatorService.java
index ff3a6ff89..77b0f2a1d 100644
--- a/native/SalesforceSDK/src/com/salesforce/androidsdk/auth/AuthenticatorService.java
+++ b/native/SalesforceSDK/src/com/salesforce/androidsdk/auth/AuthenticatorService.java
@@ -1,226 +1,226 @@
/*
* Copyright (c) 2011, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - 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.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT OWNER OR 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.
*/
package com.salesforce.androidsdk.auth;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.ClientProtocolException;
import android.accounts.AbstractAccountAuthenticator;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.accounts.NetworkErrorException;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.salesforce.androidsdk.app.ForceApp;
import com.salesforce.androidsdk.auth.OAuth2.OAuthFailedException;
import com.salesforce.androidsdk.auth.OAuth2.TokenEndpointResponse;
import com.salesforce.androidsdk.rest.ClientManager.LoginOptions;
/**
* The service used for taking care of authentication for a Salesforce-based application.
* See {@link <a href="http://developer.android.com/reference/android/accounts/AbstractAccountAuthenticator.html">AbstractAccountAuthenticator</a>}.
*/
public class AuthenticatorService extends Service {
private static Authenticator authenticator;
// Keys to extra info in the account
public static final String KEY_LOGIN_URL = "loginUrl";
public static final String KEY_INSTANCE_URL = "instanceUrl";
public static final String KEY_USER_ID = "userId";
public static final String KEY_CLIENT_ID = "clientId";
public static final String KEY_ORG_ID = "orgId";
public static final String KEY_USERNAME = "username";
public static final String KEY_ID_URL = "id";
public static final String KEY_CLIENT_SECRET = "clientSecret";
private Authenticator getAuthenticator() {
if (authenticator == null)
authenticator = new Authenticator(this);
return authenticator;
}
@Override
public IBinder onBind(Intent intent) {
if (intent.getAction().equals(AccountManager.ACTION_AUTHENTICATOR_INTENT))
return getAuthenticator().getIBinder();
return null;
}
/**
* The Authenticator for salesforce accounts.
* - addAccount Start the login flow (by launching the activity filtering the salesforce.intent.action.LOGIN intent).
* - getAuthToken Refresh the token by calling {@link OAuth2#refreshAuthToken(HttpAccess, URI, String, String) OAuth2.refreshAuthToken}.
*/
private static class Authenticator extends AbstractAccountAuthenticator {
private final Context context;
Authenticator(Context ctx) {
super(ctx);
this.context = ctx;
}
@Override
public Bundle addAccount(
AccountAuthenticatorResponse response,
String accountType,
String authTokenType,
String[] requiredFeatures,
Bundle options)
throws NetworkErrorException {
// Log.i("Authenticator:addAccount", "Options: " + options);
return makeAuthIntentBundle(response, options);
}
/**
* Uses the refresh token to get a new access token.
* Remember that the authenticator runs under its own separate process, so if you want to debug you
* need to attach to the :auth process, and not the main chatter process.
*/
@Override
public Bundle getAuthToken(
AccountAuthenticatorResponse response,
Account account,
String authTokenType,
Bundle options) throws NetworkErrorException {
// Log.i("Authenticator:getAuthToken", "Get auth token for " + account.name);
final AccountManager mgr = AccountManager.get(context);
final String passcodeHash = LoginOptions.fromBundle(options).passcodeHash;
final String refreshToken = ForceApp.decryptWithPasscode(mgr.getPassword(account), passcodeHash);
final String loginServer = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_LOGIN_URL), passcodeHash);
final String clientId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_CLIENT_ID), passcodeHash);
final String instServer = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_INSTANCE_URL), passcodeHash);
final String userId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_USER_ID), passcodeHash);
final String orgId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_ORG_ID), passcodeHash);
final String username = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_USERNAME), passcodeHash);
final String encClientSecret = mgr.getUserData(account, AuthenticatorService.KEY_CLIENT_SECRET);
String clientSecret = null;
if (encClientSecret != null) {
clientSecret = ForceApp.decryptWithPasscode(encClientSecret, passcodeHash);
}
final Bundle resBundle = new Bundle();
try {
final TokenEndpointResponse tr = OAuth2.refreshAuthToken(HttpAccess.DEFAULT, new URI(loginServer), clientId, refreshToken, clientSecret);
// Handle the case where the org has been migrated to a new instance, or has turned on my domains.
if (!instServer.equalsIgnoreCase(tr.instanceUrl)) {
mgr.setUserData(account, AuthenticatorService.KEY_INSTANCE_URL, ForceApp.encryptWithPasscode(tr.instanceUrl, passcodeHash));
}
// Update auth token in account.
mgr.setUserData(account, AccountManager.KEY_AUTHTOKEN, ForceApp.encryptWithPasscode(tr.authToken, passcodeHash));
resBundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
resBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
resBundle.putString(AccountManager.KEY_AUTHTOKEN, tr.authToken);
resBundle.putString(AuthenticatorService.KEY_LOGIN_URL, ForceApp.encryptWithPasscode(loginServer, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_INSTANCE_URL, ForceApp.encryptWithPasscode(instServer, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_CLIENT_ID, ForceApp.encryptWithPasscode(clientId, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_USERNAME, ForceApp.encryptWithPasscode(username, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_USER_ID, ForceApp.encryptWithPasscode(userId, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_ORG_ID, ForceApp.encryptWithPasscode(orgId, passcodeHash));
String encrClientSecret = null;
if (clientSecret != null) {
encrClientSecret = ForceApp.encryptWithPasscode(clientSecret, passcodeHash);
}
resBundle.putString(AuthenticatorService.KEY_CLIENT_SECRET, encrClientSecret);
// Log.i("Authenticator:getAuthToken", "Returning auth bundle for " + account.name);
} catch (ClientProtocolException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (IOException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (URISyntaxException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (OAuthFailedException e) {
if (e.isRefreshTokenInvalid()) {
- Log.i("Authenticator:getAuthToken", "Invalid Refresh Token: (Error: " + e.response.error + ")");
+ Log.i("Authenticator:getAuthToken", "Invalid Refresh Token: (Error: " + e.response.error + ", Status Code: " + e.httpStatusCode + ")");
// the exception explicitly indicates that the refresh token is no longer valid.
return makeAuthIntentBundle(response, options);
}
resBundle.putString(AccountManager.KEY_ERROR_CODE, e.response.error);
resBundle.putString(AccountManager.KEY_ERROR_MESSAGE, e.response.errorDescription);
}
// Log.i("Authenticator:getAuthToken", "Result: " + resBundle);
return resBundle;
}
/**
* Return bundle with intent to start the login flow.
*
* @param response
* @param options
* @return
*/
private Bundle makeAuthIntentBundle(AccountAuthenticatorResponse response, Bundle options) {
Bundle reply = new Bundle();
Intent i = new Intent(context, ForceApp.APP.getLoginActivityClass());
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
if (options != null)
i.putExtras(options);
reply.putParcelable(AccountManager.KEY_INTENT, i);
return reply;
}
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
return null;
}
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException {
return null;
}
@Override
public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) {
return null;
}
@Override
public String getAuthTokenLabel(String authTokenType) {
return null;
}
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException {
return null;
}
}
}
| true | true | public Bundle getAuthToken(
AccountAuthenticatorResponse response,
Account account,
String authTokenType,
Bundle options) throws NetworkErrorException {
// Log.i("Authenticator:getAuthToken", "Get auth token for " + account.name);
final AccountManager mgr = AccountManager.get(context);
final String passcodeHash = LoginOptions.fromBundle(options).passcodeHash;
final String refreshToken = ForceApp.decryptWithPasscode(mgr.getPassword(account), passcodeHash);
final String loginServer = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_LOGIN_URL), passcodeHash);
final String clientId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_CLIENT_ID), passcodeHash);
final String instServer = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_INSTANCE_URL), passcodeHash);
final String userId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_USER_ID), passcodeHash);
final String orgId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_ORG_ID), passcodeHash);
final String username = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_USERNAME), passcodeHash);
final String encClientSecret = mgr.getUserData(account, AuthenticatorService.KEY_CLIENT_SECRET);
String clientSecret = null;
if (encClientSecret != null) {
clientSecret = ForceApp.decryptWithPasscode(encClientSecret, passcodeHash);
}
final Bundle resBundle = new Bundle();
try {
final TokenEndpointResponse tr = OAuth2.refreshAuthToken(HttpAccess.DEFAULT, new URI(loginServer), clientId, refreshToken, clientSecret);
// Handle the case where the org has been migrated to a new instance, or has turned on my domains.
if (!instServer.equalsIgnoreCase(tr.instanceUrl)) {
mgr.setUserData(account, AuthenticatorService.KEY_INSTANCE_URL, ForceApp.encryptWithPasscode(tr.instanceUrl, passcodeHash));
}
// Update auth token in account.
mgr.setUserData(account, AccountManager.KEY_AUTHTOKEN, ForceApp.encryptWithPasscode(tr.authToken, passcodeHash));
resBundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
resBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
resBundle.putString(AccountManager.KEY_AUTHTOKEN, tr.authToken);
resBundle.putString(AuthenticatorService.KEY_LOGIN_URL, ForceApp.encryptWithPasscode(loginServer, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_INSTANCE_URL, ForceApp.encryptWithPasscode(instServer, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_CLIENT_ID, ForceApp.encryptWithPasscode(clientId, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_USERNAME, ForceApp.encryptWithPasscode(username, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_USER_ID, ForceApp.encryptWithPasscode(userId, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_ORG_ID, ForceApp.encryptWithPasscode(orgId, passcodeHash));
String encrClientSecret = null;
if (clientSecret != null) {
encrClientSecret = ForceApp.encryptWithPasscode(clientSecret, passcodeHash);
}
resBundle.putString(AuthenticatorService.KEY_CLIENT_SECRET, encrClientSecret);
// Log.i("Authenticator:getAuthToken", "Returning auth bundle for " + account.name);
} catch (ClientProtocolException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (IOException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (URISyntaxException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (OAuthFailedException e) {
if (e.isRefreshTokenInvalid()) {
Log.i("Authenticator:getAuthToken", "Invalid Refresh Token: (Error: " + e.response.error + ")");
// the exception explicitly indicates that the refresh token is no longer valid.
return makeAuthIntentBundle(response, options);
}
resBundle.putString(AccountManager.KEY_ERROR_CODE, e.response.error);
resBundle.putString(AccountManager.KEY_ERROR_MESSAGE, e.response.errorDescription);
}
// Log.i("Authenticator:getAuthToken", "Result: " + resBundle);
return resBundle;
}
| public Bundle getAuthToken(
AccountAuthenticatorResponse response,
Account account,
String authTokenType,
Bundle options) throws NetworkErrorException {
// Log.i("Authenticator:getAuthToken", "Get auth token for " + account.name);
final AccountManager mgr = AccountManager.get(context);
final String passcodeHash = LoginOptions.fromBundle(options).passcodeHash;
final String refreshToken = ForceApp.decryptWithPasscode(mgr.getPassword(account), passcodeHash);
final String loginServer = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_LOGIN_URL), passcodeHash);
final String clientId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_CLIENT_ID), passcodeHash);
final String instServer = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_INSTANCE_URL), passcodeHash);
final String userId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_USER_ID), passcodeHash);
final String orgId = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_ORG_ID), passcodeHash);
final String username = ForceApp.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_USERNAME), passcodeHash);
final String encClientSecret = mgr.getUserData(account, AuthenticatorService.KEY_CLIENT_SECRET);
String clientSecret = null;
if (encClientSecret != null) {
clientSecret = ForceApp.decryptWithPasscode(encClientSecret, passcodeHash);
}
final Bundle resBundle = new Bundle();
try {
final TokenEndpointResponse tr = OAuth2.refreshAuthToken(HttpAccess.DEFAULT, new URI(loginServer), clientId, refreshToken, clientSecret);
// Handle the case where the org has been migrated to a new instance, or has turned on my domains.
if (!instServer.equalsIgnoreCase(tr.instanceUrl)) {
mgr.setUserData(account, AuthenticatorService.KEY_INSTANCE_URL, ForceApp.encryptWithPasscode(tr.instanceUrl, passcodeHash));
}
// Update auth token in account.
mgr.setUserData(account, AccountManager.KEY_AUTHTOKEN, ForceApp.encryptWithPasscode(tr.authToken, passcodeHash));
resBundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
resBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
resBundle.putString(AccountManager.KEY_AUTHTOKEN, tr.authToken);
resBundle.putString(AuthenticatorService.KEY_LOGIN_URL, ForceApp.encryptWithPasscode(loginServer, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_INSTANCE_URL, ForceApp.encryptWithPasscode(instServer, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_CLIENT_ID, ForceApp.encryptWithPasscode(clientId, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_USERNAME, ForceApp.encryptWithPasscode(username, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_USER_ID, ForceApp.encryptWithPasscode(userId, passcodeHash));
resBundle.putString(AuthenticatorService.KEY_ORG_ID, ForceApp.encryptWithPasscode(orgId, passcodeHash));
String encrClientSecret = null;
if (clientSecret != null) {
encrClientSecret = ForceApp.encryptWithPasscode(clientSecret, passcodeHash);
}
resBundle.putString(AuthenticatorService.KEY_CLIENT_SECRET, encrClientSecret);
// Log.i("Authenticator:getAuthToken", "Returning auth bundle for " + account.name);
} catch (ClientProtocolException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (IOException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (URISyntaxException e) {
Log.w("Authenticator:getAuthToken", "", e);
throw new NetworkErrorException(e);
} catch (OAuthFailedException e) {
if (e.isRefreshTokenInvalid()) {
Log.i("Authenticator:getAuthToken", "Invalid Refresh Token: (Error: " + e.response.error + ", Status Code: " + e.httpStatusCode + ")");
// the exception explicitly indicates that the refresh token is no longer valid.
return makeAuthIntentBundle(response, options);
}
resBundle.putString(AccountManager.KEY_ERROR_CODE, e.response.error);
resBundle.putString(AccountManager.KEY_ERROR_MESSAGE, e.response.errorDescription);
}
// Log.i("Authenticator:getAuthToken", "Result: " + resBundle);
return resBundle;
}
|
diff --git a/ToolReplenish/src/com/onyxchills/toolreplenish/PlayerHandListener.java b/ToolReplenish/src/com/onyxchills/toolreplenish/PlayerHandListener.java
index b9c4450..e7d2e93 100644
--- a/ToolReplenish/src/com/onyxchills/toolreplenish/PlayerHandListener.java
+++ b/ToolReplenish/src/com/onyxchills/toolreplenish/PlayerHandListener.java
@@ -1,55 +1,57 @@
package com.onyxchills.toolreplenish;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerItemHeldEvent;
public class PlayerHandListener implements Listener
{
@EventHandler
public boolean onPlayerRightClick(PlayerItemHeldEvent event)
{
Player player = event.getPlayer();
Material item = player.getItemInHand().getType();
if(player.isSneaking())
{
if(player.hasPermission("toolreplenish.fix"))
{
+ /*
if(item == Material.WOOD_SPADE || item == Material.WOOD_SWORD || item == Material.WOOD_PICKAXE || item == Material.WOOD_AXE || item == Material.WOOD_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-59));
return true;
}
else if(item == Material.STONE_SPADE || item == Material.STONE_SWORD || item == Material.STONE_PICKAXE || item == Material.STONE_AXE || item == Material.STONE_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-131));
return true;
}
else if(item == Material.IRON_SPADE || item == Material.IRON_SWORD || item == Material.IRON_PICKAXE || item == Material.IRON_AXE || item == Material.IRON_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-250));
return true;
}
- else if(item == Material.GOLD_SPADE || item == Material.GOLD_SWORD || item == Material.GOLD_PICKAXE || item == Material.GOLD_AXE || item == Material.GOLD_HOE)
+ */
+ if(item == Material.GOLD_SPADE || item == Material.GOLD_SWORD || item == Material.GOLD_PICKAXE || item == Material.GOLD_AXE || item == Material.GOLD_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-32));
return true;
}
- else if(item == Material.DIAMOND_SPADE || item == Material.DIAMOND_SWORD || item == Material.DIAMOND_PICKAXE || item == Material.DIAMOND_AXE || item == Material.DIAMOND_HOE)
- {
- player.getItemInHand().setDurability((short) ((item.getMaxDurability())-1561));
- return true;
- }
+ //else if(item == Material.DIAMOND_SPADE || item == Material.DIAMOND_SWORD || item == Material.DIAMOND_PICKAXE || item == Material.DIAMOND_AXE || item == Material.DIAMOND_HOE)
+ //{
+ // player.getItemInHand().setDurability((short) ((item.getMaxDurability())-1561));
+ // return true;
+ //}
}
}
else
{
}
return false;
}
}
| false | true | public boolean onPlayerRightClick(PlayerItemHeldEvent event)
{
Player player = event.getPlayer();
Material item = player.getItemInHand().getType();
if(player.isSneaking())
{
if(player.hasPermission("toolreplenish.fix"))
{
if(item == Material.WOOD_SPADE || item == Material.WOOD_SWORD || item == Material.WOOD_PICKAXE || item == Material.WOOD_AXE || item == Material.WOOD_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-59));
return true;
}
else if(item == Material.STONE_SPADE || item == Material.STONE_SWORD || item == Material.STONE_PICKAXE || item == Material.STONE_AXE || item == Material.STONE_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-131));
return true;
}
else if(item == Material.IRON_SPADE || item == Material.IRON_SWORD || item == Material.IRON_PICKAXE || item == Material.IRON_AXE || item == Material.IRON_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-250));
return true;
}
else if(item == Material.GOLD_SPADE || item == Material.GOLD_SWORD || item == Material.GOLD_PICKAXE || item == Material.GOLD_AXE || item == Material.GOLD_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-32));
return true;
}
else if(item == Material.DIAMOND_SPADE || item == Material.DIAMOND_SWORD || item == Material.DIAMOND_PICKAXE || item == Material.DIAMOND_AXE || item == Material.DIAMOND_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-1561));
return true;
}
}
}
else
{
}
return false;
}
| public boolean onPlayerRightClick(PlayerItemHeldEvent event)
{
Player player = event.getPlayer();
Material item = player.getItemInHand().getType();
if(player.isSneaking())
{
if(player.hasPermission("toolreplenish.fix"))
{
/*
if(item == Material.WOOD_SPADE || item == Material.WOOD_SWORD || item == Material.WOOD_PICKAXE || item == Material.WOOD_AXE || item == Material.WOOD_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-59));
return true;
}
else if(item == Material.STONE_SPADE || item == Material.STONE_SWORD || item == Material.STONE_PICKAXE || item == Material.STONE_AXE || item == Material.STONE_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-131));
return true;
}
else if(item == Material.IRON_SPADE || item == Material.IRON_SWORD || item == Material.IRON_PICKAXE || item == Material.IRON_AXE || item == Material.IRON_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-250));
return true;
}
*/
if(item == Material.GOLD_SPADE || item == Material.GOLD_SWORD || item == Material.GOLD_PICKAXE || item == Material.GOLD_AXE || item == Material.GOLD_HOE)
{
player.getItemInHand().setDurability((short) ((item.getMaxDurability())-32));
return true;
}
//else if(item == Material.DIAMOND_SPADE || item == Material.DIAMOND_SWORD || item == Material.DIAMOND_PICKAXE || item == Material.DIAMOND_AXE || item == Material.DIAMOND_HOE)
//{
// player.getItemInHand().setDurability((short) ((item.getMaxDurability())-1561));
// return true;
//}
}
}
else
{
}
return false;
}
|
diff --git a/x10.compiler/src/x10/ast/X10CanonicalTypeNode_c.java b/x10.compiler/src/x10/ast/X10CanonicalTypeNode_c.java
index 33bc2c991..30827d896 100644
--- a/x10.compiler/src/x10/ast/X10CanonicalTypeNode_c.java
+++ b/x10.compiler/src/x10/ast/X10CanonicalTypeNode_c.java
@@ -1,318 +1,318 @@
/*
* 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.Iterator;
import java.util.List;
import polyglot.ast.CanonicalTypeNode;
import polyglot.ast.CanonicalTypeNode_c;
import polyglot.ast.Expr;
import polyglot.ast.Node;
import polyglot.ast.TypeNode;
import polyglot.frontend.Globals;
import polyglot.frontend.SetResolverGoal;
import polyglot.types.ClassDef;
import polyglot.types.CodeDef;
import polyglot.types.ConstructorDef;
import polyglot.types.Context;
import polyglot.types.Def;
import polyglot.types.Flags;
import polyglot.types.LazyRef;
import polyglot.types.Ref;
import polyglot.types.SemanticException;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.types.Types;
import polyglot.util.CodeWriter;
import polyglot.util.InternalCompilerError;
import polyglot.util.Position;
import polyglot.visit.PrettyPrinter;
import polyglot.visit.TypeBuilder;
import polyglot.visit.TypeCheckPreparer;
import polyglot.visit.TypeChecker;
import polyglot.visit.ContextVisitor;
import polyglot.visit.NodeVisitor;
import x10.constraint.XConstraint;
import x10.errors.Errors;
import x10.extension.X10Del;
import x10.types.ClosureDef;
import x10.types.ClosureType_c;
import x10.types.ConstrainedType;
import x10.types.ParameterType;
import x10.types.X10ClassDef;
import x10.types.X10ClassType;
import polyglot.types.Context;
import x10.types.X10ParsedClassType;
import x10.types.XTypeTranslator;
import polyglot.types.TypeSystem;
import x10.types.constraints.CConstraint;
import x10.visit.X10TypeChecker;
/**
* The X10 version of a CanonicalTypeNode.
* Has an associated DepParameterExpr.
* @author vj
*
*/
public class X10CanonicalTypeNode_c extends CanonicalTypeNode_c implements X10CanonicalTypeNode, AddFlags {
public X10CanonicalTypeNode_c(Position pos, Type type) {
this(pos, Types.<Type>ref(type));
}
public X10CanonicalTypeNode_c(Position pos, Ref<? extends Type> type) {
super(pos, type);
}
Flags flags;
public void addFlags(Flags f) {
flags = f;
}
@Override
public Node typeCheck(ContextVisitor tc) {
Context c = (Context) tc.context();
TypeSystem ts = (TypeSystem) tc.typeSystem();
// Expand, and transfer flags from the type node to the type.
Type t = Types.get(type);
t = ts.expandMacros(t);
Type xt = t;
if (flags != null) {
xt = Types.processFlags(flags, xt);
flags = null;
}
((Ref<Type>) type).update(xt);
if (t instanceof ParameterType) {
ParameterType pt = (ParameterType) t;
Def def = Types.get(pt.def());
boolean inConstructor = false;
Context p = c;
// Pop back to the right context before proceeding
while (p.pop() != null && (p.currentClassDef() != def || p.currentCode() instanceof ClosureDef))
p = p.pop();
if (p.currentCode() instanceof ConstructorDef) {
ConstructorDef td = (ConstructorDef) p.currentCode();
Type container = Types.get(td.container());
if (container instanceof X10ClassType) {
X10ClassType ct = (X10ClassType) container;
if (ct.def() == def) {
inConstructor = true;
}
}
}
if (p.inStaticContext() && def instanceof ClassDef && ! inConstructor) {
Errors.issue(tc.job(),
new Errors.CannotReferToTypeParameterFromStaticContext(pt, def, position()));
}
if (flags != null && ! flags.equals(Flags.NONE)) {
Errors.issue(tc.job(),
new Errors.CannotQualifyTypeParameter(pt, def, flags, position()));
}
}
try {
checkType(tc.context(), t, position());
} catch (SemanticException e) {
Errors.issue(tc.job(), e, this);
}
List<AnnotationNode> as = ((X10Del) this.del()).annotations();
if (as != null && !as.isEmpty()) {
// Eh. Why not?
// if (c.inAnnotation()) {
// throw new SemanticException("Annotations not permitted within annotations.", position());
// }
List<Type> annotationTypes = new ArrayList<Type>();
for (AnnotationNode an : as) {
Type at = an.annotationInterface();
annotationTypes.add(at);
}
Type newType = ts.AnnotatedType(position(), t, annotationTypes);
Ref<Type> tref = (Ref<Type>) type;
tref.update(newType);
}
Node n = super.typeCheck(tc);
return n;
}
// todo: C:\cygwin\home\Yoav\intellij\sourceforge\x10.tests\examples\Benchmarks\SeqArray1.x10
// C:\cygwin\home\Yoav\intellij\sourceforge\x10.tests\examples\Benchmarks\SeqArray2b.x10
// C:\cygwin\home\Yoav\intellij\sourceforge\x10.tests\examples\Constructs\Array\Array1.x10
@Override
public void setResolver(Node parent, final TypeCheckPreparer v) {
if (typeRef() instanceof LazyRef<?>) {
LazyRef<Type> r = (LazyRef<Type>) typeRef();
if (!r.isResolverSet()) {
TypeChecker tc = new X10TypeChecker(v.job(), v.typeSystem(), v.nodeFactory(), v.getMemo());
// similarly to TypeNode_c, freezing is not needed.
tc = (TypeChecker) tc.context(v.context().freeze());
r.setResolver(new X10TypeCheckTypeGoal(parent, this, tc, r));
}
}
}
@Override
public Node conformanceCheck(ContextVisitor tc) {
Type t = type();
XConstraint c = Types.realX(t);
if (! c.consistent()) {
Errors.issue(tc.job(),
new Errors.InvalidType(t, position()));
}
TypeSystem ts = (TypeSystem) t.typeSystem();
if (! ts.consistent(t, tc.context())) {
Errors.issue(tc.job(), new Errors.TypeInconsistent(t,position()));
}
return this;
}
public static void checkType(Context context, Type t, Position pos) throws SemanticException {
if (t == null) throw new SemanticException("Invalid type.", pos);
if (t instanceof ConstrainedType) {
ConstrainedType ct = (ConstrainedType) t;
Type base = Types.get(ct.baseType());
// if (base instanceof ParameterType) {
// throw new SemanticException("Invalid type; cannot constrain a type parameter.", position());
// }
checkType(context, base, pos);
}
- if (t instanceof X10ClassType) {
+ if (t instanceof X10ClassType && ((X10ClassType) t).error()==null) {
X10ClassType ct = (X10ClassType) t;
X10ClassDef def = ct.x10Def();
final List<Type> typeArgs = ct.typeArguments();
final int typeArgNum = typeArgs == null ? 0 : typeArgs.size();
final List<ParameterType> typeParam = def.typeParameters();
final int typeParamNum = typeParam.size();
// I want to check that all generic classes have all the required type arguments, i.e., X10TypeMixin.checkMissingParameters(t, position())
// E.g., that you always write: Array[...] and never Array.
// But that is not true for a static method, e.g., Array.make(...)
// so instead we do this check in all other places (e.g., field access, method definitions, new calls, etc)
// But I can check it if there are typeArguments.
if (typeArgNum > 0) Types.checkMissingParameters(t,pos);
for (int j = 0; j < typeArgNum; j++) {
Type actualType = typeArgs.get(j);
Types.checkMissingParameters(actualType,pos);
ParameterType correspondingParam = typeParam.get(j);
if (actualType.isVoid()) {
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with type " + actualType + ".", pos);
}
}
// A invariant parameter may not be instantiated on a covariant or contravariant parameter.
// A contravariant parameter may not be instantiated on a covariant parameter.
// A covariant parameter may not be instantiated on a contravariant parameter.
for (int j = 0; j < typeArgNum; j++) {
Type actualType = typeArgs.get(j);
ParameterType correspondingParam = typeParam.get(j);
ParameterType.Variance correspondingVariance = def.variances().get(j);
if (actualType instanceof ParameterType) {
ParameterType pt = (ParameterType) actualType;
if (pt.def() instanceof X10ClassDef) {
X10ClassDef actualDef = (X10ClassDef) pt.def();
for (int i = 0; i < actualDef.typeParameters().size(); i++) {
ParameterType.Variance actualVariance;
if (i < actualDef.variances().size())
actualVariance = actualDef.variances().get(i);
else
actualVariance = ParameterType.Variance.INVARIANT;
if (pt.typeEquals(actualDef.typeParameters().get(i), context)) {
switch (correspondingVariance) {
case INVARIANT:
switch (actualVariance) {
case CONTRAVARIANT:
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with contravariant parameter " + pt + " of " + actualDef + ".", pos);
case COVARIANT:
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with covariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
case CONTRAVARIANT:
switch (actualVariance) {
case COVARIANT:
throw new SemanticException("Cannot instantiate contravariant parameter " + correspondingParam + " of " + def + " with covariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
case COVARIANT:
switch (actualVariance) {
case CONTRAVARIANT:
throw new SemanticException("Cannot instantiate covariant parameter " + correspondingParam + " of " + def + " with contravariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
}
}
}
}
}
}
}
}
public String toString() {
return (flags == null ? "" : flags.toString() + " ") + super.toString();
}
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
prettyPrint(w, tr, true);
}
public void prettyPrint(CodeWriter w, PrettyPrinter tr, Boolean extras) {
if (type == null) {
w.write("<unknown-type>");
} else {
type.get().print(w);
final X10ParsedClassType baseType = Types.myBaseType(type.get());
if (extras && baseType!=null
&& !(baseType instanceof ClosureType_c)) {
List<Type> typeArguments = baseType.typeArguments();
if (typeArguments != null && typeArguments.size() > 0) {
w.write("[");
w.allowBreak(2, 2, "", 0); // miser mode
w.begin(0);
for (Iterator<Type> i = typeArguments.iterator(); i.hasNext(); ) {
Type t = i.next();
t.print(w);
if (i.hasNext()) {
w.write(",");
w.allowBreak(0, " ");
}
}
w.write("]");
w.end();
}
}
if (extras && type.get() instanceof ConstrainedType) {
((ConstrainedType) type.get()).printConstraint(w);
}
}
}
}
| true | true | public static void checkType(Context context, Type t, Position pos) throws SemanticException {
if (t == null) throw new SemanticException("Invalid type.", pos);
if (t instanceof ConstrainedType) {
ConstrainedType ct = (ConstrainedType) t;
Type base = Types.get(ct.baseType());
// if (base instanceof ParameterType) {
// throw new SemanticException("Invalid type; cannot constrain a type parameter.", position());
// }
checkType(context, base, pos);
}
if (t instanceof X10ClassType) {
X10ClassType ct = (X10ClassType) t;
X10ClassDef def = ct.x10Def();
final List<Type> typeArgs = ct.typeArguments();
final int typeArgNum = typeArgs == null ? 0 : typeArgs.size();
final List<ParameterType> typeParam = def.typeParameters();
final int typeParamNum = typeParam.size();
// I want to check that all generic classes have all the required type arguments, i.e., X10TypeMixin.checkMissingParameters(t, position())
// E.g., that you always write: Array[...] and never Array.
// But that is not true for a static method, e.g., Array.make(...)
// so instead we do this check in all other places (e.g., field access, method definitions, new calls, etc)
// But I can check it if there are typeArguments.
if (typeArgNum > 0) Types.checkMissingParameters(t,pos);
for (int j = 0; j < typeArgNum; j++) {
Type actualType = typeArgs.get(j);
Types.checkMissingParameters(actualType,pos);
ParameterType correspondingParam = typeParam.get(j);
if (actualType.isVoid()) {
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with type " + actualType + ".", pos);
}
}
// A invariant parameter may not be instantiated on a covariant or contravariant parameter.
// A contravariant parameter may not be instantiated on a covariant parameter.
// A covariant parameter may not be instantiated on a contravariant parameter.
for (int j = 0; j < typeArgNum; j++) {
Type actualType = typeArgs.get(j);
ParameterType correspondingParam = typeParam.get(j);
ParameterType.Variance correspondingVariance = def.variances().get(j);
if (actualType instanceof ParameterType) {
ParameterType pt = (ParameterType) actualType;
if (pt.def() instanceof X10ClassDef) {
X10ClassDef actualDef = (X10ClassDef) pt.def();
for (int i = 0; i < actualDef.typeParameters().size(); i++) {
ParameterType.Variance actualVariance;
if (i < actualDef.variances().size())
actualVariance = actualDef.variances().get(i);
else
actualVariance = ParameterType.Variance.INVARIANT;
if (pt.typeEquals(actualDef.typeParameters().get(i), context)) {
switch (correspondingVariance) {
case INVARIANT:
switch (actualVariance) {
case CONTRAVARIANT:
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with contravariant parameter " + pt + " of " + actualDef + ".", pos);
case COVARIANT:
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with covariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
case CONTRAVARIANT:
switch (actualVariance) {
case COVARIANT:
throw new SemanticException("Cannot instantiate contravariant parameter " + correspondingParam + " of " + def + " with covariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
case COVARIANT:
switch (actualVariance) {
case CONTRAVARIANT:
throw new SemanticException("Cannot instantiate covariant parameter " + correspondingParam + " of " + def + " with contravariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
}
}
}
}
}
}
}
}
| public static void checkType(Context context, Type t, Position pos) throws SemanticException {
if (t == null) throw new SemanticException("Invalid type.", pos);
if (t instanceof ConstrainedType) {
ConstrainedType ct = (ConstrainedType) t;
Type base = Types.get(ct.baseType());
// if (base instanceof ParameterType) {
// throw new SemanticException("Invalid type; cannot constrain a type parameter.", position());
// }
checkType(context, base, pos);
}
if (t instanceof X10ClassType && ((X10ClassType) t).error()==null) {
X10ClassType ct = (X10ClassType) t;
X10ClassDef def = ct.x10Def();
final List<Type> typeArgs = ct.typeArguments();
final int typeArgNum = typeArgs == null ? 0 : typeArgs.size();
final List<ParameterType> typeParam = def.typeParameters();
final int typeParamNum = typeParam.size();
// I want to check that all generic classes have all the required type arguments, i.e., X10TypeMixin.checkMissingParameters(t, position())
// E.g., that you always write: Array[...] and never Array.
// But that is not true for a static method, e.g., Array.make(...)
// so instead we do this check in all other places (e.g., field access, method definitions, new calls, etc)
// But I can check it if there are typeArguments.
if (typeArgNum > 0) Types.checkMissingParameters(t,pos);
for (int j = 0; j < typeArgNum; j++) {
Type actualType = typeArgs.get(j);
Types.checkMissingParameters(actualType,pos);
ParameterType correspondingParam = typeParam.get(j);
if (actualType.isVoid()) {
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with type " + actualType + ".", pos);
}
}
// A invariant parameter may not be instantiated on a covariant or contravariant parameter.
// A contravariant parameter may not be instantiated on a covariant parameter.
// A covariant parameter may not be instantiated on a contravariant parameter.
for (int j = 0; j < typeArgNum; j++) {
Type actualType = typeArgs.get(j);
ParameterType correspondingParam = typeParam.get(j);
ParameterType.Variance correspondingVariance = def.variances().get(j);
if (actualType instanceof ParameterType) {
ParameterType pt = (ParameterType) actualType;
if (pt.def() instanceof X10ClassDef) {
X10ClassDef actualDef = (X10ClassDef) pt.def();
for (int i = 0; i < actualDef.typeParameters().size(); i++) {
ParameterType.Variance actualVariance;
if (i < actualDef.variances().size())
actualVariance = actualDef.variances().get(i);
else
actualVariance = ParameterType.Variance.INVARIANT;
if (pt.typeEquals(actualDef.typeParameters().get(i), context)) {
switch (correspondingVariance) {
case INVARIANT:
switch (actualVariance) {
case CONTRAVARIANT:
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with contravariant parameter " + pt + " of " + actualDef + ".", pos);
case COVARIANT:
throw new SemanticException("Cannot instantiate invariant parameter " + correspondingParam + " of " + def + " with covariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
case CONTRAVARIANT:
switch (actualVariance) {
case COVARIANT:
throw new SemanticException("Cannot instantiate contravariant parameter " + correspondingParam + " of " + def + " with covariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
case COVARIANT:
switch (actualVariance) {
case CONTRAVARIANT:
throw new SemanticException("Cannot instantiate covariant parameter " + correspondingParam + " of " + def + " with contravariant parameter " + pt + " of " + actualDef + ".", pos);
}
break;
}
}
}
}
}
}
}
}
|
diff --git a/GnuBackgammon/src/it/alcacoop/backgammon/layers/TwoPlayersScreen.java b/GnuBackgammon/src/it/alcacoop/backgammon/layers/TwoPlayersScreen.java
index 6193644..a7f7715 100644
--- a/GnuBackgammon/src/it/alcacoop/backgammon/layers/TwoPlayersScreen.java
+++ b/GnuBackgammon/src/it/alcacoop/backgammon/layers/TwoPlayersScreen.java
@@ -1,338 +1,338 @@
/*
##################################################################
# GNU BACKGAMMON MOBILE #
##################################################################
# #
# Authors: Domenico Martella - Davide Saurino #
# E-mail: [email protected] #
# Date: 19/12/2012 #
# #
##################################################################
# #
# Copyright (C) 2012 Alca Societa' Cooperativa #
# #
# This file is part of GNU BACKGAMMON MOBILE. #
# GNU BACKGAMMON MOBILE 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. #
# #
# GNU BACKGAMMON MOBILE 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 v3 along with this program. #
# If not, see <http://http://www.gnu.org/licenses/> #
# #
##################################################################
*/
package it.alcacoop.backgammon.layers;
import it.alcacoop.backgammon.GnuBackgammon;
import it.alcacoop.backgammon.actions.MyActions;
import it.alcacoop.backgammon.actors.FixedButtonGroup;
import it.alcacoop.backgammon.fsm.BaseFSM.Events;
import it.alcacoop.backgammon.ui.IconButton;
import it.alcacoop.backgammon.ui.UIDialog;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
public class TwoPlayersScreen extends BaseScreen {
private Label connecting;
private Table table;
private FixedButtonGroup type;
private Label llocal;
private Label lfibs;
private Label ltiga;
private Label lplay;
private ScrollPane sp;
private int variant = 0; //0=LOCAL,1=FIBS,2=TIGA,3=GPLAY
public TwoPlayersScreen(){
ClickListener cl = new ClickListener() {
public void clicked(InputEvent event, float x, float y) {
String s = ((TextButton)event.getListenerActor()).getText().toString().toUpperCase();
if (!s.equals("BACK"))
s+=variant;
GnuBackgammon.fsm.processEvent(Events.BUTTON_CLICKED, s);
};
};
llocal = new Label("", GnuBackgammon.skin);
llocal.setWrap(true);
String sl = "LOCAL\n\n" +
"Play against human player on the same device\n" +
"As on single player mode, you can choose from 1 to 15 points match," +
"with or without cube, an between two variant: " +
"\n1. Backgammon" +
"\n2. Nackgammon";
llocal.setText(sl);
ltiga = new Label("", GnuBackgammon.skin);
ltiga.setWrap(true);
String st = "TIGERGAMMON\n\n" +
"TigerGammon is just another backgammon server like FIBS (First internet Backgammon Server).\n" +
"TigerGammon wants to keep the institution FIBS alive. " +
"TigerGammon works just like FIBS. Over time you will see features " +
"that exceed, what you can see on FIBS\n\n" +
"ANDREAS HAUSMANN features TigerGammon. He is another Fibster discontent " +
"with the flaws of FIBS just like so many others.\n\n" +
"Like FIBS, TigerGammon needs a username/password account.\nNOTE: FIBS account is " +
"not compatible with TigerGammon account - You must create another one, with different ranking\n\n" +
"Please do not forget your password. There is currently no way " +
"for the TigerGammon administrator to retrieve this information. If you " +
"forget your password then you must start again under a new username.";
ltiga.setText(st);
lfibs = new Label("", GnuBackgammon.skin);
lfibs.setWrap(true);
String sf = "FIBS\n\n" +
"FIBS is the First Internet Backgammon Server, " +
"it allows Internet users to play backgammon in real-time against " +
"real people (and even some bots). There are players of every " +
"conceivable ability logging onto FIBS, from absolute beginners " +
"to serious backgammon champion contenders. \n\n" +
"NOTE: At the moment FIBS needs validation for new users, so " +
- "you can't crate accounts within Backgammon Mobile.\n\n" +
+ "you can't create accounts within Backgammon Mobile.\n\n" +
"You have to do it from 'http://fibs.com' and contact FIBS administrator " +
- "at '[email protected]' with your username (not your password!) to request validation.\n" +
+ "sending an email at '[email protected]' with your username (not password!).\n" +
"As FIBS is a free server run by one person, this may take up to a day " +
"and occasionally longer.\n" +
"Alternatively you can get a try on our primary choice: TigerGammon!";
lfibs.setText(sf);
lplay = new Label("", GnuBackgammon.skin);
lplay.setWrap(true);
String sg = "Google Play Games\n\n" +
"Play against your Google+ friends or random opponent\n\nCOMING SOON...";
lplay.setText(sg);
stage.addListener(new InputListener() {
@Override
public boolean keyDown(InputEvent event, int keycode) {
if(Gdx.input.isKeyPressed(Keys.BACK)||Gdx.input.isKeyPressed(Keys.ESCAPE)) {
if (UIDialog.isOpened()) return false;
GnuBackgammon.fsm.processEvent(Events.BUTTON_CLICKED, "BACK");
}
return super.keyDown(event, keycode);
}
});
type = new FixedButtonGroup();
Label titleLabel = new Label("TWO PLAYERS SETTINGS", GnuBackgammon.skin);
float height = stage.getHeight()/8.5f;
float pad = 0;
table = new Table();
table.setWidth(stage.getWidth()*0.9f);
table.setHeight(stage.getHeight()*0.9f);
table.setX((stage.getWidth()-table.getWidth())/2);
table.setY((stage.getHeight()-table.getHeight())/2);
TextButton play = new TextButton("PLAY", GnuBackgammon.skin);
play.addListener(cl);
TextButton back = new TextButton("BACK", GnuBackgammon.skin);
back.addListener(cl);
TextButtonStyle ts = GnuBackgammon.skin.get("toggle", TextButtonStyle.class);
IconButton local = new IconButton("Local", GnuBackgammon.atlas.findRegion("dp"), ts);
IconButton fibs = new IconButton("FIBS", GnuBackgammon.atlas.findRegion("mpl"), ts);
IconButton tiga = new IconButton("TigerGammon", GnuBackgammon.atlas.findRegion("mpl"), ts);
IconButton gplay = new IconButton("Google Play Games", GnuBackgammon.atlas.findRegion("gpl"), ts);
type.add(local);
type.add(fibs);
type.add(tiga);
type.add(gplay);
local.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(llocal).left().top().expandX().fillX();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 0;
GnuBackgammon.Instance.server = "";
}
});
fibs.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(lfibs).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 1;
GnuBackgammon.Instance.server = "fibs.com";
}
});
tiga.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(ltiga).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 2;
GnuBackgammon.Instance.server = "ti-ga.com";
}
});
gplay.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(lplay).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 3;
if (!GnuBackgammon.Instance.nativeFunctions.gserviceIsSignedIn())
UIDialog.getGServiceLoginDialog();
}
});
table.add(titleLabel).colspan(7);
table.row();
table.add().fill().expandX().colspan(7).height(height/2);
Table t1 = new Table();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(local).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(tiga).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(fibs).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(gplay).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expand().fill();
Table text = new Table();
text.add(llocal).expandX().fillX();
text.row();
text.add().fillY().expandY();
sp = new ScrollPane(text, GnuBackgammon.skin.get("info", ScrollPaneStyle.class));
sp.setFadeScrollBars(false);
sp.setForceOverscroll(false, false);
sp.setOverscroll(false, false);
table.row();
table.add(t1).colspan(3).fill().expand();
table.add(sp).colspan(4).fill().expand().padLeft(stage.getWidth()/20);
table.row();
table.add().fill().expand().colspan(7).height(height/2);
table.row().height(height);
table.add();
table.add(back).fill().colspan(2);
table.add();
table.add(play).fill().colspan(2);
table.add();
stage.addActor(table);
connecting = new Label("Connecting to server...", GnuBackgammon.skin);
connecting.setVisible(false);
connecting.setX((stage.getWidth()-connecting.getWidth())/2);
connecting.setY(height*1.5f);
connecting.addAction(Actions.forever(Actions.sequence(Actions.alpha(0.5f, 0.4f), Actions.alpha(1, 0.4f))));
stage.addActor(connecting);
}
public void hideConnecting() {
connecting.setVisible(false);
Gdx.graphics.setContinuousRendering(false);
Gdx.graphics.requestRendering();
}
public void showConnecting(String msg) {
connecting.setText(msg);
connecting.setX((stage.getWidth()-connecting.getWidth())/2);
connecting.setVisible(true);
Gdx.graphics.setContinuousRendering(true);
Gdx.graphics.requestRendering();
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0.1f, 0.45f, 0.08f, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
stage.act(delta);
stage.draw();
if (sp.getVelocityY()!=0) Gdx.graphics.requestRendering();
}
@Override
public void initialize() {
table.setColor(1,1,1,0);
table.setX(-stage.getWidth());
}
@Override
public void show() {
super.show();
Gdx.input.setInputProcessor(stage);
Gdx.input.setCatchBackKey(true);
table.addAction(MyActions.sequence(Actions.parallel(Actions.fadeIn(animationTime),Actions.moveTo((stage.getWidth()-table.getWidth())/2, (stage.getHeight()-table.getHeight())/2, animationTime))));
}
@Override
public void fadeOut() {
table.addAction(MyActions.sequence(Actions.parallel(Actions.fadeOut(animationTime),Actions.moveTo(-stage.getWidth(), (stage.getHeight()-table.getHeight())/2, animationTime))));
}
}
| false | true | public TwoPlayersScreen(){
ClickListener cl = new ClickListener() {
public void clicked(InputEvent event, float x, float y) {
String s = ((TextButton)event.getListenerActor()).getText().toString().toUpperCase();
if (!s.equals("BACK"))
s+=variant;
GnuBackgammon.fsm.processEvent(Events.BUTTON_CLICKED, s);
};
};
llocal = new Label("", GnuBackgammon.skin);
llocal.setWrap(true);
String sl = "LOCAL\n\n" +
"Play against human player on the same device\n" +
"As on single player mode, you can choose from 1 to 15 points match," +
"with or without cube, an between two variant: " +
"\n1. Backgammon" +
"\n2. Nackgammon";
llocal.setText(sl);
ltiga = new Label("", GnuBackgammon.skin);
ltiga.setWrap(true);
String st = "TIGERGAMMON\n\n" +
"TigerGammon is just another backgammon server like FIBS (First internet Backgammon Server).\n" +
"TigerGammon wants to keep the institution FIBS alive. " +
"TigerGammon works just like FIBS. Over time you will see features " +
"that exceed, what you can see on FIBS\n\n" +
"ANDREAS HAUSMANN features TigerGammon. He is another Fibster discontent " +
"with the flaws of FIBS just like so many others.\n\n" +
"Like FIBS, TigerGammon needs a username/password account.\nNOTE: FIBS account is " +
"not compatible with TigerGammon account - You must create another one, with different ranking\n\n" +
"Please do not forget your password. There is currently no way " +
"for the TigerGammon administrator to retrieve this information. If you " +
"forget your password then you must start again under a new username.";
ltiga.setText(st);
lfibs = new Label("", GnuBackgammon.skin);
lfibs.setWrap(true);
String sf = "FIBS\n\n" +
"FIBS is the First Internet Backgammon Server, " +
"it allows Internet users to play backgammon in real-time against " +
"real people (and even some bots). There are players of every " +
"conceivable ability logging onto FIBS, from absolute beginners " +
"to serious backgammon champion contenders. \n\n" +
"NOTE: At the moment FIBS needs validation for new users, so " +
"you can't crate accounts within Backgammon Mobile.\n\n" +
"You have to do it from 'http://fibs.com' and contact FIBS administrator " +
"at '[email protected]' with your username (not your password!) to request validation.\n" +
"As FIBS is a free server run by one person, this may take up to a day " +
"and occasionally longer.\n" +
"Alternatively you can get a try on our primary choice: TigerGammon!";
lfibs.setText(sf);
lplay = new Label("", GnuBackgammon.skin);
lplay.setWrap(true);
String sg = "Google Play Games\n\n" +
"Play against your Google+ friends or random opponent\n\nCOMING SOON...";
lplay.setText(sg);
stage.addListener(new InputListener() {
@Override
public boolean keyDown(InputEvent event, int keycode) {
if(Gdx.input.isKeyPressed(Keys.BACK)||Gdx.input.isKeyPressed(Keys.ESCAPE)) {
if (UIDialog.isOpened()) return false;
GnuBackgammon.fsm.processEvent(Events.BUTTON_CLICKED, "BACK");
}
return super.keyDown(event, keycode);
}
});
type = new FixedButtonGroup();
Label titleLabel = new Label("TWO PLAYERS SETTINGS", GnuBackgammon.skin);
float height = stage.getHeight()/8.5f;
float pad = 0;
table = new Table();
table.setWidth(stage.getWidth()*0.9f);
table.setHeight(stage.getHeight()*0.9f);
table.setX((stage.getWidth()-table.getWidth())/2);
table.setY((stage.getHeight()-table.getHeight())/2);
TextButton play = new TextButton("PLAY", GnuBackgammon.skin);
play.addListener(cl);
TextButton back = new TextButton("BACK", GnuBackgammon.skin);
back.addListener(cl);
TextButtonStyle ts = GnuBackgammon.skin.get("toggle", TextButtonStyle.class);
IconButton local = new IconButton("Local", GnuBackgammon.atlas.findRegion("dp"), ts);
IconButton fibs = new IconButton("FIBS", GnuBackgammon.atlas.findRegion("mpl"), ts);
IconButton tiga = new IconButton("TigerGammon", GnuBackgammon.atlas.findRegion("mpl"), ts);
IconButton gplay = new IconButton("Google Play Games", GnuBackgammon.atlas.findRegion("gpl"), ts);
type.add(local);
type.add(fibs);
type.add(tiga);
type.add(gplay);
local.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(llocal).left().top().expandX().fillX();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 0;
GnuBackgammon.Instance.server = "";
}
});
fibs.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(lfibs).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 1;
GnuBackgammon.Instance.server = "fibs.com";
}
});
tiga.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(ltiga).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 2;
GnuBackgammon.Instance.server = "ti-ga.com";
}
});
gplay.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(lplay).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 3;
if (!GnuBackgammon.Instance.nativeFunctions.gserviceIsSignedIn())
UIDialog.getGServiceLoginDialog();
}
});
table.add(titleLabel).colspan(7);
table.row();
table.add().fill().expandX().colspan(7).height(height/2);
Table t1 = new Table();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(local).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(tiga).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(fibs).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(gplay).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expand().fill();
Table text = new Table();
text.add(llocal).expandX().fillX();
text.row();
text.add().fillY().expandY();
sp = new ScrollPane(text, GnuBackgammon.skin.get("info", ScrollPaneStyle.class));
sp.setFadeScrollBars(false);
sp.setForceOverscroll(false, false);
sp.setOverscroll(false, false);
table.row();
table.add(t1).colspan(3).fill().expand();
table.add(sp).colspan(4).fill().expand().padLeft(stage.getWidth()/20);
table.row();
table.add().fill().expand().colspan(7).height(height/2);
table.row().height(height);
table.add();
table.add(back).fill().colspan(2);
table.add();
table.add(play).fill().colspan(2);
table.add();
stage.addActor(table);
connecting = new Label("Connecting to server...", GnuBackgammon.skin);
connecting.setVisible(false);
connecting.setX((stage.getWidth()-connecting.getWidth())/2);
connecting.setY(height*1.5f);
connecting.addAction(Actions.forever(Actions.sequence(Actions.alpha(0.5f, 0.4f), Actions.alpha(1, 0.4f))));
stage.addActor(connecting);
}
| public TwoPlayersScreen(){
ClickListener cl = new ClickListener() {
public void clicked(InputEvent event, float x, float y) {
String s = ((TextButton)event.getListenerActor()).getText().toString().toUpperCase();
if (!s.equals("BACK"))
s+=variant;
GnuBackgammon.fsm.processEvent(Events.BUTTON_CLICKED, s);
};
};
llocal = new Label("", GnuBackgammon.skin);
llocal.setWrap(true);
String sl = "LOCAL\n\n" +
"Play against human player on the same device\n" +
"As on single player mode, you can choose from 1 to 15 points match," +
"with or without cube, an between two variant: " +
"\n1. Backgammon" +
"\n2. Nackgammon";
llocal.setText(sl);
ltiga = new Label("", GnuBackgammon.skin);
ltiga.setWrap(true);
String st = "TIGERGAMMON\n\n" +
"TigerGammon is just another backgammon server like FIBS (First internet Backgammon Server).\n" +
"TigerGammon wants to keep the institution FIBS alive. " +
"TigerGammon works just like FIBS. Over time you will see features " +
"that exceed, what you can see on FIBS\n\n" +
"ANDREAS HAUSMANN features TigerGammon. He is another Fibster discontent " +
"with the flaws of FIBS just like so many others.\n\n" +
"Like FIBS, TigerGammon needs a username/password account.\nNOTE: FIBS account is " +
"not compatible with TigerGammon account - You must create another one, with different ranking\n\n" +
"Please do not forget your password. There is currently no way " +
"for the TigerGammon administrator to retrieve this information. If you " +
"forget your password then you must start again under a new username.";
ltiga.setText(st);
lfibs = new Label("", GnuBackgammon.skin);
lfibs.setWrap(true);
String sf = "FIBS\n\n" +
"FIBS is the First Internet Backgammon Server, " +
"it allows Internet users to play backgammon in real-time against " +
"real people (and even some bots). There are players of every " +
"conceivable ability logging onto FIBS, from absolute beginners " +
"to serious backgammon champion contenders. \n\n" +
"NOTE: At the moment FIBS needs validation for new users, so " +
"you can't create accounts within Backgammon Mobile.\n\n" +
"You have to do it from 'http://fibs.com' and contact FIBS administrator " +
"sending an email at '[email protected]' with your username (not password!).\n" +
"As FIBS is a free server run by one person, this may take up to a day " +
"and occasionally longer.\n" +
"Alternatively you can get a try on our primary choice: TigerGammon!";
lfibs.setText(sf);
lplay = new Label("", GnuBackgammon.skin);
lplay.setWrap(true);
String sg = "Google Play Games\n\n" +
"Play against your Google+ friends or random opponent\n\nCOMING SOON...";
lplay.setText(sg);
stage.addListener(new InputListener() {
@Override
public boolean keyDown(InputEvent event, int keycode) {
if(Gdx.input.isKeyPressed(Keys.BACK)||Gdx.input.isKeyPressed(Keys.ESCAPE)) {
if (UIDialog.isOpened()) return false;
GnuBackgammon.fsm.processEvent(Events.BUTTON_CLICKED, "BACK");
}
return super.keyDown(event, keycode);
}
});
type = new FixedButtonGroup();
Label titleLabel = new Label("TWO PLAYERS SETTINGS", GnuBackgammon.skin);
float height = stage.getHeight()/8.5f;
float pad = 0;
table = new Table();
table.setWidth(stage.getWidth()*0.9f);
table.setHeight(stage.getHeight()*0.9f);
table.setX((stage.getWidth()-table.getWidth())/2);
table.setY((stage.getHeight()-table.getHeight())/2);
TextButton play = new TextButton("PLAY", GnuBackgammon.skin);
play.addListener(cl);
TextButton back = new TextButton("BACK", GnuBackgammon.skin);
back.addListener(cl);
TextButtonStyle ts = GnuBackgammon.skin.get("toggle", TextButtonStyle.class);
IconButton local = new IconButton("Local", GnuBackgammon.atlas.findRegion("dp"), ts);
IconButton fibs = new IconButton("FIBS", GnuBackgammon.atlas.findRegion("mpl"), ts);
IconButton tiga = new IconButton("TigerGammon", GnuBackgammon.atlas.findRegion("mpl"), ts);
IconButton gplay = new IconButton("Google Play Games", GnuBackgammon.atlas.findRegion("gpl"), ts);
type.add(local);
type.add(fibs);
type.add(tiga);
type.add(gplay);
local.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(llocal).left().top().expandX().fillX();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 0;
GnuBackgammon.Instance.server = "";
}
});
fibs.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(lfibs).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 1;
GnuBackgammon.Instance.server = "fibs.com";
}
});
tiga.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(ltiga).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 2;
GnuBackgammon.Instance.server = "ti-ga.com";
}
});
gplay.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
GnuBackgammon.Instance.snd.playMoveStart();
Table text = new Table();
text.add(lplay).left().top().expand().fill();
text.row();
text.add().fill().expand();
sp.setWidget(text);
variant = 3;
if (!GnuBackgammon.Instance.nativeFunctions.gserviceIsSignedIn())
UIDialog.getGServiceLoginDialog();
}
});
table.add(titleLabel).colspan(7);
table.row();
table.add().fill().expandX().colspan(7).height(height/2);
Table t1 = new Table();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(local).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(tiga).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(fibs).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expandX().fill().height(height/10);
t1.row();
t1.add(gplay).fillX().expandX().height(height).padRight(pad);
t1.row();
t1.add().expand().fill();
Table text = new Table();
text.add(llocal).expandX().fillX();
text.row();
text.add().fillY().expandY();
sp = new ScrollPane(text, GnuBackgammon.skin.get("info", ScrollPaneStyle.class));
sp.setFadeScrollBars(false);
sp.setForceOverscroll(false, false);
sp.setOverscroll(false, false);
table.row();
table.add(t1).colspan(3).fill().expand();
table.add(sp).colspan(4).fill().expand().padLeft(stage.getWidth()/20);
table.row();
table.add().fill().expand().colspan(7).height(height/2);
table.row().height(height);
table.add();
table.add(back).fill().colspan(2);
table.add();
table.add(play).fill().colspan(2);
table.add();
stage.addActor(table);
connecting = new Label("Connecting to server...", GnuBackgammon.skin);
connecting.setVisible(false);
connecting.setX((stage.getWidth()-connecting.getWidth())/2);
connecting.setY(height*1.5f);
connecting.addAction(Actions.forever(Actions.sequence(Actions.alpha(0.5f, 0.4f), Actions.alpha(1, 0.4f))));
stage.addActor(connecting);
}
|
diff --git a/src/java/org/infoglue/deliver/util/VelocityTemplateProcessor.java b/src/java/org/infoglue/deliver/util/VelocityTemplateProcessor.java
index a9f5e348d..d67a4f7d6 100755
--- a/src/java/org/infoglue/deliver/util/VelocityTemplateProcessor.java
+++ b/src/java/org/infoglue/deliver/util/VelocityTemplateProcessor.java
@@ -1,146 +1,146 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* 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. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including 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 org.infoglue.deliver.util;
import org.apache.log4j.Logger;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.*;
import org.infoglue.cms.applications.common.VisualFormatter;
import org.infoglue.cms.io.FileHelper;
import org.infoglue.cms.util.CmsPropertyHandler;
import org.infoglue.deliver.applications.databeans.DeliveryContext;
import org.infoglue.deliver.controllers.kernel.impl.simple.TemplateController;
import java.util.Map;
import java.util.Iterator;
import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
/**
*
* @author Mattias Bogeblad
*/
public class VelocityTemplateProcessor
{
private final static Logger logger = Logger.getLogger(VelocityTemplateProcessor.class.getName());
/**
* This method takes arguments and renders a template given as a string to the specified outputstream.
* Improve later - cache for example the engine.
*/
public void renderTemplate(Map params, PrintWriter pw, String templateAsString) throws Exception
{
renderTemplate(params, pw, templateAsString, false);
}
/**
* This method takes arguments and renders a template given as a string to the specified outputstream.
* Improve later - cache for example the engine.
*/
public void renderTemplate(Map params, PrintWriter pw, String templateAsString, boolean forceVelocity) throws Exception
{
try
{
Timer timer = new Timer();
timer.setActive(false);
if(templateAsString.indexOf("<%") > -1 || templateAsString.indexOf("http://java.sun.com/products/jsp/dtd/jspcore_1_0.dtd") > -1)
{
dispatchJSP(params, pw, templateAsString);
}
else
{
boolean useFreeMarker = false;
String useFreeMarkerString = CmsPropertyHandler.getProperty("useFreeMarker");
if(useFreeMarkerString != null && useFreeMarkerString.equalsIgnoreCase("true"))
useFreeMarker = true;
- if(useFreeMarker && !forceVelocity)
+ if((useFreeMarker || templateAsString.indexOf("<#-- IG:FreeMarker -->") > -1) && !forceVelocity)
{
FreemarkerTemplateProcessor.getProcessor().renderTemplate(params, pw, templateAsString);
}
else
{
Velocity.init();
VelocityContext context = new VelocityContext();
Iterator i = params.keySet().iterator();
while(i.hasNext())
{
String key = (String)i.next();
context.put(key, params.get(key));
}
Reader reader = new StringReader(templateAsString);
boolean finished = Velocity.evaluate(context, pw, "Generator Error", reader);
}
}
timer.printElapsedTime("End renderTemplate");
}
catch(Exception e)
{
logger.warn("templateAsString:" + templateAsString);
throw e;
}
}
/**
* This methods renders a template which is written in JSP. The string is written to disk and then called.
*
* @param params
* @param pw
* @param templateAsString
* @throws ServletException
* @throws IOException
*/
public void dispatchJSP(Map params, PrintWriter pw, String templateAsString) throws ServletException, IOException, Exception
{
int hashCode = templateAsString.hashCode();
String contextRootPath = CmsPropertyHandler.getProperty("contextRootPath");
String fileName = contextRootPath + "jsp" + File.separator + "Template_" + hashCode + ".jsp";
File template = new File(fileName);
if(!template.exists())
FileHelper.writeToFile(template, templateAsString, false);
TemplateController templateController = (TemplateController)params.get("templateLogic");
DeliveryContext deliveryContext = templateController.getDeliveryContext();
RequestDispatcher dispatch = templateController.getHttpServletRequest().getRequestDispatcher("/jsp/Template_" + hashCode + ".jsp");
templateController.getHttpServletRequest().setAttribute("org.infoglue.cms.deliver.templateLogic", templateController);
CharResponseWrapper wrapper = new CharResponseWrapper(deliveryContext.getHttpServletResponse());
dispatch.include(templateController.getHttpServletRequest(), wrapper);
String result = wrapper.toString();
pw.println(result);
}
}
| true | true | public void renderTemplate(Map params, PrintWriter pw, String templateAsString, boolean forceVelocity) throws Exception
{
try
{
Timer timer = new Timer();
timer.setActive(false);
if(templateAsString.indexOf("<%") > -1 || templateAsString.indexOf("http://java.sun.com/products/jsp/dtd/jspcore_1_0.dtd") > -1)
{
dispatchJSP(params, pw, templateAsString);
}
else
{
boolean useFreeMarker = false;
String useFreeMarkerString = CmsPropertyHandler.getProperty("useFreeMarker");
if(useFreeMarkerString != null && useFreeMarkerString.equalsIgnoreCase("true"))
useFreeMarker = true;
if(useFreeMarker && !forceVelocity)
{
FreemarkerTemplateProcessor.getProcessor().renderTemplate(params, pw, templateAsString);
}
else
{
Velocity.init();
VelocityContext context = new VelocityContext();
Iterator i = params.keySet().iterator();
while(i.hasNext())
{
String key = (String)i.next();
context.put(key, params.get(key));
}
Reader reader = new StringReader(templateAsString);
boolean finished = Velocity.evaluate(context, pw, "Generator Error", reader);
}
}
timer.printElapsedTime("End renderTemplate");
}
catch(Exception e)
{
logger.warn("templateAsString:" + templateAsString);
throw e;
}
}
| public void renderTemplate(Map params, PrintWriter pw, String templateAsString, boolean forceVelocity) throws Exception
{
try
{
Timer timer = new Timer();
timer.setActive(false);
if(templateAsString.indexOf("<%") > -1 || templateAsString.indexOf("http://java.sun.com/products/jsp/dtd/jspcore_1_0.dtd") > -1)
{
dispatchJSP(params, pw, templateAsString);
}
else
{
boolean useFreeMarker = false;
String useFreeMarkerString = CmsPropertyHandler.getProperty("useFreeMarker");
if(useFreeMarkerString != null && useFreeMarkerString.equalsIgnoreCase("true"))
useFreeMarker = true;
if((useFreeMarker || templateAsString.indexOf("<#-- IG:FreeMarker -->") > -1) && !forceVelocity)
{
FreemarkerTemplateProcessor.getProcessor().renderTemplate(params, pw, templateAsString);
}
else
{
Velocity.init();
VelocityContext context = new VelocityContext();
Iterator i = params.keySet().iterator();
while(i.hasNext())
{
String key = (String)i.next();
context.put(key, params.get(key));
}
Reader reader = new StringReader(templateAsString);
boolean finished = Velocity.evaluate(context, pw, "Generator Error", reader);
}
}
timer.printElapsedTime("End renderTemplate");
}
catch(Exception e)
{
logger.warn("templateAsString:" + templateAsString);
throw e;
}
}
|
diff --git a/netbout/netbout-rest/src/main/java/com/netbout/rest/FastRs.java b/netbout/netbout-rest/src/main/java/com/netbout/rest/FastRs.java
index 3c311e5eb..fbea40e43 100644
--- a/netbout/netbout-rest/src/main/java/com/netbout/rest/FastRs.java
+++ b/netbout/netbout-rest/src/main/java/com/netbout/rest/FastRs.java
@@ -1,119 +1,119 @@
/**
* Copyright (c) 2009-2011, netBout.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are PROHIBITED without prior written permission from
* the author. This product may NOT be used anywhere and on any computer
* except the server platform of netBout Inc. located at www.netbout.com.
* Federal copyright law prohibits unauthorized reproduction by any means
* and imposes fines up to $25,000 for violation. If you received
* this code occasionally and without intent to use it, please report this
* incident to the author by email.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS 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 COPYRIGHT
* OWNER OR 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.
*/
package com.netbout.rest;
import com.netbout.rest.page.PageBuilder;
import com.netbout.spi.Bout;
import com.netbout.spi.Identity;
import com.netbout.spi.Participant;
import com.netbout.spi.Urn;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
/**
* Fast-lane URIs.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
*/
@Path("/fast")
public final class FastRs extends AbstractRs {
/**
* Start a new bout with this first message and participants.
* @param participants List of participants (comma separated)
* @param message The message to post
* @param leader Who should be a leader (0 = me, 1 = first in the list
* of participants, etc.)
* @return The JAX-RS response
*/
@GET
@Path("/start")
public Response start(@QueryParam("participants") final String participants,
@QueryParam("message") final String message,
@QueryParam("leader") @DefaultValue("0") final String leader) {
if (participants == null || message == null) {
throw new ForwardException(
this,
this.base(),
"Query params 'participants' and 'message' are mandatory"
);
}
final Identity identity = this.identity();
final Bout bout = identity.start();
int pos = 1;
for (String dude : participants.split(",")) {
Participant invited;
try {
invited = bout.invite(identity.friend(Urn.create(dude)));
} catch (com.netbout.spi.UnreachableUrnException ex) {
throw new ForwardException(this, this.base(), ex);
} catch (com.netbout.spi.DuplicateInvitationException ex) {
throw new ForwardException(this, this.base(), ex);
}
- if (Integer.valueOf(leader) == pos) {
+ if (Integer.parseInt(leader) == pos) {
invited.consign();
}
++pos;
}
try {
bout.post(message);
} catch (com.netbout.spi.MessagePostException ex) {
throw new ForwardException(this, this.base(), ex);
}
return new PageBuilder()
.build(AbstractPage.class)
.init(this)
.authenticated(identity)
.status(Response.Status.SEE_OTHER)
.location(this.base().path("/{num}").build(bout.number()))
.build();
}
/**
* Start a new bout with this first message and participants.
* @param participants List of participants (comma separated)
* @param message The message to post
* @param leader Who should be a leader (0 = me, 1 = first in the list
* of participants, etc.)
* @return The JAX-RS response
*/
@POST
@Path("/start")
public Response startPost(
@FormParam("participants") final String participants,
@FormParam("message") final String message,
@QueryParam("leader") @DefaultValue("0") final String leader) {
return this.start(participants, message, leader);
}
}
| true | true | public Response start(@QueryParam("participants") final String participants,
@QueryParam("message") final String message,
@QueryParam("leader") @DefaultValue("0") final String leader) {
if (participants == null || message == null) {
throw new ForwardException(
this,
this.base(),
"Query params 'participants' and 'message' are mandatory"
);
}
final Identity identity = this.identity();
final Bout bout = identity.start();
int pos = 1;
for (String dude : participants.split(",")) {
Participant invited;
try {
invited = bout.invite(identity.friend(Urn.create(dude)));
} catch (com.netbout.spi.UnreachableUrnException ex) {
throw new ForwardException(this, this.base(), ex);
} catch (com.netbout.spi.DuplicateInvitationException ex) {
throw new ForwardException(this, this.base(), ex);
}
if (Integer.valueOf(leader) == pos) {
invited.consign();
}
++pos;
}
try {
bout.post(message);
} catch (com.netbout.spi.MessagePostException ex) {
throw new ForwardException(this, this.base(), ex);
}
return new PageBuilder()
.build(AbstractPage.class)
.init(this)
.authenticated(identity)
.status(Response.Status.SEE_OTHER)
.location(this.base().path("/{num}").build(bout.number()))
.build();
}
| public Response start(@QueryParam("participants") final String participants,
@QueryParam("message") final String message,
@QueryParam("leader") @DefaultValue("0") final String leader) {
if (participants == null || message == null) {
throw new ForwardException(
this,
this.base(),
"Query params 'participants' and 'message' are mandatory"
);
}
final Identity identity = this.identity();
final Bout bout = identity.start();
int pos = 1;
for (String dude : participants.split(",")) {
Participant invited;
try {
invited = bout.invite(identity.friend(Urn.create(dude)));
} catch (com.netbout.spi.UnreachableUrnException ex) {
throw new ForwardException(this, this.base(), ex);
} catch (com.netbout.spi.DuplicateInvitationException ex) {
throw new ForwardException(this, this.base(), ex);
}
if (Integer.parseInt(leader) == pos) {
invited.consign();
}
++pos;
}
try {
bout.post(message);
} catch (com.netbout.spi.MessagePostException ex) {
throw new ForwardException(this, this.base(), ex);
}
return new PageBuilder()
.build(AbstractPage.class)
.init(this)
.authenticated(identity)
.status(Response.Status.SEE_OTHER)
.location(this.base().path("/{num}").build(bout.number()))
.build();
}
|
diff --git a/src/app/net/onlite/morplay/mongo/MongoStore.java b/src/app/net/onlite/morplay/mongo/MongoStore.java
index a12a89c..331f3fc 100644
--- a/src/app/net/onlite/morplay/mongo/MongoStore.java
+++ b/src/app/net/onlite/morplay/mongo/MongoStore.java
@@ -1,88 +1,88 @@
package net.onlite.morplay.mongo;
import com.github.jmkgreen.morphia.Datastore;
import com.github.jmkgreen.morphia.query.Query;
/**
* Responsible for operations on database.
*/
public class MongoStore {
/**
* Morphia datastore implementation
*/
private Datastore datastore;
/**
* Mongo collections cache
*/
private static final MongoCollectionCache collectionCache = new MongoCollectionCache();
/**
* Constructor.
* Initialize mongo connection.
* @param datastore Morphia datastore implementation instance
*/
public MongoStore(Datastore datastore) {
this.datastore = datastore;
}
/**
* Get collection
* @param entityClass Entity class instance
* @param <T> Entity type
* @return Collection wrapper
*/
- protected <T> MongoCollection<T> collection(Class<T> entityClass) {
+ public <T> MongoCollection<T> collection(Class<T> entityClass) {
// We need to create concrete classes for specific entity type
/**
* Concrete atomic operation class
*/
class TAtomicOperation extends AtomicOperation<T> {
public TAtomicOperation(Datastore ds, Query<T> query, boolean multiple) {
super(ds, query, multiple);
}
}
/**
* Concrete collection class
*/
class TMongoCollection extends MongoCollection<T> {
public TMongoCollection(Class<T> entityClass, Datastore ds) {
super(entityClass, ds);
}
@Override
public AtomicOperation<T> atomic(Filter... filters) {
return new TAtomicOperation(ds, query(filters), false);
}
@Override
public AtomicOperation<T> atomicAll(Filter... filters) {
return new TAtomicOperation(ds, query(filters), true);
}
}
if (collectionCache.contains(entityClass, ds())) {
return collectionCache.get(entityClass, ds(), TMongoCollection.class);
}
return collectionCache.add(entityClass, ds(), new TMongoCollection(entityClass, ds()));
}
/**
* Return morphia data store implementation.
* @return Datastore implementation instance.
*/
public Datastore ds() {
return datastore;
}
/**
* Reset cache
*/
public static void resetCache() {
collectionCache.clear();
}
}
| true | true | protected <T> MongoCollection<T> collection(Class<T> entityClass) {
// We need to create concrete classes for specific entity type
/**
* Concrete atomic operation class
*/
class TAtomicOperation extends AtomicOperation<T> {
public TAtomicOperation(Datastore ds, Query<T> query, boolean multiple) {
super(ds, query, multiple);
}
}
/**
* Concrete collection class
*/
class TMongoCollection extends MongoCollection<T> {
public TMongoCollection(Class<T> entityClass, Datastore ds) {
super(entityClass, ds);
}
@Override
public AtomicOperation<T> atomic(Filter... filters) {
return new TAtomicOperation(ds, query(filters), false);
}
@Override
public AtomicOperation<T> atomicAll(Filter... filters) {
return new TAtomicOperation(ds, query(filters), true);
}
}
if (collectionCache.contains(entityClass, ds())) {
return collectionCache.get(entityClass, ds(), TMongoCollection.class);
}
return collectionCache.add(entityClass, ds(), new TMongoCollection(entityClass, ds()));
}
| public <T> MongoCollection<T> collection(Class<T> entityClass) {
// We need to create concrete classes for specific entity type
/**
* Concrete atomic operation class
*/
class TAtomicOperation extends AtomicOperation<T> {
public TAtomicOperation(Datastore ds, Query<T> query, boolean multiple) {
super(ds, query, multiple);
}
}
/**
* Concrete collection class
*/
class TMongoCollection extends MongoCollection<T> {
public TMongoCollection(Class<T> entityClass, Datastore ds) {
super(entityClass, ds);
}
@Override
public AtomicOperation<T> atomic(Filter... filters) {
return new TAtomicOperation(ds, query(filters), false);
}
@Override
public AtomicOperation<T> atomicAll(Filter... filters) {
return new TAtomicOperation(ds, query(filters), true);
}
}
if (collectionCache.contains(entityClass, ds())) {
return collectionCache.get(entityClass, ds(), TMongoCollection.class);
}
return collectionCache.add(entityClass, ds(), new TMongoCollection(entityClass, ds()));
}
|
diff --git a/booking/src/main/java/org/sample/booking/controllers/Application.java b/booking/src/main/java/org/sample/booking/controllers/Application.java
index 8b061466..65992af1 100644
--- a/booking/src/main/java/org/sample/booking/controllers/Application.java
+++ b/booking/src/main/java/org/sample/booking/controllers/Application.java
@@ -1,140 +1,140 @@
/*
* Copyright (C) 2011 eXo Platform SAS.
*
* This 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 (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.sample.booking.controllers;
import org.juzu.Action;
import org.juzu.Path;
import org.juzu.View;
import org.juzu.Response;
import org.juzu.template.Template;
import javax.inject.Inject;
import java.io.IOException;
import org.sample.booking.*;
import org.sample.booking.models.User;
/** @author <a href="mailto:[email protected]">Julien Viet</a> */
public class Application
{
/*
@Before
static void addUser() {
User user = connected();
if(user != null) {
renderArgs.put("user", user);
}
}
static User connected() {
if(renderArgs.get("user") != null) {
return renderArgs.get("user", User.class);
}
String username = session.get("user");
if(username != null) {
return User.find("byUsername", username).first();
}
return null;
}
// ~~
*/
@Inject @Path("index.gtmpl")
Template index;
@Inject @Path("register.gtmpl")
Template register;
@Inject
Login login;
@Inject
Hotels hotels;
@Inject
Flash flash;
@View
public void index() throws IOException
{
if (login.isConnected())
{
hotels.index();
}
else
{
index.render();
}
}
@View
public void register() throws IOException
{
register.render();
}
@Action
public Response saveUser(String username, String name, String password, String verifyPassword)
{
/*
validation.required(verifyPassword);
validation.equals(verifyPassword, user.password).message("Your password doesn't match");
if(validation.hasErrors()) {
render("@register", user, verifyPassword);
}
*/
User user = new User(name, password, verifyPassword);
user.username = username;
User.create(user);
login.setUserName(user.username);
flash.setSuccess("Welcome, " + user.name);
return Application_.index();
}
@Action
public Response login(String username, String password)
{
System.out.println("Want login " + username + " " + password);
User user = User.find(username, password);
if (user != null)
{
- login.setUserName(user.name);
+ login.setUserName(user.username);
flash.setSuccess("Welcome, " + user.name);
return Hotels_.index();
}
else
{
// Oops
flash.setUsername(username);
flash.setError("Login failed");
return null;
}
}
@Action
public Response logout()
{
login.setUserName(null);
return Application_.index();
}
}
| true | true | public Response login(String username, String password)
{
System.out.println("Want login " + username + " " + password);
User user = User.find(username, password);
if (user != null)
{
login.setUserName(user.name);
flash.setSuccess("Welcome, " + user.name);
return Hotels_.index();
}
else
{
// Oops
flash.setUsername(username);
flash.setError("Login failed");
return null;
}
}
| public Response login(String username, String password)
{
System.out.println("Want login " + username + " " + password);
User user = User.find(username, password);
if (user != null)
{
login.setUserName(user.username);
flash.setSuccess("Welcome, " + user.name);
return Hotels_.index();
}
else
{
// Oops
flash.setUsername(username);
flash.setError("Login failed");
return null;
}
}
|
diff --git a/src/main/java/com/rackspace/cloud/api/docs/calabash/extensions/CopyTransformImage.java b/src/main/java/com/rackspace/cloud/api/docs/calabash/extensions/CopyTransformImage.java
index 06dbfd6..76d3821 100644
--- a/src/main/java/com/rackspace/cloud/api/docs/calabash/extensions/CopyTransformImage.java
+++ b/src/main/java/com/rackspace/cloud/api/docs/calabash/extensions/CopyTransformImage.java
@@ -1,292 +1,292 @@
package com.rackspace.cloud.api.docs.calabash.extensions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmNode;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
import com.rackspace.cloud.api.docs.calabash.extensions.util.RelativePath;
import com.xmlcalabash.core.XProcException;
import com.xmlcalabash.util.ProcessMatch;
import com.xmlcalabash.util.ProcessMatchingNodes;
/**
* Created with IntelliJ IDEA.
* User: ykamran
* Date: 9/12/12
* Time: 6:29 PM
* To change this template use File | Settings | File Templates.
*/
public class CopyTransformImage implements ProcessMatchingNodes {
private String xpath;
private Map<String, String> baseUriToDirMap = new HashMap<String, String>();
private AtomicInteger simpleUniqueNumberGenerator = new AtomicInteger();
private Map<String, String> processedFilesMapForHtmlOutput = new HashMap<String, String>();
private Set<String> processedFilesSetForPdfOutput = new HashSet<String>();
private ProcessMatch matcher;
private URI targetDirectoryUri;
private URI targetHtmlContentDirectoryUri;
private String outputType;
private boolean errorsFound = false;
private Log log = null;
public Log getLog() {
if (log == null) {
log = new SystemStreamLog();
}
return log;
}
public CopyTransformImage(String _xpath, URI _targetDirectory, URI _targetHtmlContentDirectoryUri, String _outputType) {
this.xpath = _xpath;
this.targetDirectoryUri = _targetDirectory;
this.targetHtmlContentDirectoryUri = _targetHtmlContentDirectoryUri;
this.outputType = _outputType;
}
public boolean hasErrors() {
return errorsFound;
}
public String getXPath() {
return xpath;
}
public void setMatcher (ProcessMatch matcher) {
this.matcher = matcher;
}
private String processSelectedImage(XdmNode imageDataFileRef) {
final URI baseUri = imageDataFileRef.getBaseURI();
final String fileRef = imageDataFileRef.getStringValue();
final URI baseDirUri = baseUri.resolve(".");
String srcImgFilePath = FilenameUtils.normalize(baseDirUri.getPath() + File.separator + fileRef);
- File srcImgFile = getFileHandle(srcImgFilePath);
+ File srcImgFile = getFileHandle(srcImgFilePath.trim());
if (fileRef.toLowerCase().startsWith("http://") ||
fileRef.toLowerCase().startsWith("https://")) {
getLog().warn("Found reference to an external image " + fileRef + " in " + baseUri.getPath());
return fileRef;
}
else if (outputType.equals("pdf")) {
//Need to check only for the existence of the image file
if (this.processedFilesSetForPdfOutput.contains(srcImgFilePath)) {
//do nothing as any errors for missing files would already have been reported
}
else if (isImageForHtmlOnly(imageDataFileRef.getParent())) {
//ignore this imagedata
}
else if (! fileExists(srcImgFile)) {
reportImageNotFoundError(baseUri, fileRef, srcImgFile);
}
this.processedFilesSetForPdfOutput.add(srcImgFilePath);
//For pdf output always return the input fileRef
return fileRef;
}
else if (outputType.equals("html")) {
//check if we have already copied this particular image to webhelp folder
if (this.processedFilesMapForHtmlOutput.containsKey(srcImgFilePath)) {
return this.processedFilesMapForHtmlOutput.get(srcImgFilePath);
}
String targetDirPath = calculateTargetDirPath(baseUri.getPath(), fileRef);
File targetDir = makeDirs(targetDirPath);
String relativePathToCopiedFile;
//For HTML, we need a more elaborate check for missing images
if (isImageForPdfOnly(imageDataFileRef.getParent())) {
//ignore this imagedata
relativePathToCopiedFile = fileRef;
}
else if (! fileExists(srcImgFile)) {
reportImageNotFoundError(baseUri, fileRef, srcImgFile);
relativePathToCopiedFile = fileRef;
}
else if ("svg".equalsIgnoreCase(FilenameUtils.getExtension(srcImgFilePath))) {
//convert the svg to the relevant type and copy
File svgFile = getFileHandle(srcImgFilePath);
File copiedFile = new TransformSVGToPNG().transformAndCopy(svgFile, targetDir);
relativePathToCopiedFile = RelativePath.getRelativePath(new File(targetHtmlContentDirectoryUri), copiedFile);
}
else {
//simply copy the src file to the destination
File copiedFile = copyFile(srcImgFile, targetDir);
relativePathToCopiedFile = RelativePath.getRelativePath(new File(targetHtmlContentDirectoryUri), copiedFile);
}
this.processedFilesMapForHtmlOutput.put(srcImgFilePath, relativePathToCopiedFile);
return relativePathToCopiedFile;
}
else {
//we only know how to handle "pdf" and "html" outputTypes so just return the value
return fileRef;
}
}
private boolean isImageForHtmlOnly(XdmNode imageDataNode) {
return parentRoleEquals(imageDataNode, "html");
}
private boolean isImageForPdfOnly(XdmNode imageDataNode) {
return parentRoleEquals(imageDataNode, "fo") || parentRoleEquals(imageDataNode, "pdf");
}
private boolean parentRoleEquals(XdmNode node, String role) {
XdmNode parent = node.getParent();
String parentRole = (parent==null ? null : parent.getAttributeValue(new QName("role")));
if (parentRole != null &&
parentRole.equalsIgnoreCase(role)) {
return true;
}
return false;
}
private String calculateTargetDirPath(String baseUriPath, String fileRef) {
String targetDirForBaseUri = null;
if (this.baseUriToDirMap.containsKey(baseUriPath)) {
targetDirForBaseUri = this.baseUriToDirMap.get(baseUriPath);
} else {
targetDirForBaseUri = "" + this.simpleUniqueNumberGenerator.incrementAndGet();
this.baseUriToDirMap.put(baseUriPath, targetDirForBaseUri);
}
String targetDirForFileRef = FilenameUtils.getPathNoEndSeparator(fileRef.replaceAll("\\.\\.", "a"));
return (targetDirForBaseUri + File.separator + targetDirForFileRef);
}
private File copyFile(File srcFile, File targetDir) {
try {
FileUtils.copyFileToDirectory(srcFile, targetDir);
} catch (IOException e) {
getLog().error("Unable to copy file: " + srcFile.getAbsolutePath() + " to " + targetDir.getAbsolutePath());
throw new XProcException(e);
}
return new File(targetDir.getAbsolutePath() + File.separator + srcFile.getName());
}
private void reportImageNotFoundError(URI baseUri, String fileRef, File srcImgFile) {
getLog().error( "File not found: '" + srcImgFile + "'. " +
"File is referred in '" + baseUri.getPath() + "' fileRef='" + fileRef + "'.");
this.errorsFound = true;
}
private boolean fileExists(File file) {
try {
return file==null ? false : file.exists() && file.getCanonicalPath().endsWith(file.getName());
} catch (IOException e) {
getLog().error("Unable to access file: " + file.getAbsolutePath());
return false;
}
}
private File makeDirs(String relativePath) {
File dir = new File(targetDirectoryUri.getPath(), relativePath);
if (dir.exists() || dir.mkdir() || dir.mkdirs()) {
return dir;
} else {
getLog().error("Unable to create directory: " + dir.getAbsolutePath());
return null;
}
}
private File getFileHandle(String filePath) {
File handle = new File(filePath);
return (handle.isDirectory() ? null : handle);
}
@Override
public boolean processStartDocument(XdmNode node) throws SaxonApiException {
return true;//process children
}
@Override
public void processEndDocument(XdmNode node) throws SaxonApiException {
//do nothing
}
@Override
public boolean processStartElement(XdmNode node) throws SaxonApiException {
return true;//process children
}
@Override
public void processAttribute(XdmNode node) throws SaxonApiException {
String newValue = processSelectedImage(node);
matcher.addAttribute(node, newValue);
}
@Override
public void processEndElement(XdmNode node) throws SaxonApiException { }
@Override
public void processText(XdmNode node) throws SaxonApiException {
String newValue = processSelectedImage(node);
matcher.addText(newValue);
}
@Override
public void processComment(XdmNode node) throws SaxonApiException {
String newValue = processSelectedImage(node);
matcher.addText(newValue);}
@Override
public void processPI(XdmNode node) throws SaxonApiException {
String newValue = processSelectedImage(node);
matcher.addText(newValue);
}
private class TransformSVGToPNG {
File transformAndCopy(File svgFile, File targetDir) {
String pngFileName = FilenameUtils.getBaseName(svgFile.getPath()) + ".png";
File pngFile = new File(targetDir, pngFileName);
PNGTranscoder t = new PNGTranscoder();
try {
TranscoderInput input = new TranscoderInput(svgFile.toURI().toString());
pngFile.createNewFile();
OutputStream ostream = new FileOutputStream(pngFile);
TranscoderOutput output = new TranscoderOutput(ostream);
t.transcode(input, output);
ostream.flush();
ostream.close();
return pngFile;
} catch (IOException e) {
getLog().error("An error occured while transforming " + svgFile.getAbsolutePath() + " to " + pngFile.getAbsolutePath());
throw new XProcException(e);
} catch (TranscoderException e) {
getLog().error("Unable to convert " + svgFile.getAbsolutePath() + " to png");
throw new XProcException(e);
}
}
}
}
| true | true | private String processSelectedImage(XdmNode imageDataFileRef) {
final URI baseUri = imageDataFileRef.getBaseURI();
final String fileRef = imageDataFileRef.getStringValue();
final URI baseDirUri = baseUri.resolve(".");
String srcImgFilePath = FilenameUtils.normalize(baseDirUri.getPath() + File.separator + fileRef);
File srcImgFile = getFileHandle(srcImgFilePath);
if (fileRef.toLowerCase().startsWith("http://") ||
fileRef.toLowerCase().startsWith("https://")) {
getLog().warn("Found reference to an external image " + fileRef + " in " + baseUri.getPath());
return fileRef;
}
else if (outputType.equals("pdf")) {
//Need to check only for the existence of the image file
if (this.processedFilesSetForPdfOutput.contains(srcImgFilePath)) {
//do nothing as any errors for missing files would already have been reported
}
else if (isImageForHtmlOnly(imageDataFileRef.getParent())) {
//ignore this imagedata
}
else if (! fileExists(srcImgFile)) {
reportImageNotFoundError(baseUri, fileRef, srcImgFile);
}
this.processedFilesSetForPdfOutput.add(srcImgFilePath);
//For pdf output always return the input fileRef
return fileRef;
}
else if (outputType.equals("html")) {
//check if we have already copied this particular image to webhelp folder
if (this.processedFilesMapForHtmlOutput.containsKey(srcImgFilePath)) {
return this.processedFilesMapForHtmlOutput.get(srcImgFilePath);
}
String targetDirPath = calculateTargetDirPath(baseUri.getPath(), fileRef);
File targetDir = makeDirs(targetDirPath);
String relativePathToCopiedFile;
//For HTML, we need a more elaborate check for missing images
if (isImageForPdfOnly(imageDataFileRef.getParent())) {
//ignore this imagedata
relativePathToCopiedFile = fileRef;
}
else if (! fileExists(srcImgFile)) {
reportImageNotFoundError(baseUri, fileRef, srcImgFile);
relativePathToCopiedFile = fileRef;
}
else if ("svg".equalsIgnoreCase(FilenameUtils.getExtension(srcImgFilePath))) {
//convert the svg to the relevant type and copy
File svgFile = getFileHandle(srcImgFilePath);
File copiedFile = new TransformSVGToPNG().transformAndCopy(svgFile, targetDir);
relativePathToCopiedFile = RelativePath.getRelativePath(new File(targetHtmlContentDirectoryUri), copiedFile);
}
else {
//simply copy the src file to the destination
File copiedFile = copyFile(srcImgFile, targetDir);
relativePathToCopiedFile = RelativePath.getRelativePath(new File(targetHtmlContentDirectoryUri), copiedFile);
}
this.processedFilesMapForHtmlOutput.put(srcImgFilePath, relativePathToCopiedFile);
return relativePathToCopiedFile;
}
else {
//we only know how to handle "pdf" and "html" outputTypes so just return the value
return fileRef;
}
}
| private String processSelectedImage(XdmNode imageDataFileRef) {
final URI baseUri = imageDataFileRef.getBaseURI();
final String fileRef = imageDataFileRef.getStringValue();
final URI baseDirUri = baseUri.resolve(".");
String srcImgFilePath = FilenameUtils.normalize(baseDirUri.getPath() + File.separator + fileRef);
File srcImgFile = getFileHandle(srcImgFilePath.trim());
if (fileRef.toLowerCase().startsWith("http://") ||
fileRef.toLowerCase().startsWith("https://")) {
getLog().warn("Found reference to an external image " + fileRef + " in " + baseUri.getPath());
return fileRef;
}
else if (outputType.equals("pdf")) {
//Need to check only for the existence of the image file
if (this.processedFilesSetForPdfOutput.contains(srcImgFilePath)) {
//do nothing as any errors for missing files would already have been reported
}
else if (isImageForHtmlOnly(imageDataFileRef.getParent())) {
//ignore this imagedata
}
else if (! fileExists(srcImgFile)) {
reportImageNotFoundError(baseUri, fileRef, srcImgFile);
}
this.processedFilesSetForPdfOutput.add(srcImgFilePath);
//For pdf output always return the input fileRef
return fileRef;
}
else if (outputType.equals("html")) {
//check if we have already copied this particular image to webhelp folder
if (this.processedFilesMapForHtmlOutput.containsKey(srcImgFilePath)) {
return this.processedFilesMapForHtmlOutput.get(srcImgFilePath);
}
String targetDirPath = calculateTargetDirPath(baseUri.getPath(), fileRef);
File targetDir = makeDirs(targetDirPath);
String relativePathToCopiedFile;
//For HTML, we need a more elaborate check for missing images
if (isImageForPdfOnly(imageDataFileRef.getParent())) {
//ignore this imagedata
relativePathToCopiedFile = fileRef;
}
else if (! fileExists(srcImgFile)) {
reportImageNotFoundError(baseUri, fileRef, srcImgFile);
relativePathToCopiedFile = fileRef;
}
else if ("svg".equalsIgnoreCase(FilenameUtils.getExtension(srcImgFilePath))) {
//convert the svg to the relevant type and copy
File svgFile = getFileHandle(srcImgFilePath);
File copiedFile = new TransformSVGToPNG().transformAndCopy(svgFile, targetDir);
relativePathToCopiedFile = RelativePath.getRelativePath(new File(targetHtmlContentDirectoryUri), copiedFile);
}
else {
//simply copy the src file to the destination
File copiedFile = copyFile(srcImgFile, targetDir);
relativePathToCopiedFile = RelativePath.getRelativePath(new File(targetHtmlContentDirectoryUri), copiedFile);
}
this.processedFilesMapForHtmlOutput.put(srcImgFilePath, relativePathToCopiedFile);
return relativePathToCopiedFile;
}
else {
//we only know how to handle "pdf" and "html" outputTypes so just return the value
return fileRef;
}
}
|
diff --git a/core/src/java/ru/brandanalyst/core/db/provider/BrandDictionaryProvider.java b/core/src/java/ru/brandanalyst/core/db/provider/BrandDictionaryProvider.java
index 600e442..255b1b7 100644
--- a/core/src/java/ru/brandanalyst/core/db/provider/BrandDictionaryProvider.java
+++ b/core/src/java/ru/brandanalyst/core/db/provider/BrandDictionaryProvider.java
@@ -1,83 +1,83 @@
package ru.brandanalyst.core.db.provider;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import ru.brandanalyst.core.model.BrandDictionaryItem;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: Dmitry Batkovich
* Date: 11/2/11
* Time: 9:50 PM
*/
public class BrandDictionaryProvider {
private static final Logger log = Logger.getLogger(BrandDictionaryProvider.class);
private SimpleJdbcTemplate jdbcTemplate;
public BrandDictionaryProvider(SimpleJdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void cleanDataStore() {
jdbcTemplate.update("TRUNCATE TABLE Dictionary");
}
public BrandDictionaryItem getDictionaryItem(long brandId) {
SqlRowSet rowSet = jdbcTemplate.getJdbcOperations().queryForRowSet("SELECT BrandId, Brand.Name, Term FROM BrandDictionary INNER JOIN Brand ON BrandId = Brand.Id WHERE BrandId = " + Long.toString(brandId) + " ORDER BY BrandId");
BrandDictionaryItem dictItem;
try {
if (rowSet.next()) {
String brandName = rowSet.getString("Name");
dictItem = new BrandDictionaryItem(brandName,brandId);
} else {
return null;
}
do {
String item = rowSet.getString("Term");
dictItem.addItem(item);
} while (rowSet.next());
return dictItem;
} catch (Exception e) {
log.error("can't get dictionary item from db");
return null;
}
}
public List<BrandDictionaryItem> getDictionary() {
- SqlRowSet rowSet = jdbcTemplate.getJdbcOperations().queryForRowSet("SELECT (BrandId, Brand.Name, Item) FROM BrandDictionary INNER JOIN Brand ON BrandId = Brand.Id ORDER BY BrandId");
+ SqlRowSet rowSet = jdbcTemplate.getJdbcOperations().queryForRowSet("SELECT BrandId, Brand.Name, Term FROM BrandDictionary INNER JOIN Brand ON BrandId = Brand.Id ORDER BY BrandId");
List<BrandDictionaryItem> dictionary = new ArrayList<BrandDictionaryItem>();
try {
long curBrandId;
if (rowSet.next()) {
- String brandName = rowSet.getString("Brand.Name");
+ String brandName = rowSet.getString("Name");
curBrandId = rowSet.getLong("BrandId");
dictionary.add(new BrandDictionaryItem(brandName, curBrandId));
} else {
return null;
}
int curBrandNum = 0;
do {
long nextBrandId = rowSet.getLong("BrandId");
if (nextBrandId != curBrandId) {
- dictionary.add(new BrandDictionaryItem(rowSet.getString("Brand.Name"), nextBrandId));
+ dictionary.add(new BrandDictionaryItem(rowSet.getString("Name"), nextBrandId));
curBrandId = nextBrandId;
curBrandNum++;
}
dictionary.get(curBrandNum).addItem(rowSet.getString("Term"));
} while (rowSet.next());
return dictionary;
} catch (Exception e) {
log.error("can't get dictionary from db");
return null;
}
}
}
| false | true | public List<BrandDictionaryItem> getDictionary() {
SqlRowSet rowSet = jdbcTemplate.getJdbcOperations().queryForRowSet("SELECT (BrandId, Brand.Name, Item) FROM BrandDictionary INNER JOIN Brand ON BrandId = Brand.Id ORDER BY BrandId");
List<BrandDictionaryItem> dictionary = new ArrayList<BrandDictionaryItem>();
try {
long curBrandId;
if (rowSet.next()) {
String brandName = rowSet.getString("Brand.Name");
curBrandId = rowSet.getLong("BrandId");
dictionary.add(new BrandDictionaryItem(brandName, curBrandId));
} else {
return null;
}
int curBrandNum = 0;
do {
long nextBrandId = rowSet.getLong("BrandId");
if (nextBrandId != curBrandId) {
dictionary.add(new BrandDictionaryItem(rowSet.getString("Brand.Name"), nextBrandId));
curBrandId = nextBrandId;
curBrandNum++;
}
dictionary.get(curBrandNum).addItem(rowSet.getString("Term"));
} while (rowSet.next());
return dictionary;
} catch (Exception e) {
log.error("can't get dictionary from db");
return null;
}
}
| public List<BrandDictionaryItem> getDictionary() {
SqlRowSet rowSet = jdbcTemplate.getJdbcOperations().queryForRowSet("SELECT BrandId, Brand.Name, Term FROM BrandDictionary INNER JOIN Brand ON BrandId = Brand.Id ORDER BY BrandId");
List<BrandDictionaryItem> dictionary = new ArrayList<BrandDictionaryItem>();
try {
long curBrandId;
if (rowSet.next()) {
String brandName = rowSet.getString("Name");
curBrandId = rowSet.getLong("BrandId");
dictionary.add(new BrandDictionaryItem(brandName, curBrandId));
} else {
return null;
}
int curBrandNum = 0;
do {
long nextBrandId = rowSet.getLong("BrandId");
if (nextBrandId != curBrandId) {
dictionary.add(new BrandDictionaryItem(rowSet.getString("Name"), nextBrandId));
curBrandId = nextBrandId;
curBrandNum++;
}
dictionary.get(curBrandNum).addItem(rowSet.getString("Term"));
} while (rowSet.next());
return dictionary;
} catch (Exception e) {
log.error("can't get dictionary from db");
return null;
}
}
|
diff --git a/src/main/java/org/utgenome/weaver/db/ImportBED.java b/src/main/java/org/utgenome/weaver/db/ImportBED.java
index 5c23243..98e388b 100755
--- a/src/main/java/org/utgenome/weaver/db/ImportBED.java
+++ b/src/main/java/org/utgenome/weaver/db/ImportBED.java
@@ -1,137 +1,137 @@
/*--------------------------------------------------------------------------
* Copyright 2011 utgenome.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.
*--------------------------------------------------------------------------*/
//--------------------------------------
// genome-weaver Project
//
// ImportBED.java
// Since: 2011/07/19
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.weaver.db;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import org.utgenome.UTGBException;
import org.utgenome.format.bed.BED2SilkReader;
import org.utgenome.weaver.GenomeWeaverCommand;
import org.utgenome.weaver.db.BlockArray.Block;
import org.xerial.lens.SilkLens;
import org.xerial.util.ObjectHandler;
import org.xerial.util.ObjectHandlerBase;
import org.xerial.util.log.Logger;
import org.xerial.util.opt.Argument;
import org.xerial.util.opt.Option;
public class ImportBED extends GenomeWeaverCommand
{
private static Logger _logger = Logger.getLogger(ImportBED.class);
@Override
public String getOneLineDescription() {
return "Import chromatin annotation written in BED format";
}
@Argument(index = 0)
private String bedFile;
@Option(symbol = "b", description = "bin size. default = 10000")
private int binSize = 10000;
@Override
public void execute(String[] args) throws Exception {
if (bedFile == null) {
throw new UTGBException("no input file is given");
}
final BlockArrayTable chromatinAnnotation = new BlockArrayTable();
// Prepare binning code: BEDAnnotation object stream -> BinInGenome<BEDAnnotaion>
final BinSplitter<BEDAnnotation> splitter = new BinSplitter<BEDAnnotation>(binSize,
new ObjectHandlerBase<BinInGenome<BEDAnnotation>>() {
@Override
public void handle(BinInGenome<BEDAnnotation> input) throws Exception {
// Handle bins
_logger.info("Processing bin %s", input);
- // Block data for scores
+ // Create block data for scores
Block ba = new Block(input.range);
for (BEDAnnotation each : input.data()) {
for (int x = each.getStart(); x < each.getEnd(); ++x)
ba.set(x - 1, each.score); // Use 0-origin
}
// Put the block to the table
chromatinAnnotation.getBlockArray(input.chr).add(ba);
}
});
- // Load BED file and create priority search trees for each chromosome
+ // Load BED file and create BEDAnnotation object strem
// BED (0-origin) -> Silk (1-origin) -> BEDAnnotation object stream
Reader bedIn = new BED2SilkReader(new BufferedReader(new FileReader(bedFile)));
try {
SilkLens.findFromSilk(bedIn, "gene", BEDAnnotation.class, new ObjectHandler<BEDAnnotation>() {
int count = 0;
@Override
public void init() throws Exception {
_logger.info("Loading BED file: " + bedFile);
}
@Override
public void handle(BEDAnnotation input) throws Exception {
// Send the input entry to the bin splitter
splitter.handle(input);
count++;
if (count % 10000 == 0) {
_logger.info("Loaded %,d entries", count);
}
}
@Override
public void finish() throws Exception {
splitter.finish(); // dump the remaining entries
_logger.info("Loaded %,d entries", count);
}
});
}
finally {
bedIn.close();
}
// Save the block array table to a file
File out = new File(bedFile + ".bin");
_logger.info("Save to %s", out);
chromatinAnnotation.saveTo(out);
// You can load the binary data as follows:
// BlockArrayTable loadedData = BlockArrayTable.loadFrom(new File(".bed.bin"));
// Query chromatin state data
for (String chr : chromatinAnnotation.keySet()) {
_logger.info(chr);
BlockArray ba = chromatinAnnotation.getBlockArray(chr);
int max = ba.getMaxLength();
for (int x = 0; x < max; ++x) {
_logger.info(ba.get(x));
}
}
}
}
| false | true | public void execute(String[] args) throws Exception {
if (bedFile == null) {
throw new UTGBException("no input file is given");
}
final BlockArrayTable chromatinAnnotation = new BlockArrayTable();
// Prepare binning code: BEDAnnotation object stream -> BinInGenome<BEDAnnotaion>
final BinSplitter<BEDAnnotation> splitter = new BinSplitter<BEDAnnotation>(binSize,
new ObjectHandlerBase<BinInGenome<BEDAnnotation>>() {
@Override
public void handle(BinInGenome<BEDAnnotation> input) throws Exception {
// Handle bins
_logger.info("Processing bin %s", input);
// Block data for scores
Block ba = new Block(input.range);
for (BEDAnnotation each : input.data()) {
for (int x = each.getStart(); x < each.getEnd(); ++x)
ba.set(x - 1, each.score); // Use 0-origin
}
// Put the block to the table
chromatinAnnotation.getBlockArray(input.chr).add(ba);
}
});
// Load BED file and create priority search trees for each chromosome
// BED (0-origin) -> Silk (1-origin) -> BEDAnnotation object stream
Reader bedIn = new BED2SilkReader(new BufferedReader(new FileReader(bedFile)));
try {
SilkLens.findFromSilk(bedIn, "gene", BEDAnnotation.class, new ObjectHandler<BEDAnnotation>() {
int count = 0;
@Override
public void init() throws Exception {
_logger.info("Loading BED file: " + bedFile);
}
@Override
public void handle(BEDAnnotation input) throws Exception {
// Send the input entry to the bin splitter
splitter.handle(input);
count++;
if (count % 10000 == 0) {
_logger.info("Loaded %,d entries", count);
}
}
@Override
public void finish() throws Exception {
splitter.finish(); // dump the remaining entries
_logger.info("Loaded %,d entries", count);
}
});
}
finally {
bedIn.close();
}
// Save the block array table to a file
File out = new File(bedFile + ".bin");
_logger.info("Save to %s", out);
chromatinAnnotation.saveTo(out);
// You can load the binary data as follows:
// BlockArrayTable loadedData = BlockArrayTable.loadFrom(new File(".bed.bin"));
// Query chromatin state data
for (String chr : chromatinAnnotation.keySet()) {
_logger.info(chr);
BlockArray ba = chromatinAnnotation.getBlockArray(chr);
int max = ba.getMaxLength();
for (int x = 0; x < max; ++x) {
_logger.info(ba.get(x));
}
}
}
| public void execute(String[] args) throws Exception {
if (bedFile == null) {
throw new UTGBException("no input file is given");
}
final BlockArrayTable chromatinAnnotation = new BlockArrayTable();
// Prepare binning code: BEDAnnotation object stream -> BinInGenome<BEDAnnotaion>
final BinSplitter<BEDAnnotation> splitter = new BinSplitter<BEDAnnotation>(binSize,
new ObjectHandlerBase<BinInGenome<BEDAnnotation>>() {
@Override
public void handle(BinInGenome<BEDAnnotation> input) throws Exception {
// Handle bins
_logger.info("Processing bin %s", input);
// Create block data for scores
Block ba = new Block(input.range);
for (BEDAnnotation each : input.data()) {
for (int x = each.getStart(); x < each.getEnd(); ++x)
ba.set(x - 1, each.score); // Use 0-origin
}
// Put the block to the table
chromatinAnnotation.getBlockArray(input.chr).add(ba);
}
});
// Load BED file and create BEDAnnotation object strem
// BED (0-origin) -> Silk (1-origin) -> BEDAnnotation object stream
Reader bedIn = new BED2SilkReader(new BufferedReader(new FileReader(bedFile)));
try {
SilkLens.findFromSilk(bedIn, "gene", BEDAnnotation.class, new ObjectHandler<BEDAnnotation>() {
int count = 0;
@Override
public void init() throws Exception {
_logger.info("Loading BED file: " + bedFile);
}
@Override
public void handle(BEDAnnotation input) throws Exception {
// Send the input entry to the bin splitter
splitter.handle(input);
count++;
if (count % 10000 == 0) {
_logger.info("Loaded %,d entries", count);
}
}
@Override
public void finish() throws Exception {
splitter.finish(); // dump the remaining entries
_logger.info("Loaded %,d entries", count);
}
});
}
finally {
bedIn.close();
}
// Save the block array table to a file
File out = new File(bedFile + ".bin");
_logger.info("Save to %s", out);
chromatinAnnotation.saveTo(out);
// You can load the binary data as follows:
// BlockArrayTable loadedData = BlockArrayTable.loadFrom(new File(".bed.bin"));
// Query chromatin state data
for (String chr : chromatinAnnotation.keySet()) {
_logger.info(chr);
BlockArray ba = chromatinAnnotation.getBlockArray(chr);
int max = ba.getMaxLength();
for (int x = 0; x < max; ++x) {
_logger.info(ba.get(x));
}
}
}
|
diff --git a/src/main/us/exultant/mdm/Plumbing.java b/src/main/us/exultant/mdm/Plumbing.java
index b4613b0..d8202b1 100644
--- a/src/main/us/exultant/mdm/Plumbing.java
+++ b/src/main/us/exultant/mdm/Plumbing.java
@@ -1,130 +1,130 @@
/*
* Copyright 2012, 2013 Eric Myhre <http://exultant.us>
*
* This file is part of mdm <https://github.com/heavenlyhash/mdm/>.
*
* mdm 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 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 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 us.exultant.mdm;
import java.io.*;
import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.errors.*;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.transport.*;
import us.exultant.ahs.util.*;
public class Plumbing {
public static void fetch(Repository repo, MdmModule module) throws MdmException {
switch (module.getStatus().getType()) {
case INITIALIZED:
return;
case MISSING:
throw new MajorBug();
case UNINITIALIZED:
if (module.getRepo() == null)
try {
RepositoryBuilder builder = new RepositoryBuilder();
builder.setWorkTree(new File(repo.getWorkTree()+"/"+module.getPath()));
module.repo = builder.build();
module.repo.create(false);
} catch (IOException e) {
throw new MdmException("failed to write data to submodule "+module.getHandle(), e);
}
try {
initLocalConfig(repo, module);
repo.getConfig().save();
} catch (IOException e) {
throw new MdmException("failed to save changes to local git configuration file", e);
}
try {
setMdmRemote(module);
module.getRepo().getConfig().save();
} catch (IOException e) {
throw new MdmException("failed to save changes to submodule git configuration file for "+module.getHandle(), e);
}
case REV_CHECKED_OUT:
final String versionBranchName = "mdm/release/"+module.getVersionName();
/* Fetch only the branch labelled with the version requested. */
try {
RefSpec ref = new RefSpec()
.setForceUpdate(true)
- .setSource(versionBranchName)
- .setDestination(versionBranchName);
+ .setSource("refs/heads/"+versionBranchName)
+ .setDestination("refs/heads/"+versionBranchName);
new Git(module.getRepo()).fetch()
.setRemote("origin")
.setRefSpecs(ref)
.call();
} catch (InvalidRemoteException e) {
throw new MdmException("could not find remote repository for module "+module.getHandle(), e);
} catch (TransportException e) {
throw new MdmException("transport failed! check your connectivity and try again?", e);
} catch (GitAPIException e) {
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
}
/* Drop the files into the working tree. */
try {
new Git(module.getRepo()).checkout()
.setName(versionBranchName)
.setForce(true)
.call();
} catch (RefAlreadyExistsException e) {
/* I'm not creating a new branch, so this exception wouldn't even make sense. */
throw new MajorBug(e);
} catch (RefNotFoundException e) {
/* I just got this branch, so we shouldn't have a problem here. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (InvalidRefNameException e) {
/* I just got this branch, so we shouldn't have a problem here. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (CheckoutConflictException e) {
/* I'm using force mode, so this shouldnt happen. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (GitAPIException e) {
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
}
}
}
/**
* Similar to calling `git submodule init [module]`. Also updates the MdmModule cache of values.
* @return true if repo.getConfig() has been modified and should be saved.
*/
public static boolean initLocalConfig(Repository repo, MdmModule module) {
// Ignore entry if URL is already present in config file
if (module.getUrlLocal() != null) return false;
// Copy 'url' and 'update' fields to local repo config
module.urlLocal = module.getUrlHistoric();
repo.getConfig().setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, module.getPath(), ConfigConstants.CONFIG_KEY_URL, module.getUrlLocal());
repo.getConfig().setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, module.getPath(), ConfigConstants.CONFIG_KEY_UPDATE, "none");
return true;
}
/**
* Equivalent of calling `git remote add -t mdm/init origin [url]` — set up
* the remote origin and use the "-t" option here to limit what can be
* automatically dragged down from the network by a `git pull` (this is necessary
* because even pulling in the parent project will recurse to fetching submodule
* content as well).
*/
public static void setMdmRemote(MdmModule module) {
module.getRepo().getConfig().setString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin", ConfigConstants.CONFIG_KEY_URL, module.getUrlLocal());
module.getRepo().getConfig().setString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin", "fetch", "+refs/heads/mdm/init:refs/remotes/origin/mdm/init");
}
}
| true | true | public static void fetch(Repository repo, MdmModule module) throws MdmException {
switch (module.getStatus().getType()) {
case INITIALIZED:
return;
case MISSING:
throw new MajorBug();
case UNINITIALIZED:
if (module.getRepo() == null)
try {
RepositoryBuilder builder = new RepositoryBuilder();
builder.setWorkTree(new File(repo.getWorkTree()+"/"+module.getPath()));
module.repo = builder.build();
module.repo.create(false);
} catch (IOException e) {
throw new MdmException("failed to write data to submodule "+module.getHandle(), e);
}
try {
initLocalConfig(repo, module);
repo.getConfig().save();
} catch (IOException e) {
throw new MdmException("failed to save changes to local git configuration file", e);
}
try {
setMdmRemote(module);
module.getRepo().getConfig().save();
} catch (IOException e) {
throw new MdmException("failed to save changes to submodule git configuration file for "+module.getHandle(), e);
}
case REV_CHECKED_OUT:
final String versionBranchName = "mdm/release/"+module.getVersionName();
/* Fetch only the branch labelled with the version requested. */
try {
RefSpec ref = new RefSpec()
.setForceUpdate(true)
.setSource(versionBranchName)
.setDestination(versionBranchName);
new Git(module.getRepo()).fetch()
.setRemote("origin")
.setRefSpecs(ref)
.call();
} catch (InvalidRemoteException e) {
throw new MdmException("could not find remote repository for module "+module.getHandle(), e);
} catch (TransportException e) {
throw new MdmException("transport failed! check your connectivity and try again?", e);
} catch (GitAPIException e) {
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
}
/* Drop the files into the working tree. */
try {
new Git(module.getRepo()).checkout()
.setName(versionBranchName)
.setForce(true)
.call();
} catch (RefAlreadyExistsException e) {
/* I'm not creating a new branch, so this exception wouldn't even make sense. */
throw new MajorBug(e);
} catch (RefNotFoundException e) {
/* I just got this branch, so we shouldn't have a problem here. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (InvalidRefNameException e) {
/* I just got this branch, so we shouldn't have a problem here. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (CheckoutConflictException e) {
/* I'm using force mode, so this shouldnt happen. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (GitAPIException e) {
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
}
}
}
| public static void fetch(Repository repo, MdmModule module) throws MdmException {
switch (module.getStatus().getType()) {
case INITIALIZED:
return;
case MISSING:
throw new MajorBug();
case UNINITIALIZED:
if (module.getRepo() == null)
try {
RepositoryBuilder builder = new RepositoryBuilder();
builder.setWorkTree(new File(repo.getWorkTree()+"/"+module.getPath()));
module.repo = builder.build();
module.repo.create(false);
} catch (IOException e) {
throw new MdmException("failed to write data to submodule "+module.getHandle(), e);
}
try {
initLocalConfig(repo, module);
repo.getConfig().save();
} catch (IOException e) {
throw new MdmException("failed to save changes to local git configuration file", e);
}
try {
setMdmRemote(module);
module.getRepo().getConfig().save();
} catch (IOException e) {
throw new MdmException("failed to save changes to submodule git configuration file for "+module.getHandle(), e);
}
case REV_CHECKED_OUT:
final String versionBranchName = "mdm/release/"+module.getVersionName();
/* Fetch only the branch labelled with the version requested. */
try {
RefSpec ref = new RefSpec()
.setForceUpdate(true)
.setSource("refs/heads/"+versionBranchName)
.setDestination("refs/heads/"+versionBranchName);
new Git(module.getRepo()).fetch()
.setRemote("origin")
.setRefSpecs(ref)
.call();
} catch (InvalidRemoteException e) {
throw new MdmException("could not find remote repository for module "+module.getHandle(), e);
} catch (TransportException e) {
throw new MdmException("transport failed! check your connectivity and try again?", e);
} catch (GitAPIException e) {
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
}
/* Drop the files into the working tree. */
try {
new Git(module.getRepo()).checkout()
.setName(versionBranchName)
.setForce(true)
.call();
} catch (RefAlreadyExistsException e) {
/* I'm not creating a new branch, so this exception wouldn't even make sense. */
throw new MajorBug(e);
} catch (RefNotFoundException e) {
/* I just got this branch, so we shouldn't have a problem here. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (InvalidRefNameException e) {
/* I just got this branch, so we shouldn't have a problem here. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (CheckoutConflictException e) {
/* I'm using force mode, so this shouldnt happen. */
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
} catch (GitAPIException e) {
throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e);
}
}
}
|
diff --git a/etrading/src/main/java/common/messaging/MessageConsumer.java b/etrading/src/main/java/common/messaging/MessageConsumer.java
index 97b6a72..6d22695 100644
--- a/etrading/src/main/java/common/messaging/MessageConsumer.java
+++ b/etrading/src/main/java/common/messaging/MessageConsumer.java
@@ -1,105 +1,105 @@
package common.messaging;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import com.higherfrequencytrading.chronicle.Excerpt;
import com.higherfrequencytrading.chronicle.impl.IndexedChronicle;
import common.Logger;
/*
* A helper class to receive messages.
*
* Internally uses Java Chronicle library.
*
* https://github.com/asim2025/etrading.git
*
* @author asim2025
*/
public class MessageConsumer {
private static final Logger log = Logger.getInstance(MessageConsumer.class);
private static final String ROOT_DIR = System.getProperty("java.io.tmpdir") + File.separator;
private List<MessageListener> listeners = new LinkedList<>();
private IndexedChronicle chr;
private IndexedChronicle idxChr;
private Thread runner;
public MessageConsumer(String dest) throws IOException {
chr = new IndexedChronicle(ROOT_DIR + dest);
idxChr = new IndexedChronicle(ROOT_DIR + dest + "_idx");
runner = new Thread(new Runner());
runner.setName("MessageConsumer");
runner.start();
}
public void addListener(MessageListener listener) {
log.info("register listener:" + listener);
listeners.add(listener);
}
public void deleteListener(MessageListener listener) {
log.info("remove listener:" + listener);
listeners.remove(listener);
}
private class Runner implements Runnable {
@Override
public void run() {
while (true) {
Excerpt excerpt = chr.createExcerpt();
long size = excerpt.size();
long index = getLastIndex();
while (index < size && listeners.size() > 0) {
log.debug("index:" + index + ",size:" + size);
excerpt.index(index);
Object o = excerpt.readObject();
for (MessageListener l : listeners) {
log.info("notifying listener:" + l);
l.onMessage(o);
}
index++;
size = excerpt.size();
saveIndex(index);
}
- excerpt.finish();
+ excerpt.close();
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
private long getLastIndex() {
Excerpt ex = idxChr.createExcerpt();
long size = ex.size();
long index = 1;
if (size > 0) {
ex.index(size-1);
index = ex.readLong();
ex.close();
}
return index;
}
private void saveIndex(long idx) {
Excerpt ex = idxChr.createExcerpt();
ex.startExcerpt(64);
ex.writeLong(idx);
ex.finish();
}
}
}
| true | true | public void run() {
while (true) {
Excerpt excerpt = chr.createExcerpt();
long size = excerpt.size();
long index = getLastIndex();
while (index < size && listeners.size() > 0) {
log.debug("index:" + index + ",size:" + size);
excerpt.index(index);
Object o = excerpt.readObject();
for (MessageListener l : listeners) {
log.info("notifying listener:" + l);
l.onMessage(o);
}
index++;
size = excerpt.size();
saveIndex(index);
}
excerpt.finish();
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
| public void run() {
while (true) {
Excerpt excerpt = chr.createExcerpt();
long size = excerpt.size();
long index = getLastIndex();
while (index < size && listeners.size() > 0) {
log.debug("index:" + index + ",size:" + size);
excerpt.index(index);
Object o = excerpt.readObject();
for (MessageListener l : listeners) {
log.info("notifying listener:" + l);
l.onMessage(o);
}
index++;
size = excerpt.size();
saveIndex(index);
}
excerpt.close();
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
|
diff --git a/src/rajawali/primitives/Cube.java b/src/rajawali/primitives/Cube.java
index ffcd2271..e7ac31af 100644
--- a/src/rajawali/primitives/Cube.java
+++ b/src/rajawali/primitives/Cube.java
@@ -1,193 +1,193 @@
package rajawali.primitives;
import rajawali.BaseObject3D;
/**
* A cube primitive. The constructor takes two boolean arguments that indicate whether certain buffers should be
* created or not. Not creating these buffers can reduce memory footprint.
* <p>
* When creating solid color cube both <code>createTextureCoordinates</code> and <code>createVertexColorBuffer</code>
* can be set to <code>false</code>.
* <p>
* When creating a textured cube <code>createTextureCoordinates</code> should be set to <code>true</code> and
* <code>createVertexColorBuffer</code> should be set to <code>false</code>.
* <p>
* When creating a cube without a texture but with different colors per texture <code>createTextureCoordinates</code>
* should be set to <code>false</code> and <code>createVertexColorBuffer</code> should be set to <code>true</code>.
*
* @author dennis.ippel
*
*/
public class Cube extends BaseObject3D {
private float mSize;
private boolean mIsSkybox;
private boolean mCreateTextureCoords;
private boolean mCreateVertexColorBuffer;
/**
* Creates a cube primitive. Calling this constructor will create texture coordinates but no vertex color buffer.
* @param size The size of the cube.
*/
public Cube(float size) {
this(size, false, false, true, false);
}
/**
* Creates a cube primitive. Calling this constructor will create texture coordinates but no vertex color buffer.
*
* @param size The size of the cube.
* @param isSkybox A boolean that indicates whether this is a skybox or not. If set to true the normals will
* be inverted.
*/
public Cube(float size, boolean isSkybox) {
this(size, isSkybox, true, true, false);
}
/**
* Creates a cube primitive. Calling this constructor will create texture coordinates but no vertex color buffer.
*
* @param size The size of the cube.
* @param isSkybox A boolean that indicates whether this is a skybox or not. If set to true the normals will
* be inverted.
* @param hasCubemapTexture A boolean that indicates a cube map texture will be used (6 textures) or a regular
* single texture.
*/
public Cube(float size, boolean isSkybox, boolean hasCubemapTexture)
{
this(size, isSkybox, hasCubemapTexture, true, false);
}
/**
* Creates a cube primitive.
*
* @param size The size of the cube.
* @param isSkybox A boolean that indicates whether this is a skybox or not. If set to true the normals will
* be inverted.
* @param hasCubemapTexture A boolean that indicates a cube map texture will be used (6 textures) or a regular
* single texture.
* @param createTextureCoordinates A boolean that indicates whether the texture coordinates should be calculated or not.
* @param createVertexColorBuffer A boolean that indicates whether a vertex color buffer should be created or not.
*/
public Cube(float size, boolean isSkybox, boolean hasCubemapTexture, boolean createTextureCoordinates,
boolean createVertexColorBuffer) {
super();
mIsSkybox = isSkybox;
mSize = size;
mHasCubemapTexture = hasCubemapTexture;
mCreateTextureCoords = createTextureCoordinates;
mCreateVertexColorBuffer = createVertexColorBuffer;
init();
}
private void init()
{
float halfSize = mSize * .5f;
float[] vertices = {
halfSize, halfSize, halfSize, -halfSize, halfSize, halfSize,
-halfSize, -halfSize, halfSize, halfSize, -halfSize, halfSize, // 0-1-halfSize-3 front
halfSize, halfSize, halfSize, halfSize, -halfSize, halfSize,
halfSize, -halfSize, -halfSize, halfSize, halfSize, -halfSize,// 0-3-4-5 right
halfSize, -halfSize, -halfSize, -halfSize, -halfSize, -halfSize,
-halfSize, halfSize, -halfSize, halfSize, halfSize, -halfSize,// 4-7-6-5 back
-halfSize, halfSize, halfSize, -halfSize, halfSize, -halfSize,
-halfSize, -halfSize, -halfSize, -halfSize, -halfSize, halfSize,// 1-6-7-halfSize left
halfSize, halfSize, halfSize, halfSize, halfSize, -halfSize,
-halfSize, halfSize, -halfSize, -halfSize, halfSize, halfSize, // top
halfSize, -halfSize, halfSize, -halfSize, -halfSize, halfSize,
-halfSize, -halfSize, -halfSize, halfSize, -halfSize, -halfSize,// bottom
};
float t = 1;
float[] textureCoords = null;
float[] skyboxTextureCoords = null;
if (mCreateTextureCoords && !mIsSkybox)
{
textureCoords = new float[]
{
0, 1, 1, 1, 1, 0, 0, 0, // front
0, 1, 1, 1, 1, 0, 0, 0, // up
0, 1, 1, 1, 1, 0, 0, 0, // back
0, 1, 1, 1, 1, 0, 0, 0, // down
0, 1, 1, 1, 1, 0, 0, 0, // right
0, 1, 1, 1, 1, 0, 0, 0, // left
};
}
- else if (mCreateTextureCoords && mIsSkybox)
+ else if (mIsSkybox && mHasCubemapTexture)
{
skyboxTextureCoords = new float[] {
-t, t, t, t, t, t, t, -t, t, -t, -t, t, // front
t, t, -t, t, -t, -t, t, -t, t, t, t, t, // up
-t, -t, -t, t, -t, -t, t, t, -t, -t, t, -t, // back
-t, t, -t, -t, t, t, -t, -t, t, -t, -t, -t, // down
-t, t, t, -t, t, -t, t, t, -t, t, t, t, // right
-t, -t, t, t, -t, t, t, -t, -t, -t, -t, -t, // left
};
}
else if (mIsSkybox && !mHasCubemapTexture)
{
skyboxTextureCoords = new float[] {
.25f, .3333f, .5f, .3333f, .5f, .6666f, .25f, .6666f, // front
.25f, .3333f, .25f, .6666f, 0, .6666f, 0, .3333f, // left
1, .6666f, .75f, .6666f, .75f, .3333f, 1, .3333f, // back
.5f, .3333f, .75f, .3333f, .75f, .6666f, .5f, .6666f, // right
.25f, .3333f, .25f, 0, .5f, 0, .5f, .3333f, // up
.25f, .6666f, .5f, .6666f, .5f, 1, .25f, 1 // down
};
}
float[] colors = null;
if (mCreateVertexColorBuffer)
{
colors = new float[] {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
}
float n = 1;
float[] normals = {
0, 0, n, 0, 0, n, 0, 0, n, 0, 0, n, // front
n, 0, 0, n, 0, 0, n, 0, 0, n, 0, 0, // right
0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, -n, // back
-n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, // left
0, n, 0, 0, n, 0, 0, n, 0, 0, n, 0, // top
0, -n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, // bottom
};
int[] indices = {
0, 1, 2, 0, 2, 3,
4, 5, 6, 4, 6, 7,
8, 9, 10, 8, 10, 11,
12, 13, 14, 12, 14, 15,
16, 17, 18, 16, 18, 19,
20, 21, 22, 20, 22, 23,
};
int[] skyboxIndices = {
2, 1, 0, 3, 2, 0,
6, 5, 4, 7, 6, 4,
10, 9, 8, 11, 10, 8,
14, 13, 12, 15, 14, 12,
18, 17, 16, 19, 18, 16,
22, 21, 20, 23, 22, 20
};
setData(vertices, normals, mIsSkybox || mHasCubemapTexture ? skyboxTextureCoords : textureCoords, colors,
mIsSkybox && mHasCubemapTexture ? skyboxIndices : indices);
vertices = null;
normals = null;
skyboxTextureCoords = null;
textureCoords = null;
colors = null;
skyboxIndices = null;
indices = null;
}
}
| true | true | private void init()
{
float halfSize = mSize * .5f;
float[] vertices = {
halfSize, halfSize, halfSize, -halfSize, halfSize, halfSize,
-halfSize, -halfSize, halfSize, halfSize, -halfSize, halfSize, // 0-1-halfSize-3 front
halfSize, halfSize, halfSize, halfSize, -halfSize, halfSize,
halfSize, -halfSize, -halfSize, halfSize, halfSize, -halfSize,// 0-3-4-5 right
halfSize, -halfSize, -halfSize, -halfSize, -halfSize, -halfSize,
-halfSize, halfSize, -halfSize, halfSize, halfSize, -halfSize,// 4-7-6-5 back
-halfSize, halfSize, halfSize, -halfSize, halfSize, -halfSize,
-halfSize, -halfSize, -halfSize, -halfSize, -halfSize, halfSize,// 1-6-7-halfSize left
halfSize, halfSize, halfSize, halfSize, halfSize, -halfSize,
-halfSize, halfSize, -halfSize, -halfSize, halfSize, halfSize, // top
halfSize, -halfSize, halfSize, -halfSize, -halfSize, halfSize,
-halfSize, -halfSize, -halfSize, halfSize, -halfSize, -halfSize,// bottom
};
float t = 1;
float[] textureCoords = null;
float[] skyboxTextureCoords = null;
if (mCreateTextureCoords && !mIsSkybox)
{
textureCoords = new float[]
{
0, 1, 1, 1, 1, 0, 0, 0, // front
0, 1, 1, 1, 1, 0, 0, 0, // up
0, 1, 1, 1, 1, 0, 0, 0, // back
0, 1, 1, 1, 1, 0, 0, 0, // down
0, 1, 1, 1, 1, 0, 0, 0, // right
0, 1, 1, 1, 1, 0, 0, 0, // left
};
}
else if (mCreateTextureCoords && mIsSkybox)
{
skyboxTextureCoords = new float[] {
-t, t, t, t, t, t, t, -t, t, -t, -t, t, // front
t, t, -t, t, -t, -t, t, -t, t, t, t, t, // up
-t, -t, -t, t, -t, -t, t, t, -t, -t, t, -t, // back
-t, t, -t, -t, t, t, -t, -t, t, -t, -t, -t, // down
-t, t, t, -t, t, -t, t, t, -t, t, t, t, // right
-t, -t, t, t, -t, t, t, -t, -t, -t, -t, -t, // left
};
}
else if (mIsSkybox && !mHasCubemapTexture)
{
skyboxTextureCoords = new float[] {
.25f, .3333f, .5f, .3333f, .5f, .6666f, .25f, .6666f, // front
.25f, .3333f, .25f, .6666f, 0, .6666f, 0, .3333f, // left
1, .6666f, .75f, .6666f, .75f, .3333f, 1, .3333f, // back
.5f, .3333f, .75f, .3333f, .75f, .6666f, .5f, .6666f, // right
.25f, .3333f, .25f, 0, .5f, 0, .5f, .3333f, // up
.25f, .6666f, .5f, .6666f, .5f, 1, .25f, 1 // down
};
}
float[] colors = null;
if (mCreateVertexColorBuffer)
{
colors = new float[] {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
}
float n = 1;
float[] normals = {
0, 0, n, 0, 0, n, 0, 0, n, 0, 0, n, // front
n, 0, 0, n, 0, 0, n, 0, 0, n, 0, 0, // right
0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, -n, // back
-n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, // left
0, n, 0, 0, n, 0, 0, n, 0, 0, n, 0, // top
0, -n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, // bottom
};
int[] indices = {
0, 1, 2, 0, 2, 3,
4, 5, 6, 4, 6, 7,
8, 9, 10, 8, 10, 11,
12, 13, 14, 12, 14, 15,
16, 17, 18, 16, 18, 19,
20, 21, 22, 20, 22, 23,
};
int[] skyboxIndices = {
2, 1, 0, 3, 2, 0,
6, 5, 4, 7, 6, 4,
10, 9, 8, 11, 10, 8,
14, 13, 12, 15, 14, 12,
18, 17, 16, 19, 18, 16,
22, 21, 20, 23, 22, 20
};
setData(vertices, normals, mIsSkybox || mHasCubemapTexture ? skyboxTextureCoords : textureCoords, colors,
mIsSkybox && mHasCubemapTexture ? skyboxIndices : indices);
vertices = null;
normals = null;
skyboxTextureCoords = null;
textureCoords = null;
colors = null;
skyboxIndices = null;
indices = null;
}
| private void init()
{
float halfSize = mSize * .5f;
float[] vertices = {
halfSize, halfSize, halfSize, -halfSize, halfSize, halfSize,
-halfSize, -halfSize, halfSize, halfSize, -halfSize, halfSize, // 0-1-halfSize-3 front
halfSize, halfSize, halfSize, halfSize, -halfSize, halfSize,
halfSize, -halfSize, -halfSize, halfSize, halfSize, -halfSize,// 0-3-4-5 right
halfSize, -halfSize, -halfSize, -halfSize, -halfSize, -halfSize,
-halfSize, halfSize, -halfSize, halfSize, halfSize, -halfSize,// 4-7-6-5 back
-halfSize, halfSize, halfSize, -halfSize, halfSize, -halfSize,
-halfSize, -halfSize, -halfSize, -halfSize, -halfSize, halfSize,// 1-6-7-halfSize left
halfSize, halfSize, halfSize, halfSize, halfSize, -halfSize,
-halfSize, halfSize, -halfSize, -halfSize, halfSize, halfSize, // top
halfSize, -halfSize, halfSize, -halfSize, -halfSize, halfSize,
-halfSize, -halfSize, -halfSize, halfSize, -halfSize, -halfSize,// bottom
};
float t = 1;
float[] textureCoords = null;
float[] skyboxTextureCoords = null;
if (mCreateTextureCoords && !mIsSkybox)
{
textureCoords = new float[]
{
0, 1, 1, 1, 1, 0, 0, 0, // front
0, 1, 1, 1, 1, 0, 0, 0, // up
0, 1, 1, 1, 1, 0, 0, 0, // back
0, 1, 1, 1, 1, 0, 0, 0, // down
0, 1, 1, 1, 1, 0, 0, 0, // right
0, 1, 1, 1, 1, 0, 0, 0, // left
};
}
else if (mIsSkybox && mHasCubemapTexture)
{
skyboxTextureCoords = new float[] {
-t, t, t, t, t, t, t, -t, t, -t, -t, t, // front
t, t, -t, t, -t, -t, t, -t, t, t, t, t, // up
-t, -t, -t, t, -t, -t, t, t, -t, -t, t, -t, // back
-t, t, -t, -t, t, t, -t, -t, t, -t, -t, -t, // down
-t, t, t, -t, t, -t, t, t, -t, t, t, t, // right
-t, -t, t, t, -t, t, t, -t, -t, -t, -t, -t, // left
};
}
else if (mIsSkybox && !mHasCubemapTexture)
{
skyboxTextureCoords = new float[] {
.25f, .3333f, .5f, .3333f, .5f, .6666f, .25f, .6666f, // front
.25f, .3333f, .25f, .6666f, 0, .6666f, 0, .3333f, // left
1, .6666f, .75f, .6666f, .75f, .3333f, 1, .3333f, // back
.5f, .3333f, .75f, .3333f, .75f, .6666f, .5f, .6666f, // right
.25f, .3333f, .25f, 0, .5f, 0, .5f, .3333f, // up
.25f, .6666f, .5f, .6666f, .5f, 1, .25f, 1 // down
};
}
float[] colors = null;
if (mCreateVertexColorBuffer)
{
colors = new float[] {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
}
float n = 1;
float[] normals = {
0, 0, n, 0, 0, n, 0, 0, n, 0, 0, n, // front
n, 0, 0, n, 0, 0, n, 0, 0, n, 0, 0, // right
0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, -n, // back
-n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, // left
0, n, 0, 0, n, 0, 0, n, 0, 0, n, 0, // top
0, -n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, // bottom
};
int[] indices = {
0, 1, 2, 0, 2, 3,
4, 5, 6, 4, 6, 7,
8, 9, 10, 8, 10, 11,
12, 13, 14, 12, 14, 15,
16, 17, 18, 16, 18, 19,
20, 21, 22, 20, 22, 23,
};
int[] skyboxIndices = {
2, 1, 0, 3, 2, 0,
6, 5, 4, 7, 6, 4,
10, 9, 8, 11, 10, 8,
14, 13, 12, 15, 14, 12,
18, 17, 16, 19, 18, 16,
22, 21, 20, 23, 22, 20
};
setData(vertices, normals, mIsSkybox || mHasCubemapTexture ? skyboxTextureCoords : textureCoords, colors,
mIsSkybox && mHasCubemapTexture ? skyboxIndices : indices);
vertices = null;
normals = null;
skyboxTextureCoords = null;
textureCoords = null;
colors = null;
skyboxIndices = null;
indices = null;
}
|
diff --git a/strongbox-authentication/strongbox-authentication-xml/src/test/java/org/carlspring/strongbox/dao/xml/UsersDaoImplTest.java b/strongbox-authentication/strongbox-authentication-xml/src/test/java/org/carlspring/strongbox/dao/xml/UsersDaoImplTest.java
index fdb7066..22974c6 100644
--- a/strongbox-authentication/strongbox-authentication-xml/src/test/java/org/carlspring/strongbox/dao/xml/UsersDaoImplTest.java
+++ b/strongbox-authentication/strongbox-authentication-xml/src/test/java/org/carlspring/strongbox/dao/xml/UsersDaoImplTest.java
@@ -1,77 +1,77 @@
package org.carlspring.strongbox.dao.xml;
import org.carlspring.strongbox.security.jaas.User;
import org.carlspring.strongbox.util.encryption.EncryptionUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
/**
* @author mtodorov
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/META-INF/spring/strongbox-*-context.xml", "classpath*:/META-INF/spring/strongbox-*-context.xml"})
public class UsersDaoImplTest
{
public static final String USERNAME = "test_" + System.currentTimeMillis();
public static final String PASSWORD = EncryptionUtils.encryptWithMD5("password");
@Autowired
private UsersDao usersDao;
@Test
public void testCreateAndUpdateUser()
throws Exception
{
User user = new User();
user.setUsername(USERNAME);
user.setPassword(PASSWORD);
final long countOld = usersDao.count();
usersDao.createUser(user);
final long countNew = usersDao.count();
assertTrue("Failed to create user '" + USERNAME + "'!", countOld < countNew);
// Update the user
// TODO: SB-84: Add option to prefix passwords with their encryption algorithm
// TODO: Re-visit this at a later time
// final String changedPassword = "MD5:" + EncryptionUtils.encryptWithMD5("newpassword");
final String changedPassword = EncryptionUtils.encryptWithMD5("newpassword");
user.setPassword(changedPassword);
usersDao.updateUser(user);
User updatedUser = usersDao.findUser(USERNAME, changedPassword);
assertEquals("Failed to update the user!", changedPassword, updatedUser.getPassword());
user = updatedUser;
// Test roles
String roleName = "ADMINISTRATOR";
assertFalse("This user is already an administrator!", user.hasRole(roleName));
usersDao.assignRole(user, roleName);
updatedUser = usersDao.findUser(USERNAME);
assertTrue("Failed to assign role 'ADMINISTRATOR' to user '" + USERNAME + "'",
updatedUser.hasRole(roleName));
// Delete the user
- usersDao.removeUser(user.getUsername());
+ // usersDao.removeUser(user.getUsername());
}
}
| true | true | public void testCreateAndUpdateUser()
throws Exception
{
User user = new User();
user.setUsername(USERNAME);
user.setPassword(PASSWORD);
final long countOld = usersDao.count();
usersDao.createUser(user);
final long countNew = usersDao.count();
assertTrue("Failed to create user '" + USERNAME + "'!", countOld < countNew);
// Update the user
// TODO: SB-84: Add option to prefix passwords with their encryption algorithm
// TODO: Re-visit this at a later time
// final String changedPassword = "MD5:" + EncryptionUtils.encryptWithMD5("newpassword");
final String changedPassword = EncryptionUtils.encryptWithMD5("newpassword");
user.setPassword(changedPassword);
usersDao.updateUser(user);
User updatedUser = usersDao.findUser(USERNAME, changedPassword);
assertEquals("Failed to update the user!", changedPassword, updatedUser.getPassword());
user = updatedUser;
// Test roles
String roleName = "ADMINISTRATOR";
assertFalse("This user is already an administrator!", user.hasRole(roleName));
usersDao.assignRole(user, roleName);
updatedUser = usersDao.findUser(USERNAME);
assertTrue("Failed to assign role 'ADMINISTRATOR' to user '" + USERNAME + "'",
updatedUser.hasRole(roleName));
// Delete the user
usersDao.removeUser(user.getUsername());
}
| public void testCreateAndUpdateUser()
throws Exception
{
User user = new User();
user.setUsername(USERNAME);
user.setPassword(PASSWORD);
final long countOld = usersDao.count();
usersDao.createUser(user);
final long countNew = usersDao.count();
assertTrue("Failed to create user '" + USERNAME + "'!", countOld < countNew);
// Update the user
// TODO: SB-84: Add option to prefix passwords with their encryption algorithm
// TODO: Re-visit this at a later time
// final String changedPassword = "MD5:" + EncryptionUtils.encryptWithMD5("newpassword");
final String changedPassword = EncryptionUtils.encryptWithMD5("newpassword");
user.setPassword(changedPassword);
usersDao.updateUser(user);
User updatedUser = usersDao.findUser(USERNAME, changedPassword);
assertEquals("Failed to update the user!", changedPassword, updatedUser.getPassword());
user = updatedUser;
// Test roles
String roleName = "ADMINISTRATOR";
assertFalse("This user is already an administrator!", user.hasRole(roleName));
usersDao.assignRole(user, roleName);
updatedUser = usersDao.findUser(USERNAME);
assertTrue("Failed to assign role 'ADMINISTRATOR' to user '" + USERNAME + "'",
updatedUser.hasRole(roleName));
// Delete the user
// usersDao.removeUser(user.getUsername());
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/economy/WalletHandler.java b/src/FE_SRC_COMMON/com/ForgeEssentials/economy/WalletHandler.java
index 85daf8522..e427004d5 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/economy/WalletHandler.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/economy/WalletHandler.java
@@ -1,94 +1,94 @@
package com.ForgeEssentials.economy;
import java.util.HashMap;
import net.minecraft.entity.player.EntityPlayer;
import com.ForgeEssentials.api.data.ClassContainer;
import com.ForgeEssentials.api.data.DataStorageManager;
import com.ForgeEssentials.api.economy.IEconManager;
import cpw.mods.fml.common.IPlayerTracker;
/**
* Call these methods to modify a target's Wallet.
*/
public class WalletHandler implements IPlayerTracker, IEconManager
{
private static ClassContainer con = new ClassContainer(Wallet.class);
private static HashMap<String, Wallet> wallets = new HashMap<String, Wallet>();
@Override
public void addToWallet(int amountToAdd, String player)
{
wallets.get(player).amount = wallets.get(player).amount + amountToAdd;
}
@Override
public int getWallet(String player)
{
return wallets.get(player).amount;
}
@Override
public void removeFromWallet(int amountToSubtract, String player)
{
wallets.get(player).amount = wallets.get(player).amount - amountToSubtract;
}
@Override
public void setWallet(int setAmount, EntityPlayer player)
{
wallets.get(player.username).amount = setAmount;
}
@Override
public String currency(int amount)
{
if (amount == 1)
return ConfigEconomy.currencySingular;
else
return ConfigEconomy.currencyPlural;
}
@Override
public String getMoneyString(String username)
{
int am = getWallet(username);
return am + " " + currency(am);
}
/*
* Player tracker stuff
*/
@Override
public void onPlayerLogin(EntityPlayer player)
{
Wallet wallet = (Wallet) DataStorageManager.getReccomendedDriver().loadObject(con, player.username);
if (wallet == null)
{
wallet = new Wallet(player, ModuleEconomy.startbuget);
}
- wallets.put(wallet.getUsername(), wallet);
+ wallets.put(player.username, wallet);
}
@Override
public void onPlayerLogout(EntityPlayer player)
{
if (wallets.containsKey(player.username))
{
DataStorageManager.getReccomendedDriver().saveObject(con, wallets.remove(player.username));
}
}
@Override
public void onPlayerChangedDimension(EntityPlayer player)
{
}
@Override
public void onPlayerRespawn(EntityPlayer player)
{
}
}
| true | true | public void onPlayerLogin(EntityPlayer player)
{
Wallet wallet = (Wallet) DataStorageManager.getReccomendedDriver().loadObject(con, player.username);
if (wallet == null)
{
wallet = new Wallet(player, ModuleEconomy.startbuget);
}
wallets.put(wallet.getUsername(), wallet);
}
| public void onPlayerLogin(EntityPlayer player)
{
Wallet wallet = (Wallet) DataStorageManager.getReccomendedDriver().loadObject(con, player.username);
if (wallet == null)
{
wallet = new Wallet(player, ModuleEconomy.startbuget);
}
wallets.put(player.username, wallet);
}
|
diff --git a/src/StatementsNode.java b/src/StatementsNode.java
index 8a77524..d48b962 100644
--- a/src/StatementsNode.java
+++ b/src/StatementsNode.java
@@ -1,46 +1,46 @@
import java.util.ArrayList;
public class StatementsNode extends ASTNode
{
public StatementsNode(int yyline, int yycol)
{
super(yyline, yycol);
}
public void checkSemantics() throws Exception
{
for (ASTNode statement : this.getChildren())
{
statement.checkSemantics();
}
/*
* Check to make sure function has a return statement that
* is guarenteed to be executed (if it is not a void function)
* and does not have any unreachable code
*
* The type of the return statement is verified in ReturnNode
*/
boolean hasReturn = false;
for (ASTNode statement : this.getChildren())
{
if (hasReturn == true)
{
throw new Exception("Line: " + this.getYyline() + ": Unreachable code!");
}
- if (statement.getType().equalsIgnoreCase("return"))
+ if ("return".equalsIgnoreCase(statement.getType()))
{
hasReturn = true;
}
}
if (hasReturn == true)
{
setType("return");
}
}
public String generateCode()
{
return "";
}
}
| true | true | public void checkSemantics() throws Exception
{
for (ASTNode statement : this.getChildren())
{
statement.checkSemantics();
}
/*
* Check to make sure function has a return statement that
* is guarenteed to be executed (if it is not a void function)
* and does not have any unreachable code
*
* The type of the return statement is verified in ReturnNode
*/
boolean hasReturn = false;
for (ASTNode statement : this.getChildren())
{
if (hasReturn == true)
{
throw new Exception("Line: " + this.getYyline() + ": Unreachable code!");
}
if (statement.getType().equalsIgnoreCase("return"))
{
hasReturn = true;
}
}
if (hasReturn == true)
{
setType("return");
}
}
| public void checkSemantics() throws Exception
{
for (ASTNode statement : this.getChildren())
{
statement.checkSemantics();
}
/*
* Check to make sure function has a return statement that
* is guarenteed to be executed (if it is not a void function)
* and does not have any unreachable code
*
* The type of the return statement is verified in ReturnNode
*/
boolean hasReturn = false;
for (ASTNode statement : this.getChildren())
{
if (hasReturn == true)
{
throw new Exception("Line: " + this.getYyline() + ": Unreachable code!");
}
if ("return".equalsIgnoreCase(statement.getType()))
{
hasReturn = true;
}
}
if (hasReturn == true)
{
setType("return");
}
}
|
diff --git a/src/test/java/algorithm/TestAlgorithm.java b/src/test/java/algorithm/TestAlgorithm.java
index 90f22d5..a431b9d 100644
--- a/src/test/java/algorithm/TestAlgorithm.java
+++ b/src/test/java/algorithm/TestAlgorithm.java
@@ -1,175 +1,176 @@
package algorithm;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import crowdtrust.BinarySubTask;
import crowdtrust.Account;
import db.DbInitialiser;
import db.LoginDb;
import db.RegisterDb;
import db.SubTaskDb;
import db.TaskDb;
import db.CrowdDb;
import junit.framework.TestCase;
public class TestAlgorithm extends TestCase {
protected static int annotatorNumber = 10;
protected static int totalPos = 1000; //Annotators when created have
protected static int totalNeg = 1000; //'Answered' 2000 questions
protected AnnotatorModel[] annotators;
public TestAlgorithm(String name){
super(name);
}
public void testAlgorithm(){
boolean labs = false;
if(labs){
DbInitialiser.init();
}
//Lets create some annotators with id's 1 - 1000 and place them in array
annotators = new AnnotatorModel[annotatorNumber];
for(int i = 0; i < annotatorNumber; i++){
String uuid = UUID.randomUUID().toString();
uuid = uuid.replace("-", "");
uuid = uuid.substring(0, 12);
annotators[i] = new AnnotatorModel(uuid, uuid);
}
//Set up the annotators so they can answer binary question
Random rand = new Random();
for(int i = 0; i < annotatorNumber; i++){
int truePos = rand.nextInt(999) + 1;
int trueNeg = rand.nextInt(999) + 1;
annotators[i].setUpBinary(truePos, trueNeg, totalPos, totalNeg);
}
if(labs){
//Add them to the Database
for(int i = 0; i < annotatorNumber; i++){
RegisterDb.addUser("[email protected]", annotators[i].getUsername(), annotators[i].getPassword(), true);
annotators[i].setId(LoginDb.checkUserDetails(annotators[i].getUsername(), annotators[i].getPassword()));
+ AnnotatorModel a = annotators[i];
System.out.println("annotator " +
- annotators[i].bee.getId() +
- "truePosRate =" + annotators[i].binary.truePosRate +
- "trueNegRate =" + annotators[i].binary.trueNegRate);
+ a.bee.getId() +
+ " truePosRate =" + a.binary.truePos/a.binary.totalPos +
+ " trueNegRate =" + a.binary.trueNeg/a.binary.totalNeg);
}
//Lets make a client
RegisterDb.addUser("[email protected]", "gio", "gio", false);
int accountId = LoginDb.checkUserDetails("gio", "gio");
//Lets add a binary task to the database
long expiry = getDate();
float accuracy = (float)0.7;
List<String> testQs = new LinkedList<String>();
testQs.add("test q1");
testQs.add("test q2");
assertTrue(TaskDb.addTask(accountId,"BinaryTestTask", "This is a test?", accuracy, 1, 1, 1, 15, expiry, testQs)>0);
//List of answers
LinkedList<AnnotatorSubTaskAnswer> answers = new LinkedList<AnnotatorSubTaskAnswer>();
System.out.println("About to get Task id");
System.out.println("John Task Id: " + TaskDb.getTaskId("BinaryTestTask"));
System.out.println("Got it");
//Lets create a linked list of subTasks
for(int i = 0; i < 10; i++){
String uuid = UUID.randomUUID().toString();
uuid = uuid.replace("-", "");
uuid = uuid.substring(0, 12);
SubTaskDb.addSubtask(uuid, TaskDb.getTaskId("BinaryTestTask"));
int id = SubTaskDb.getSubTaskId(uuid);
System.out.println("Subtask Id: " + id);
BinarySubTask bst = new BinarySubTask(id,0,0,0);
AnnotatorSubTaskAnswer asta = new AnnotatorSubTaskAnswer(bst.getId(), bst, new BinaryTestData(rand.nextInt(2)));
answers.add(asta);
}
//Give all the annotators the answers
for(int i = 0; i < annotatorNumber; i++){
annotators[i].setTasks(answers);
}
System.out.println("Given annotators answers");
printAnswers(answers);
System.out.println("---------Beginnign to answer tasks--------------------");
int parent_task_id = TaskDb.getTaskId("BinaryTestTask");
int annotatorIndex = rand.nextInt(annotatorNumber - 1);
AnnotatorModel a = annotators[annotatorIndex];
BinarySubTask t = (BinarySubTask) SubTaskDb.getRandomSubTask(parent_task_id, a.bee.getId(), 1);
System.out.println("Got first");
while( t != null){
annotatorIndex = rand.nextInt(annotatorNumber - 1);
a = annotators[annotatorIndex];
System.out.println("Annotator: " + a.username + " |Task: " + t.getId());
a.answerTask(t);
t = (BinarySubTask) SubTaskDb.getRandomSubTask(parent_task_id, a.bee.getId(),1);
}
System.out.println("------------------------------------------------------ ");
DbInitialiser.init();
}
}
protected void printAnswers(LinkedList<AnnotatorSubTaskAnswer> answers){
System.out.println("-------------Printing Answers------------------");
Iterator<AnnotatorSubTaskAnswer> i = answers.iterator();
while(i.hasNext()){
AnnotatorSubTaskAnswer temp = i.next();
System.out.println("Answer id: " + temp.getId());
System.out.println("Actual answer: " + ((BinaryTestData)temp.getAlgoTestData()).getActualAnswer());
}
System.out.println("-----------------------------------------------");
}
protected long getDate(){
long ret = 0 ;
String str_date = "11-June-15";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yy");
try {
date = (Date)formatter.parse(str_date);
ret = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return ret;
}
protected void printExpertList(){
System.out.println("-----------Printing Expert List----------------");
System.out.println("-----------------------------------------------");
List<Account> experts = CrowdDb.getAllExperts();
for(Account account : experts) {
System.out.println("id =" + account.getId() + " name = " + account.getName());
}
}
protected void printBotList(){
System.out.println("-----------Printing Bots List-------------------");
System.out.println("------------------------------------------------");
List<Account> bots = CrowdDb.getAllExperts();
for(Account account : bots) {
System.out.println("id =" + account.getId() + " name = " + account.getName());
}
}
}
| false | true | public void testAlgorithm(){
boolean labs = false;
if(labs){
DbInitialiser.init();
}
//Lets create some annotators with id's 1 - 1000 and place them in array
annotators = new AnnotatorModel[annotatorNumber];
for(int i = 0; i < annotatorNumber; i++){
String uuid = UUID.randomUUID().toString();
uuid = uuid.replace("-", "");
uuid = uuid.substring(0, 12);
annotators[i] = new AnnotatorModel(uuid, uuid);
}
//Set up the annotators so they can answer binary question
Random rand = new Random();
for(int i = 0; i < annotatorNumber; i++){
int truePos = rand.nextInt(999) + 1;
int trueNeg = rand.nextInt(999) + 1;
annotators[i].setUpBinary(truePos, trueNeg, totalPos, totalNeg);
}
if(labs){
//Add them to the Database
for(int i = 0; i < annotatorNumber; i++){
RegisterDb.addUser("[email protected]", annotators[i].getUsername(), annotators[i].getPassword(), true);
annotators[i].setId(LoginDb.checkUserDetails(annotators[i].getUsername(), annotators[i].getPassword()));
System.out.println("annotator " +
annotators[i].bee.getId() +
"truePosRate =" + annotators[i].binary.truePosRate +
"trueNegRate =" + annotators[i].binary.trueNegRate);
}
//Lets make a client
RegisterDb.addUser("[email protected]", "gio", "gio", false);
int accountId = LoginDb.checkUserDetails("gio", "gio");
//Lets add a binary task to the database
long expiry = getDate();
float accuracy = (float)0.7;
List<String> testQs = new LinkedList<String>();
testQs.add("test q1");
testQs.add("test q2");
assertTrue(TaskDb.addTask(accountId,"BinaryTestTask", "This is a test?", accuracy, 1, 1, 1, 15, expiry, testQs)>0);
//List of answers
LinkedList<AnnotatorSubTaskAnswer> answers = new LinkedList<AnnotatorSubTaskAnswer>();
System.out.println("About to get Task id");
System.out.println("John Task Id: " + TaskDb.getTaskId("BinaryTestTask"));
System.out.println("Got it");
//Lets create a linked list of subTasks
for(int i = 0; i < 10; i++){
String uuid = UUID.randomUUID().toString();
uuid = uuid.replace("-", "");
uuid = uuid.substring(0, 12);
SubTaskDb.addSubtask(uuid, TaskDb.getTaskId("BinaryTestTask"));
int id = SubTaskDb.getSubTaskId(uuid);
System.out.println("Subtask Id: " + id);
BinarySubTask bst = new BinarySubTask(id,0,0,0);
AnnotatorSubTaskAnswer asta = new AnnotatorSubTaskAnswer(bst.getId(), bst, new BinaryTestData(rand.nextInt(2)));
answers.add(asta);
}
//Give all the annotators the answers
for(int i = 0; i < annotatorNumber; i++){
annotators[i].setTasks(answers);
}
System.out.println("Given annotators answers");
printAnswers(answers);
System.out.println("---------Beginnign to answer tasks--------------------");
int parent_task_id = TaskDb.getTaskId("BinaryTestTask");
int annotatorIndex = rand.nextInt(annotatorNumber - 1);
AnnotatorModel a = annotators[annotatorIndex];
BinarySubTask t = (BinarySubTask) SubTaskDb.getRandomSubTask(parent_task_id, a.bee.getId(), 1);
System.out.println("Got first");
while( t != null){
annotatorIndex = rand.nextInt(annotatorNumber - 1);
a = annotators[annotatorIndex];
System.out.println("Annotator: " + a.username + " |Task: " + t.getId());
a.answerTask(t);
t = (BinarySubTask) SubTaskDb.getRandomSubTask(parent_task_id, a.bee.getId(),1);
}
System.out.println("------------------------------------------------------ ");
DbInitialiser.init();
}
}
| public void testAlgorithm(){
boolean labs = false;
if(labs){
DbInitialiser.init();
}
//Lets create some annotators with id's 1 - 1000 and place them in array
annotators = new AnnotatorModel[annotatorNumber];
for(int i = 0; i < annotatorNumber; i++){
String uuid = UUID.randomUUID().toString();
uuid = uuid.replace("-", "");
uuid = uuid.substring(0, 12);
annotators[i] = new AnnotatorModel(uuid, uuid);
}
//Set up the annotators so they can answer binary question
Random rand = new Random();
for(int i = 0; i < annotatorNumber; i++){
int truePos = rand.nextInt(999) + 1;
int trueNeg = rand.nextInt(999) + 1;
annotators[i].setUpBinary(truePos, trueNeg, totalPos, totalNeg);
}
if(labs){
//Add them to the Database
for(int i = 0; i < annotatorNumber; i++){
RegisterDb.addUser("[email protected]", annotators[i].getUsername(), annotators[i].getPassword(), true);
annotators[i].setId(LoginDb.checkUserDetails(annotators[i].getUsername(), annotators[i].getPassword()));
AnnotatorModel a = annotators[i];
System.out.println("annotator " +
a.bee.getId() +
" truePosRate =" + a.binary.truePos/a.binary.totalPos +
" trueNegRate =" + a.binary.trueNeg/a.binary.totalNeg);
}
//Lets make a client
RegisterDb.addUser("[email protected]", "gio", "gio", false);
int accountId = LoginDb.checkUserDetails("gio", "gio");
//Lets add a binary task to the database
long expiry = getDate();
float accuracy = (float)0.7;
List<String> testQs = new LinkedList<String>();
testQs.add("test q1");
testQs.add("test q2");
assertTrue(TaskDb.addTask(accountId,"BinaryTestTask", "This is a test?", accuracy, 1, 1, 1, 15, expiry, testQs)>0);
//List of answers
LinkedList<AnnotatorSubTaskAnswer> answers = new LinkedList<AnnotatorSubTaskAnswer>();
System.out.println("About to get Task id");
System.out.println("John Task Id: " + TaskDb.getTaskId("BinaryTestTask"));
System.out.println("Got it");
//Lets create a linked list of subTasks
for(int i = 0; i < 10; i++){
String uuid = UUID.randomUUID().toString();
uuid = uuid.replace("-", "");
uuid = uuid.substring(0, 12);
SubTaskDb.addSubtask(uuid, TaskDb.getTaskId("BinaryTestTask"));
int id = SubTaskDb.getSubTaskId(uuid);
System.out.println("Subtask Id: " + id);
BinarySubTask bst = new BinarySubTask(id,0,0,0);
AnnotatorSubTaskAnswer asta = new AnnotatorSubTaskAnswer(bst.getId(), bst, new BinaryTestData(rand.nextInt(2)));
answers.add(asta);
}
//Give all the annotators the answers
for(int i = 0; i < annotatorNumber; i++){
annotators[i].setTasks(answers);
}
System.out.println("Given annotators answers");
printAnswers(answers);
System.out.println("---------Beginnign to answer tasks--------------------");
int parent_task_id = TaskDb.getTaskId("BinaryTestTask");
int annotatorIndex = rand.nextInt(annotatorNumber - 1);
AnnotatorModel a = annotators[annotatorIndex];
BinarySubTask t = (BinarySubTask) SubTaskDb.getRandomSubTask(parent_task_id, a.bee.getId(), 1);
System.out.println("Got first");
while( t != null){
annotatorIndex = rand.nextInt(annotatorNumber - 1);
a = annotators[annotatorIndex];
System.out.println("Annotator: " + a.username + " |Task: " + t.getId());
a.answerTask(t);
t = (BinarySubTask) SubTaskDb.getRandomSubTask(parent_task_id, a.bee.getId(),1);
}
System.out.println("------------------------------------------------------ ");
DbInitialiser.init();
}
}
|
diff --git a/src/net/derkholm/nmica/extra/app/MotifSetThresholder.java b/src/net/derkholm/nmica/extra/app/MotifSetThresholder.java
index 88d2442..58babfb 100644
--- a/src/net/derkholm/nmica/extra/app/MotifSetThresholder.java
+++ b/src/net/derkholm/nmica/extra/app/MotifSetThresholder.java
@@ -1,97 +1,97 @@
package net.derkholm.nmica.extra.app;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import net.derkholm.nmica.build.NMExtraApp;
import net.derkholm.nmica.motif.Motif;
import net.derkholm.nmica.motif.MotifIOTools;
import org.bjv2.util.cli.App;
import org.bjv2.util.cli.Option;
@App(overview = "Set the threshold for ", generateStub = true)
@NMExtraApp(launchName = "nmthreshold")
public class MotifSetThresholder {
private double scoreThreshold=0.0;
private Set names = null;
private String outFileName;
private File inFile;
@Option(help="The input motif set file")
public void setMotifs(File f) {
this.inFile = f;
}
@Option(help="The score threshold to set")
public void setScoreThreshold(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
System.err.printf("ERROR: invalid scoreThreshold=%e%n",d);
}
if (d > 0) {
System.err.printf("ERROR: scoreThreshold %e > 0%n",d);
System.exit(1);
}
this.scoreThreshold = d;
}
@Option(help="Names of motifs to set the threshold for. " +
"If unspecified, all motifs in the set will be given the specified threshold",
optional=true)
public void setNames(String[] strings) {
this.names = new HashSet();
for (String s : strings) {
this.names.add(s);
}
}
@Option(help="Output filename",optional=true)
public void setOut(String str) {
this.outFileName = str;
}
public void main(String[] args) throws FileNotFoundException, Exception {
FileReader reader = null;
BufferedReader bufferedReader = null;
Motif[] motifs = null;
try {
reader = new FileReader(inFile);
if (reader != null) {
bufferedReader = new BufferedReader(reader);
}
motifs = MotifIOTools.loadMotifSetXML(bufferedReader);
} catch (IOException ioe) {
System.err.printf("Could not read from file %s %n",inFile.getCanonicalFile());
ioe.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
if (reader != null)
reader.close();
}
if (motifs == null || motifs.length == 0) {
System.err.printf("Could not read motif set from %n");
}
for (Motif m : motifs) {
- if (this.names.contains(m.getName()) || names == null) {
+ if (names == null || this.names.contains(m.getName())) {
m.setThreshold(scoreThreshold);
}
}
if (outFileName != null) {
MotifIOTools.writeMotifSetXML(
new BufferedOutputStream(
new FileOutputStream(outFileName)), motifs);
} else {
MotifIOTools.writeMotifSetXML(System.out, motifs);
}
}
}
| true | true | public void main(String[] args) throws FileNotFoundException, Exception {
FileReader reader = null;
BufferedReader bufferedReader = null;
Motif[] motifs = null;
try {
reader = new FileReader(inFile);
if (reader != null) {
bufferedReader = new BufferedReader(reader);
}
motifs = MotifIOTools.loadMotifSetXML(bufferedReader);
} catch (IOException ioe) {
System.err.printf("Could not read from file %s %n",inFile.getCanonicalFile());
ioe.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
if (reader != null)
reader.close();
}
if (motifs == null || motifs.length == 0) {
System.err.printf("Could not read motif set from %n");
}
for (Motif m : motifs) {
if (this.names.contains(m.getName()) || names == null) {
m.setThreshold(scoreThreshold);
}
}
if (outFileName != null) {
MotifIOTools.writeMotifSetXML(
new BufferedOutputStream(
new FileOutputStream(outFileName)), motifs);
} else {
MotifIOTools.writeMotifSetXML(System.out, motifs);
}
}
| public void main(String[] args) throws FileNotFoundException, Exception {
FileReader reader = null;
BufferedReader bufferedReader = null;
Motif[] motifs = null;
try {
reader = new FileReader(inFile);
if (reader != null) {
bufferedReader = new BufferedReader(reader);
}
motifs = MotifIOTools.loadMotifSetXML(bufferedReader);
} catch (IOException ioe) {
System.err.printf("Could not read from file %s %n",inFile.getCanonicalFile());
ioe.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
if (reader != null)
reader.close();
}
if (motifs == null || motifs.length == 0) {
System.err.printf("Could not read motif set from %n");
}
for (Motif m : motifs) {
if (names == null || this.names.contains(m.getName())) {
m.setThreshold(scoreThreshold);
}
}
if (outFileName != null) {
MotifIOTools.writeMotifSetXML(
new BufferedOutputStream(
new FileOutputStream(outFileName)), motifs);
} else {
MotifIOTools.writeMotifSetXML(System.out, motifs);
}
}
|
diff --git a/src/asl/seedscan/config/ConfigReader.java b/src/asl/seedscan/config/ConfigReader.java
index 920f928..1fd5202 100644
--- a/src/asl/seedscan/config/ConfigReader.java
+++ b/src/asl/seedscan/config/ConfigReader.java
@@ -1,291 +1,291 @@
/*
* Copyright 2012, United States Geological Survey or
* third-party contributors as indicated by the @author tags.
*
* 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
* (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 asl.seedscan.config;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.XMLConstants;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.SAXException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import asl.logging.LogFileConfig;
import asl.logging.LogDatabaseConfig;
import asl.seedscan.scan.Scan;
import asl.seedscan.scan.ScanOperation;
import asl.seedscan.scan.ScanFrequency;
/**
*
*/
public class ConfigReader
{
private static final Logger logger = Logger.getLogger("asl.seedscan.config.ConfigReader");
DocumentBuilderFactory domFactory = null;
private SchemaFactory schemaFactory = null;
private DocumentBuilder builder = null;
private Schema schema = null;
private Validator validator = null;
private Document doc = null;
private XPath xpath = null;
private boolean validate = false;
private boolean ready = false;
private Configuration config = null;
// constructor(s)
public ConfigReader()
{
_construct(null);
}
public ConfigReader(File schemaFile)
{
_construct(schemaFile);
}
private void _construct(File schemaFile)
{
xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new ConfigNamespaceContext());
domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
if (schemaFile != null) {
schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
schema = schemaFactory.newSchema(schemaFile);
} catch (SAXException e) {
logger.severe("Could not read validation file '" +schemaFile+ "'.\n Details: " +e);
throw new RuntimeException("Could not read validation file.");
}
validate = true;
}
try {
builder = domFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
logger.severe("Invalid configuration for SAX parser.\n Details: " +e);
throw new RuntimeException("Invalid configuration for SAX parser.");
}
}
public Configuration getConfiguration()
{
return config;
}
// read and validate the configuration
public void loadConfiguration(File configFile)
{
config = new Configuration();
if (validate) {
Validator validator = schema.newValidator();
try {
validator.validate(new StreamSource(configFile));
logger.info("Configuration file passed validation.");
} catch (SAXException e) {
logger.severe("Configuration file did not pass validation.\n Details: " +e);
throw new RuntimeException("Configuration file failed validation.");
} catch (IOException e) {
logger.severe("Failed to read configuration from file '" +configFile+ "'.\n Details: " +e);
throw new RuntimeException("Could not read configuration file.");
}
}
try {
doc = builder.parse(configFile);
logger.info("Configuration file parsed.");
} catch (SAXException e) {
logger.severe("Could not assemble DOM from config file '" +configFile+ "'.\n Details: " +e);
throw new RuntimeException("Could not assemble configuration from file.");
} catch (IOException e) {
logger.severe("Could not read config file '" +configFile+ "'.\n Details:" +e);
throw new RuntimeException("Could not read configuration file.");
}
try {
parseConfig();
} catch (XPathExpressionException e) {
logger.severe("XPath expression error!\n Details: " +e);
e.printStackTrace();
throw new RuntimeException("XPath expression error.");
} catch (FileNotFoundException e) {
logger.severe("Configuration error!\n Details: " +e);
e.printStackTrace();
throw new RuntimeException("Configuration error.");
} catch (IOException e) {
logger.severe("Configuration error!\n Details: " +e);
e.printStackTrace();
throw new RuntimeException("Configuration error.");
}
ready = true;
}
// parse the configuration
private void parseConfig()
throws FileNotFoundException,
IOException,
XPathExpressionException
{
parseConfig(null);
}
private void parseConfig(String configPassword)
throws FileNotFoundException,
IOException,
XPathExpressionException
{
logger.info("Parsing the configuration file");
logger.fine("Document: " + doc);
// Lock File
logger.fine("Parsing lockfile.");
config.setLockFile(xpath.evaluate("//cfg:seedscan/cfg:lockfile/text()", doc));
// Parse Log Config
- LogConfig logConfig = new LogConfig();
+ LogFileConfig logConfig = new LogFileConfig();
//config.put("log-levels", xpath.evaluate("//cfg:seedscan/cfg:log/cfg:level/text()", doc));
String pathLog = "//cfg:seedscan/cfg:log";
logConfig.setDirectory(xpath.evaluate(pathLog+"/cfg:directory/text()", doc));
logConfig.setPrefix( xpath.evaluate(pathLog+"/cfg:prefix/text()", doc));
logConfig.setSuffix( xpath.evaluate(pathLog+"/cfg:suffix/text()", doc));
NodeList nodes = (NodeList)xpath.evaluate(pathLog+"/cfg:levels/cfg:level",
doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
NamedNodeMap attribs = node.getAttributes();
Node nameAttrib = attribs.getNamedItem("cfg:name");
String name = nameAttrib.getNodeValue();
String level = node.getTextContent();
logConfig.setLevel(name, Level.parse(level));
logger.fine("File logging context '" +name+ "' set to level " +level);
}
// Parse Database Config
DatabaseConfig dbConfig = new DatabaseConfig();
Password password;
logger.fine("Parsing database.");
String pathDB = "//cfg:seedscan/cfg:database";
dbConfig.setURI( xpath.evaluate(pathDB+"/cfg:uri/text()", doc));
dbConfig.setUsername(xpath.evaluate(pathDB+"/cfg:username/text()", doc));
String pathPass = pathDB + "/cfg:password";
nodes = (NodeList)xpath.evaluate(pathPass+"/cfg:plain",
doc, XPathConstants.NODESET);
if (nodes.getLength() > 0) {
String text = xpath.evaluate(pathPass+"/cfg:plain/text()", doc);
password = (Password)(new TextPassword(text));
} else {
HexBinaryAdapter hexbin = new HexBinaryAdapter();
String pathEnc = pathPass + "/cfg:encrypted";
String salt = xpath.evaluate(pathEnc+"/cfg:salt/text()", doc);
String iv = xpath.evaluate(pathEnc+"/cfg:iv/text()", doc);
String cipherText = xpath.evaluate(pathEnc+"/cfg:ciphertext/text()", doc);
String hmac = xpath.evaluate(pathEnc+"/cfg:hmac/text()", doc);
EncryptedPassword cryptPass = new EncryptedPassword(hexbin.unmarshal(iv),
hexbin.unmarshal(cipherText),
hexbin.unmarshal(hmac));
PassKey passKey = new PassKey(configPassword, 16, hexbin.unmarshal(salt));
cryptPass.setKey(passKey.getKey());
password = (Password)cryptPass;
}
dbConfig.setPassword(password);
nodes = (NodeList)xpath.evaluate(pathDB+"/cfg:levels/cfg:level",
doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
NamedNodeMap attribs = node.getAttributes();
Node nameAttrib = attribs.getNamedItem("cfg:name");
String name = nameAttrib.getNodeValue();
String level = node.getTextContent();
dbConfig.setLevel(name, Level.parse(level));
logger.fine("Database logging context '" +name+ "' set to level " +level);
}
// Parse Scans
logger.fine("Parsing scans.");
int id;
String key;
NodeList scans = (NodeList)xpath.evaluate("/cfg:seedscan/cfg:scans/cfg:scan",
doc, XPathConstants.NODESET);
if ((scans == null) || (scans.getLength() < 1)) {
logger.warning("No scans in configuration.");
}
else {
int scanCount = scans.getLength();
for (int i=0; i < scanCount; i++) {
Node node = scans.item(i);
Scan scan = new Scan();
scan.setPathPattern(xpath.evaluate("./cfg:path/text()", node));
scan.setStartDepth(Integer.parseInt(xpath.evaluate("./cfg:start_depth/text()", node)));
scan.setScanDepth(Integer.parseInt(xpath.evaluate("./cfg:scan_depth/text()", node)));
ScanFrequency frequency = new ScanFrequency();
// TODO: parse frequency
scan.setScanFrequency(frequency);
NodeList ops = (NodeList)xpath.evaluate("./cfg:operations/cfg:operation",
node, XPathConstants.NODESET);
int opCount = ops.getLength();
if ((ops == null) || (opCount < 1)) {
logger.warning("No operations found in scan " +i+ ".");
} else {
for (int j=1; j <= opCount; j++) {
ScanOperation operation = new ScanOperation();
scan.addOperation(operation);
}
}
config.addScan(scan);
}
}
logger.fine("Configuration: " + config);
}
}
| true | true | private void parseConfig(String configPassword)
throws FileNotFoundException,
IOException,
XPathExpressionException
{
logger.info("Parsing the configuration file");
logger.fine("Document: " + doc);
// Lock File
logger.fine("Parsing lockfile.");
config.setLockFile(xpath.evaluate("//cfg:seedscan/cfg:lockfile/text()", doc));
// Parse Log Config
LogConfig logConfig = new LogConfig();
//config.put("log-levels", xpath.evaluate("//cfg:seedscan/cfg:log/cfg:level/text()", doc));
String pathLog = "//cfg:seedscan/cfg:log";
logConfig.setDirectory(xpath.evaluate(pathLog+"/cfg:directory/text()", doc));
logConfig.setPrefix( xpath.evaluate(pathLog+"/cfg:prefix/text()", doc));
logConfig.setSuffix( xpath.evaluate(pathLog+"/cfg:suffix/text()", doc));
NodeList nodes = (NodeList)xpath.evaluate(pathLog+"/cfg:levels/cfg:level",
doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
NamedNodeMap attribs = node.getAttributes();
Node nameAttrib = attribs.getNamedItem("cfg:name");
String name = nameAttrib.getNodeValue();
String level = node.getTextContent();
logConfig.setLevel(name, Level.parse(level));
logger.fine("File logging context '" +name+ "' set to level " +level);
}
// Parse Database Config
DatabaseConfig dbConfig = new DatabaseConfig();
Password password;
logger.fine("Parsing database.");
String pathDB = "//cfg:seedscan/cfg:database";
dbConfig.setURI( xpath.evaluate(pathDB+"/cfg:uri/text()", doc));
dbConfig.setUsername(xpath.evaluate(pathDB+"/cfg:username/text()", doc));
String pathPass = pathDB + "/cfg:password";
nodes = (NodeList)xpath.evaluate(pathPass+"/cfg:plain",
doc, XPathConstants.NODESET);
if (nodes.getLength() > 0) {
String text = xpath.evaluate(pathPass+"/cfg:plain/text()", doc);
password = (Password)(new TextPassword(text));
} else {
HexBinaryAdapter hexbin = new HexBinaryAdapter();
String pathEnc = pathPass + "/cfg:encrypted";
String salt = xpath.evaluate(pathEnc+"/cfg:salt/text()", doc);
String iv = xpath.evaluate(pathEnc+"/cfg:iv/text()", doc);
String cipherText = xpath.evaluate(pathEnc+"/cfg:ciphertext/text()", doc);
String hmac = xpath.evaluate(pathEnc+"/cfg:hmac/text()", doc);
EncryptedPassword cryptPass = new EncryptedPassword(hexbin.unmarshal(iv),
hexbin.unmarshal(cipherText),
hexbin.unmarshal(hmac));
PassKey passKey = new PassKey(configPassword, 16, hexbin.unmarshal(salt));
cryptPass.setKey(passKey.getKey());
password = (Password)cryptPass;
}
dbConfig.setPassword(password);
nodes = (NodeList)xpath.evaluate(pathDB+"/cfg:levels/cfg:level",
doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
NamedNodeMap attribs = node.getAttributes();
Node nameAttrib = attribs.getNamedItem("cfg:name");
String name = nameAttrib.getNodeValue();
String level = node.getTextContent();
dbConfig.setLevel(name, Level.parse(level));
logger.fine("Database logging context '" +name+ "' set to level " +level);
}
// Parse Scans
logger.fine("Parsing scans.");
int id;
String key;
NodeList scans = (NodeList)xpath.evaluate("/cfg:seedscan/cfg:scans/cfg:scan",
doc, XPathConstants.NODESET);
if ((scans == null) || (scans.getLength() < 1)) {
logger.warning("No scans in configuration.");
}
else {
int scanCount = scans.getLength();
for (int i=0; i < scanCount; i++) {
Node node = scans.item(i);
Scan scan = new Scan();
scan.setPathPattern(xpath.evaluate("./cfg:path/text()", node));
scan.setStartDepth(Integer.parseInt(xpath.evaluate("./cfg:start_depth/text()", node)));
scan.setScanDepth(Integer.parseInt(xpath.evaluate("./cfg:scan_depth/text()", node)));
ScanFrequency frequency = new ScanFrequency();
// TODO: parse frequency
scan.setScanFrequency(frequency);
NodeList ops = (NodeList)xpath.evaluate("./cfg:operations/cfg:operation",
node, XPathConstants.NODESET);
int opCount = ops.getLength();
if ((ops == null) || (opCount < 1)) {
logger.warning("No operations found in scan " +i+ ".");
} else {
for (int j=1; j <= opCount; j++) {
ScanOperation operation = new ScanOperation();
scan.addOperation(operation);
}
}
config.addScan(scan);
}
}
logger.fine("Configuration: " + config);
}
| private void parseConfig(String configPassword)
throws FileNotFoundException,
IOException,
XPathExpressionException
{
logger.info("Parsing the configuration file");
logger.fine("Document: " + doc);
// Lock File
logger.fine("Parsing lockfile.");
config.setLockFile(xpath.evaluate("//cfg:seedscan/cfg:lockfile/text()", doc));
// Parse Log Config
LogFileConfig logConfig = new LogFileConfig();
//config.put("log-levels", xpath.evaluate("//cfg:seedscan/cfg:log/cfg:level/text()", doc));
String pathLog = "//cfg:seedscan/cfg:log";
logConfig.setDirectory(xpath.evaluate(pathLog+"/cfg:directory/text()", doc));
logConfig.setPrefix( xpath.evaluate(pathLog+"/cfg:prefix/text()", doc));
logConfig.setSuffix( xpath.evaluate(pathLog+"/cfg:suffix/text()", doc));
NodeList nodes = (NodeList)xpath.evaluate(pathLog+"/cfg:levels/cfg:level",
doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
NamedNodeMap attribs = node.getAttributes();
Node nameAttrib = attribs.getNamedItem("cfg:name");
String name = nameAttrib.getNodeValue();
String level = node.getTextContent();
logConfig.setLevel(name, Level.parse(level));
logger.fine("File logging context '" +name+ "' set to level " +level);
}
// Parse Database Config
DatabaseConfig dbConfig = new DatabaseConfig();
Password password;
logger.fine("Parsing database.");
String pathDB = "//cfg:seedscan/cfg:database";
dbConfig.setURI( xpath.evaluate(pathDB+"/cfg:uri/text()", doc));
dbConfig.setUsername(xpath.evaluate(pathDB+"/cfg:username/text()", doc));
String pathPass = pathDB + "/cfg:password";
nodes = (NodeList)xpath.evaluate(pathPass+"/cfg:plain",
doc, XPathConstants.NODESET);
if (nodes.getLength() > 0) {
String text = xpath.evaluate(pathPass+"/cfg:plain/text()", doc);
password = (Password)(new TextPassword(text));
} else {
HexBinaryAdapter hexbin = new HexBinaryAdapter();
String pathEnc = pathPass + "/cfg:encrypted";
String salt = xpath.evaluate(pathEnc+"/cfg:salt/text()", doc);
String iv = xpath.evaluate(pathEnc+"/cfg:iv/text()", doc);
String cipherText = xpath.evaluate(pathEnc+"/cfg:ciphertext/text()", doc);
String hmac = xpath.evaluate(pathEnc+"/cfg:hmac/text()", doc);
EncryptedPassword cryptPass = new EncryptedPassword(hexbin.unmarshal(iv),
hexbin.unmarshal(cipherText),
hexbin.unmarshal(hmac));
PassKey passKey = new PassKey(configPassword, 16, hexbin.unmarshal(salt));
cryptPass.setKey(passKey.getKey());
password = (Password)cryptPass;
}
dbConfig.setPassword(password);
nodes = (NodeList)xpath.evaluate(pathDB+"/cfg:levels/cfg:level",
doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
NamedNodeMap attribs = node.getAttributes();
Node nameAttrib = attribs.getNamedItem("cfg:name");
String name = nameAttrib.getNodeValue();
String level = node.getTextContent();
dbConfig.setLevel(name, Level.parse(level));
logger.fine("Database logging context '" +name+ "' set to level " +level);
}
// Parse Scans
logger.fine("Parsing scans.");
int id;
String key;
NodeList scans = (NodeList)xpath.evaluate("/cfg:seedscan/cfg:scans/cfg:scan",
doc, XPathConstants.NODESET);
if ((scans == null) || (scans.getLength() < 1)) {
logger.warning("No scans in configuration.");
}
else {
int scanCount = scans.getLength();
for (int i=0; i < scanCount; i++) {
Node node = scans.item(i);
Scan scan = new Scan();
scan.setPathPattern(xpath.evaluate("./cfg:path/text()", node));
scan.setStartDepth(Integer.parseInt(xpath.evaluate("./cfg:start_depth/text()", node)));
scan.setScanDepth(Integer.parseInt(xpath.evaluate("./cfg:scan_depth/text()", node)));
ScanFrequency frequency = new ScanFrequency();
// TODO: parse frequency
scan.setScanFrequency(frequency);
NodeList ops = (NodeList)xpath.evaluate("./cfg:operations/cfg:operation",
node, XPathConstants.NODESET);
int opCount = ops.getLength();
if ((ops == null) || (opCount < 1)) {
logger.warning("No operations found in scan " +i+ ".");
} else {
for (int j=1; j <= opCount; j++) {
ScanOperation operation = new ScanOperation();
scan.addOperation(operation);
}
}
config.addScan(scan);
}
}
logger.fine("Configuration: " + config);
}
|
diff --git a/src/main/java/ru/histone/evaluator/nodes/NodeFactory.java b/src/main/java/ru/histone/evaluator/nodes/NodeFactory.java
index ee47fb3..d8d0dfe 100644
--- a/src/main/java/ru/histone/evaluator/nodes/NodeFactory.java
+++ b/src/main/java/ru/histone/evaluator/nodes/NodeFactory.java
@@ -1,349 +1,367 @@
/**
* Copyright 2012 MegaFon
*
* 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 ru.histone.evaluator.nodes;
import com.fasterxml.jackson.core.io.CharTypes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.DecimalNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import ru.histone.utils.IOUtils;
import ru.histone.utils.StringUtils;
import sun.security.util.BigInt;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class NodeFactory {
private ObjectMapper jackson;
public final Node UNDEFINED;
public final BooleanHistoneNode TRUE;
public final BooleanHistoneNode FALSE;
public final Node NULL;
public final NumberHistoneNode UNDEFINED_NUMBER;
public NodeFactory(ObjectMapper jackson) {
this.jackson = jackson;
UNDEFINED = new UndefinedNode(this);
UNDEFINED_NUMBER = new UndefinedNumberHistoneNode(this);
NULL = new NullHistoneNode(this);
TRUE = new BooleanHistoneNode(this, true);
FALSE = new BooleanHistoneNode(this, false);
}
public ObjectHistoneNode object() {
return new ObjectHistoneNode(this);
}
public ObjectHistoneNode object(ObjectHistoneNode src) {
ObjectHistoneNode node = src.isGlobalObject() ? new GlobalObjectNode(this) : object();
for (Map.Entry<Object, Node> entry : src.getElements().entrySet()) {
node.add(entry.getKey(), entry.getValue());
}
// node.elements = new LinkedHashMap<Object, Node>(src.elements);
return node;
}
/**
* Create array node object and fill it with nodes from specified arguments
*
* @param elements node elements to use for creating new array object
* @return new array node object
*/
public ObjectHistoneNode object(Node... elements) {
if (elements == null) {
return object();
}
ObjectHistoneNode node = object();
for (Node item : elements) {
node.add(item);
}
return node;
}
/**
* Create array node object and fill it with nodes from specified arguments
*
* @param elements node elements to use for creating new array object
* @return new array node object
*/
public ObjectHistoneNode object(String... elements) {
if (elements == null) {
return object();
}
ObjectHistoneNode node = object();
for (String item : elements) {
node.add(string(item));
}
return node;
}
public ObjectHistoneNode object(Collection<Node> elements) {
if (elements == null) {
return object();
}
ObjectHistoneNode node = object();
for (Node item : elements) {
node.add(item);
}
return node;
}
public ObjectHistoneNode object(ArrayNode src) {
if (src == null) {
return object();
}
ObjectHistoneNode node = object();
for (JsonNode entry : src) {
node.add(jsonToNode(entry));
}
return node;
}
/**
* Create src type src and fill it with items from specified ObjectNode src
*
* @param src source src ot use for copying items from
* @return created obejct
*/
public ObjectHistoneNode object(ObjectNode src) {
if (src == null) {
return object();
}
ObjectHistoneNode node = object();
Iterator<Map.Entry<String, JsonNode>> iter = src.fields();
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
node.add(entry.getKey(), jsonToNode(entry.getValue()));
}
return node;
}
public Node jsonToNode(JsonNode json) {
if (json == null || json.isNull()) {
return this.NULL;
}
if (json.isArray()) {
return object((ArrayNode) json);
}
if (json.isObject()) {
return object((ObjectNode) json);
}
if (!json.isValueNode()) {
throw new IllegalArgumentException(String.format("Unknown type of JsonNode = '%s'", json.toString()));
}
if (json.isBoolean()) {
return json.booleanValue() ? this.TRUE : this.FALSE;
}
if (json.isNumber()) {
return number(json.decimalValue());
}
if (json.isTextual()) {
return string(json.asText());
}
throw new IllegalArgumentException(String.format("Unknown type of JsonNode = '%s'", json.toString()));
}
public ObjectNode jsonObject() {
return jackson.getNodeFactory().objectNode();
}
public ArrayNode jsonArray() {
return jackson.getNodeFactory().arrayNode();
}
public String toJsonString(JsonNode jsonNode) {
if (jsonNode.isBigDecimal()) {
BigDecimal number = ((DecimalNode) jsonNode).decimalValue();
return number.toPlainString();
+ } else if (jsonNode.isArray()) {
+ ArrayNode node = (ArrayNode) jsonNode;
+ StringBuilder sb = new StringBuilder();
+ sb.append('[');
+ if (node.size() != 0) {
+ Iterator<JsonNode> it = node.elements();
+ int count = 0;
+ for (; it.hasNext();) {
+ JsonNode en = it.next();
+ if (count > 0) {
+ sb.append(',');
+ }
+ ++count;
+ sb.append(toJsonString(en));
+ }
+ }
+ sb.append(']');
+ return sb.toString();
} else if (jsonNode.isObject()) {
ObjectNode objNode = (ObjectNode) jsonNode;
StringBuilder sb = new StringBuilder();
sb.append("{");
if (objNode.size() != 0) {
Iterator<Map.Entry<String, JsonNode>> it = ((ObjectNode) jsonNode).fields();
int count = 0;
for (; it.hasNext();) {
Map.Entry<String, JsonNode> en = it.next();
//don't show entry with only undefined node
if (en.getValue().isObject() && ((ObjectNode) en.getValue()).size() == 0) {
continue;
}
if (count > 0) {
sb.append(",");
}
++count;
sb.append('"');
CharTypes.appendQuoted(sb, en.getKey());
sb.append('"');
sb.append(':');
sb.append(toJsonString(en.getValue()));
}
}
sb.append("}");
return sb.toString();
}
return jsonNode.toString();
}
public StringHistoneNode string(JsonNode value) {
return new StringHistoneNode(this, value.asText());
}
public StringHistoneNode string(String value) {
return new StringHistoneNode(this, value);
}
public JsonNode jsonString(String value) {
return jackson.getNodeFactory().textNode(value);
}
/**
* Create number type object using specified value
*
* @param value value
* @return number type object
*/
public NumberHistoneNode number(BigDecimal value) {
return new NumberHistoneNode(this, value);
}
/**
* Create number type object using specified value
*
* @param value value
* @return number type object
*/
public NumberHistoneNode number(int value) {
return new NumberHistoneNode(this, BigDecimal.valueOf(value));
}
/**
* Create number type object using specified value
*
* @param value value
* @return number type object
* @throws NumberFormatException if {@code value} is infinite or NaN.
*/
public NumberHistoneNode number(double value) {
return new NumberHistoneNode(this, BigDecimal.valueOf(value));
}
public JsonNode jsonNumber(BigDecimal value) {
return jackson.getNodeFactory().numberNode(value);
}
public JsonNode jsonNumber(BigInteger val) {
return jackson.getNodeFactory().numberNode(val);
}
public JsonNode jsonNode(Reader reader) throws IOException {
return jackson.readTree(reader);
}
public Node string(InputStream resourceStream) throws IOException {
String content = IOUtils.toString(resourceStream, "UTF-8");
return string(content);
}
public StringHistoneNode string() {
return new StringHistoneNode(this, StringUtils.EMPTY);
}
public JsonNode jsonBoolean(Boolean value) {
return jackson.getNodeFactory().booleanNode(value);
}
public JsonNode jsonNull() {
return jackson.getNodeFactory().nullNode();
}
/**
* Create AST node using node type and node items
*
* @param type node type
* @param items items to put into node
* @return AST node
*/
public ArrayNode jsonArray(int type, JsonNode... items) {
ArrayNode result = jackson.createArrayNode();
result.add(jackson.getNodeFactory().numberNode(type));
fillArrayWithArgs(result, items);
return result;
}
/**
* Create JSON array using specified items
*
* @param items items to pout into array
* @return JSON array
*/
public ArrayNode jsonArray(JsonNode... items) {
ArrayNode result = jackson.createArrayNode();
fillArrayWithArgs(result, items);
return result;
}
private void fillArrayWithArgs(ArrayNode result, Object[] items) {
for (Object item : items) {
if (item instanceof String) {
result.add(jackson.getNodeFactory().textNode((String) item));
} else if (item instanceof Number) {
if (item instanceof BigDecimal) {
result.add(jackson.getNodeFactory().numberNode((BigDecimal) item));
} else if (item instanceof BigInteger) {
result.add(jackson.getNodeFactory().numberNode((BigInteger) item));
} else {
throw new RuntimeException("Type " + item.getClass() + " in unsupported");//TODO
}
} else if (item instanceof JsonNode) {
result.add((JsonNode) item);
} else if (item == null) {
result.add(jackson.getNodeFactory().nullNode());
}
}
}
public JsonNode removeLast(ArrayNode array) {
JsonNode result = null;
Iterator<JsonNode> iter = array.iterator();
while (iter.hasNext()) {
result = iter.next();
}
iter.remove();
return result;
}
}
| true | true | public String toJsonString(JsonNode jsonNode) {
if (jsonNode.isBigDecimal()) {
BigDecimal number = ((DecimalNode) jsonNode).decimalValue();
return number.toPlainString();
} else if (jsonNode.isObject()) {
ObjectNode objNode = (ObjectNode) jsonNode;
StringBuilder sb = new StringBuilder();
sb.append("{");
if (objNode.size() != 0) {
Iterator<Map.Entry<String, JsonNode>> it = ((ObjectNode) jsonNode).fields();
int count = 0;
for (; it.hasNext();) {
Map.Entry<String, JsonNode> en = it.next();
//don't show entry with only undefined node
if (en.getValue().isObject() && ((ObjectNode) en.getValue()).size() == 0) {
continue;
}
if (count > 0) {
sb.append(",");
}
++count;
sb.append('"');
CharTypes.appendQuoted(sb, en.getKey());
sb.append('"');
sb.append(':');
sb.append(toJsonString(en.getValue()));
}
}
sb.append("}");
return sb.toString();
}
return jsonNode.toString();
}
| public String toJsonString(JsonNode jsonNode) {
if (jsonNode.isBigDecimal()) {
BigDecimal number = ((DecimalNode) jsonNode).decimalValue();
return number.toPlainString();
} else if (jsonNode.isArray()) {
ArrayNode node = (ArrayNode) jsonNode;
StringBuilder sb = new StringBuilder();
sb.append('[');
if (node.size() != 0) {
Iterator<JsonNode> it = node.elements();
int count = 0;
for (; it.hasNext();) {
JsonNode en = it.next();
if (count > 0) {
sb.append(',');
}
++count;
sb.append(toJsonString(en));
}
}
sb.append(']');
return sb.toString();
} else if (jsonNode.isObject()) {
ObjectNode objNode = (ObjectNode) jsonNode;
StringBuilder sb = new StringBuilder();
sb.append("{");
if (objNode.size() != 0) {
Iterator<Map.Entry<String, JsonNode>> it = ((ObjectNode) jsonNode).fields();
int count = 0;
for (; it.hasNext();) {
Map.Entry<String, JsonNode> en = it.next();
//don't show entry with only undefined node
if (en.getValue().isObject() && ((ObjectNode) en.getValue()).size() == 0) {
continue;
}
if (count > 0) {
sb.append(",");
}
++count;
sb.append('"');
CharTypes.appendQuoted(sb, en.getKey());
sb.append('"');
sb.append(':');
sb.append(toJsonString(en.getValue()));
}
}
sb.append("}");
return sb.toString();
}
return jsonNode.toString();
}
|
diff --git a/src/main/java/net/pterodactylus/wotns/main/Resolver.java b/src/main/java/net/pterodactylus/wotns/main/Resolver.java
index 7ec725c..1c00144 100644
--- a/src/main/java/net/pterodactylus/wotns/main/Resolver.java
+++ b/src/main/java/net/pterodactylus/wotns/main/Resolver.java
@@ -1,125 +1,125 @@
/*
* WoTNS - Resolver.java - Copyright © 2011 David Roden
*
* 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
* (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 net.pterodactylus.wotns.main;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import net.pterodactylus.util.object.Default;
import net.pterodactylus.wotns.freenet.wot.Identity;
import net.pterodactylus.wotns.freenet.wot.IdentityManager;
import net.pterodactylus.wotns.freenet.wot.OwnIdentity;
import net.pterodactylus.wotns.freenet.wot.Trust;
import freenet.keys.FreenetURI;
/**
* TODO
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class Resolver {
private final IdentityManager identityManager;
private String ownIdentityId;
public Resolver(IdentityManager identityManager) {
this.identityManager = identityManager;
}
public void setOwnIdentityId(String ownIdentityId) {
this.ownIdentityId = ownIdentityId;
}
//
// ACTIONS
//
public FreenetURI resolveURI(String shortUri) throws MalformedURLException {
int firstSlash = shortUri.indexOf('/');
if (firstSlash == -1) {
throw new MalformedURLException("At least one slash is required.");
}
String shortName = shortUri.substring(0, firstSlash);
String target = shortUri.substring(firstSlash + 1);
Identity identity = locateIdentity(shortName);
System.out.println("located identity: " + identity);
if (identity == null) {
return null;
}
return new FreenetURI(identity.getProperty("tns." + target));
}
//
// PRIVATE METHODS
//
private Identity locateIdentity(String shortName) {
int atSign = shortName.indexOf('@');
String identityName = shortName;
String keyStart = "";
if (atSign > -1) {
identityName = shortName.substring(0, atSign);
keyStart = shortName.substring(atSign + 1);
}
@SuppressWarnings("hiding")
final OwnIdentity ownIdentity;
if (this.ownIdentityId == null) {
Set<OwnIdentity> ownIdentities = identityManager.getAllOwnIdentities();
if (!ownIdentities.isEmpty()) {
ownIdentity = ownIdentities.iterator().next();
} else {
ownIdentity = null;
}
} else {
ownIdentity = identityManager.getOwnIdentity(ownIdentityId);
}
if (ownIdentity == null) {
return null;
}
System.out.println("using own identity " + ownIdentity + " to resolve " + shortName);
- Set<Identity> trustedIdentities = Default.forNull(identityManager.getTrustedIdentities(ownIdentity), Collections.<Identity>emptySet());
+ Set<Identity> trustedIdentities = Default.forNull(identityManager.getTrustedIdentities(ownIdentity), Collections.<Identity> emptySet());
List<Identity> matchingIdentities = new ArrayList<Identity>();
System.out.println("checking " + trustedIdentities);
for (Identity identity : trustedIdentities) {
if (identity.getNickname().equals(identityName) && identity.getId().startsWith(keyStart)) {
matchingIdentities.add(identity);
}
}
if (matchingIdentities.isEmpty()) {
return null;
}
Collections.sort(matchingIdentities, new Comparator<Identity>() {
@Override
public int compare(Identity leftIdentity, Identity rightIdentity) {
Trust leftTrust = leftIdentity.getTrust(ownIdentity);
Trust rightTrust = rightIdentity.getTrust(ownIdentity);
int leftTrustCombined = ((leftTrust.getExplicit() != null) ? leftTrust.getExplicit() : 0) + ((leftTrust.getImplicit() != null) ? leftTrust.getImplicit() : 0);
int rightTrustCombined = ((rightTrust.getExplicit() != null) ? rightTrust.getExplicit() : 0) + ((rightTrust.getImplicit() != null) ? rightTrust.getImplicit() : 0);
return leftTrustCombined - rightTrustCombined;
}
});
return matchingIdentities.get(0);
}
}
| true | true | private Identity locateIdentity(String shortName) {
int atSign = shortName.indexOf('@');
String identityName = shortName;
String keyStart = "";
if (atSign > -1) {
identityName = shortName.substring(0, atSign);
keyStart = shortName.substring(atSign + 1);
}
@SuppressWarnings("hiding")
final OwnIdentity ownIdentity;
if (this.ownIdentityId == null) {
Set<OwnIdentity> ownIdentities = identityManager.getAllOwnIdentities();
if (!ownIdentities.isEmpty()) {
ownIdentity = ownIdentities.iterator().next();
} else {
ownIdentity = null;
}
} else {
ownIdentity = identityManager.getOwnIdentity(ownIdentityId);
}
if (ownIdentity == null) {
return null;
}
System.out.println("using own identity " + ownIdentity + " to resolve " + shortName);
Set<Identity> trustedIdentities = Default.forNull(identityManager.getTrustedIdentities(ownIdentity), Collections.<Identity>emptySet());
List<Identity> matchingIdentities = new ArrayList<Identity>();
System.out.println("checking " + trustedIdentities);
for (Identity identity : trustedIdentities) {
if (identity.getNickname().equals(identityName) && identity.getId().startsWith(keyStart)) {
matchingIdentities.add(identity);
}
}
if (matchingIdentities.isEmpty()) {
return null;
}
Collections.sort(matchingIdentities, new Comparator<Identity>() {
@Override
public int compare(Identity leftIdentity, Identity rightIdentity) {
Trust leftTrust = leftIdentity.getTrust(ownIdentity);
Trust rightTrust = rightIdentity.getTrust(ownIdentity);
int leftTrustCombined = ((leftTrust.getExplicit() != null) ? leftTrust.getExplicit() : 0) + ((leftTrust.getImplicit() != null) ? leftTrust.getImplicit() : 0);
int rightTrustCombined = ((rightTrust.getExplicit() != null) ? rightTrust.getExplicit() : 0) + ((rightTrust.getImplicit() != null) ? rightTrust.getImplicit() : 0);
return leftTrustCombined - rightTrustCombined;
}
});
return matchingIdentities.get(0);
}
| private Identity locateIdentity(String shortName) {
int atSign = shortName.indexOf('@');
String identityName = shortName;
String keyStart = "";
if (atSign > -1) {
identityName = shortName.substring(0, atSign);
keyStart = shortName.substring(atSign + 1);
}
@SuppressWarnings("hiding")
final OwnIdentity ownIdentity;
if (this.ownIdentityId == null) {
Set<OwnIdentity> ownIdentities = identityManager.getAllOwnIdentities();
if (!ownIdentities.isEmpty()) {
ownIdentity = ownIdentities.iterator().next();
} else {
ownIdentity = null;
}
} else {
ownIdentity = identityManager.getOwnIdentity(ownIdentityId);
}
if (ownIdentity == null) {
return null;
}
System.out.println("using own identity " + ownIdentity + " to resolve " + shortName);
Set<Identity> trustedIdentities = Default.forNull(identityManager.getTrustedIdentities(ownIdentity), Collections.<Identity> emptySet());
List<Identity> matchingIdentities = new ArrayList<Identity>();
System.out.println("checking " + trustedIdentities);
for (Identity identity : trustedIdentities) {
if (identity.getNickname().equals(identityName) && identity.getId().startsWith(keyStart)) {
matchingIdentities.add(identity);
}
}
if (matchingIdentities.isEmpty()) {
return null;
}
Collections.sort(matchingIdentities, new Comparator<Identity>() {
@Override
public int compare(Identity leftIdentity, Identity rightIdentity) {
Trust leftTrust = leftIdentity.getTrust(ownIdentity);
Trust rightTrust = rightIdentity.getTrust(ownIdentity);
int leftTrustCombined = ((leftTrust.getExplicit() != null) ? leftTrust.getExplicit() : 0) + ((leftTrust.getImplicit() != null) ? leftTrust.getImplicit() : 0);
int rightTrustCombined = ((rightTrust.getExplicit() != null) ? rightTrust.getExplicit() : 0) + ((rightTrust.getImplicit() != null) ? rightTrust.getImplicit() : 0);
return leftTrustCombined - rightTrustCombined;
}
});
return matchingIdentities.get(0);
}
|
diff --git a/user/test/com/google/gwt/user/client/WindowTest.java b/user/test/com/google/gwt/user/client/WindowTest.java
index 3f1ceef1b..d5f44078f 100644
--- a/user/test/com/google/gwt/user/client/WindowTest.java
+++ b/user/test/com/google/gwt/user/client/WindowTest.java
@@ -1,80 +1,80 @@
/*
* Copyright 2008 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.gwt.user.client;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Test Case for {@link Cookies}.
*/
public class WindowTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.user.User";
}
public void testLocation() {
// testing reload, replace, and assign seemed to hang our junit harness. Therefore
// only testing subset of Location that is testable.
// As we have no control over these values we cannot assert much about them.
String hash = Window.Location.getHash();
String host = Window.Location.getHost();
String hostName = Window.Location.getHostName();
String href = Window.Location.getHref();
assertNull(Window.Location.getParameter("fuzzy bunny"));
String path = Window.Location.getPath();
String port = Window.Location.getPort();
String protocol = Window.Location.getProtocol();
String query = Window.Location.getQueryString();
// Check that the sum is equal to its parts.
assertEquals(host, hostName + ":" + port);
assertEquals(href, protocol + "//" + host + path + query + hash);
}
/**
* Tests the ability of the Window to get the client size correctly with and
* without visible scroll bars.
*/
- public void testGetClientSize() {
+ public void disabledTestGetClientSize() {
// Get the dimensions without any scroll bars
Window.enableScrolling(false);
final int oldClientHeight = Window.getClientHeight();
final int oldClientWidth = Window.getClientWidth();
assertTrue(oldClientHeight > 0);
assertTrue(oldClientWidth > 0);
// Compare to the dimensions with scroll bars
Window.enableScrolling(true);
final Label largeDOM = new Label();
largeDOM.setPixelSize(oldClientWidth + 100, oldClientHeight + 100);
RootPanel.get().add(largeDOM);
DeferredCommand.addCommand(new Command() {
public void execute() {
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
assertTrue(newClientHeight < oldClientHeight);
assertTrue(newClientWidth < oldClientWidth);
finishTest();
}
});
delayTestFinish(200);
}
}
| true | true | public void testGetClientSize() {
// Get the dimensions without any scroll bars
Window.enableScrolling(false);
final int oldClientHeight = Window.getClientHeight();
final int oldClientWidth = Window.getClientWidth();
assertTrue(oldClientHeight > 0);
assertTrue(oldClientWidth > 0);
// Compare to the dimensions with scroll bars
Window.enableScrolling(true);
final Label largeDOM = new Label();
largeDOM.setPixelSize(oldClientWidth + 100, oldClientHeight + 100);
RootPanel.get().add(largeDOM);
DeferredCommand.addCommand(new Command() {
public void execute() {
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
assertTrue(newClientHeight < oldClientHeight);
assertTrue(newClientWidth < oldClientWidth);
finishTest();
}
});
delayTestFinish(200);
}
| public void disabledTestGetClientSize() {
// Get the dimensions without any scroll bars
Window.enableScrolling(false);
final int oldClientHeight = Window.getClientHeight();
final int oldClientWidth = Window.getClientWidth();
assertTrue(oldClientHeight > 0);
assertTrue(oldClientWidth > 0);
// Compare to the dimensions with scroll bars
Window.enableScrolling(true);
final Label largeDOM = new Label();
largeDOM.setPixelSize(oldClientWidth + 100, oldClientHeight + 100);
RootPanel.get().add(largeDOM);
DeferredCommand.addCommand(new Command() {
public void execute() {
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
assertTrue(newClientHeight < oldClientHeight);
assertTrue(newClientWidth < oldClientWidth);
finishTest();
}
});
delayTestFinish(200);
}
|
diff --git a/src/me/makskay/bukkit/tidy/tasks/KillExpiredIssuesTask.java b/src/me/makskay/bukkit/tidy/tasks/KillExpiredIssuesTask.java
index e2bfb1a..83d8d8a 100644
--- a/src/me/makskay/bukkit/tidy/tasks/KillExpiredIssuesTask.java
+++ b/src/me/makskay/bukkit/tidy/tasks/KillExpiredIssuesTask.java
@@ -1,34 +1,36 @@
package me.makskay.bukkit.tidy.tasks;
import java.util.Set;
import me.makskay.bukkit.tidy.TidyPlugin;
public class KillExpiredIssuesTask implements Runnable { // TODO this needs to be tested, it might hang if there's a bunch of issues
private TidyPlugin plugin;
public KillExpiredIssuesTask(TidyPlugin plugin) {
this.plugin = plugin;
}
public void run() {
boolean isOpen = true;
+ boolean isSticky = false;
String key = "";
Set<String> keys = plugin.issuesYml.getConfig().getConfigurationSection("issues").getKeys(false);
- while (isOpen) {
+ while (isOpen || isSticky) {
if (!keys.iterator().hasNext()) {
return;
}
key = keys.iterator().next();
isOpen = plugin.issuesYml.getConfig().getBoolean("issues." + key + ".open");
+ isSticky = plugin.issuesYml.getConfig().getBoolean("issues." + key + ".sticky");
}
long currentTime = System.currentTimeMillis();
long deltaTime = currentTime - plugin.issuesYml.getConfig().getLong("issues." + key + ".timestamp");
if (deltaTime > 259200000) { // 259200000 == 3 days (TODO make the number of days configurable)
plugin.issuesYml.getConfig().set("issues." + key, null);
}
}
}
| false | true | public void run() {
boolean isOpen = true;
String key = "";
Set<String> keys = plugin.issuesYml.getConfig().getConfigurationSection("issues").getKeys(false);
while (isOpen) {
if (!keys.iterator().hasNext()) {
return;
}
key = keys.iterator().next();
isOpen = plugin.issuesYml.getConfig().getBoolean("issues." + key + ".open");
}
long currentTime = System.currentTimeMillis();
long deltaTime = currentTime - plugin.issuesYml.getConfig().getLong("issues." + key + ".timestamp");
if (deltaTime > 259200000) { // 259200000 == 3 days (TODO make the number of days configurable)
plugin.issuesYml.getConfig().set("issues." + key, null);
}
}
| public void run() {
boolean isOpen = true;
boolean isSticky = false;
String key = "";
Set<String> keys = plugin.issuesYml.getConfig().getConfigurationSection("issues").getKeys(false);
while (isOpen || isSticky) {
if (!keys.iterator().hasNext()) {
return;
}
key = keys.iterator().next();
isOpen = plugin.issuesYml.getConfig().getBoolean("issues." + key + ".open");
isSticky = plugin.issuesYml.getConfig().getBoolean("issues." + key + ".sticky");
}
long currentTime = System.currentTimeMillis();
long deltaTime = currentTime - plugin.issuesYml.getConfig().getLong("issues." + key + ".timestamp");
if (deltaTime > 259200000) { // 259200000 == 3 days (TODO make the number of days configurable)
plugin.issuesYml.getConfig().set("issues." + key, null);
}
}
|
diff --git a/client/net/minecraftforge/client/ForgeHooksClient.java b/client/net/minecraftforge/client/ForgeHooksClient.java
index 154387072..9163e7255 100644
--- a/client/net/minecraftforge/client/ForgeHooksClient.java
+++ b/client/net/minecraftforge/client/ForgeHooksClient.java
@@ -1,281 +1,280 @@
package net.minecraftforge.client;
import java.util.HashMap;
import java.util.Random;
import java.util.TreeSet;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.client.FMLClientHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.client.texturepacks.ITexturePack;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.RenderEngine;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraftforge.client.event.DrawBlockHighlightEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.client.event.TextureLoadEvent;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.common.IArmorTextureProvider;
import net.minecraftforge.common.MinecraftForge;
import static net.minecraftforge.client.IItemRenderer.ItemRenderType.*;
import static net.minecraftforge.client.IItemRenderer.ItemRendererHelper.*;
public class ForgeHooksClient
{
static RenderEngine engine()
{
return FMLClientHandler.instance().getClient().renderEngine;
}
@Deprecated //Deprecated in 1.5.1, move to the more detailed one below.
@SuppressWarnings("deprecation")
public static String getArmorTexture(ItemStack armor, String _default)
{
String result = null;
if (armor.getItem() instanceof IArmorTextureProvider)
{
result = ((IArmorTextureProvider)armor.getItem()).getArmorTextureFile(armor);
}
return result != null ? result : _default;
}
public static String getArmorTexture(Entity entity, ItemStack armor, String _default, int slot, int layer)
{
String result = armor.getItem().getArmorTexture(armor, entity, slot, layer);
return result != null ? result : _default;
}
public static boolean renderEntityItem(EntityItem entity, ItemStack item, float bobing, float rotation, Random random, RenderEngine engine, RenderBlocks renderBlocks)
{
IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, ENTITY);
if (customRenderer == null)
{
return false;
}
if (customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_ROTATION))
{
GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F);
}
if (!customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_BOBBING))
{
GL11.glTranslatef(0.0F, -bobing, 0.0F);
}
boolean is3D = customRenderer.shouldUseRenderHelper(ENTITY, item, BLOCK_3D);
- if (item.getItem() instanceof ItemBlock && (is3D || RenderBlocks.renderItemIn3d(Block.blocksList[item.itemID].getRenderType())))
+ engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
+ if (is3D || (item.itemID < Block.blocksList.length && RenderBlocks.renderItemIn3d(Block.blocksList[item.itemID].getRenderType())))
{
- engine.bindTexture("/terrain.png");
- int renderType = Block.blocksList[item.itemID].getRenderType();
+ int renderType = (item.itemID < Block.blocksList.length ? Block.blocksList[item.itemID].getRenderType() : 1);
float scale = (renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2 ? 0.5F : 0.25F);
if (RenderItem.renderInFrame)
{
GL11.glScalef(1.25F, 1.25F, 1.25F);
GL11.glTranslatef(0.0F, 0.05F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
}
GL11.glScalef(scale, scale, scale);
int size = item.stackSize;
int count = (size > 20 ? 4 : (size > 5 ? 3 : (size > 1 ? 2 : 1)));
for(int j = 0; j < count; j++)
{
GL11.glPushMatrix();
if (j > 0)
{
GL11.glTranslatef(
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F);
}
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
GL11.glPopMatrix();
}
}
else
{
- engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
GL11.glScalef(0.5F, 0.5F, 0.5F);
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
}
return true;
}
public static boolean renderInventoryItem(RenderBlocks renderBlocks, RenderEngine engine, ItemStack item, boolean inColor, float zLevel, float x, float y)
{
IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, INVENTORY);
if (customRenderer == null)
{
return false;
}
engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
if (customRenderer.shouldUseRenderHelper(INVENTORY, item, INVENTORY_BLOCK))
{
GL11.glPushMatrix();
GL11.glTranslatef(x - 2, y + 3, -3.0F + zLevel);
GL11.glScalef(10F, 10F, 10F);
GL11.glTranslatef(1.0F, 0.5F, 1.0F);
GL11.glScalef(1.0F, 1.0F, -1F);
GL11.glRotatef(210F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(45F, 0.0F, 1.0F, 0.0F);
if(inColor)
{
int color = Item.itemsList[item.itemID].getColorFromItemStack(item, 0);
float r = (float)(color >> 16 & 0xff) / 255F;
float g = (float)(color >> 8 & 0xff) / 255F;
float b = (float)(color & 0xff) / 255F;
GL11.glColor4f(r, g, b, 1.0F);
}
GL11.glRotatef(-90F, 0.0F, 1.0F, 0.0F);
renderBlocks.useInventoryTint = inColor;
customRenderer.renderItem(INVENTORY, item, renderBlocks);
renderBlocks.useInventoryTint = true;
GL11.glPopMatrix();
}
else
{
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPushMatrix();
GL11.glTranslatef(x, y, -3.0F + zLevel);
if (inColor)
{
int color = Item.itemsList[item.itemID].getColorFromItemStack(item, 0);
float r = (float)(color >> 16 & 255) / 255.0F;
float g = (float)(color >> 8 & 255) / 255.0F;
float b = (float)(color & 255) / 255.0F;
GL11.glColor4f(r, g, b, 1.0F);
}
customRenderer.renderItem(INVENTORY, item, renderBlocks);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
}
return true;
}
public static void renderEquippedItem(IItemRenderer customRenderer, RenderBlocks renderBlocks, EntityLiving entity, ItemStack item)
{
if (customRenderer.shouldUseRenderHelper(EQUIPPED, item, EQUIPPED_BLOCK))
{
GL11.glPushMatrix();
GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
customRenderer.renderItem(EQUIPPED, item, renderBlocks, entity);
GL11.glPopMatrix();
}
else
{
GL11.glPushMatrix();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glTranslatef(0.0F, -0.3F, 0.0F);
GL11.glScalef(1.5F, 1.5F, 1.5F);
GL11.glRotatef(50.0F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(335.0F, 0.0F, 0.0F, 1.0F);
GL11.glTranslatef(-0.9375F, -0.0625F, 0.0F);
customRenderer.renderItem(EQUIPPED, item, renderBlocks, entity);
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPopMatrix();
}
}
//Optifine Helper Functions u.u, these are here specifically for Optifine
//Note: When using Optfine, these methods are invoked using reflection, which
//incurs a major performance penalty.
public static void orientBedCamera(Minecraft mc, EntityLiving entity)
{
int x = MathHelper.floor_double(entity.posX);
int y = MathHelper.floor_double(entity.posY);
int z = MathHelper.floor_double(entity.posZ);
Block block = Block.blocksList[mc.theWorld.getBlockId(x, y, z)];
if (block != null && block.isBed(mc.theWorld, x, y, z, entity))
{
int var12 = block.getBedDirection(mc.theWorld, x, y, z);
GL11.glRotatef((float)(var12 * 90), 0.0F, 1.0F, 0.0F);
}
}
public static boolean onDrawBlockHighlight(RenderGlobal context, EntityPlayer player, MovingObjectPosition target, int subID, ItemStack currentItem, float partialTicks)
{
return MinecraftForge.EVENT_BUS.post(new DrawBlockHighlightEvent(context, player, target, subID, currentItem, partialTicks));
}
public static void dispatchRenderLast(RenderGlobal context, float partialTicks)
{
MinecraftForge.EVENT_BUS.post(new RenderWorldLastEvent(context, partialTicks));
}
public static void onTextureLoad(String texture, ITexturePack pack)
{
MinecraftForge.EVENT_BUS.post(new TextureLoadEvent(texture, pack));
}
public static void onTextureStitchedPre(TextureMap map)
{
MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Pre(map));
}
public static void onTextureStitchedPost(TextureMap map)
{
MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Post(map));
}
/**
* This is added for Optifine's convenience. And to explode if a ModMaker is developing.
* @param texture
*/
public static void onTextureLoadPre(String texture)
{
if (Tessellator.renderingWorldRenderer)
{
String msg = String.format("Warning: Texture %s not preloaded, will cause render glitches!", texture);
System.out.println(msg);
if (Tessellator.class.getPackage() != null)
{
if (Tessellator.class.getPackage().getName().startsWith("net.minecraft."))
{
Minecraft mc = FMLClientHandler.instance().getClient();
if (mc.ingameGUI != null)
{
mc.ingameGUI.getChatGUI().printChatMessage(msg);
}
}
}
}
}
static int renderPass = -1;
public static void setRenderPass(int pass)
{
renderPass = pass;
}
public static ModelBiped getArmorModel(EntityLiving entityLiving, ItemStack itemStack, int slotID, ModelBiped _default)
{
ModelBiped modelbiped = itemStack.getItem().getArmorModel(entityLiving, itemStack, slotID);
return modelbiped == null ? _default : modelbiped;
}
}
| false | true | public static boolean renderEntityItem(EntityItem entity, ItemStack item, float bobing, float rotation, Random random, RenderEngine engine, RenderBlocks renderBlocks)
{
IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, ENTITY);
if (customRenderer == null)
{
return false;
}
if (customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_ROTATION))
{
GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F);
}
if (!customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_BOBBING))
{
GL11.glTranslatef(0.0F, -bobing, 0.0F);
}
boolean is3D = customRenderer.shouldUseRenderHelper(ENTITY, item, BLOCK_3D);
if (item.getItem() instanceof ItemBlock && (is3D || RenderBlocks.renderItemIn3d(Block.blocksList[item.itemID].getRenderType())))
{
engine.bindTexture("/terrain.png");
int renderType = Block.blocksList[item.itemID].getRenderType();
float scale = (renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2 ? 0.5F : 0.25F);
if (RenderItem.renderInFrame)
{
GL11.glScalef(1.25F, 1.25F, 1.25F);
GL11.glTranslatef(0.0F, 0.05F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
}
GL11.glScalef(scale, scale, scale);
int size = item.stackSize;
int count = (size > 20 ? 4 : (size > 5 ? 3 : (size > 1 ? 2 : 1)));
for(int j = 0; j < count; j++)
{
GL11.glPushMatrix();
if (j > 0)
{
GL11.glTranslatef(
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F);
}
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
GL11.glPopMatrix();
}
}
else
{
engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
GL11.glScalef(0.5F, 0.5F, 0.5F);
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
}
return true;
}
| public static boolean renderEntityItem(EntityItem entity, ItemStack item, float bobing, float rotation, Random random, RenderEngine engine, RenderBlocks renderBlocks)
{
IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, ENTITY);
if (customRenderer == null)
{
return false;
}
if (customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_ROTATION))
{
GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F);
}
if (!customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_BOBBING))
{
GL11.glTranslatef(0.0F, -bobing, 0.0F);
}
boolean is3D = customRenderer.shouldUseRenderHelper(ENTITY, item, BLOCK_3D);
engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
if (is3D || (item.itemID < Block.blocksList.length && RenderBlocks.renderItemIn3d(Block.blocksList[item.itemID].getRenderType())))
{
int renderType = (item.itemID < Block.blocksList.length ? Block.blocksList[item.itemID].getRenderType() : 1);
float scale = (renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2 ? 0.5F : 0.25F);
if (RenderItem.renderInFrame)
{
GL11.glScalef(1.25F, 1.25F, 1.25F);
GL11.glTranslatef(0.0F, 0.05F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
}
GL11.glScalef(scale, scale, scale);
int size = item.stackSize;
int count = (size > 20 ? 4 : (size > 5 ? 3 : (size > 1 ? 2 : 1)));
for(int j = 0; j < count; j++)
{
GL11.glPushMatrix();
if (j > 0)
{
GL11.glTranslatef(
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F);
}
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
GL11.glPopMatrix();
}
}
else
{
GL11.glScalef(0.5F, 0.5F, 0.5F);
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
}
return true;
}
|
diff --git a/src/main/java/org/spout/engine/world/SpoutBlock.java b/src/main/java/org/spout/engine/world/SpoutBlock.java
index c8eb3b207..ab1701cd4 100644
--- a/src/main/java/org/spout/engine/world/SpoutBlock.java
+++ b/src/main/java/org/spout/engine/world/SpoutBlock.java
@@ -1,308 +1,308 @@
/*
* This file is part of SpoutAPI (http://www.spout.org/).
*
* SpoutAPI is licensed under the SpoutDev License Version 1.
*
* SpoutAPI 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* SpoutAPI 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,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.engine.world;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.spout.api.Source;
import org.spout.api.entity.BlockController;
import org.spout.api.generator.biome.Biome;
import org.spout.api.geo.World;
import org.spout.api.geo.cuboid.Block;
import org.spout.api.geo.cuboid.Chunk;
import org.spout.api.geo.cuboid.Region;
import org.spout.api.geo.discrete.Point;
import org.spout.api.material.BlockMaterial;
import org.spout.api.material.block.BlockFace;
import org.spout.api.material.source.DataSource;
import org.spout.api.material.source.MaterialSource;
import org.spout.api.math.Vector3;
import org.spout.api.util.StringUtil;
public class SpoutBlock implements Block {
private int x, y, z;
private World world;
private Source source;
private Chunk chunk;
public SpoutBlock(Block source) {
this(source.getWorld(), source.getX(), source.getY(), source.getZ(), source.getSource());
if (source instanceof SpoutBlock) {
this.chunk = ((SpoutBlock) source).chunk;
}
}
public SpoutBlock(Point position, Source source) {
this(position.getWorld(), position.getBlockX(), position.getBlockY(), position.getBlockZ(), source);
}
public SpoutBlock(World world, int x, int y, int z, Source source) {
this(world, x, y, z, null, source);
}
public SpoutBlock(World world, int x, int y, int z, Chunk chunk, Source source) {
this.x = x;
this.y = y;
this.z = z;
this.world = world;
this.source = source == null ? world : source;
this.chunk = chunk != null && chunk.containsBlock(x, y, z) ? chunk : null;
}
@Override
public Point getPosition() {
return new Point(this.world, this.x + 0.5f, this.y + 0.5f, this.z + 0.5f);
}
@Override
public Chunk getChunk() {
if (this.chunk == null || !this.chunk.isLoaded()) {
this.chunk = this.world.getChunkFromBlock(this.x, this.y, this.z, true);
}
return this.chunk;
}
@Override
public World getWorld() {
return this.world;
}
@Override
public int getX() {
return this.x;
}
@Override
public int getY() {
return this.y;
}
@Override
public int getZ() {
return this.z;
}
@Override
public Block setX(int x) {
SpoutBlock sb = this.clone();
sb.x = x;
sb.chunk = null;
return sb;
}
@Override
public Block setY(int y) {
SpoutBlock sb = this.clone();
sb.y = y;
sb.chunk = null;
return sb;
}
@Override
public Block setZ(int z) {
SpoutBlock sb = this.clone();
sb.z = z;
sb.chunk = null;
return sb;
}
@Override
public Block translate(BlockFace offset) {
return this.translate(offset.getOffset());
}
@Override
public Block translate(Vector3 offset) {
return this.translate((int) offset.getX(), (int) offset.getY(), (int) offset.getZ());
}
@Override
public Block translate(int dx, int dy, int dz) {
SpoutBlock sb = this.clone();
sb.x += dx;
sb.y += dy;
sb.z += dz;
sb.chunk = null;
return sb;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (other != null && other instanceof Block) {
Block b = (Block) other;
return b.getWorld() == this.getWorld() && b.getX() == this.getX() && b.getY() == this.getY() && b.getZ() == this.getZ();
} else {
return false;
}
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(getWorld()).append(getX()).append(getY()).append(getZ()).toHashCode();
}
@Override
public SpoutBlock clone() {
return new SpoutBlock(this);
}
@Override
public String toString() {
return StringUtil.toNamedString(this, this.world, this.x, this.y, this.z);
}
@Override
public SpoutBlock setMaterial(MaterialSource material, int data) {
if (material.getMaterial() instanceof BlockMaterial) {
this.getChunk().setBlockMaterial(this.x, y, z, (BlockMaterial) material.getMaterial(), (short) data, this.source);
} else {
throw new IllegalArgumentException("Can't set a block to a non-block material!");
}
return this;
}
@Override
public SpoutBlock setData(DataSource data) {
return this.setData(data.getData());
}
@Override
public SpoutBlock setData(int data) {
this.getChunk().setBlockData(this.x, this.y, this.z, (short) data, this.source);
return this;
}
@Override
public short getData() {
return this.getChunk().getBlockData(this.x, this.y, this.z);
}
@Override
public Source getSource() {
return this.source;
}
@Override
public Block setSource(Source source) {
SpoutBlock block = this.clone();
block.source = source == null ? block.world : source;
return block;
}
@Override
public BlockMaterial getSubMaterial() {
return this.getMaterial().getSubMaterial(this.getData());
}
@Override
public Region getRegion() {
return this.getChunk().getRegion();
}
@Override
public BlockMaterial getMaterial() {
return this.getChunk().getBlockMaterial(this.x, this.y, this.z);
}
@Override
public Block setMaterial(MaterialSource material) {
return this.setMaterial(material, material.getData());
}
@Override
public Block setMaterial(MaterialSource material, DataSource data) {
return this.setMaterial(material, data.getData());
}
@Override
public byte getLight() {
return this.getChunk().getBlockLight(this.x, this.y, this.z);
}
@Override
public Block setLight(byte level) {
this.getChunk().setBlockLight(this.x, this.y, this.z, level, this.source);
return this;
}
@Override
public byte getSkyLight() {
return this.getChunk().getBlockSkyLight(this.x, this.y, this.z);
}
@Override
public Block setSkyLight(byte level) {
this.getChunk().setBlockSkyLight(this.x, this.y, this.z, level, this.source);
return this;
}
@Override
public BlockController getController() {
return getRegion().getBlockController(x, y, z);
}
@Override
public Block setController(BlockController controller) {
getRegion().setBlockController(x, y, z, controller);
return this;
}
@Override
public boolean hasController() {
return getController() != null;
}
@Override
public Block update() {
return this.update(true);
}
@Override
public Block update(boolean around) {
- Chunk chunk = this.getChunk();
- chunk.updateBlockPhysics(this.x, this.y, this.z, this.source);
+ World world = this.getWorld();
+ world.updateBlockPhysics(this.x, this.y, this.z, this.source);
if (around) {
//South and North
- chunk.updateBlockPhysics(this.x + 1, this.y, this.z, this.source);
- chunk.updateBlockPhysics(this.x - 1, this.y, this.z, this.source);
+ world.updateBlockPhysics(this.x + 1, this.y, this.z, this.source);
+ world.updateBlockPhysics(this.x - 1, this.y, this.z, this.source);
//West and East
- chunk.updateBlockPhysics(this.x, this.y, this.z + 1, this.source);
- chunk.updateBlockPhysics(this.x, this.y, this.z - 1, this.source);
+ world.updateBlockPhysics(this.x, this.y, this.z + 1, this.source);
+ world.updateBlockPhysics(this.x, this.y, this.z - 1, this.source);
//Above and Below
- chunk.updateBlockPhysics(this.x, this.y + 1, this.z, this.source);
- chunk.updateBlockPhysics(this.x, this.y - 1, this.z, this.source);
+ world.updateBlockPhysics(this.x, this.y + 1, this.z, this.source);
+ world.updateBlockPhysics(this.x, this.y - 1, this.z, this.source);
}
return this;
}
@Override
public Biome getBiomeType() {
return world.getBiomeType(x, y, z);
}
}
| false | true | public Block update(boolean around) {
Chunk chunk = this.getChunk();
chunk.updateBlockPhysics(this.x, this.y, this.z, this.source);
if (around) {
//South and North
chunk.updateBlockPhysics(this.x + 1, this.y, this.z, this.source);
chunk.updateBlockPhysics(this.x - 1, this.y, this.z, this.source);
//West and East
chunk.updateBlockPhysics(this.x, this.y, this.z + 1, this.source);
chunk.updateBlockPhysics(this.x, this.y, this.z - 1, this.source);
//Above and Below
chunk.updateBlockPhysics(this.x, this.y + 1, this.z, this.source);
chunk.updateBlockPhysics(this.x, this.y - 1, this.z, this.source);
}
return this;
}
| public Block update(boolean around) {
World world = this.getWorld();
world.updateBlockPhysics(this.x, this.y, this.z, this.source);
if (around) {
//South and North
world.updateBlockPhysics(this.x + 1, this.y, this.z, this.source);
world.updateBlockPhysics(this.x - 1, this.y, this.z, this.source);
//West and East
world.updateBlockPhysics(this.x, this.y, this.z + 1, this.source);
world.updateBlockPhysics(this.x, this.y, this.z - 1, this.source);
//Above and Below
world.updateBlockPhysics(this.x, this.y + 1, this.z, this.source);
world.updateBlockPhysics(this.x, this.y - 1, this.z, this.source);
}
return this;
}
|
diff --git a/src/main/java/no/steria/swhrs/RegistrationServlet.java b/src/main/java/no/steria/swhrs/RegistrationServlet.java
index 93cdbaf..15d1fc3 100644
--- a/src/main/java/no/steria/swhrs/RegistrationServlet.java
+++ b/src/main/java/no/steria/swhrs/RegistrationServlet.java
@@ -1,106 +1,106 @@
package no.steria.swhrs;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.ajax.JSONObjectConvertor;
import org.joda.time.LocalDate;
import org.json.JSONWriter;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class RegistrationServlet extends HttpServlet{
private static final long serialVersionUID = -1090477374982937503L;
private HibernateHourRegDao db;
public void init() throws ServletException {
db = new HibernateHourRegDao(Parameters.DB_JNDI);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getRequestURL().toString().contains(("hours/list"))) {
resp.setContentType("application/json");
List<HourRegistration> hrlist = db.getHours(1, LocalDate.now());
JSONObject json = new JSONObject();
for (HourRegistration hr: hrlist) {
json.put(Integer.toString(hr.getProjectnumber()), hr.getHours());
}
String jsonText = json.toString();
System.out.println(jsonText);
resp.getWriter().write(jsonText);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getRequestURL().toString().contains(("hours/registration"))) {
int personId = Integer.parseInt(req.getParameter("personId"));
String favourite = req.getParameter("fav");
String pNr = req.getParameter("projectNr");
int projectNr = Integer.parseInt(req.getParameter("projectNr").trim());
double hours = Double.parseDouble(req.getParameter("hours"));
String date = req.getParameter("date");
System.out.println("Trying to save project: " + pNr);
saveRegToDatabase(personId, projectNr, LocalDate.now(), hours);
}
if (req.getRequestURL().toString().contains(("hours/login"))) {
System.out.println("Kom hit");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("Username:" +username+" Password: "+password);
int autoLoginExpire = (60*60*24);
- //Byttes ut n�r database er oppe
+ //Change this when database is up
//if(db.validateUser(username, password) == true){
if(username.equals("steria") && password.equals("123")){
Cookie loginCookie = new Cookie("USERNAME", username);
loginCookie.setMaxAge(autoLoginExpire);
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.append("Login ok");
}else{
resp.setStatus(403);
System.out.println("FAIL");
}
}
}
private void saveRegToDatabase(int personId, int projectNr, LocalDate date, double hours) {
HourRegistration reg = HourRegistration.createRegistration(personId, projectNr, LocalDate.now(), hours);
db.saveHours(reg);
System.out.println("Saving registration with data: " + projectNr + "," +hours+ ", " +LocalDate.now());
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
db.beginTransaction();
super.service(req, resp);
db.endTransaction(true);
//TODO sleng p� en finally her s� den ender transaksjonen hvis servleten kr�sjer
}
}
| true | true | protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getRequestURL().toString().contains(("hours/registration"))) {
int personId = Integer.parseInt(req.getParameter("personId"));
String favourite = req.getParameter("fav");
String pNr = req.getParameter("projectNr");
int projectNr = Integer.parseInt(req.getParameter("projectNr").trim());
double hours = Double.parseDouble(req.getParameter("hours"));
String date = req.getParameter("date");
System.out.println("Trying to save project: " + pNr);
saveRegToDatabase(personId, projectNr, LocalDate.now(), hours);
}
if (req.getRequestURL().toString().contains(("hours/login"))) {
System.out.println("Kom hit");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("Username:" +username+" Password: "+password);
int autoLoginExpire = (60*60*24);
//Byttes ut n�r database er oppe
//if(db.validateUser(username, password) == true){
if(username.equals("steria") && password.equals("123")){
Cookie loginCookie = new Cookie("USERNAME", username);
loginCookie.setMaxAge(autoLoginExpire);
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.append("Login ok");
}else{
resp.setStatus(403);
System.out.println("FAIL");
}
}
}
| protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getRequestURL().toString().contains(("hours/registration"))) {
int personId = Integer.parseInt(req.getParameter("personId"));
String favourite = req.getParameter("fav");
String pNr = req.getParameter("projectNr");
int projectNr = Integer.parseInt(req.getParameter("projectNr").trim());
double hours = Double.parseDouble(req.getParameter("hours"));
String date = req.getParameter("date");
System.out.println("Trying to save project: " + pNr);
saveRegToDatabase(personId, projectNr, LocalDate.now(), hours);
}
if (req.getRequestURL().toString().contains(("hours/login"))) {
System.out.println("Kom hit");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("Username:" +username+" Password: "+password);
int autoLoginExpire = (60*60*24);
//Change this when database is up
//if(db.validateUser(username, password) == true){
if(username.equals("steria") && password.equals("123")){
Cookie loginCookie = new Cookie("USERNAME", username);
loginCookie.setMaxAge(autoLoginExpire);
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.append("Login ok");
}else{
resp.setStatus(403);
System.out.println("FAIL");
}
}
}
|
diff --git a/c/YetiType.java b/c/YetiType.java
index 44779b7..4d04d63 100644
--- a/c/YetiType.java
+++ b/c/YetiType.java
@@ -1,1610 +1,1614 @@
// ex: set sts=4 sw=4 expandtab:
/**
* Yeti type analyzer.
* Uses Hindley-Milner type inference algorithm
* with extensions for polymorphic structs and variants.
* Copyright (c) 2007,2008 Madis Janson
* 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 name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS 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 AUTHOR 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.
*/
package yeti.lang.compiler;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public final class YetiType implements YetiParser, YetiBuiltins {
static final int VAR = 0;
static final int UNIT = 1;
static final int STR = 2;
static final int NUM = 3;
static final int BOOL = 4;
static final int CHAR = 5;
static final int NONE = 6;
static final int LIST_MARKER = 7;
static final int MAP_MARKER = 8;
static final int FUN = 9; // a -> b
static final int MAP = 10; // value, index, (LIST | MAP)
static final int STRUCT = 11;
static final int VARIANT = 12;
static final int JAVA = 13;
static final int JAVA_ARRAY = 14;
static final int FL_ORDERED_REQUIRED = 1;
static final int FIELD_NON_POLYMORPHIC = 1;
static final int FIELD_MUTABLE = 2;
static final Type[] NO_PARAM = {};
static final Type UNIT_TYPE = new Type(UNIT, NO_PARAM);
static final Type NUM_TYPE = new Type(NUM, NO_PARAM);
static final Type STR_TYPE = new Type(STR, NO_PARAM);
static final Type BOOL_TYPE = new Type(BOOL, NO_PARAM);
static final Type CHAR_TYPE = new Type(CHAR, NO_PARAM);
static final Type NO_TYPE = new Type(NONE, NO_PARAM);
static final Type LIST_TYPE = new Type(LIST_MARKER, NO_PARAM);
static final Type MAP_TYPE = new Type(MAP_MARKER, NO_PARAM);
static final Type ORDERED = orderedVar(1);
static final Type A = new Type(1);
static final Type B = new Type(1);
static final Type C = new Type(1);
static final Type D = new Type(1);
static final Type EQ_TYPE = fun2Arg(A, A, BOOL_TYPE);
static final Type LG_TYPE = fun2Arg(ORDERED, ORDERED, BOOL_TYPE);
static final Type NUMOP_TYPE = fun2Arg(NUM_TYPE, NUM_TYPE, NUM_TYPE);
static final Type BOOLOP_TYPE = fun2Arg(BOOL_TYPE, BOOL_TYPE, BOOL_TYPE);
static final Type A_B_LIST_TYPE =
new Type(MAP, new Type[] { A, B, LIST_TYPE });
static final Type C_B_LIST_TYPE =
new Type(MAP, new Type[] { C, B, LIST_TYPE });
static final Type NUM_LIST_TYPE =
new Type(MAP, new Type[] { NUM_TYPE, B, LIST_TYPE });
static final Type A_B_MAP_TYPE =
new Type(MAP, new Type[] { B, A, MAP_TYPE });
static final Type A_B_C_MAP_TYPE =
new Type(MAP, new Type[] { B, A, C });
static final Type A_LIST_TYPE =
new Type(MAP, new Type[] { A, NO_TYPE, LIST_TYPE });
static final Type C_LIST_TYPE =
new Type(MAP, new Type[] { C, NO_TYPE, LIST_TYPE });
static final Type D_LIST_TYPE =
new Type(MAP, new Type[] { D, NO_TYPE, LIST_TYPE });
static final Type A_MLIST_TYPE =
new Type(MAP, new Type[] { A, NUM_TYPE, LIST_TYPE });
static final Type STRING_ARRAY =
new Type(MAP, new Type[] { STR_TYPE, NUM_TYPE, LIST_TYPE });
static final Type CONS_TYPE = fun2Arg(A, A_B_LIST_TYPE, A_LIST_TYPE);
static final Type LAZYCONS_TYPE =
fun2Arg(A, fun(C, A_B_LIST_TYPE), A_LIST_TYPE);
static final Type A_TO_UNIT = fun(A, UNIT_TYPE);
static final Type IN_TYPE = fun2Arg(A, A_B_MAP_TYPE, BOOL_TYPE);
static final Type COMPOSE_TYPE = fun2Arg(fun(B, C), fun(A, B), fun(A, C));
static final Type BOOL_TO_BOOL = fun(BOOL_TYPE, BOOL_TYPE);
static final Type FOR_TYPE =
fun2Arg(A_B_LIST_TYPE, fun(A, UNIT_TYPE), UNIT_TYPE);
static final Type STR2_PRED_TYPE = fun2Arg(STR_TYPE, STR_TYPE, BOOL_TYPE);
static final Type[] PRIMITIVES =
{ null, UNIT_TYPE, STR_TYPE, NUM_TYPE, BOOL_TYPE, CHAR_TYPE,
NO_TYPE, LIST_TYPE, MAP_TYPE };
static final String[] TYPE_NAMES =
{ "var", "()", "string", "number", "boolean", "char",
"none", "list", "hash", "fun", "list", "struct", "variant",
"object" };
static final Scope ROOT_SCOPE =
bindCompare("==", EQ_TYPE, COND_EQ, // equals returns 0 for false
bindCompare("!=", EQ_TYPE, COND_NOT, // equals returns 0 for false
bindCompare("<" , LG_TYPE, COND_LT,
bindCompare("<=", LG_TYPE, COND_LE,
bindCompare(">" , LG_TYPE, COND_GT,
bindCompare(">=", LG_TYPE, COND_GE,
bindPoly("_argv", STRING_ARRAY, new Argv(), 0,
bindPoly(".", COMPOSE_TYPE, new Compose(), 0,
bindCore("id", fun(A, A), "ID",
bindCore("const", fun2Arg(A, B, A), "CONST",
bindCore("flip", fun(fun2Arg(A, B, C), fun2Arg(B, A, C)), "FLIP",
bindCore("print", A_TO_UNIT, "PRINT",
bindCore("println", A_TO_UNIT, "PRINTLN",
bindCore("readln", fun(UNIT_TYPE, STR_TYPE), "READLN",
bindCore("number", fun(STR_TYPE, NUM_TYPE), "NUM",
bindCore("randomInt", fun(NUM_TYPE, NUM_TYPE), "RANDINT",
bindCore("array", fun(A_B_LIST_TYPE, A_MLIST_TYPE), "ARRAY",
bindCore("reverse", fun(A_B_LIST_TYPE, A_LIST_TYPE), "REVERSE",
bindCore("head", fun(A_B_LIST_TYPE, A), "HEAD",
bindCore("tail", fun(A_B_LIST_TYPE, A_LIST_TYPE), "TAIL",
bindCore("forHash",
fun2Arg(A_B_MAP_TYPE, fun2Arg(A, B, UNIT_TYPE), UNIT_TYPE),
"FORHASH",
bindCore("map",
fun2Arg(fun(A, C), A_B_LIST_TYPE, C_B_LIST_TYPE), "MAP",
bindCore("map2",
fun(fun2Arg(A, C, D),
fun2Arg(A_B_LIST_TYPE, C_B_LIST_TYPE, D_LIST_TYPE)), "MAP2",
bindCore("mapHash",
fun2Arg(fun2Arg(A, B, C), A_B_MAP_TYPE, C_LIST_TYPE), "MAPHASH",
bindCore("fold",
fun2Arg(fun2Arg(C, A, C), C, fun(A_B_LIST_TYPE, C)), "FOLD",
bindCore("filter",
fun2Arg(fun(A, BOOL_TYPE), A_B_LIST_TYPE, A_LIST_TYPE), "FILTER",
bindCore("find",
fun2Arg(fun(A, BOOL_TYPE), A_B_LIST_TYPE, A_LIST_TYPE), "FIND",
bindCore("contains", fun2Arg(A, A_B_LIST_TYPE, BOOL_TYPE), "CONTAINS",
bindCore("any",
fun2Arg(fun(A, BOOL_TYPE), A_B_LIST_TYPE, BOOL_TYPE), "ANY",
bindCore("all",
fun2Arg(fun(A, BOOL_TYPE), A_B_LIST_TYPE, BOOL_TYPE), "ALL",
bindCore("index", fun2Arg(A, A_B_LIST_TYPE, NUM_TYPE), "INDEX",
bindCore("sum", fun(NUM_LIST_TYPE, NUM_TYPE), "SUM",
bindCore("setHashDefault",
fun2Arg(A_B_MAP_TYPE, fun(A, B), UNIT_TYPE), "SET_HASH_DEFAULT",
bindCore("at", fun2Arg(A_B_C_MAP_TYPE, A, B), "AT",
bindCore("empty?", fun(A_B_LIST_TYPE, BOOL_TYPE), "EMPTY",
bindCore("min", fun2Arg(ORDERED, ORDERED, ORDERED), "MIN",
bindCore("max", fun2Arg(ORDERED, ORDERED, ORDERED), "MAX",
bindCore("fromSome", fun2Arg(C, fun(A, C), fun(variantOf(
new String[] { "Some", "None" }, new Type[] { A, B }), C)),
"FROM_SOME",
bindCore("replace",
fun2Arg(STR_TYPE, STR_TYPE, fun(STR_TYPE, STR_TYPE)), "REPLACE",
bindPoly("in", IN_TYPE, new InOp(), 0,
bindPoly("::", CONS_TYPE, new Cons(), 0,
bindPoly(":.", LAZYCONS_TYPE, new LazyCons(), 0,
bindPoly("ignore", A_TO_UNIT, new Ignore(), 0,
bindPoly("for", FOR_TYPE, new For(), 0,
bindScope("+", new ArithOpFun("add", NUMOP_TYPE),
bindScope("-", new ArithOpFun("sub", NUMOP_TYPE),
bindScope("*", new ArithOpFun("mul", NUMOP_TYPE),
bindScope("/", new ArithOpFun("div", NUMOP_TYPE),
bindScope("%", new ArithOpFun("rem", NUMOP_TYPE),
bindScope("div", new ArithOpFun("intDiv", NUMOP_TYPE),
bindScope("shl", new ArithOpFun("shl", NUMOP_TYPE),
bindScope("shr", new ArithOpFun("shr", NUMOP_TYPE),
bindScope("=~", new MatchOpFun(),
bindScope("not", new NotOp(),
bindScope("and", new BoolOpFun(false),
bindScope("or", new BoolOpFun(true),
bindScope("false", new BooleanConstant(false),
bindScope("true", new BooleanConstant(true),
null))))))))))))))))))))))))))))))))))))))))))))))))))))))))));
static Scope bindScope(String name, Binder binder, Scope scope) {
return new Scope(scope, name, binder);
}
static Scope bindCompare(String op, Type type, int code, Scope scope) {
return bindPoly(op, type, new Compare(type, code), 0, scope);
}
static Scope bindCore(String name, Type type, String field, Scope scope) {
return bindPoly(name, type, new CoreFun(type, field), 0, scope);
}
static Type fun(Type a, Type res) {
return new Type(FUN, new Type[] { a, res });
}
static Type fun2Arg(Type a, Type b, Type res) {
return new Type(FUN,
new Type[] { a, new Type(FUN, new Type[] { b, res }) });
}
static Type variantOf(String[] na, Type[] ta) {
Type t = new Type(VARIANT, ta);
t.partialMembers = new HashMap();
for (int i = 0; i < na.length; ++i) {
t.partialMembers.put(na[i], ta[i]);
}
return t;
}
static final class Type {
int type;
Map partialMembers;
Map finalMembers;
Type[] param;
Type ref;
int depth;
int flags;
int field;
boolean seen;
JavaType javaType;
Type(int depth) {
this.depth = depth;
}
Type(int type, Type[] param) {
this.type = type;
this.param = param;
}
Type(String javaSig) {
type = JAVA;
this.javaType = JavaType.fromDescription(javaSig);
param = NO_PARAM;
}
private String hstr(Map vars, Map refs) {
StringBuffer res = new StringBuffer();
boolean variant = type == VARIANT;
if (partialMembers != null) {
for (Iterator i = partialMembers.entrySet().iterator();
i.hasNext();) {
Map.Entry e = (Map.Entry) i.next();
if (res.length() != 0) {
res.append(variant ? " | " : "; ");
}
res.append(e.getKey());
res.append(variant ? " " : " is ");
res.append(((Type) e.getValue()).str(vars, refs));
}
}
if (finalMembers != null) {
for (Iterator i = finalMembers.entrySet().iterator();
i.hasNext();) {
Map.Entry e = (Map.Entry) i.next();
if (partialMembers != null &&
partialMembers.containsKey(e.getKey())) {
continue;
}
if (res.length() != 0) {
res.append(variant ? " | " : "; .");
}
res.append(e.getKey());
res.append(variant ? " " : " is ");
res.append(((Type) e.getValue()).str(vars, refs));
}
}
return res.toString();
}
private String getVarName(Map vars) {
String v = (String) vars.get(this);
if (v == null) {
v = "'";
int n = vars.size();
do {
v += (char) ('a' + n % 26);
n /= 26;
} while (n > 0);
vars.put(this, v);
}
return v;
}
String str(Map vars, Map refs) {
if (ref != null) {
return ref.str(vars, refs);
}
if (type == VAR) {
return getVarName(vars);
}
if (type < PRIMITIVES.length) {
return TYPE_NAMES[type];
}
String[] recRef = (String[]) refs.get(this);
if (recRef == null) {
refs.put(this, recRef = new String[1]);
} else {
if (recRef[0] == null) {
recRef[0] = getVarName(vars);
}
return recRef[0];
}
String res = null;
switch (type) {
case FUN:
res = (param[0].type == FUN
? "(" + param[0].str(vars, refs) + ")"
: param[0].str(vars, refs)) + " -> " +
param[1].str(vars, refs);
break;
case STRUCT:
res = "{" + hstr(vars, refs) + "}";
break;
case VARIANT:
res = hstr(vars, refs);
break;
case MAP:
res = param[2].type == LIST_MARKER
? (param[1].type == NONE ? "list<" :
param[1].type == NUM ? "array<" : "list?<")
+ param[0].str(vars, refs) + ">"
: param[2].type == MAP_MARKER ||
param[1].type != NUM && param[1].type != VAR
? "hash<" + param[1].str(vars, refs) + ", "
+ param[0].str(vars, refs) + ">"
: "map<" + param[1].str(vars, refs) + ", "
+ param[0].str(vars, refs) + ">";
break;
case JAVA:
res = javaType.str(vars, refs, param);
break;
case JAVA_ARRAY:
res = param[0].str(vars, refs) + "[]";
break;
default:
return TYPE_NAMES[type];
}
return recRef[0] == null
? res : "(" + res + " is " + recRef[0] + ")";
}
public String toString() {
return str(new HashMap(), new HashMap());
}
Type deref() {
Type res = this;
while (res.ref != null) {
res = res.ref;
}
for (Type next, type = this; type.ref != null; type = next) {
next = type.ref;
type.ref = res;
}
return res;
}
}
static Type mutableFieldRef(Type src) {
Type t = new Type(src.depth);
t.ref = src.ref;
t.flags = src.flags;
t.field = FIELD_MUTABLE;
return t;
}
static Type fieldRef(int depth, Type ref, int kind) {
Type t = new Type(depth);
t.ref = ref.deref();
t.field = kind;
return t;
}
static final class Scope {
Scope outer;
String name;
Binder binder;
Type[] free;
Closure closure; // non-null means outer scopes must be proxied
Type importClass;
public Scope(Scope outer, String name, Binder binder) {
this.outer = outer;
this.name = name;
this.binder = binder;
}
}
static Type orderedVar(int maxDepth) {
Type type = new Type(maxDepth);
type.flags = FL_ORDERED_REQUIRED;
return type;
}
static void limitDepth(Type type, int maxDepth) {
type = type.deref();
if (type.type != VAR) {
if (type.seen) {
return;
}
type.seen = true;
for (int i = type.param.length; --i >= 0;) {
limitDepth(type.param[i], maxDepth);
}
type.seen = false;
} else if (type.depth > maxDepth) {
type.depth = maxDepth;
}
}
static class TypeException extends Exception {
boolean special;
TypeException(String what) {
super(what);
}
}
static void mismatch(Type a, Type b) throws TypeException {
throw new TypeException("Type mismatch: " + a + " is not " + b);
}
static void finalizeStruct(Type partial, Type src) throws TypeException {
if (src.finalMembers == null || partial.partialMembers == null /*||
partial.finalMembers != null*/) {
return; // nothing to check
}
Iterator i = partial.partialMembers.entrySet().iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
Type ff = (Type) src.finalMembers.get(entry.getKey());
if (ff == null) {
throw new TypeException("Type mismatch: " + src + " => "
+ partial + " (member missing: " + entry.getKey() + ")");
}
Type partField = (Type) entry.getValue();
if (partField.field == FIELD_MUTABLE && ff.field != FIELD_MUTABLE) {
throw new TypeException("Field '" + entry.getKey()
+ "' constness mismatch: " + src + " => " + partial);
}
unify(partField, ff);
}
}
static void unifyMembers(Type a, Type b) throws TypeException {
Map ff;
if (((a.flags ^ b.flags) & FL_ORDERED_REQUIRED) != 0) {
// VARIANT types are sometimes ordered.
// when all their variant parameters are ordered types.
if ((a.flags & FL_ORDERED_REQUIRED) != 0) {
requireOrdered(b);
} else {
requireOrdered(a);
}
}
if (a.finalMembers == null) {
ff = b.finalMembers;
} else if (b.finalMembers == null) {
ff = a.finalMembers;
} else {
// unify final members
ff = new HashMap(a.finalMembers);
for (Iterator i = ff.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
Type f = (Type) b.finalMembers.get(entry.getKey());
if (f != null) {
Type t = (Type) entry.getValue();
unify(f, t);
// constness spreads
if (t.field != f.field) {
if (t.field == 0) {
entry.setValue(t = f);
}
t.field = FIELD_NON_POLYMORPHIC;
}
} else {
i.remove();
}
}
if (ff.isEmpty()) {
mismatch(a, b);
}
}
finalizeStruct(a, b);
finalizeStruct(b, a);
if (a.partialMembers == null) {
a.partialMembers = b.partialMembers;
} else if (b.partialMembers != null) {
// join partial members
Iterator i = a.partialMembers.entrySet().iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
Type f = (Type) b.partialMembers.get(entry.getKey());
if (f != null) {
unify((Type) entry.getValue(), f);
// mutability spreads
if (f.field >= FIELD_NON_POLYMORPHIC) {
entry.setValue(f);
}
}
}
a.partialMembers.putAll(b.partialMembers);
}
a.finalMembers = ff;
if (ff == null) {
ff = a.partialMembers;
} else if (a.partialMembers != null) {
ff = new HashMap(ff);
ff.putAll(a.partialMembers);
}
a.param = (Type[]) ff.values().toArray(new Type[ff.size()]);
b.type = VAR;
b.ref = a;
}
static void unifyJava(Type jt, Type t) throws TypeException {
String descr = jt.javaType.description;
if (t.type != JAVA) {
if (t.type == UNIT && descr == "V")
return;
mismatch(jt, t);
}
if (descr == t.javaType.description) {
return;
}
mismatch(jt, t);
}
static void requireOrdered(Type type) throws TypeException {
switch (type.type) {
case VARIANT:
if ((type.flags & FL_ORDERED_REQUIRED) == 0) {
if (type.partialMembers != null) {
Iterator i = type.partialMembers.values().iterator();
while (i.hasNext()) {
requireOrdered((Type) i.next());
}
}
if (type.finalMembers != null) {
Iterator i = type.finalMembers.values().iterator();
while (i.hasNext()) {
requireOrdered((Type) i.next());
}
type.flags |= FL_ORDERED_REQUIRED;
}
}
return;
case MAP:
requireOrdered(type.param[2]);
requireOrdered(type.param[0]);
return;
case VAR:
if (type.ref != null) {
requireOrdered(type.ref);
} else {
type.flags |= FL_ORDERED_REQUIRED;
}
case NUM:
case STR:
case UNIT:
case LIST_MARKER:
return;
}
TypeException ex = new TypeException(type + " is not an ordered type");
ex.special = true;
throw ex;
}
static void occursCheck(Type type, Type var) throws TypeException {
type = type.deref();
if (type == var) {
TypeException ex = new TypeException("Cyclic type");
ex.special = true;
throw ex;
}
if (type.param != null && type.type != VARIANT) {
for (int i = type.param.length; --i >= 0;) {
occursCheck(type.param[i], var);
}
}
}
static void unifyToVar(Type var, Type from) throws TypeException {
occursCheck(from, var);
if ((var.flags & FL_ORDERED_REQUIRED) != 0) {
requireOrdered(from);
}
limitDepth(from, var.depth);
var.ref = from;
}
static void unify(Type a, Type b) throws TypeException {
a = a.deref();
b = b.deref();
if (a == b) {
} else if (a.type == VAR) {
unifyToVar(a, b);
} else if (b.type == VAR) {
unifyToVar(b, a);
} else if (a.type == JAVA) {
unifyJava(a, b);
} else if (b.type == JAVA) {
unifyJava(b, a);
} else if (a.type != b.type) {
mismatch(a, b);
} else if (a.type == STRUCT || a.type == VARIANT) {
unifyMembers(a, b);
} else {
for (int i = 0, cnt = a.param.length; i < cnt; ++i) {
unify(a.param[i], b.param[i]);
}
}
}
static Map copyTypeMap(Map types, Map free, Map known) {
Map result = new HashMap();
for (Iterator i = types.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
result.put(entry.getKey(),
copyType((Type) entry.getValue(), free, known));
}
return result;
}
static Type copyType(Type type, Map free, Map known) {
type = type.deref();
if (type.type == VAR) {
Type var = (Type) free.get(type);
return var == null ? type : var;
}
if (type.param.length == 0) {
return type;
}
Type copy = (Type) known.get(type);
if (copy != null) {
return copy;
}
Type[] param = new Type[type.param.length];
copy = new Type(type.type, param);
known.put(type, copy);
for (int i = param.length; --i >= 0;) {
param[i] = copyType(type.param[i], free, known);
}
if (type.partialMembers != null) {
copy.partialMembers = copyTypeMap(type.partialMembers, free, known);
}
if (type.finalMembers != null) {
copy.finalMembers = copyTypeMap(type.finalMembers, free, known);
}
return copy;
}
static BindRef resolve(String sym, Node where, Scope scope, int depth) {
for (; scope != null; scope = scope.outer) {
if (scope.name == sym && scope.binder != null) {
BindRef ref = scope.binder.getRef(where.line);
if (scope.free == null || scope.free.length == 0) {
return ref;
}
HashMap vars = new HashMap();
for (int i = scope.free.length; --i >= 0;) {
Type free = new Type(depth);
free.flags = scope.free[i].flags;
vars.put(scope.free[i], free);
}
ref.type = copyType(ref.type, vars, new HashMap());
return ref;
}
if (scope.closure != null) {
BindRef ref = scope.closure.refProxy(
resolve(sym, where, scope.outer, depth));
return ref;
}
}
throw new CompileException(where, "Unknown identifier: " + sym);
}
static Type resolveClass(String name, Node where, Scope scope) {
if (name.indexOf('/') >= 0) {
return new Type("L" + name + ';');
}
for (; scope != null; scope = scope.outer) {
if (scope.name == name && scope.importClass != null) {
return scope.importClass;
}
}
throw new CompileException(where, "Class not imported: " + name);
}
static void unusedBinding(Bind bind) {
throw new CompileException(bind, "Unused binding: " + bind.name);
}
static Code analyze(Node node, Scope scope, int depth) {
if (node instanceof Sym) {
String sym = ((Sym) node).sym;
if (Character.isUpperCase(sym.charAt(0))) {
return variantConstructor(sym, depth);
}
return resolve(sym, node, scope, depth);
}
if (node instanceof NumLit) {
return new NumericConstant(((NumLit) node).num);
}
if (node instanceof Str) {
return new StringConstant(((Str) node).str);
}
if (node instanceof UnitLiteral) {
return new UnitConstant();
}
if (node instanceof Seq) {
return analSeq(((Seq) node).st, scope, depth);
}
if (node instanceof Bind) {
Function r = singleBind((Bind) node, scope, depth);
if (!((BindExpr) r.selfBind).used) {
unusedBinding((Bind) node);
}
return r;
}
if (node instanceof BinOp) {
BinOp op = (BinOp) node;
if (op.op == "") {
return apply(node, analyze(op.left, scope, depth),
analyze(op.right, scope, depth), depth);
}
if (op.op == FIELD_OP) {
if (op.right instanceof NList) {
return keyRefExpr(analyze(op.left, scope, depth),
(NList) op.right, scope, depth);
}
return selectMember(op, scope, depth);
}
if (op.op == ":=") {
return assignOp(op, scope, depth);
}
if (op.op == "\\") {
return lambda(new Function(null),
new Lambda(new Sym("_").pos(op.line, op.col),
op.right, null), scope, depth);
}
if (op.op == "is") {
return isOp(op, ((IsOp) op).type,
analyze(op.right, scope, depth), depth);
}
if (op.op == "#") {
return objectRef((ObjectRefOp) op, scope, depth);
}
if (op.op == "loop") {
return loop(op, scope, depth);
}
+ if (op.left == null) {
+ throw new CompileException(op,
+ "Internal error (incomplete operator " + op.op + ")");
+ }
// TODO: unary -
return apply(op.right,
apply(op, resolve(op.op, op, scope, depth),
analyze(op.left, scope, depth), depth),
analyze(op.right, scope, depth), depth);
}
if (node instanceof Condition) {
return cond((Condition) node, scope, depth);
}
if (node instanceof Struct) {
return structType((Struct) node, scope, depth);
}
if (node instanceof NList) {
return list((NList) node, scope, depth);
}
if (node instanceof Lambda) {
return lambda(new Function(null), (Lambda) node, scope, depth);
}
if (node instanceof Case) {
return caseType((Case) node, scope, depth);
}
if (node instanceof ConcatStr) {
return concatStr((ConcatStr) node, scope, depth);
}
if (node instanceof Load) {
String name = ((Load) node).moduleName;
return new LoadModule(name, YetiTypeVisitor.getType(node, name));
}
if (node instanceof RSection) {
return rsection((RSection) node, scope, depth);
}
if (node instanceof NewOp) {
NewOp op = (NewOp) node;
Code[] args = mapArgs(op.arguments, scope, depth);
return new NewExpr(JavaType.resolveConstructor(op,
resolveClass(op.name, op, scope), args),
args, op.line);
}
throw new CompileException(node,
"I think that this " + node + " should not be here.");
}
static Type nodeToMembers(int type, TypeNode[] param, Map free, int depth) {
Map members = new HashMap();
Type[] tp = new Type[param.length];
for (int i = 0; i < param.length; ++i) {
tp[i] = nodeToType(param[i].param[0], free, depth);
if (members.put(param[i].name, tp[i]) != null) {
throw new CompileException(param[i], "Duplicate field name "
+ param[i].name + " in structure type");
}
}
Type result = new Type(type, tp);
result.partialMembers = members;
result.finalMembers = new HashMap(members);
return result;
}
static void expectsParam(TypeNode t, int count) {
if (t.param == null ? count != 0 : t.param.length != count) {
throw new CompileException(t, "type " + t.name + " expects "
+ count + " parameters");
}
}
static final Object[][] PRIMITIVE_TYPE_MAPPING = {
{ "()", UNIT_TYPE },
{ "boolean", BOOL_TYPE },
{ "char", CHAR_TYPE },
{ "number", NUM_TYPE },
{ "string", STR_TYPE }
};
static Type nodeToType(TypeNode node, Map free, int depth) {
String name = node.name;
for (int i = PRIMITIVE_TYPE_MAPPING.length; --i >= 0;) {
if (PRIMITIVE_TYPE_MAPPING[i][0] == name) {
expectsParam(node, 0);
return (Type) PRIMITIVE_TYPE_MAPPING[i][1];
}
}
if (name == "") {
return nodeToMembers(STRUCT, node.param, free, depth);
}
if (name == "|") {
return nodeToMembers(VARIANT, node.param, free, depth);
}
if (name == "->") {
expectsParam(node, 2);
Type[] tp = { nodeToType(node.param[0], free, depth),
nodeToType(node.param[1], free, depth) };
return new Type(FUN, tp);
}
if (name == "array") {
expectsParam(node, 1);
Type[] tp = { nodeToType(node.param[0], free, depth),
NUM_TYPE, LIST_TYPE };
return new Type(MAP, tp);
}
if (name == "list") {
expectsParam(node, 1);
Type[] tp = { nodeToType(node.param[0], free, depth),
NO_TYPE, LIST_TYPE };
return new Type(MAP, tp);
}
if (name == "list?") {
expectsParam(node, 1);
Type[] tp = { nodeToType(node.param[0], free, depth),
new Type(depth), LIST_TYPE };
return new Type(MAP, tp);
}
if (name == "hash") {
expectsParam(node, 2);
Type[] tp = { nodeToType(node.param[1], free, depth),
nodeToType(node.param[0], free, depth), MAP_TYPE };
return new Type(MAP, tp);
}
if (Character.isUpperCase(name.charAt(0))) {
return nodeToMembers(VARIANT, new TypeNode[] { node }, free, depth);
}
if (name.startsWith("'")) {
Type t = (Type) free.get(name);
if (t == null) {
free.put(name, t = new Type(depth));
}
return t;
}
throw new CompileException(node, "Unknown type: " + name);
}
static Code isOp(Node is, TypeNode type, Code value, int depth) {
Type t = nodeToType(type, new HashMap(), depth);
try {
unify(value.type, t);
} catch (TypeException ex) {
throw new CompileException(is, ex.getMessage() +
" (when checking " + value.type + " is " + t + ")");
}
return value;
}
static Code[] mapArgs(Node[] args, Scope scope, int depth) {
if (args == null)
return null;
Code[] res = new Code[args.length];
for (int i = 0; i < args.length; ++i) {
res[i] = analyze(args[i], scope, depth);
}
return res;
}
static Code objectRef(ObjectRefOp ref, Scope scope, int depth) {
Code obj = analyze(ref.right, scope, depth);
Code[] args = mapArgs(ref.arguments, scope, depth);
return new VirtualMethodCall(obj,
JavaType.resolveVMethod(ref, obj.type, args),
args, ref.line);
}
static Code apply(Node where, Code fun, Code arg, int depth) {
Type[] applyFun = { arg.type, new Type(depth) };
try {
unify(fun.type, new Type(FUN, applyFun));
} catch (TypeException ex) {
throw new CompileException(where,
"Cannot apply " + arg.type + " to " + fun.type + "\n " +
ex.getMessage());
}
return fun.apply(arg, applyFun[1], where.line);
}
static Code rsection(RSection section, Scope scope, int depth) {
if (section.sym == FIELD_OP) {
LinkedList parts = new LinkedList();
Node x = section.arg;
for (BinOp op; x instanceof BinOp; x = op.left) {
op = (BinOp) x;
if (op.op != FIELD_OP) {
throw new CompileException(op,
"Unexpected " + op.op + " in field selector");
}
checkSelectorSym(op, op.right);
parts.addFirst(((Sym) op.right).sym);
}
checkSelectorSym(section, x);
parts.addFirst(((Sym) x).sym);
String[] fields =
(String[]) parts.toArray(new String[parts.size()]);
Type res = new Type(depth), arg = res;
for (int i = fields.length; --i >= 0;) {
arg = selectMemberType(arg, fields[i], depth);
}
return new SelectMemberFun(new Type(FUN, new Type[] { arg, res }),
fields);
}
Code fun = resolve(section.sym, section, scope, depth);
Code arg = analyze(section.arg, scope, depth);
Type[] r = { new Type(depth), new Type(depth) };
Type[] afun = { r[0], new Type(FUN, new Type[] { arg.type, r[1] }) };
try {
unify(fun.type, new Type(FUN, afun));
} catch (TypeException ex) {
throw new CompileException(section,
"Cannot apply " + arg.type + " as a 2nd argument to " +
fun.type + "\n " + ex.getMessage());
}
return fun.apply2nd(arg, new Type(FUN, r), section.line);
}
static Code variantConstructor(String name, int depth) {
Type arg = new Type(depth);
Type tag = new Type(VARIANT, new Type[] { arg });
tag.partialMembers = new HashMap();
tag.partialMembers.put(name, arg);
Type[] fun = { arg, tag };
return new VariantConstructor(new Type(FUN, fun), name);
}
static void checkSelectorSym(Node op, Node sym) {
if (!(sym instanceof Sym)) {
if (sym == null) {
throw new CompileException(op, "What's that dot doing here?");
}
throw new CompileException(sym, "Illegal ." + sym);
}
}
static Type selectMemberType(Type res, String field, int depth) {
Type arg = new Type(STRUCT, new Type[] { res });
arg.partialMembers = new HashMap();
arg.partialMembers.put(field, res);
return arg;
}
static Code selectMember(BinOp op, Scope scope, int depth) {
final Type res = new Type(depth);
checkSelectorSym(op, op.right);
final String field = ((Sym) op.right).sym;
Type arg = selectMemberType(res, field, depth);
Code src = analyze(op.left, scope, depth);
try {
unify(arg, src.type);
} catch (TypeException ex) {
throw new CompileException(op.right,
src.type + " do not have ." + field + " field\n", ex);
}
boolean poly = src.polymorph && src.type.finalMembers != null &&
((Type) src.type.finalMembers.get(field)).field == 0;
return new SelectMember(res, src, field, op.line, poly) {
boolean mayAssign() {
Type t = st.type.deref();
Type given;
if (t.finalMembers != null &&
(given = (Type) t.finalMembers.get(field)) != null &&
(given.field != FIELD_MUTABLE)) {
return false;
}
Type self = (Type) t.partialMembers.get(field);
if (self.field != FIELD_MUTABLE) {
// XXX couldn't we get along with res.field = FIELD_MUTABLE?
t.partialMembers.put(field, mutableFieldRef(res));
}
return true;
}
};
}
static Code keyRefExpr(Code val, NList keyList, Scope scope, int depth) {
if (keyList.items == null || keyList.items.length == 0) {
throw new CompileException(keyList, ".[] - missing key expression");
}
if (keyList.items.length != 1) {
throw new CompileException(keyList, "Unexpected , inside .[]");
}
Code key = analyze(keyList.items[0], scope, depth);
Type[] param = { new Type(depth), key.type, new Type(depth) };
try {
unify(val.type, new Type(MAP, param));
} catch (TypeException ex) {
throw new CompileException(keyList, val.type +
" cannot be referenced by " + key.type + " key", ex);
}
return new KeyRefExpr(param[0], val, key, keyList.line);
}
static Code assignOp(BinOp op, Scope scope, int depth) {
Code left = analyze(op.left, scope, depth);
Code right = analyze(op.right, scope, depth);
try {
unify(left.type, right.type);
} catch (TypeException ex) {
throw new CompileException(op, ex.getMessage());
}
Code assign = left.assign(right);
if (assign == null) {
throw new CompileException(op,
"Non-mutable expression on the left of the assign operator :=");
}
assign.type = UNIT_TYPE;
return assign;
}
static Code concatStr(ConcatStr concat, Scope scope, int depth) {
Code[] parts = new Code[concat.param.length];
for (int i = 0; i < parts.length; ++i) {
parts[i] = analyze(concat.param[i], scope, depth);
}
return new ConcatStrings(parts);
}
static Code cond(Condition condition, Scope scope, int depth) {
Node[][] choices = condition.choices;
Code[][] conds = new Code[choices.length][];
Type result = null;
boolean poly = true;
for (int i = 0; i < choices.length; ++i) {
Node[] choice = choices[i];
Code val = analyze(choice[0], scope, depth);
if (choice.length == 1) {
conds[i] = new Code[] { val };
} else {
Code cond = analyze(choice[1], scope, depth);
try {
unify(BOOL_TYPE, cond.type);
} catch (TypeException ex) {
throw new CompileException(choice[1],
"if condition must have a boolean type (but here was "
+ cond.type + ")");
}
conds[i] = new Code[] { val, cond };
}
poly &= val.polymorph;
if (result == null) {
result = val.type;
} else {
try {
unify(result, val.type);
} catch (TypeException ex) {
throw new CompileException(choice[0],
"This if branch has a " + val.type +
" type, while another was a " + result, ex);
}
}
}
return new ConditionalExpr(result, conds, poly);
}
static Code loop(BinOp loop, Scope scope, int depth) {
Code cond = analyze(loop.left != null ? loop.left : loop.right,
scope, depth);
try {
unify(BOOL_TYPE, cond.type);
} catch (TypeException ex) {
throw new CompileException(loop.left,
"Loop condition must have a boolean type (but here was "
+ cond.type + ")");
}
if (loop.left == null) {
return new LoopExpr(cond, new UnitConstant());
}
Code body = analyze(loop.right, scope, depth);
try {
unify(body.type, UNIT_TYPE);
} catch (TypeException ex) {
throw new CompileException(loop.right,
"Loop body must have a unit type, not " + body.type, ex);
}
return new LoopExpr(cond, body);
}
static void getFreeVar(List vars, List deny, Type type, int depth) {
if (type.seen) {
return;
}
if (deny != null && type.field >= FIELD_NON_POLYMORPHIC) {
vars = deny; // anything under mutable field is evil
}
Type t = type.deref();
if (t.type != VAR) {
if (t.type == FUN) {
deny = null;
}
type.seen = true;
for (int i = t.param.length; --i >= 0;) {
getFreeVar(vars, deny, t.param[i], depth);
}
type.seen = false;
} else if (t.depth > depth && vars.indexOf(t) < 0) {
vars.add(t);
}
}
static Scope bindPoly(String name, Type valueType, Binder value,
int depth, Scope scope) {
List free = new ArrayList(), deny = new ArrayList();
getFreeVar(free, deny, valueType, depth);
if (deny.size() != 0) {
for (int i = free.size(); --i >= 0;) {
if (deny.indexOf(free.get(i)) >= 0) {
free.remove(i);
}
}
}
scope = new Scope(scope, name, value);
scope.free = (Type[]) free.toArray(new Type[free.size()]);
return scope;
}
static void registerVar(BindExpr binder, Scope scope) {
while (scope != null) {
if (scope.closure != null) {
scope.closure.addVar(binder);
return;
}
scope = scope.outer;
}
}
static Function singleBind(Bind bind, Scope scope, int depth) {
if (!(bind.expr instanceof Lambda)) {
throw new CompileException(bind,
"Closed binding must be a function binding");
}
// recursive binding
Function lambda = new Function(new Type(depth + 1));
BindExpr binder = new BindExpr(lambda, bind.var);
lambda.selfBind = binder;
lambdaBind(lambda, bind,
new Scope(scope, bind.name, binder), depth + 1);
return lambda;
}
static Code analSeq(Node[] nodes, Scope scope, int depth) {
BindExpr[] bindings = new BindExpr[nodes.length];
SeqExpr result = null, last = null, cur;
for (int i = 0; i < nodes.length - 1; ++i) {
if (nodes[i] instanceof Bind) {
Bind bind = (Bind) nodes[i];
BindExpr binder;
if (bind.expr instanceof Lambda) {
binder = (BindExpr) singleBind(bind, scope, depth).selfBind;
} else {
Code code = analyze(bind.expr, scope, depth + 1);
binder = new BindExpr(code, bind.var);
if (bind.type != null) {
isOp(bind, bind.type, binder.st, depth);
}
}
if (binder.st.polymorph && !bind.var) {
scope = bindPoly(bind.name, binder.st.type, binder,
depth, scope);
} else {
scope = new Scope(scope, bind.name, binder);
}
if (bind.var) {
registerVar(binder, scope.outer);
}
bindings[i] = binder;
cur = binder;
} else if (nodes[i] instanceof Load) {
LoadModule m = (LoadModule) analyze(nodes[i], scope, depth);
if (m.type.type == STRUCT) {
Iterator j = m.type.finalMembers.entrySet().iterator();
while (j.hasNext()) {
Map.Entry e = (Map.Entry) j.next();
String name = ((String) e.getKey()).intern();
Type t = (Type) e.getValue();
scope = bindPoly(name, t, m.bindField(name, t),
depth, scope);
}
} else if (m.type.type != UNIT) {
throw new CompileException(nodes[i],
"Expected module with struct or unit type here (" +
((Load) nodes[i]).moduleName + " has type " + m.type +
", but only structs can be exploded)");
}
cur = new SeqExpr(m);
} else if (nodes[i] instanceof Import) {
String name = ((Import) nodes[i]).className;
int lastSlash = name.lastIndexOf('/');
scope = new Scope(scope, (lastSlash < 0 ? name
: name.substring(lastSlash + 1)).intern(), null);
scope.importClass = new Type("L" + name + ';');
continue;
} else {
Code code = analyze(nodes[i], scope, depth);
try {
unify(UNIT_TYPE, code.type);
} catch (TypeException ex) {
throw new CompileException(nodes[i],
"Unit type expected here, not a " + code.type);
}
code.ignoreValue();
cur = new SeqExpr(code);
}
if (last == null) {
result = last = cur;
} else {
last.result = cur;
last = cur;
}
}
Code code = analyze(nodes[nodes.length - 1], scope, depth);
for (int i = bindings.length; --i >= 0;) {
if (bindings[i] != null && !bindings[i].used) {
unusedBinding((Bind) nodes[i]);
}
}
if (last == null) {
return code;
}
for (cur = result; cur != null; cur = (SeqExpr) cur.result) {
cur.type = code.type;
}
last.result = code;
result.polymorph = code.polymorph;
return result;
}
static Code lambdaBind(Function to, Bind bind, Scope scope, int depth) {
if (bind.type != null) {
isOp(bind, bind.type, to, depth);
}
return lambda(to, (Lambda) bind.expr, scope, depth);
}
static Code lambda(Function to, Lambda lambda, Scope scope, int depth) {
Type expected = to.type == null ? null : to.type.deref();
to.polymorph = true;
Scope bodyScope;
if (lambda.arg instanceof Sym) {
if (expected != null && expected.type == FUN) {
to.arg.type = expected.param[0];
} else {
to.arg.type = new Type(depth);
}
bodyScope = new Scope(scope, ((Sym) lambda.arg).sym, to);
} else if (lambda.arg instanceof UnitLiteral) {
to.arg.type = UNIT_TYPE;
bodyScope = new Scope(scope, null, to);
} else {
throw new CompileException(lambda.arg,
"Bad argument: " + lambda.arg);
}
bodyScope.closure = to;
if (lambda.expr instanceof Lambda) {
Function f = new Function(expected != null && expected.type == FUN
? expected.param[1] : null);
// make f to know about its outer scope before processing it
to.setBody(f);
lambda(f, (Lambda) lambda.expr, bodyScope, depth);
} else {
to.setBody(analyze(lambda.expr, bodyScope, depth));
}
Type fun = new Type(FUN, new Type[] { to.arg.type, to.body.type });
if (to.type != null) {
try {
unify(fun, to.type);
} catch (TypeException ex) {
throw new CompileException(lambda,
"Function type " + fun + " is not " + to.type
+ " (self-binding)\n " + ex.getMessage());
}
}
to.type = fun;
to.bindName = lambda.bindName;
to.body.markTail();
return to;
}
static Code structType(Struct st, Scope scope, int depth) {
Node[] nodes = st.fields;
if (nodes.length == 0) {
throw new CompileException(st, "No sense in empty struct");
}
Scope local = scope;
Map fields = new HashMap();
Map codeFields = new HashMap();
String[] names = new String[nodes.length];
Code[] values = new Code[nodes.length];
StructConstructor result = new StructConstructor(names, values);
result.polymorph = true;
// Functions see struct members in their scope
for (int i = 0; i < nodes.length; ++i) {
if (!(nodes[i] instanceof Bind)) {
throw new CompileException(nodes[i],
"Unexpected beast in the structure (" + nodes[i] +
"), please give me some field binding.");
}
Bind field = (Bind) nodes[i];
if (fields.containsKey(field.name)) {
throw new CompileException(field, "Duplicate field "
+ field.name + " in the structure");
}
Code code = values[i] = field.expr instanceof Lambda
? new Function(new Type(depth))
: analyze(field.expr, scope, depth);
names[i] = field.name;
fields.put(field.name,
field.var ? fieldRef(depth, code.type, FIELD_MUTABLE) :
code.polymorph || field.expr instanceof Lambda ? code.type
: fieldRef(depth, code.type, FIELD_NON_POLYMORPHIC));
local = new Scope(local, field.name,
result.bind(i, code, field.var));
}
for (int i = 0; i < nodes.length; ++i) {
Bind field = (Bind) nodes[i];
if (field.expr instanceof Lambda) {
lambdaBind((Function) values[i], field, local, depth);
}
}
result.type = new Type(STRUCT,
(Type[]) fields.values().toArray(new Type[fields.size()]));
result.type.finalMembers = fields;
return result;
}
static Scope badPattern(Node pattern) {
throw new CompileException(pattern, "Bad case pattern: " + pattern);
}
// oh holy fucking shit, this code sucks. horrible abuse of BinOps...
static Code caseType(Case ex, Scope scope, int depth) {
Node[] choices = ex.choices;
if (choices.length == 0) {
throw new CompileException(ex, "case expects some option!");
}
Code val = analyze(ex.value, scope, depth);
Map variants = new HashMap();
CaseExpr result = new CaseExpr(val);
result.polymorph = true;
for (int i = 0; i < choices.length; ++i) {
Scope local = scope;
BinOp choice;
if (!(choices[i] instanceof BinOp) ||
(choice = (BinOp) choices[i]).op != ":") {
throw new CompileException(choices[i],
"Expecting option, not a " + choices[i]);
}
if (!(choice.left instanceof BinOp)) {
badPattern(choice.left); // TODO
}
// binop. so try to extract a damn variant constructor.
BinOp pat = (BinOp) choice.left;
String variant = null;
if (pat.op != "" || !(pat.left instanceof Sym) ||
!Character.isUpperCase(
(variant = ((Sym) pat.left).sym).charAt(0))) {
badPattern(pat); // binop pat should be a variant
}
Choice caseChoice = result.addVariantChoice(variant);
Type variantArg = null;
if (!(pat.right instanceof Sym)) {
if (pat.right instanceof UnitLiteral) {
variantArg = UNIT_TYPE;
} else {
badPattern(pat); // TODO
}
} else {
variantArg = new Type(depth);
// got some constructor, store to map.
local = new Scope(local, ((Sym) pat.right).sym,
caseChoice.bindParam(variantArg));
}
Type old = (Type) variants.put(variant, variantArg);
if (old != null) { // same constructor already. shall be same type.
try {
unify(old, variantArg);
} catch (TypeException e) {
throw new CompileException(pat.right, e.getMessage());
}
}
// nothing intresting, just get option expr and merge to result
Code opt = analyze(choice.right, local, depth);
result.polymorph &= opt.polymorph;
if (result.type == null) {
result.type = opt.type;
} else {
try {
unify(result.type, opt.type);
} catch (TypeException e) {
throw new CompileException(choice.right,
"This choice has a " + opt.type +
" type, while another was a " + result.type, e);
}
}
caseChoice.setExpr(opt);
}
Type variantType = new Type(VARIANT,
(Type[]) variants.values().toArray(new Type[variants.size()]));
variantType.finalMembers = variants;
try {
unify(val.type, variantType);
} catch (TypeException e) {
throw new CompileException(ex.value,
"Inferred type for case argument is " + variantType +
", but a " + val.type + " is given\n (" +
e.getMessage() + ")");
}
return result;
}
static Code list(NList list, Scope scope, int depth) {
Node[] items = list.items == null ? new Node[0] : list.items;
Code[] keyItems = null;
Code[] codeItems = new Code[items.length];
Type type = null;
Type keyType = NO_TYPE;
Type kind = null;
BinOp bin;
for (int i = 0; i < items.length; ++i) {
if (items[i] instanceof BinOp &&
(bin = (BinOp) items[i]).op == ":") {
Code key = analyze(bin.left, scope, depth);
if (kind != MAP_TYPE) {
if (kind != null) {
throw new CompileException(bin,
"Unexpected : in list" + (i != 1 ? "" :
" (or the key is missing on the first item?)"));
}
keyType = key.type;
kind = MAP_TYPE;
keyItems = new Code[items.length];
} else {
try {
unify(keyType, key.type);
} catch (TypeException ex) {
throw new CompileException(items[i],
"This map element has " + keyType +
"key, but others have had " + keyType, ex);
}
}
keyItems[i] = key;
codeItems[i] = analyze(bin.right, scope, depth);
} else {
if (kind == MAP_TYPE) {
throw new CompileException(items[i],
"Map item is missing a key");
}
kind = LIST_TYPE;
if (items[i] instanceof BinOp &&
(bin = (BinOp) items[i]).op == "..") {
Code from = analyze(bin.left, scope, depth);
Code to = analyze(bin.right, scope, depth);
Node n = null; Type t = null;
try {
n = bin.left;
unify(t = from.type, NUM_TYPE);
n = bin.right;
unify(t = to.type, NUM_TYPE);
} catch (TypeException ex) {
throw new CompileException(n, ".. range expects " +
"limit to be number, not a " + t, ex);
}
codeItems[i] = new Range(from, to);
} else {
codeItems[i] = analyze(items[i], scope, depth);
}
}
if (type == null) {
type = codeItems[i].type;
} else {
try {
unify(type, codeItems[i].type);
} catch (TypeException ex) {
throw new CompileException(items[i], (kind == LIST_TYPE
? "This list element is " : "This map element is ") +
codeItems[i].type + ", but others have been " + type,
ex);
}
}
}
if (type == null) {
type = new Type(depth);
}
if (kind == null) {
kind = LIST_TYPE;
}
if (list.items == null) {
keyType = new Type(depth);
kind = MAP_TYPE;
}
Code res = kind == LIST_TYPE ? (Code) new ListConstructor(codeItems)
: new MapConstructor(keyItems, codeItems);
res.type = new Type(MAP, new Type[] { type, keyType, kind });
res.polymorph = kind == LIST_TYPE;
return res;
}
public static RootClosure toCode(String sourceName, char[] src, int flags) {
Object oldSrc = currentSrc.get();
currentSrc.set(src);
try {
Parser parser = new Parser(sourceName, src, flags);
Node n = parser.parse();
if ((flags & YetiC.CF_PRINT_PARSE_TREE) != 0) {
System.err.println(n.show());
}
RootClosure root = new RootClosure();
Scope scope = new Scope(ROOT_SCOPE, null, null);
scope.closure = root;
root.code = analyze(n, scope, 0);
root.type = root.code.type;
root.moduleName = parser.moduleName;
if ((flags & YetiC.CF_COMPILE_MODULE) == 0 &&
parser.moduleName == null) {
try {
unify(root.type, UNIT_TYPE);
} catch (TypeException ex) {
throw new CompileException(n,
"Program body must have a unit type, not "
+ root.type, ex);
}
} else { // MODULE
List free = new ArrayList(), deny = new ArrayList();
getFreeVar(free, deny, root.type, -1);
//System.err.println("checked module type, free are " + free
// + ", deny " + deny);
if (!deny.isEmpty() ||
!free.isEmpty() && !root.code.polymorph) {
throw new CompileException(n,
"Module type is not fully defined");
}
}
return root;
} catch (CompileException ex) {
if (ex.fn == null) {
ex.fn = sourceName;
}
throw ex;
} finally {
currentSrc.set(oldSrc);
}
}
}
| true | true | static Code analyze(Node node, Scope scope, int depth) {
if (node instanceof Sym) {
String sym = ((Sym) node).sym;
if (Character.isUpperCase(sym.charAt(0))) {
return variantConstructor(sym, depth);
}
return resolve(sym, node, scope, depth);
}
if (node instanceof NumLit) {
return new NumericConstant(((NumLit) node).num);
}
if (node instanceof Str) {
return new StringConstant(((Str) node).str);
}
if (node instanceof UnitLiteral) {
return new UnitConstant();
}
if (node instanceof Seq) {
return analSeq(((Seq) node).st, scope, depth);
}
if (node instanceof Bind) {
Function r = singleBind((Bind) node, scope, depth);
if (!((BindExpr) r.selfBind).used) {
unusedBinding((Bind) node);
}
return r;
}
if (node instanceof BinOp) {
BinOp op = (BinOp) node;
if (op.op == "") {
return apply(node, analyze(op.left, scope, depth),
analyze(op.right, scope, depth), depth);
}
if (op.op == FIELD_OP) {
if (op.right instanceof NList) {
return keyRefExpr(analyze(op.left, scope, depth),
(NList) op.right, scope, depth);
}
return selectMember(op, scope, depth);
}
if (op.op == ":=") {
return assignOp(op, scope, depth);
}
if (op.op == "\\") {
return lambda(new Function(null),
new Lambda(new Sym("_").pos(op.line, op.col),
op.right, null), scope, depth);
}
if (op.op == "is") {
return isOp(op, ((IsOp) op).type,
analyze(op.right, scope, depth), depth);
}
if (op.op == "#") {
return objectRef((ObjectRefOp) op, scope, depth);
}
if (op.op == "loop") {
return loop(op, scope, depth);
}
// TODO: unary -
return apply(op.right,
apply(op, resolve(op.op, op, scope, depth),
analyze(op.left, scope, depth), depth),
analyze(op.right, scope, depth), depth);
}
if (node instanceof Condition) {
return cond((Condition) node, scope, depth);
}
if (node instanceof Struct) {
return structType((Struct) node, scope, depth);
}
if (node instanceof NList) {
return list((NList) node, scope, depth);
}
if (node instanceof Lambda) {
return lambda(new Function(null), (Lambda) node, scope, depth);
}
if (node instanceof Case) {
return caseType((Case) node, scope, depth);
}
if (node instanceof ConcatStr) {
return concatStr((ConcatStr) node, scope, depth);
}
if (node instanceof Load) {
String name = ((Load) node).moduleName;
return new LoadModule(name, YetiTypeVisitor.getType(node, name));
}
if (node instanceof RSection) {
return rsection((RSection) node, scope, depth);
}
if (node instanceof NewOp) {
NewOp op = (NewOp) node;
Code[] args = mapArgs(op.arguments, scope, depth);
return new NewExpr(JavaType.resolveConstructor(op,
resolveClass(op.name, op, scope), args),
args, op.line);
}
throw new CompileException(node,
"I think that this " + node + " should not be here.");
}
| static Code analyze(Node node, Scope scope, int depth) {
if (node instanceof Sym) {
String sym = ((Sym) node).sym;
if (Character.isUpperCase(sym.charAt(0))) {
return variantConstructor(sym, depth);
}
return resolve(sym, node, scope, depth);
}
if (node instanceof NumLit) {
return new NumericConstant(((NumLit) node).num);
}
if (node instanceof Str) {
return new StringConstant(((Str) node).str);
}
if (node instanceof UnitLiteral) {
return new UnitConstant();
}
if (node instanceof Seq) {
return analSeq(((Seq) node).st, scope, depth);
}
if (node instanceof Bind) {
Function r = singleBind((Bind) node, scope, depth);
if (!((BindExpr) r.selfBind).used) {
unusedBinding((Bind) node);
}
return r;
}
if (node instanceof BinOp) {
BinOp op = (BinOp) node;
if (op.op == "") {
return apply(node, analyze(op.left, scope, depth),
analyze(op.right, scope, depth), depth);
}
if (op.op == FIELD_OP) {
if (op.right instanceof NList) {
return keyRefExpr(analyze(op.left, scope, depth),
(NList) op.right, scope, depth);
}
return selectMember(op, scope, depth);
}
if (op.op == ":=") {
return assignOp(op, scope, depth);
}
if (op.op == "\\") {
return lambda(new Function(null),
new Lambda(new Sym("_").pos(op.line, op.col),
op.right, null), scope, depth);
}
if (op.op == "is") {
return isOp(op, ((IsOp) op).type,
analyze(op.right, scope, depth), depth);
}
if (op.op == "#") {
return objectRef((ObjectRefOp) op, scope, depth);
}
if (op.op == "loop") {
return loop(op, scope, depth);
}
if (op.left == null) {
throw new CompileException(op,
"Internal error (incomplete operator " + op.op + ")");
}
// TODO: unary -
return apply(op.right,
apply(op, resolve(op.op, op, scope, depth),
analyze(op.left, scope, depth), depth),
analyze(op.right, scope, depth), depth);
}
if (node instanceof Condition) {
return cond((Condition) node, scope, depth);
}
if (node instanceof Struct) {
return structType((Struct) node, scope, depth);
}
if (node instanceof NList) {
return list((NList) node, scope, depth);
}
if (node instanceof Lambda) {
return lambda(new Function(null), (Lambda) node, scope, depth);
}
if (node instanceof Case) {
return caseType((Case) node, scope, depth);
}
if (node instanceof ConcatStr) {
return concatStr((ConcatStr) node, scope, depth);
}
if (node instanceof Load) {
String name = ((Load) node).moduleName;
return new LoadModule(name, YetiTypeVisitor.getType(node, name));
}
if (node instanceof RSection) {
return rsection((RSection) node, scope, depth);
}
if (node instanceof NewOp) {
NewOp op = (NewOp) node;
Code[] args = mapArgs(op.arguments, scope, depth);
return new NewExpr(JavaType.resolveConstructor(op,
resolveClass(op.name, op, scope), args),
args, op.line);
}
throw new CompileException(node,
"I think that this " + node + " should not be here.");
}
|
diff --git a/src/jregex/Matcher.java b/src/jregex/Matcher.java
index 37ecc7105..a20c8fd6a 100644
--- a/src/jregex/Matcher.java
+++ b/src/jregex/Matcher.java
@@ -1,2296 +1,2296 @@
/**
* Copyright (c) 2001, Sergey A. Samokhodkin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of jregex nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS 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 REGENTS OR 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.
*
* @version 1.2_01
*/
package jregex;
import java.util.*;
import java.io.*;
/**
* Matcher instance is an automaton that actually performs matching. It provides the following methods:
* <li> searching for a matching substrings : matcher.find() or matcher.findAll();
* <li> testing whether a text matches a whole pattern : matcher.matches();
* <li> testing whether the text matches the beginning of a pattern : matcher.matchesPrefix();
* <li> searching with custom options : matcher.find(int options)
* <p>
* <b>Obtaining results</b><br>
* After the search succeded, i.e. if one of above methods returned <code>true</code>
* one may obtain an information on the match:
* <li> may check whether some group is captured : matcher.isCaptured(int);
* <li> may obtain start and end positions of the match and its length : matcher.start(int),matcher.end(int),matcher.length(int);
* <li> may obtain match contents as String : matcher.group(int).<br>
* The same way can be obtained the match prefix and suffix information.
* The appropriate methods are grouped in MatchResult interface, which the Matcher class implements.<br>
* Matcher objects are not thread-safe, so only one thread may use a matcher instance at a time.
* Note, that Pattern objects are thread-safe(the same instanse may be shared between
* multiple threads), and the typical tactics in multithreaded applications is to have one Pattern instance per expression(a singleton),
* and one Matcher object per thread.
*/
public class Matcher implements MatchResult{
/* Matching options*/
/**
* The same effect as "^" without REFlags.MULTILINE.
* @see Matcher#find(int)
*/
public static final int ANCHOR_START=1;
/**
* The same effect as "\\G".
* @see Matcher#find(int)
*/
public static final int ANCHOR_LASTMATCH=2;
/**
* The same effect as "$" without REFlags.MULTILINE.
* @see Matcher#find(int)
*/
public static final int ANCHOR_END=4;
/**
* Experimental option; if a text ends up before the end of a pattern,report a match.
* @see Matcher#find(int)
*/
public static final int ACCEPT_INCOMPLETE=8;
//see search(ANCHOR_START|...)
private static Term startAnchor=new Term(Term.START);
//see search(ANCHOR_LASTMATCH|...)
private static Term lastMatchAnchor=new Term(Term.LAST_MATCH_END);
private Pattern re;
private int[] counters;
private MemReg[] memregs;
private LAEntry[] lookaheads;
private int counterCount;
private int memregCount;
private int lookaheadCount;
private char[] data;
private int offset,end,wOffset,wEnd;
private boolean shared;
private SearchEntry top; //stack entry
private SearchEntry first; //object pool entry
private SearchEntry defaultEntry; //called when moving the window
private boolean called;
private int minQueueLength;
private String cache;
//cache may be longer than the actual data
//and contrariwise; so cacheOffset may have both signs.
//cacheOffset is actually -(data offset).
private int cacheOffset,cacheLength;
private MemReg prefixBounds,suffixBounds,targetBounds;
Matcher(Pattern regex){
this.re=regex;
//int memregCount=(memregs=new MemReg[regex.memregs]).length;
//for(int i=0;i<memregCount;i++){
// this.memregs[i]=new MemReg(-1); //unlikely to SearchEntry, in this case we know memreg indicies by definition
//}
//counters=new int[regex.counters];
//int lookaheadCount=(lookaheads=new LAEntry[regex.lookaheads]).length;
//for(int i=0;i<lookaheadCount;i++){
// this.lookaheads[i]=new LAEntry();
//}
int memregCount,counterCount,lookaheadCount;
if((memregCount=regex.memregs)>0){
MemReg[] memregs=new MemReg[memregCount];
for(int i=0;i<memregCount;i++){
memregs[i]=new MemReg(-1); //unlikely to SearchEntry, in this case we know memreg indicies by definition
}
this.memregs=memregs;
}
if((counterCount=regex.counters)>0) counters=new int[counterCount];
if((lookaheadCount=regex.lookaheads)>0){
LAEntry[] lookaheads=new LAEntry[lookaheadCount];
for(int i=0;i<lookaheadCount;i++){
lookaheads[i]=new LAEntry();
}
this.lookaheads=lookaheads;
}
this.memregCount=memregCount;
this.counterCount=counterCount;
this.lookaheadCount=lookaheadCount;
first=new SearchEntry();
defaultEntry=new SearchEntry();
minQueueLength=regex.stringRepr.length()/2; // just evaluation!!!
}
/**
* This method allows to efficiently pass data between matchers.
* Note that a matcher may pass data to itself:<pre>
* Matcher m=new Pattern("\\w+").matcher(myString);
* if(m.find())m.setTarget(m,m.SUFFIX); //forget all that is not a suffix
* </pre>
* Resets current search position to zero.
* @param m - a matcher that is a source of data
* @param groupId - which group to take data from
* @see Matcher#setTarget(java.lang.String)
* @see Matcher#setTarget(java.lang.String,int,int)
* @see Matcher#setTarget(char[],int,int)
* @see Matcher#setTarget(java.io.Reader,int)
*/
public final void setTarget(Matcher m, int groupId){
MemReg mr=m.bounds(groupId);
//System.out.println("setTarget("+m+","+groupId+")");
//System.out.println(" in="+mr.in);
//System.out.println(" out="+mr.out);
if(mr==null) throw new IllegalArgumentException("group #"+groupId+" is not assigned");
data=m.data;
offset=mr.in;
end=mr.out;
cache=m.cache;
cacheLength=m.cacheLength;
cacheOffset=m.cacheOffset;
if(m!=this){
shared=true;
m.shared=true;
}
init();
}
/**
* Supplies a text to search in/match with.
* Resets current search position to zero.
* @param text - a data
* @see Matcher#setTarget(jregex.Matcher,int)
* @see Matcher#setTarget(java.lang.String,int,int)
* @see Matcher#setTarget(char[],int,int)
* @see Matcher#setTarget(java.io.Reader,int)
*/
public void setTarget(String text){
setTarget(text,0,text.length());
}
/**
* Supplies a text to search in/match with, as a part of String.
* Resets current search position to zero.
* @param text - a data source
* @param start - where the target starts
* @param len - how long is the target
* @see Matcher#setTarget(jregex.Matcher,int)
* @see Matcher#setTarget(java.lang.String)
* @see Matcher#setTarget(char[],int,int)
* @see Matcher#setTarget(java.io.Reader,int)
*/
public void setTarget(String text,int start,int len){
char[] mychars=data;
if(mychars==null || shared || mychars.length<len){
data=mychars=new char[(int)(1.7f*len)];
shared=false;
}
text.getChars(start,len,mychars,0); //(srcBegin,srcEnd,dst[],dstBegin)
offset=0;
end=len;
cache=text;
cacheOffset=-start;
cacheLength=text.length();
init();
}
/**
* Supplies a text to search in/match with, as a part of char array.
* Resets current search position to zero.
* @param text - a data source
* @param start - where the target starts
* @param len - how long is the target
* @see Matcher#setTarget(jregex.Matcher,int)
* @see Matcher#setTarget(java.lang.String)
* @see Matcher#setTarget(java.lang.String,int,int)
* @see Matcher#setTarget(java.io.Reader,int)
*/
public void setTarget(char[] text,int start,int len){
setTarget(text,start,len,true);
}
/**
* To be used with much care.
* Supplies a text to search in/match with, as a part of a char array, as above, but also allows to permit
* to use the array as internal buffer for subsequent inputs. That is, if we call it with <code>shared=false</code>:<pre>
* myMatcher.setTarget(myCharArray,x,y,<b>false</b>); //we declare that array contents is NEITHER shared NOR will be used later, so may modifications on it are permitted
* </pre>
* then we should expect the array contents to be changed on subsequent setTarget(..) operations.
* Such method may yield some increase in perfomanse in the case of multiple setTarget() calls.
* Resets current search position to zero.
* @param text - a data source
* @param start - where the target starts
* @param len - how long is the target
* @param shared - if <code>true<code>: data are shared or used later, <b>don't</b> modify it; if <code>false<code>: possible modifications of the text on subsequent <code>setTarget()</code> calls are perceived and allowed.
* @see Matcher#setTarget(jregex.Matcher,int)
* @see Matcher#setTarget(java.lang.String)
* @see Matcher#setTarget(java.lang.String,int,int)
* @see Matcher#setTarget(char[],int,int)
* @see Matcher#setTarget(java.io.Reader,int)
*/
public final void setTarget(char[] text,int start,int len,boolean shared){
cache=null;
data=text;
offset=start;
end=start+len;
this.shared=shared;
init();
}
/**
* Supplies a text to search in/match with through a stream.
* Resets current search position to zero.
* @param in - a data stream;
* @param len - how much characters should be read; if len is -1, read the entire stream.
* @see Matcher#setTarget(jregex.Matcher,int)
* @see Matcher#setTarget(java.lang.String)
* @see Matcher#setTarget(java.lang.String,int,int)
* @see Matcher#setTarget(char[],int,int)
*/
public void setTarget(Reader in,int len)throws IOException{
if(len<0){
setAll(in);
return;
}
char[] mychars=data;
boolean shared=this.shared;
if(mychars==null || shared || mychars.length<len){
mychars=new char[len];
shared=false;
}
int count=0;
int c;
while((c=in.read(mychars,count,len))>=0){
len-=c;
count+=c;
if(len==0) break;
}
setTarget(mychars,0,count,shared);
}
private void setAll(Reader in)throws IOException{
char[] mychars=data;
int free;
boolean shared=this.shared;
if(mychars==null || shared){
mychars=new char[free=1024];
shared=false;
}
else free=mychars.length;
int count=0;
int c;
while((c=in.read(mychars,count,free))>=0){
free-=c;
count+=c;
if(free==0){
int newsize=count*3;
char[] newchars=new char[newsize];
System.arraycopy(mychars,0,newchars,0,count);
mychars=newchars;
free=newsize-count;
shared=false;
}
}
setTarget(mychars,0,count,shared);
}
private final String getString(int start,int end){
String src=cache;
if(src!=null){
int co=cacheOffset;
return src.substring(start-co,end-co);
}
int tOffset,tEnd,tLen=(tEnd=this.end)-(tOffset=this.offset);
char[] data=this.data;
if((end-start)>=(tLen/3)){
//it makes sence to make a cache
cache=src=new String(data,tOffset,tLen);
cacheOffset=tOffset;
cacheLength=tLen;
return src.substring(start-tOffset,end-tOffset);
}
return new String(data,start,end-start);
}
/* Matching */
/**
* Tells whether the entire target matches the beginning of the pattern.
* The whole pattern is also regarded as its beginning.<br>
* This feature allows to find a mismatch by examining only a beginning part of
* the target (as if the beginning of the target doesn't match the beginning of the pattern, then the entire target
* also couldn't match).<br>
* For example the following assertions yield <code>true<code>:<pre>
* Pattern p=new Pattern("abcd");
* p.matcher("").matchesPrefix();
* p.matcher("a").matchesPrefix();
* p.matcher("ab").matchesPrefix();
* p.matcher("abc").matchesPrefix();
* p.matcher("abcd").matchesPrefix();
* </pre>
* and the following yield <code>false<code>:<pre>
* p.matcher("b").isPrefix();
* p.matcher("abcdef").isPrefix();
* p.matcher("x").isPrefix();
* </pre>
* @return true if the entire target matches the beginning of the pattern
*/
public final boolean matchesPrefix(){
setPosition(0);
return search(ANCHOR_START|ACCEPT_INCOMPLETE|ANCHOR_END);
}
/**
* Just an old name for isPrefix().<br>
* Retained for backwards compatibility.
* @deprecated Replaced by isPrefix()
*/
public final boolean isStart(){
return matchesPrefix();
}
/**
* Tells whether a current target matches the whole pattern.
* For example the following yields the <code>true<code>:<pre>
* Pattern p=new Pattern("\\w+");
* p.matcher("a").matches();
* p.matcher("ab").matches();
* p.matcher("abc").matches();
* </pre>
* and the following yields the <code>false<code>:<pre>
* p.matcher("abc def").matches();
* p.matcher("bcd ").matches();
* p.matcher(" bcd").matches();
* p.matcher("#xyz#").matches();
* </pre>
* @return whether a current target matches the whole pattern.
*/
public final boolean matches(){
if(called) setPosition(0);
return search(ANCHOR_START|ANCHOR_END);
}
/**
* Just a combination of setTarget(String) and matches().
* @param s the target string;
* @return whether the specified string matches the whole pattern.
*/
public final boolean matches(String s){
setTarget(s);
return search(ANCHOR_START|ANCHOR_END);
}
/**
* Allows to set a position the subsequent find()/find(int) will start from.
* @param pos the position to start from;
* @see Matcher#find()
* @see Matcher#find(int)
*/
public void setPosition(int pos){
wOffset=offset+pos;
wEnd=-1;
called=false;
flush();
}
public void setOffset(int offset){
this.offset = offset;
wOffset=offset;
wEnd=-1;
called=false;
flush();
}
/**
* Searches through a target for a matching substring, starting from just after the end of last match.
* If there wasn't any search performed, starts from zero.
* @return <code>true</code> if a match found.
*/
public final boolean find(){
if(called) skip();
return search(0);
}
/**
* Searches through a target for a matching substring, starting from just after the end of last match.
* If there wasn't any search performed, starts from zero.
* @param anchors a zero or a combination(bitwise OR) of ANCHOR_START,ANCHOR_END,ANCHOR_LASTMATCH,ACCEPT_INCOMPLETE
* @return <code>true</code> if a match found.
*/
public final boolean find(int anchors){
if(called) skip();
return search(anchors);
}
/**
* The same as findAll(int), but with default behaviour;
*/
public MatchIterator findAll(){
return findAll(0);
}
/**
* Returns an iterator over the matches found by subsequently calling find(options), the search starts from the zero position.
*/
public MatchIterator findAll(final int options){
//setPosition(0);
return new MatchIterator(){
private boolean checked=false;
private boolean hasMore=false;
public boolean hasMore(){
if(!checked) check();
return hasMore;
}
public MatchResult nextMatch(){
if(!checked) check();
if(!hasMore) throw new NoSuchElementException();
checked=false;
return Matcher.this;
}
private final void check(){
hasMore=find(options);
checked=true;
}
public int count(){
if(!checked) check();
if(!hasMore) return 0;
int c=1;
while(find(options))c++;
checked=false;
return c;
}
};
}
/**
* Continues to search from where the last search left off.
* The same as proceed(0).
* @see Matcher#proceed(int)
*/
public final boolean proceed(){
return proceed(0);
}
/**
* Continues to search from where the last search left off using specified options:<pre>
* Matcher m=new Pattern("\\w+").matcher("abc");
* while(m.proceed(0)){
* System.out.println(m.group(0));
* }
* </pre>
* Output:<pre>
* abc
* ab
* a
* bc
* b
* c
* </pre>
* For example, let's find all odd nubmers occuring in a text:<pre>
* Matcher m=new Pattern("\\d+").matcher("123");
* while(m.proceed(0)){
* String match=m.group(0);
* if(isOdd(Integer.parseInt(match))) System.out.println(match);
* }
*
* static boolean isOdd(int i){
* return (i&1)>0;
* }
* </pre>
* This outputs:<pre>
* 123
* 1
* 23
* 3
* </pre>
* Note that using <code>find()</code> method we would find '123' only.
* @param options search options, some of ANCHOR_START|ANCHOR_END|ANCHOR_LASTMATCH|ACCEPT_INCOMPLETE; zero value(default) stands for usual search for substring.
*/
public final boolean proceed(int options){
//System.out.println("next() : top="+top);
if(called){
if(top==null){
wOffset++;
}
}
return search(0);
}
/**
* Sets the current search position just after the end of last match.
*/
public final void skip(){
int we=wEnd;
if(wOffset==we){ //requires special handling
//if no variants at 'wOutside',advance pointer and clear
if(top==null){
wOffset++;
flush();
}
//otherwise, if there exist a variant,
//don't clear(), i.e. allow it to match
return;
}
else{
if(we<0) wOffset=0;
else wOffset=we;
}
//rflush(); //rflush() works faster on simple regexes (with a small group/branch number)
flush();
}
private final void init(){
//wOffset=-1;
//System.out.println("init(): offset="+offset+", end="+end);
wOffset=offset;
wEnd=-1;
called=false;
flush();
}
/**
* Resets the internal state.
*/
private final void flush(){
top=null;
defaultEntry.reset(0);
/*
int c=0;
SearchEntry se=first;
while(se!=null){
c++;
se=se.on;
}
System.out.println("queue: allocated="+c+", truncating to "+minQueueLength);
new Exception().printStackTrace();
*/
first.reset(minQueueLength);
//first.reset(0);
for(int i=memregs.length-1;i>0;i--){
MemReg mr=memregs[i];
mr.in=mr.out=-1;
}
for(int i=memregs.length-1;i>0;i--){
MemReg mr=memregs[i];
mr.in=mr.out=-1;
}
called=false;
}
//reverse flush
//may work significantly faster,
//need testing
private final void rflush(){
SearchEntry entry=top;
top=null;
MemReg[] memregs=this.memregs;
int[] counters=this.counters;
while(entry!=null){
SearchEntry next=entry.sub;
SearchEntry.popState(entry,memregs,counters);
entry=next;
}
SearchEntry.popState(defaultEntry,memregs,counters);
}
/**
*/
public String toString(){
return getString(wOffset,wEnd);
}
public Pattern pattern(){
return re;
}
public String target(){
return getString(offset,end);
}
/**
*/
public char[] targetChars(){
shared=true;
return data;
}
/**
*/
public int targetStart(){
return offset;
}
/**
*/
public int targetEnd(){
return end;
}
public char charAt(int i){
int in=this.wOffset;
int out=this.wEnd;
if(in<0 || out<in) throw new IllegalStateException("unassigned");
return data[in+i];
}
public char charAt(int i,int groupId){
MemReg mr=bounds(groupId);
if(mr==null) throw new IllegalStateException("group #"+groupId+" is not assigned");
int in=mr.in;
if(i<0 || i>(mr.out-in)) throw new StringIndexOutOfBoundsException(""+i);
return data[in+i];
}
public final int length(){
return wEnd-wOffset;
}
/**
*/
public final int start(){
return wOffset-offset;
}
/**
*/
public final int end(){
return wEnd-offset;
}
/**
*/
public String prefix(){
return getString(offset,wOffset);
}
/**
*/
public String suffix(){
return getString(wEnd,end);
}
/**
*/
public int groupCount(){
return memregs.length;
}
/**
*/
public String group(int n){
MemReg mr=bounds(n);
if(mr==null) return null;
return getString(mr.in,mr.out);
}
/**
*/
public String group(String name){
Integer id=re.groupId(name);
if(id==null) throw new IllegalArgumentException("<"+name+"> isn't defined");
return group(id.intValue());
}
/**
*/
public boolean getGroup(int n,TextBuffer tb){
MemReg mr=bounds(n);
if(mr==null) return false;
int in;
tb.append(data,in=mr.in,mr.out-in);
return true;
}
/**
*/
public boolean getGroup(String name,TextBuffer tb){
Integer id=re.groupId(name);
if(id==null) throw new IllegalArgumentException("unknown group: \""+name+"\"");
return getGroup(id.intValue(),tb);
}
/**
*/
public boolean getGroup(int n,StringBuffer sb){
MemReg mr=bounds(n);
if(mr==null) return false;
int in;
sb.append(data,in=mr.in,mr.out-in);
return true;
}
/**
*/
public boolean getGroup(String name,StringBuffer sb){
Integer id=re.groupId(name);
if(id==null) throw new IllegalArgumentException("unknown group: \""+name+"\"");
return getGroup(id.intValue(),sb);
}
/**
*/
public String[] groups(){
MemReg[] memregs=this.memregs;
String[] groups=new String[memregs.length];
int in,out;
MemReg mr;
for(int i=0;i<memregs.length;i++){
in=(mr=memregs[i]).in;
out=mr.out;
if((in=mr.in)<0 || mr.out<in) continue;
groups[i]=getString(in,out);
}
return groups;
}
/**
*/
public Vector groupv(){
MemReg[] memregs=this.memregs;
Vector v=new Vector();
int in,out;
MemReg mr;
for(int i=0;i<memregs.length;i++){
mr=bounds(i);
if(mr==null){
v.addElement("empty");
continue;
}
String s=getString(mr.in,mr.out);
v.addElement(s);
}
return v;
}
private final MemReg bounds(int id){
//System.out.println("Matcher.bounds("+id+"):");
MemReg mr;
if(id>=0){
mr=memregs[id];
}
else switch(id){
case PREFIX:
mr=prefixBounds;
if(mr==null) prefixBounds=mr=new MemReg(PREFIX);
mr.in=offset;
mr.out=wOffset;
break;
case SUFFIX:
mr=suffixBounds;
if(mr==null) suffixBounds=mr=new MemReg(SUFFIX);
mr.in=wEnd;
mr.out=end;
break;
case TARGET:
mr=targetBounds;
if(mr==null) targetBounds=mr=new MemReg(TARGET);
mr.in=offset;
mr.out=end;
break;
default:
throw new IllegalArgumentException("illegal group id: "+id+"; must either nonnegative int, or MatchResult.PREFIX, or MatchResult.SUFFIX");
}
//System.out.println(" mr=["+mr.in+","+mr.out+"]");
int in;
if((in=mr.in)<0 || mr.out<in) return null;
return mr;
}
/**
*/
public final boolean isCaptured(){
return wOffset>=0 && wEnd>=wOffset;
}
/**
*/
public final boolean isCaptured(int id){
return bounds(id)!=null;
}
/**
*/
public final boolean isCaptured(String groupName){
Integer id=re.groupId(groupName);
if(id==null) throw new IllegalArgumentException("unknown group: \""+groupName+"\"");
return isCaptured(id.intValue());
}
/**
*/
public final int length(int id){
MemReg mr=bounds(id);
return mr.out-mr.in;
}
/**
*/
public final int start(int id){
return bounds(id).in-offset;
}
/**
*/
public final int end(int id){
return bounds(id).out-offset;
}
private final boolean search(int anchors){
called=true;
final int end=this.end;
int offset=this.offset;
char[] data=this.data;
int wOffset=this.wOffset;
int wEnd=this.wEnd;
MemReg[] memregs=this.memregs;
int[] counters=this.counters;
LAEntry[] lookaheads=this.lookaheads;
//int memregCount=memregs.length;
//int cntCount=counters.length;
int memregCount=this.memregCount;
int cntCount=this.counterCount;
SearchEntry defaultEntry=this.defaultEntry;
SearchEntry first=this.first;
SearchEntry top=this.top;
SearchEntry actual=null;
int cnt,regLen;
int i;
final boolean matchEnd=(anchors&ANCHOR_END)>0;
final boolean allowIncomplete=(anchors&ACCEPT_INCOMPLETE)>0;
Pattern re=this.re;
Term root=re.root;
Term term;
if(top==null){
if((anchors&ANCHOR_START)>0){
term=re.root0; //raw root
root=startAnchor;
}
else if((anchors&ANCHOR_LASTMATCH)>0){
term=re.root0; //raw root
root=lastMatchAnchor;
}
else{
term=root; //optimized root
}
i=wOffset;
actual=first;
SearchEntry.popState(defaultEntry,memregs,counters);
}
else{
top=(actual=top).sub;
term=actual.term;
i=actual.index;
SearchEntry.popState(actual,memregs,counters);
}
cnt=actual.cnt;
regLen=actual.regLen;
main:
while(wOffset<=end){
matchHere:
for(;;){
/*
System.out.print("char: "+i+", term: ");
System.out.print(term.toString());
System.out.print(" // mrs:{");
for(int dbi=0;dbi<memregs.length;dbi++){
System.out.print('[');
System.out.print(memregs[dbi].in);
System.out.print(',');
System.out.print(memregs[dbi].out);
System.out.print(']');
System.out.print(' ');
}
System.out.print("}, crs:{");
for(int dbi=0;dbi<counters.length;dbi++){
System.out.print(counters[dbi]);
if(dbi<counters.length-1)System.out.print(',');
}
System.out.println("}");
*/
int memreg,cntreg;
char c;
switch(term.type){
case Term.FIND:{
int jump=find(data,i+term.distance,end,term.target); //don't eat the last match
if(jump<0) break main; //return false
i+=jump;
wOffset=i; //force window to move
if(term.eat){
if(i==end) break;
i++;
}
term=term.next;
continue matchHere;
}
case Term.FINDREG:{
MemReg mr=memregs[term.target.memreg];
int sampleOff=mr.in;
int sampleLen=mr.out-sampleOff;
//if(sampleOff<0 || sampleLen<0) throw new Error("backreference used before definition: \\"+term.memreg);
/*@since 1.2*/
if(sampleOff<0 || sampleLen<0){
break;
}
else if(sampleLen==0){
term=term.next;
continue matchHere;
}
int jump=findReg(data,i+term.distance,sampleOff,sampleLen,term.target,end); //don't eat the last match
if(jump<0) break main; //return false
i+=jump;
wOffset=i; //force window to move
if(term.eat){
i+=sampleLen;
if(i>end) break;
}
term=term.next;
continue matchHere;
}
case Term.VOID:
term=term.next;
continue matchHere;
case Term.CHAR:
//can only be 1-char-wide
// \/
if(i>=end || data[i]!=term.c) break;
//System.out.println("CHAR: "+data[i]+", i="+i);
i++;
term=term.next;
continue matchHere;
case Term.ANY_CHAR:
//can only be 1-char-wide
// \/
if(i>=end) break;
i++;
term=term.next;
continue matchHere;
case Term.ANY_CHAR_NE:
//can only be 1-char-wide
// \/
if(i>=end || data[i]=='\n') break;
i++;
term=term.next;
continue matchHere;
case Term.END:
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
break;
case Term.END_EOL: //perl's $
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
else{
boolean matches=
i>=end |
((i+1)==end && data[i]=='\n');
if(matches){
term=term.next;
continue matchHere;
}
else break;
}
case Term.LINE_END:
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
else{
/*
if(((c=data[i])=='\r' || c=='\n') &&
(c=data[i-1])!='\r' && c!='\n'){
term=term.next;
continue matchHere;
}
*/
//5 aug 2001
if(data[i]=='\n'){
term=term.next;
continue matchHere;
}
}
break;
case Term.START: //Perl's "^"
if(i==offset){ //meets
term=term.next;
continue matchHere;
}
//break;
//changed on 27-04-2002
//due to a side effect: if ALLOW_INCOMPLETE is enabled,
//the anchorStart moves up to the end and succeeds
//(see comments at the last lines of matchHere, ~line 1830)
//Solution: if there are some entries on the stack ("^a|b$"),
//try them; otherwise it's a final 'no'
//if(top!=null) break;
//else break main;
//changed on 25-05-2002
//rationale: if the term is startAnchor,
//it's the root term by definition,
//so if it doesn't match, the entire pattern
//couldn't match too;
//otherwise we could have the following problem:
//"c|^a" against "abc" finds only "a"
if(top!=null) break;
if(term!=startAnchor) break;
else break main;
case Term.LAST_MATCH_END:
- if(i==wEnd){ //meets
+ if(i==wEnd || wEnd == -1){ //meets
term=term.next;
continue matchHere;
}
break main; //return false
case Term.LINE_START:
if(i==offset){ //meets
term=term.next;
continue matchHere;
}
else if(i<end){
/*
if(((c=data[i-1])=='\r' || c=='\n') &&
(c=data[i])!='\r' && c!='\n'){
term=term.next;
continue matchHere;
}
*/
//5 aug 2001
//if((c=data[i-1])=='\r' || c=='\n'){ ??
if((c=data[i-1])=='\n'){
term=term.next;
continue matchHere;
}
}
break;
case Term.BITSET:{
//can only be 1-char-wide
// \/
if(i>=end) break;
c=data[i];
if(!(c<=255 && term.bitset[c])^term.inverse) break;
i++;
term=term.next;
continue matchHere;
}
case Term.BITSET2:{
//can only be 1-char-wide
// \/
if(i>=end) break;
c=data[i];
boolean[] arr=term.bitset2[c>>8];
if(arr==null || !arr[c&255]^term.inverse) break;
i++;
term=term.next;
continue matchHere;
}
case Term.BOUNDARY:{
boolean ch1Meets=false,ch2Meets=false;
boolean[] bitset=term.bitset;
test1:{
int j=i-1;
//if(j<offset || j>=end) break test1;
if(j<offset) break test1;
c= data[j];
ch1Meets= (c<256 && bitset[c]);
}
test2:{
//if(i<offset || i>=end) break test2;
if(i>=end) break test2;
c= data[i];
ch2Meets= (c<256 && bitset[c]);
}
if(ch1Meets^ch2Meets^term.inverse){ //meets
term=term.next;
continue matchHere;
}
else break;
}
case Term.UBOUNDARY:{
boolean ch1Meets=false,ch2Meets=false;
boolean[][] bitset2=term.bitset2;
test1:{
int j=i-1;
//if(j<offset || j>=end) break test1;
if(j<offset) break test1;
c= data[j];
boolean[] bits=bitset2[c>>8];
ch1Meets= bits!=null && bits[c&0xff];
}
test2:{
//if(i<offset || i>=end) break test2;
if(i>=end) break test2;
c= data[i];
boolean[] bits=bitset2[c>>8];
ch2Meets= bits!=null && bits[c&0xff];
}
if(ch1Meets^ch2Meets^term.inverse){ //is boundary ^ inv
term=term.next;
continue matchHere;
}
else break;
}
case Term.DIRECTION:{
boolean ch1Meets=false,ch2Meets=false;
boolean[] bitset=term.bitset;
boolean inv=term.inverse;
//System.out.println("i="+i+", inv="+inv+", bitset="+CharacterClass.stringValue0(bitset));
int j=i-1;
//if(j>=offset && j<end){
if(j>=offset){
c= data[j];
ch1Meets= c<256 && bitset[c];
//System.out.println(" ch1Meets="+ch1Meets);
}
if(ch1Meets^inv) break;
//if(i>=offset && i<end){
if(i<end){
c= data[i];
ch2Meets= c<256 && bitset[c];
//System.out.println(" ch2Meets="+ch2Meets);
}
if(!ch2Meets^inv) break;
//System.out.println(" Ok");
term=term.next;
continue matchHere;
}
case Term.UDIRECTION:{
boolean ch1Meets=false,ch2Meets=false;
boolean[][] bitset2=term.bitset2;
boolean inv=term.inverse;
int j=i-1;
//if(j>=offset && j<end){
if(j>=offset){
c= data[j];
boolean[] bits=bitset2[c>>8];
ch1Meets= bits!=null && bits[c&0xff];
}
if(ch1Meets^inv) break;
//if(i>=offset && i<end){
if(i<end){
c= data[i];
boolean[] bits=bitset2[c>>8];
ch2Meets= bits!=null && bits[c&0xff];
}
if(!ch2Meets^inv) break;
term=term.next;
continue matchHere;
}
case Term.REG:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
int rLen;
if(sampleOffset<0 || (rLen=sampleOutside-sampleOffset)<0){
break;
}
else if(rLen==0){
term=term.next;
continue matchHere;
}
// don't prevent us from reaching the 'end'
if((i+rLen)>end) break;
if(compareRegions(data,sampleOffset,i,rLen,end)){
i+=rLen;
term=term.next;
continue matchHere;
}
break;
}
case Term.REG_I:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
int rLen;
if(sampleOffset<0 || (rLen=sampleOutside-sampleOffset)<0){
break;
}
else if(rLen==0){
term=term.next;
continue matchHere;
}
// don't prevent us from reaching the 'end'
if((i+rLen)>end) break;
if(compareRegionsI(data,sampleOffset,i,rLen,end)){
i+=rLen;
term=term.next;
continue matchHere;
}
break;
}
case Term.REPEAT_0_INF:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
//i+=(cnt=repeat(data,i,end,term.target));
if((cnt=repeat(data,i,end,term.target))<=0){
term=term.next;
continue;
}
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_MIN_INF:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
cnt=repeat(data,i,end,term.target);
if(cnt<term.minCount) break;
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_MIN_MAX:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
int out1=end;
int out2=i+term.maxCount;
cnt=repeat(data,i,out1<out2? out1: out2,term.target);
if(cnt<term.minCount) break;
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_REG_MIN_INF:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
//if(sampleOffset<0) throw new Error("register is referred before definition: "+term.memreg);
//if(sampleOutside<0 || sampleOutside<sampleOffset) throw new Error("register is referred within definition: "+term.memreg);
/*@since 1.2*/
int bitset;
if(sampleOffset<0 || (bitset=sampleOutside-sampleOffset)<0){
break;
}
else if(bitset==0){
term=term.next;
continue matchHere;
}
cnt=0;
while(compareRegions(data,i,sampleOffset,bitset,end)){
cnt++;
i+=bitset;
}
if(cnt<term.minCount) break;
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual.regLen=bitset;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_REG_MIN_MAX:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
//if(sampleOffset<0) throw new Error("register is referred before definition: "+term.memreg);
//if(sampleOutside<0 || sampleOutside<sampleOffset) throw new Error("register is referred within definition: "+term.memreg);
/*@since 1.2*/
int bitset;
if(sampleOffset<0 || (bitset=sampleOutside-sampleOffset)<0){
break;
}
else if(bitset==0){
term=term.next;
continue matchHere;
}
cnt=0;
int countBack=term.maxCount;
while(countBack>0 && compareRegions(data,i,sampleOffset,bitset,end)){
cnt++;
i+=bitset;
countBack--;
}
if(cnt<term.minCount) break;
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual.regLen=bitset;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.BACKTRACK_0:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>0){
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.BACKTRACK_MIN:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>term.minCount){
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.BACKTRACK_FIND_MIN:{
//System.out.print("<<<[cnt=");
cnt=actual.cnt;
//System.out.print(cnt+", minCnt=");
//System.out.print(term.minCount+", target=");
//System.out.print(term.target+"]");
int minCnt;
if(cnt>(minCnt=term.minCount)){
int start=i+term.distance;
if(start>end){
int exceed=start-end;
cnt-=exceed;
if(cnt<=minCnt) break;
i-=exceed;
start=end;
}
int back=findBack(data,i+term.distance,cnt-minCnt,term.target);
//System.out.print("[back="+back+"]");
if(back<0) break;
//cnt-=back;
//i-=back;
if((cnt-=back)<=minCnt){
i-=back;
if(term.eat)i++;
term=term.next;
continue;
}
i-=back;
actual.cnt=cnt;
actual.index=i;
if(term.eat)i++;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
}
case Term.BACKTRACK_FINDREG_MIN:{
//System.out.print("<<<[cnt=");
cnt=actual.cnt;
//System.out.print(cnt+", minCnt=");
//System.out.print(term.minCount+", target=");
//System.out.print(term.target);
//System.out.print("reg=<"+memregs[term.target.memreg].in+","+memregs[term.target.memreg].out+">]");
int minCnt;
if(cnt>(minCnt=term.minCount)){
int start=i+term.distance;
if(start>end){
int exceed=start-end;
cnt-=exceed;
if(cnt<=minCnt) break;
i-=exceed;
start=end;
}
MemReg mr=memregs[term.target.memreg];
int sampleOff=mr.in;
int sampleLen=mr.out-sampleOff;
//if(sampleOff<0 || sampleLen<0) throw new Error("backreference used before definition: \\"+term.memreg);
//int back=findBackReg(data,i+term.distance,sampleOff,sampleLen,cnt-minCnt,term.target,end);
//if(back<0) break;
/*@since 1.2*/
int back;
if(sampleOff<0 || sampleLen<0){
//the group is not def., as in the case of '(\w+)\1'
//treat as usual BACKTRACK_MIN
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else if(sampleLen==0){
back=1;
}
else{
back=findBackReg(data,i+term.distance,sampleOff,sampleLen,cnt-minCnt,term.target,end);
//System.out.print("[back="+back+"]");
if(back<0) break;
}
cnt-=back;
i-=back;
actual.cnt=cnt;
actual.index=i;
if(term.eat)i+=sampleLen;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
}
case Term.BACKTRACK_REG_MIN:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>term.minCount){
regLen=actual.regLen;
cnt--;
i-=regLen;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
//actual.regLen=regLen;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.GROUP_IN:{
memreg=term.memreg;
//memreg=0 is a regex itself; we don't need to handle it
//because regex bounds already are in wOffset and wEnd
if(memreg>0){
//MemReg mr=memregs[memreg];
//saveMemregState((top!=null)? top: defaultEntry,memreg,mr);
//mr.in=i;
memregs[memreg].tmp=i; //assume
}
term=term.next;
continue;
}
case Term.GROUP_OUT:
memreg=term.memreg;
//see above
if(memreg>0){
//if(term.saveState)saveMemregState((top!=null)? top: defaultEntry,memreg,memregs);
MemReg mr=memregs[memreg];
SearchEntry.saveMemregState((top!=null)? top: defaultEntry,memreg,mr);
mr.in=mr.tmp; //commit
mr.out=i;
}
term=term.next;
continue;
case Term.PLOOKBEHIND_IN:{
int tmp=i-term.distance;
if(tmp<offset) break;
//System.out.println("term="+term+", next="+term.next);
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
i=tmp;
le.actual=actual;
le.top=top;
term=term.next;
continue;
}
case Term.INDEPENDENT_IN:
case Term.PLOOKAHEAD_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
term=term.next;
continue;
}
case Term.LOOKBEHIND_CONDITION_OUT:
case Term.LOOKAHEAD_CONDITION_OUT:
case Term.PLOOKAHEAD_OUT:
case Term.PLOOKBEHIND_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
i=le.index;
actual=le.actual;
top=le.top;
term=term.next;
continue;
}
case Term.INDEPENDENT_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
actual=le.actual;
top=le.top;
term=term.next;
continue;
}
case Term.NLOOKBEHIND_IN:{
int tmp=i-term.distance;
if(tmp<offset){
term=term.failNext;
continue;
}
LAEntry le=lookaheads[term.lookaheadId];
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
i=tmp;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.NLOOKAHEAD_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.NLOOKBEHIND_OUT:
case Term.NLOOKAHEAD_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
actual=le.actual;
top=le.top;
break;
}
case Term.LOOKBEHIND_CONDITION_IN:{
int tmp=i-term.distance;
if(tmp<offset){
term=term.failNext;
continue;
}
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
i=tmp;
term=term.next;
continue;
}
case Term.LOOKAHEAD_CONDITION_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.MEMREG_CONDITION:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
if(sampleOffset>=0 && sampleOutside>=0 && sampleOutside>=sampleOffset){
term=term.next;
}
else{
term=term.failNext;
}
continue;
}
case Term.BRANCH_STORE_CNT_AUX1:
actual.regLen=regLen;
case Term.BRANCH_STORE_CNT:
actual.cnt=cnt;
case Term.BRANCH:
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
case Term.SUCCESS:
//System.out.println("success, matchEnd="+matchEnd+", i="+i+", end="+end);
if(!matchEnd || i==end){
this.wOffset=memregs[0].in=wOffset;
this.wEnd=memregs[0].out=i;
this.top=top;
return true;
}
else break;
case Term.CNT_SET_0:
cnt=0;
term=term.next;
continue;
case Term.CNT_INC:
cnt++;
term=term.next;
continue;
case Term.CNT_GT_EQ:
if(cnt>=term.maxCount){
term=term.next;
continue;
}
else break;
case Term.READ_CNT_LT:
cnt=actual.cnt;
if(cnt<term.maxCount){
term=term.next;
continue;
}
else break;
case Term.CRSTORE_CRINC:{
int cntvalue=counters[cntreg=term.cntreg];
SearchEntry.saveCntState((top!=null)? top: defaultEntry,cntreg,cntvalue);
counters[cntreg]=++cntvalue;
term=term.next;
continue;
}
case Term.CR_SET_0:
counters[term.cntreg]=0;
term=term.next;
continue;
case Term.CR_LT:
if(counters[term.cntreg]<term.maxCount){
term=term.next;
continue;
}
else break;
case Term.CR_GT_EQ:
if(counters[term.cntreg]>=term.maxCount){
term=term.next;
continue;
}
else break;
default:
throw new Error("unknown term type: "+term.type);
}
//if(top==null) break matchHere;
if(allowIncomplete && i==end){
//an attempt to implement matchesPrefix()
//not sure it's a good way
//27-04-2002: just as expencted,
//the side effect was found (and POSSIBLY fixed);
//see the case Term.START
return true;
}
if(top==null){
break matchHere;
}
//pop the stack
top=(actual=top).sub;
term=actual.term;
i=actual.index;
//System.out.println("***POP*** : branch to #"+term.instanceNum+" at "+i);
if(actual.isState){
SearchEntry.popState(actual,memregs,counters);
}
}
if(defaultEntry.isState)SearchEntry.popState(defaultEntry,memregs,counters);
term=root;
//wOffset++;
//i=wOffset;
i=++wOffset;
}
this.wOffset=wOffset;
this.top=top;
return false;
}
private static final boolean compareRegions(char[] arr, int off1, int off2, int len,int out){
//System.out.print("out="+out+", off1="+off1+", off2="+off2+", len="+len+", reg1="+new String(arr,off1,len)+", reg2="+new String(arr,off2,len));
int p1=off1+len-1;
int p2=off2+len-1;
if(p1>=out || p2>=out){
//System.out.println(" : out");
return false;
}
for(int c=len;c>0;c--,p1--,p2--){
if(arr[p1]!=arr[p2]){
//System.out.println(" : no");
return false;
}
}
//System.out.println(" : yes");
return true;
}
private static final boolean compareRegionsI(char[] arr, int off1, int off2, int len,int out){
int p1=off1+len-1;
int p2=off2+len-1;
if(p1>=out || p2>=out){
return false;
}
char c1,c2;
for(int c=len;c>0;c--,p1--,p2--){
if((c1=arr[p1])!=Character.toLowerCase(c2=arr[p2]) &&
c1!=Character.toUpperCase(c2) &&
c1!=Character.toTitleCase(c2)) return false;
}
return true;
}
//repeat while matches
private static final int repeat(char[] data,int off,int out,Term term){
//System.out.print("off="+off+", out="+out+", term="+term);
switch(term.type){
case Term.CHAR:{
char c=term.c;
int i=off;
while(i<out){
if(data[i]!=c) break;
i++;
}
//System.out.println(", returning "+(i-off));
return i-off;
}
case Term.ANY_CHAR:{
return out-off;
}
case Term.ANY_CHAR_NE:{
int i=off;
while(i<out){
if(data[i]=='\n') break;
i++;
}
return i-off;
}
case Term.BITSET:{
boolean[] arr=term.bitset;
int i=off;
char c;
if(term.inverse) while(i<out){
if((c=data[i])<=255 && arr[c]) break;
else i++;
}
else while(i<out){
if((c=data[i])<=255 && arr[c]) i++;
else break;
}
return i-off;
}
case Term.BITSET2:{
int i=off;
boolean[][] bitset2=term.bitset2;
char c;
if(term.inverse) while(i<out){
boolean[] arr=bitset2[(c=data[i])>>8];
if(arr!=null && arr[c&0xff]) break;
else i++;
}
else while(i<out){
boolean[] arr=bitset2[(c=data[i])>>8];
if(arr!=null && arr[c&0xff]) i++;
else break;
}
return i-off;
}
}
throw new Error("this kind of term can't be quantified:"+term.type);
}
//repeat while doesn't match
private static final int find(char[] data,int off,int out,Term term){
//System.out.print("off="+off+", out="+out+", term="+term);
if(off>=out) return -1;
switch(term.type){
case Term.CHAR:{
char c=term.c;
int i=off;
while(i<out){
if(data[i]==c) break;
i++;
}
//System.out.println(", returning "+(i-off));
return i-off;
}
case Term.BITSET:{
boolean[] arr=term.bitset;
int i=off;
char c;
if(!term.inverse) while(i<out){
if((c=data[i])<=255 && arr[c]) break;
else i++;
}
else while(i<out){
if((c=data[i])<=255 && arr[c]) i++;
else break;
}
return i-off;
}
case Term.BITSET2:{
int i=off;
boolean[][] bitset2=term.bitset2;
char c;
if(!term.inverse) while(i<out){
boolean[] arr=bitset2[(c=data[i])>>8];
if(arr!=null && arr[c&0xff]) break;
else i++;
}
else while(i<out){
boolean[] arr=bitset2[(c=data[i])>>8];
if(arr!=null && arr[c&0xff]) i++;
else break;
}
return i-off;
}
}
throw new IllegalArgumentException("can't seek this kind of term:"+term.type);
}
private static final int findReg(char[] data,int off,int regOff,int regLen,Term term,int out){
//System.out.print("off="+off+", out="+out+", term="+term);
if(off>=out) return -1;
int i=off;
if(term.type==Term.REG){
while(i<out){
if(compareRegions(data,i,regOff,regLen,out)) break;
i++;
}
}
else if(term.type==Term.REG_I){
while(i<out){
if(compareRegionsI(data,i,regOff,regLen,out)) break;
i++;
}
}
else throw new IllegalArgumentException("wrong findReg() target:"+term.type);
return off-i;
}
private static final int findBack(char[] data,int off,int maxCount,Term term){
//System.out.print("off="+off+", maxCount="+maxCount+", term="+term);
switch(term.type){
case Term.CHAR:{
char c=term.c;
int i=off;
int iMin=off-maxCount;
for(;;){
if(data[--i]==c) break;
if(i<=iMin) return -1;
}
//System.out.println(", returning "+(off-i));
return off-i;
}
case Term.BITSET:{
boolean[] arr=term.bitset;
int i=off;
char c;
int iMin=off-maxCount;
if(!term.inverse) for(;;){
if((c=data[--i])<=255 && arr[c]) break;
if(i<=iMin) return -1;
}
else for(;;){
if((c=data[--i])>255 || !arr[c]) break;
if(i<=iMin) return -1;
}
return off-i;
}
case Term.BITSET2:{
boolean[][] bitset2=term.bitset2;
int i=off;
char c;
int iMin=off-maxCount;
if(!term.inverse) for(;;){
boolean[] arr=bitset2[(c=data[--i])>>8];
if(arr!=null && arr[c&0xff]) break;
if(i<=iMin) return -1;
}
else for(;;){
boolean[] arr=bitset2[(c=data[--i])>>8];
if(arr==null || arr[c&0xff]) break;
if(i<=iMin) return -1;
}
return off-i;
}
}
throw new IllegalArgumentException("can't find this kind of term:"+term.type);
}
private static final int findBackReg(char[] data,int off,int regOff,int regLen,int maxCount,Term term,int out){
//assume that the cases when regLen==0 or maxCount==0 are handled by caller
int i=off;
int iMin=off-maxCount;
if(term.type==Term.REG){
/*@since 1.2*/
char first=data[regOff];
regOff++;
regLen--;
for(;;){
i--;
if(data[i]==first && compareRegions(data,i+1,regOff,regLen,out)) break;
if(i<=iMin) return -1;
}
}
else if(term.type==Term.REG_I){
/*@since 1.2*/
char c=data[regOff];
char firstLower=Character.toLowerCase(c);
char firstUpper=Character.toUpperCase(c);
char firstTitle=Character.toTitleCase(c);
regOff++;
regLen--;
for(;;){
i--;
if(((c=data[i])==firstLower || c==firstUpper || c==firstTitle) && compareRegionsI(data,i+1,regOff,regLen,out)) break;
if(i<=iMin) return -1;
}
return off-i;
}
else throw new IllegalArgumentException("wrong findBackReg() target type :"+term.type);
return off-i;
}
public String toString_d(){
StringBuffer s=new StringBuffer();
s.append("counters: ");
s.append(counters==null? 0: counters.length);
s.append("\r\nmemregs: ");
s.append(memregs.length);
for(int i=0;i<memregs.length;i++) s.append("\r\n #"+i+": ["+memregs[i].in+","+memregs[i].out+"](\""+getString(memregs[i].in,memregs[i].out)+"\")");
s.append("\r\ndata: ");
if(data!=null)s.append(data.length);
else s.append("[none]");
s.append("\r\noffset: ");
s.append(offset);
s.append("\r\nend: ");
s.append(end);
s.append("\r\nwOffset: ");
s.append(wOffset);
s.append("\r\nwEnd: ");
s.append(wEnd);
s.append("\r\nregex: ");
s.append(re);
return s.toString();
}
}
class SearchEntry{
Term term;
int index;
int cnt;
int regLen;
boolean isState;
SearchEntry sub,on;
private static class MState{
int index,in,out;
MState next,prev;
}
private static class CState{
int index,value;
CState next,prev;
}
private MState mHead,mCurrent;
private CState cHead,cCurrent;
final static void saveMemregState(SearchEntry entry,int memreg, MemReg mr){
//System.out.println("saveMemregState("+entry+","+memreg+"):");
entry.isState=true;
MState current=entry.mCurrent;
if(current==null){
MState head=entry.mHead;
if(head==null) entry.mHead=entry.mCurrent=current=new MState();
else current=head;
}
else{
MState next=current.next;
if(next==null){
current.next=next=new MState();
next.prev=current;
}
current=next;
}
current.index=memreg;
current.in=mr.in;
current.out=mr.out;
entry.mCurrent=current;
}
final static void saveCntState(SearchEntry entry,int cntreg,int value){
entry.isState=true;
CState current=entry.cCurrent;
if(current==null){
CState head=entry.cHead;
if(head==null) entry.cHead=entry.cCurrent=current=new CState();
else current=head;
}
else{
CState next=current.next;
if(next==null){
current.next=next=new CState();
next.prev=current;
}
current=next;
}
current.index=cntreg;
current.value=value;
entry.cCurrent=current;
}
final static void popState(SearchEntry entry, MemReg[] memregs, int[] counters){
//System.out.println("popState("+entry+"):");
MState ms=entry.mCurrent;
while(ms!=null){
MemReg mr=memregs[ms.index];
mr.in=ms.in;
mr.out=ms.out;
ms=ms.prev;
}
CState cs=entry.cCurrent;
while(cs!=null){
counters[cs.index]=cs.value;
cs=cs.prev;
}
entry.mCurrent=null;
entry.cCurrent=null;
entry.isState=false;
}
final void reset(int restQueue){
term=null;
index=cnt=regLen=0;
mCurrent=null;
cCurrent=null;
isState=false;
SearchEntry on=this.on;
if(on!=null){
if(restQueue>0) on.reset(restQueue-1);
else{
this.on=null;
on.sub=null;
}
}
//sub=on=null;
}
}
class MemReg{
int index;
int in=-1,out=-1;
int tmp=-1; //for assuming at GROUP_IN
MemReg(int index){
this.index=index;
}
void reset(){
in=out=-1;
}
}
class LAEntry{
int index;
SearchEntry top,actual;
}
| true | true | private final boolean search(int anchors){
called=true;
final int end=this.end;
int offset=this.offset;
char[] data=this.data;
int wOffset=this.wOffset;
int wEnd=this.wEnd;
MemReg[] memregs=this.memregs;
int[] counters=this.counters;
LAEntry[] lookaheads=this.lookaheads;
//int memregCount=memregs.length;
//int cntCount=counters.length;
int memregCount=this.memregCount;
int cntCount=this.counterCount;
SearchEntry defaultEntry=this.defaultEntry;
SearchEntry first=this.first;
SearchEntry top=this.top;
SearchEntry actual=null;
int cnt,regLen;
int i;
final boolean matchEnd=(anchors&ANCHOR_END)>0;
final boolean allowIncomplete=(anchors&ACCEPT_INCOMPLETE)>0;
Pattern re=this.re;
Term root=re.root;
Term term;
if(top==null){
if((anchors&ANCHOR_START)>0){
term=re.root0; //raw root
root=startAnchor;
}
else if((anchors&ANCHOR_LASTMATCH)>0){
term=re.root0; //raw root
root=lastMatchAnchor;
}
else{
term=root; //optimized root
}
i=wOffset;
actual=first;
SearchEntry.popState(defaultEntry,memregs,counters);
}
else{
top=(actual=top).sub;
term=actual.term;
i=actual.index;
SearchEntry.popState(actual,memregs,counters);
}
cnt=actual.cnt;
regLen=actual.regLen;
main:
while(wOffset<=end){
matchHere:
for(;;){
/*
System.out.print("char: "+i+", term: ");
System.out.print(term.toString());
System.out.print(" // mrs:{");
for(int dbi=0;dbi<memregs.length;dbi++){
System.out.print('[');
System.out.print(memregs[dbi].in);
System.out.print(',');
System.out.print(memregs[dbi].out);
System.out.print(']');
System.out.print(' ');
}
System.out.print("}, crs:{");
for(int dbi=0;dbi<counters.length;dbi++){
System.out.print(counters[dbi]);
if(dbi<counters.length-1)System.out.print(',');
}
System.out.println("}");
*/
int memreg,cntreg;
char c;
switch(term.type){
case Term.FIND:{
int jump=find(data,i+term.distance,end,term.target); //don't eat the last match
if(jump<0) break main; //return false
i+=jump;
wOffset=i; //force window to move
if(term.eat){
if(i==end) break;
i++;
}
term=term.next;
continue matchHere;
}
case Term.FINDREG:{
MemReg mr=memregs[term.target.memreg];
int sampleOff=mr.in;
int sampleLen=mr.out-sampleOff;
//if(sampleOff<0 || sampleLen<0) throw new Error("backreference used before definition: \\"+term.memreg);
/*@since 1.2*/
if(sampleOff<0 || sampleLen<0){
break;
}
else if(sampleLen==0){
term=term.next;
continue matchHere;
}
int jump=findReg(data,i+term.distance,sampleOff,sampleLen,term.target,end); //don't eat the last match
if(jump<0) break main; //return false
i+=jump;
wOffset=i; //force window to move
if(term.eat){
i+=sampleLen;
if(i>end) break;
}
term=term.next;
continue matchHere;
}
case Term.VOID:
term=term.next;
continue matchHere;
case Term.CHAR:
//can only be 1-char-wide
// \/
if(i>=end || data[i]!=term.c) break;
//System.out.println("CHAR: "+data[i]+", i="+i);
i++;
term=term.next;
continue matchHere;
case Term.ANY_CHAR:
//can only be 1-char-wide
// \/
if(i>=end) break;
i++;
term=term.next;
continue matchHere;
case Term.ANY_CHAR_NE:
//can only be 1-char-wide
// \/
if(i>=end || data[i]=='\n') break;
i++;
term=term.next;
continue matchHere;
case Term.END:
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
break;
case Term.END_EOL: //perl's $
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
else{
boolean matches=
i>=end |
((i+1)==end && data[i]=='\n');
if(matches){
term=term.next;
continue matchHere;
}
else break;
}
case Term.LINE_END:
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
else{
/*
if(((c=data[i])=='\r' || c=='\n') &&
(c=data[i-1])!='\r' && c!='\n'){
term=term.next;
continue matchHere;
}
*/
//5 aug 2001
if(data[i]=='\n'){
term=term.next;
continue matchHere;
}
}
break;
case Term.START: //Perl's "^"
if(i==offset){ //meets
term=term.next;
continue matchHere;
}
//break;
//changed on 27-04-2002
//due to a side effect: if ALLOW_INCOMPLETE is enabled,
//the anchorStart moves up to the end and succeeds
//(see comments at the last lines of matchHere, ~line 1830)
//Solution: if there are some entries on the stack ("^a|b$"),
//try them; otherwise it's a final 'no'
//if(top!=null) break;
//else break main;
//changed on 25-05-2002
//rationale: if the term is startAnchor,
//it's the root term by definition,
//so if it doesn't match, the entire pattern
//couldn't match too;
//otherwise we could have the following problem:
//"c|^a" against "abc" finds only "a"
if(top!=null) break;
if(term!=startAnchor) break;
else break main;
case Term.LAST_MATCH_END:
if(i==wEnd){ //meets
term=term.next;
continue matchHere;
}
break main; //return false
case Term.LINE_START:
if(i==offset){ //meets
term=term.next;
continue matchHere;
}
else if(i<end){
/*
if(((c=data[i-1])=='\r' || c=='\n') &&
(c=data[i])!='\r' && c!='\n'){
term=term.next;
continue matchHere;
}
*/
//5 aug 2001
//if((c=data[i-1])=='\r' || c=='\n'){ ??
if((c=data[i-1])=='\n'){
term=term.next;
continue matchHere;
}
}
break;
case Term.BITSET:{
//can only be 1-char-wide
// \/
if(i>=end) break;
c=data[i];
if(!(c<=255 && term.bitset[c])^term.inverse) break;
i++;
term=term.next;
continue matchHere;
}
case Term.BITSET2:{
//can only be 1-char-wide
// \/
if(i>=end) break;
c=data[i];
boolean[] arr=term.bitset2[c>>8];
if(arr==null || !arr[c&255]^term.inverse) break;
i++;
term=term.next;
continue matchHere;
}
case Term.BOUNDARY:{
boolean ch1Meets=false,ch2Meets=false;
boolean[] bitset=term.bitset;
test1:{
int j=i-1;
//if(j<offset || j>=end) break test1;
if(j<offset) break test1;
c= data[j];
ch1Meets= (c<256 && bitset[c]);
}
test2:{
//if(i<offset || i>=end) break test2;
if(i>=end) break test2;
c= data[i];
ch2Meets= (c<256 && bitset[c]);
}
if(ch1Meets^ch2Meets^term.inverse){ //meets
term=term.next;
continue matchHere;
}
else break;
}
case Term.UBOUNDARY:{
boolean ch1Meets=false,ch2Meets=false;
boolean[][] bitset2=term.bitset2;
test1:{
int j=i-1;
//if(j<offset || j>=end) break test1;
if(j<offset) break test1;
c= data[j];
boolean[] bits=bitset2[c>>8];
ch1Meets= bits!=null && bits[c&0xff];
}
test2:{
//if(i<offset || i>=end) break test2;
if(i>=end) break test2;
c= data[i];
boolean[] bits=bitset2[c>>8];
ch2Meets= bits!=null && bits[c&0xff];
}
if(ch1Meets^ch2Meets^term.inverse){ //is boundary ^ inv
term=term.next;
continue matchHere;
}
else break;
}
case Term.DIRECTION:{
boolean ch1Meets=false,ch2Meets=false;
boolean[] bitset=term.bitset;
boolean inv=term.inverse;
//System.out.println("i="+i+", inv="+inv+", bitset="+CharacterClass.stringValue0(bitset));
int j=i-1;
//if(j>=offset && j<end){
if(j>=offset){
c= data[j];
ch1Meets= c<256 && bitset[c];
//System.out.println(" ch1Meets="+ch1Meets);
}
if(ch1Meets^inv) break;
//if(i>=offset && i<end){
if(i<end){
c= data[i];
ch2Meets= c<256 && bitset[c];
//System.out.println(" ch2Meets="+ch2Meets);
}
if(!ch2Meets^inv) break;
//System.out.println(" Ok");
term=term.next;
continue matchHere;
}
case Term.UDIRECTION:{
boolean ch1Meets=false,ch2Meets=false;
boolean[][] bitset2=term.bitset2;
boolean inv=term.inverse;
int j=i-1;
//if(j>=offset && j<end){
if(j>=offset){
c= data[j];
boolean[] bits=bitset2[c>>8];
ch1Meets= bits!=null && bits[c&0xff];
}
if(ch1Meets^inv) break;
//if(i>=offset && i<end){
if(i<end){
c= data[i];
boolean[] bits=bitset2[c>>8];
ch2Meets= bits!=null && bits[c&0xff];
}
if(!ch2Meets^inv) break;
term=term.next;
continue matchHere;
}
case Term.REG:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
int rLen;
if(sampleOffset<0 || (rLen=sampleOutside-sampleOffset)<0){
break;
}
else if(rLen==0){
term=term.next;
continue matchHere;
}
// don't prevent us from reaching the 'end'
if((i+rLen)>end) break;
if(compareRegions(data,sampleOffset,i,rLen,end)){
i+=rLen;
term=term.next;
continue matchHere;
}
break;
}
case Term.REG_I:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
int rLen;
if(sampleOffset<0 || (rLen=sampleOutside-sampleOffset)<0){
break;
}
else if(rLen==0){
term=term.next;
continue matchHere;
}
// don't prevent us from reaching the 'end'
if((i+rLen)>end) break;
if(compareRegionsI(data,sampleOffset,i,rLen,end)){
i+=rLen;
term=term.next;
continue matchHere;
}
break;
}
case Term.REPEAT_0_INF:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
//i+=(cnt=repeat(data,i,end,term.target));
if((cnt=repeat(data,i,end,term.target))<=0){
term=term.next;
continue;
}
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_MIN_INF:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
cnt=repeat(data,i,end,term.target);
if(cnt<term.minCount) break;
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_MIN_MAX:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
int out1=end;
int out2=i+term.maxCount;
cnt=repeat(data,i,out1<out2? out1: out2,term.target);
if(cnt<term.minCount) break;
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_REG_MIN_INF:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
//if(sampleOffset<0) throw new Error("register is referred before definition: "+term.memreg);
//if(sampleOutside<0 || sampleOutside<sampleOffset) throw new Error("register is referred within definition: "+term.memreg);
/*@since 1.2*/
int bitset;
if(sampleOffset<0 || (bitset=sampleOutside-sampleOffset)<0){
break;
}
else if(bitset==0){
term=term.next;
continue matchHere;
}
cnt=0;
while(compareRegions(data,i,sampleOffset,bitset,end)){
cnt++;
i+=bitset;
}
if(cnt<term.minCount) break;
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual.regLen=bitset;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_REG_MIN_MAX:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
//if(sampleOffset<0) throw new Error("register is referred before definition: "+term.memreg);
//if(sampleOutside<0 || sampleOutside<sampleOffset) throw new Error("register is referred within definition: "+term.memreg);
/*@since 1.2*/
int bitset;
if(sampleOffset<0 || (bitset=sampleOutside-sampleOffset)<0){
break;
}
else if(bitset==0){
term=term.next;
continue matchHere;
}
cnt=0;
int countBack=term.maxCount;
while(countBack>0 && compareRegions(data,i,sampleOffset,bitset,end)){
cnt++;
i+=bitset;
countBack--;
}
if(cnt<term.minCount) break;
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual.regLen=bitset;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.BACKTRACK_0:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>0){
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.BACKTRACK_MIN:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>term.minCount){
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.BACKTRACK_FIND_MIN:{
//System.out.print("<<<[cnt=");
cnt=actual.cnt;
//System.out.print(cnt+", minCnt=");
//System.out.print(term.minCount+", target=");
//System.out.print(term.target+"]");
int minCnt;
if(cnt>(minCnt=term.minCount)){
int start=i+term.distance;
if(start>end){
int exceed=start-end;
cnt-=exceed;
if(cnt<=minCnt) break;
i-=exceed;
start=end;
}
int back=findBack(data,i+term.distance,cnt-minCnt,term.target);
//System.out.print("[back="+back+"]");
if(back<0) break;
//cnt-=back;
//i-=back;
if((cnt-=back)<=minCnt){
i-=back;
if(term.eat)i++;
term=term.next;
continue;
}
i-=back;
actual.cnt=cnt;
actual.index=i;
if(term.eat)i++;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
}
case Term.BACKTRACK_FINDREG_MIN:{
//System.out.print("<<<[cnt=");
cnt=actual.cnt;
//System.out.print(cnt+", minCnt=");
//System.out.print(term.minCount+", target=");
//System.out.print(term.target);
//System.out.print("reg=<"+memregs[term.target.memreg].in+","+memregs[term.target.memreg].out+">]");
int minCnt;
if(cnt>(minCnt=term.minCount)){
int start=i+term.distance;
if(start>end){
int exceed=start-end;
cnt-=exceed;
if(cnt<=minCnt) break;
i-=exceed;
start=end;
}
MemReg mr=memregs[term.target.memreg];
int sampleOff=mr.in;
int sampleLen=mr.out-sampleOff;
//if(sampleOff<0 || sampleLen<0) throw new Error("backreference used before definition: \\"+term.memreg);
//int back=findBackReg(data,i+term.distance,sampleOff,sampleLen,cnt-minCnt,term.target,end);
//if(back<0) break;
/*@since 1.2*/
int back;
if(sampleOff<0 || sampleLen<0){
//the group is not def., as in the case of '(\w+)\1'
//treat as usual BACKTRACK_MIN
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else if(sampleLen==0){
back=1;
}
else{
back=findBackReg(data,i+term.distance,sampleOff,sampleLen,cnt-minCnt,term.target,end);
//System.out.print("[back="+back+"]");
if(back<0) break;
}
cnt-=back;
i-=back;
actual.cnt=cnt;
actual.index=i;
if(term.eat)i+=sampleLen;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
}
case Term.BACKTRACK_REG_MIN:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>term.minCount){
regLen=actual.regLen;
cnt--;
i-=regLen;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
//actual.regLen=regLen;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.GROUP_IN:{
memreg=term.memreg;
//memreg=0 is a regex itself; we don't need to handle it
//because regex bounds already are in wOffset and wEnd
if(memreg>0){
//MemReg mr=memregs[memreg];
//saveMemregState((top!=null)? top: defaultEntry,memreg,mr);
//mr.in=i;
memregs[memreg].tmp=i; //assume
}
term=term.next;
continue;
}
case Term.GROUP_OUT:
memreg=term.memreg;
//see above
if(memreg>0){
//if(term.saveState)saveMemregState((top!=null)? top: defaultEntry,memreg,memregs);
MemReg mr=memregs[memreg];
SearchEntry.saveMemregState((top!=null)? top: defaultEntry,memreg,mr);
mr.in=mr.tmp; //commit
mr.out=i;
}
term=term.next;
continue;
case Term.PLOOKBEHIND_IN:{
int tmp=i-term.distance;
if(tmp<offset) break;
//System.out.println("term="+term+", next="+term.next);
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
i=tmp;
le.actual=actual;
le.top=top;
term=term.next;
continue;
}
case Term.INDEPENDENT_IN:
case Term.PLOOKAHEAD_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
term=term.next;
continue;
}
case Term.LOOKBEHIND_CONDITION_OUT:
case Term.LOOKAHEAD_CONDITION_OUT:
case Term.PLOOKAHEAD_OUT:
case Term.PLOOKBEHIND_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
i=le.index;
actual=le.actual;
top=le.top;
term=term.next;
continue;
}
case Term.INDEPENDENT_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
actual=le.actual;
top=le.top;
term=term.next;
continue;
}
case Term.NLOOKBEHIND_IN:{
int tmp=i-term.distance;
if(tmp<offset){
term=term.failNext;
continue;
}
LAEntry le=lookaheads[term.lookaheadId];
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
i=tmp;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.NLOOKAHEAD_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.NLOOKBEHIND_OUT:
case Term.NLOOKAHEAD_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
actual=le.actual;
top=le.top;
break;
}
case Term.LOOKBEHIND_CONDITION_IN:{
int tmp=i-term.distance;
if(tmp<offset){
term=term.failNext;
continue;
}
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
i=tmp;
term=term.next;
continue;
}
case Term.LOOKAHEAD_CONDITION_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.MEMREG_CONDITION:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
if(sampleOffset>=0 && sampleOutside>=0 && sampleOutside>=sampleOffset){
term=term.next;
}
else{
term=term.failNext;
}
continue;
}
case Term.BRANCH_STORE_CNT_AUX1:
actual.regLen=regLen;
case Term.BRANCH_STORE_CNT:
actual.cnt=cnt;
case Term.BRANCH:
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
case Term.SUCCESS:
//System.out.println("success, matchEnd="+matchEnd+", i="+i+", end="+end);
if(!matchEnd || i==end){
this.wOffset=memregs[0].in=wOffset;
this.wEnd=memregs[0].out=i;
this.top=top;
return true;
}
else break;
case Term.CNT_SET_0:
cnt=0;
term=term.next;
continue;
case Term.CNT_INC:
cnt++;
term=term.next;
continue;
case Term.CNT_GT_EQ:
if(cnt>=term.maxCount){
term=term.next;
continue;
}
else break;
case Term.READ_CNT_LT:
cnt=actual.cnt;
if(cnt<term.maxCount){
term=term.next;
continue;
}
else break;
case Term.CRSTORE_CRINC:{
int cntvalue=counters[cntreg=term.cntreg];
SearchEntry.saveCntState((top!=null)? top: defaultEntry,cntreg,cntvalue);
counters[cntreg]=++cntvalue;
term=term.next;
continue;
}
case Term.CR_SET_0:
counters[term.cntreg]=0;
term=term.next;
continue;
case Term.CR_LT:
if(counters[term.cntreg]<term.maxCount){
term=term.next;
continue;
}
else break;
case Term.CR_GT_EQ:
if(counters[term.cntreg]>=term.maxCount){
term=term.next;
continue;
}
else break;
default:
throw new Error("unknown term type: "+term.type);
}
//if(top==null) break matchHere;
if(allowIncomplete && i==end){
//an attempt to implement matchesPrefix()
//not sure it's a good way
//27-04-2002: just as expencted,
//the side effect was found (and POSSIBLY fixed);
//see the case Term.START
return true;
}
if(top==null){
break matchHere;
}
//pop the stack
top=(actual=top).sub;
term=actual.term;
i=actual.index;
//System.out.println("***POP*** : branch to #"+term.instanceNum+" at "+i);
if(actual.isState){
SearchEntry.popState(actual,memregs,counters);
}
}
if(defaultEntry.isState)SearchEntry.popState(defaultEntry,memregs,counters);
term=root;
//wOffset++;
//i=wOffset;
i=++wOffset;
}
this.wOffset=wOffset;
this.top=top;
return false;
}
| private final boolean search(int anchors){
called=true;
final int end=this.end;
int offset=this.offset;
char[] data=this.data;
int wOffset=this.wOffset;
int wEnd=this.wEnd;
MemReg[] memregs=this.memregs;
int[] counters=this.counters;
LAEntry[] lookaheads=this.lookaheads;
//int memregCount=memregs.length;
//int cntCount=counters.length;
int memregCount=this.memregCount;
int cntCount=this.counterCount;
SearchEntry defaultEntry=this.defaultEntry;
SearchEntry first=this.first;
SearchEntry top=this.top;
SearchEntry actual=null;
int cnt,regLen;
int i;
final boolean matchEnd=(anchors&ANCHOR_END)>0;
final boolean allowIncomplete=(anchors&ACCEPT_INCOMPLETE)>0;
Pattern re=this.re;
Term root=re.root;
Term term;
if(top==null){
if((anchors&ANCHOR_START)>0){
term=re.root0; //raw root
root=startAnchor;
}
else if((anchors&ANCHOR_LASTMATCH)>0){
term=re.root0; //raw root
root=lastMatchAnchor;
}
else{
term=root; //optimized root
}
i=wOffset;
actual=first;
SearchEntry.popState(defaultEntry,memregs,counters);
}
else{
top=(actual=top).sub;
term=actual.term;
i=actual.index;
SearchEntry.popState(actual,memregs,counters);
}
cnt=actual.cnt;
regLen=actual.regLen;
main:
while(wOffset<=end){
matchHere:
for(;;){
/*
System.out.print("char: "+i+", term: ");
System.out.print(term.toString());
System.out.print(" // mrs:{");
for(int dbi=0;dbi<memregs.length;dbi++){
System.out.print('[');
System.out.print(memregs[dbi].in);
System.out.print(',');
System.out.print(memregs[dbi].out);
System.out.print(']');
System.out.print(' ');
}
System.out.print("}, crs:{");
for(int dbi=0;dbi<counters.length;dbi++){
System.out.print(counters[dbi]);
if(dbi<counters.length-1)System.out.print(',');
}
System.out.println("}");
*/
int memreg,cntreg;
char c;
switch(term.type){
case Term.FIND:{
int jump=find(data,i+term.distance,end,term.target); //don't eat the last match
if(jump<0) break main; //return false
i+=jump;
wOffset=i; //force window to move
if(term.eat){
if(i==end) break;
i++;
}
term=term.next;
continue matchHere;
}
case Term.FINDREG:{
MemReg mr=memregs[term.target.memreg];
int sampleOff=mr.in;
int sampleLen=mr.out-sampleOff;
//if(sampleOff<0 || sampleLen<0) throw new Error("backreference used before definition: \\"+term.memreg);
/*@since 1.2*/
if(sampleOff<0 || sampleLen<0){
break;
}
else if(sampleLen==0){
term=term.next;
continue matchHere;
}
int jump=findReg(data,i+term.distance,sampleOff,sampleLen,term.target,end); //don't eat the last match
if(jump<0) break main; //return false
i+=jump;
wOffset=i; //force window to move
if(term.eat){
i+=sampleLen;
if(i>end) break;
}
term=term.next;
continue matchHere;
}
case Term.VOID:
term=term.next;
continue matchHere;
case Term.CHAR:
//can only be 1-char-wide
// \/
if(i>=end || data[i]!=term.c) break;
//System.out.println("CHAR: "+data[i]+", i="+i);
i++;
term=term.next;
continue matchHere;
case Term.ANY_CHAR:
//can only be 1-char-wide
// \/
if(i>=end) break;
i++;
term=term.next;
continue matchHere;
case Term.ANY_CHAR_NE:
//can only be 1-char-wide
// \/
if(i>=end || data[i]=='\n') break;
i++;
term=term.next;
continue matchHere;
case Term.END:
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
break;
case Term.END_EOL: //perl's $
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
else{
boolean matches=
i>=end |
((i+1)==end && data[i]=='\n');
if(matches){
term=term.next;
continue matchHere;
}
else break;
}
case Term.LINE_END:
if(i>=end){ //meets
term=term.next;
continue matchHere;
}
else{
/*
if(((c=data[i])=='\r' || c=='\n') &&
(c=data[i-1])!='\r' && c!='\n'){
term=term.next;
continue matchHere;
}
*/
//5 aug 2001
if(data[i]=='\n'){
term=term.next;
continue matchHere;
}
}
break;
case Term.START: //Perl's "^"
if(i==offset){ //meets
term=term.next;
continue matchHere;
}
//break;
//changed on 27-04-2002
//due to a side effect: if ALLOW_INCOMPLETE is enabled,
//the anchorStart moves up to the end and succeeds
//(see comments at the last lines of matchHere, ~line 1830)
//Solution: if there are some entries on the stack ("^a|b$"),
//try them; otherwise it's a final 'no'
//if(top!=null) break;
//else break main;
//changed on 25-05-2002
//rationale: if the term is startAnchor,
//it's the root term by definition,
//so if it doesn't match, the entire pattern
//couldn't match too;
//otherwise we could have the following problem:
//"c|^a" against "abc" finds only "a"
if(top!=null) break;
if(term!=startAnchor) break;
else break main;
case Term.LAST_MATCH_END:
if(i==wEnd || wEnd == -1){ //meets
term=term.next;
continue matchHere;
}
break main; //return false
case Term.LINE_START:
if(i==offset){ //meets
term=term.next;
continue matchHere;
}
else if(i<end){
/*
if(((c=data[i-1])=='\r' || c=='\n') &&
(c=data[i])!='\r' && c!='\n'){
term=term.next;
continue matchHere;
}
*/
//5 aug 2001
//if((c=data[i-1])=='\r' || c=='\n'){ ??
if((c=data[i-1])=='\n'){
term=term.next;
continue matchHere;
}
}
break;
case Term.BITSET:{
//can only be 1-char-wide
// \/
if(i>=end) break;
c=data[i];
if(!(c<=255 && term.bitset[c])^term.inverse) break;
i++;
term=term.next;
continue matchHere;
}
case Term.BITSET2:{
//can only be 1-char-wide
// \/
if(i>=end) break;
c=data[i];
boolean[] arr=term.bitset2[c>>8];
if(arr==null || !arr[c&255]^term.inverse) break;
i++;
term=term.next;
continue matchHere;
}
case Term.BOUNDARY:{
boolean ch1Meets=false,ch2Meets=false;
boolean[] bitset=term.bitset;
test1:{
int j=i-1;
//if(j<offset || j>=end) break test1;
if(j<offset) break test1;
c= data[j];
ch1Meets= (c<256 && bitset[c]);
}
test2:{
//if(i<offset || i>=end) break test2;
if(i>=end) break test2;
c= data[i];
ch2Meets= (c<256 && bitset[c]);
}
if(ch1Meets^ch2Meets^term.inverse){ //meets
term=term.next;
continue matchHere;
}
else break;
}
case Term.UBOUNDARY:{
boolean ch1Meets=false,ch2Meets=false;
boolean[][] bitset2=term.bitset2;
test1:{
int j=i-1;
//if(j<offset || j>=end) break test1;
if(j<offset) break test1;
c= data[j];
boolean[] bits=bitset2[c>>8];
ch1Meets= bits!=null && bits[c&0xff];
}
test2:{
//if(i<offset || i>=end) break test2;
if(i>=end) break test2;
c= data[i];
boolean[] bits=bitset2[c>>8];
ch2Meets= bits!=null && bits[c&0xff];
}
if(ch1Meets^ch2Meets^term.inverse){ //is boundary ^ inv
term=term.next;
continue matchHere;
}
else break;
}
case Term.DIRECTION:{
boolean ch1Meets=false,ch2Meets=false;
boolean[] bitset=term.bitset;
boolean inv=term.inverse;
//System.out.println("i="+i+", inv="+inv+", bitset="+CharacterClass.stringValue0(bitset));
int j=i-1;
//if(j>=offset && j<end){
if(j>=offset){
c= data[j];
ch1Meets= c<256 && bitset[c];
//System.out.println(" ch1Meets="+ch1Meets);
}
if(ch1Meets^inv) break;
//if(i>=offset && i<end){
if(i<end){
c= data[i];
ch2Meets= c<256 && bitset[c];
//System.out.println(" ch2Meets="+ch2Meets);
}
if(!ch2Meets^inv) break;
//System.out.println(" Ok");
term=term.next;
continue matchHere;
}
case Term.UDIRECTION:{
boolean ch1Meets=false,ch2Meets=false;
boolean[][] bitset2=term.bitset2;
boolean inv=term.inverse;
int j=i-1;
//if(j>=offset && j<end){
if(j>=offset){
c= data[j];
boolean[] bits=bitset2[c>>8];
ch1Meets= bits!=null && bits[c&0xff];
}
if(ch1Meets^inv) break;
//if(i>=offset && i<end){
if(i<end){
c= data[i];
boolean[] bits=bitset2[c>>8];
ch2Meets= bits!=null && bits[c&0xff];
}
if(!ch2Meets^inv) break;
term=term.next;
continue matchHere;
}
case Term.REG:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
int rLen;
if(sampleOffset<0 || (rLen=sampleOutside-sampleOffset)<0){
break;
}
else if(rLen==0){
term=term.next;
continue matchHere;
}
// don't prevent us from reaching the 'end'
if((i+rLen)>end) break;
if(compareRegions(data,sampleOffset,i,rLen,end)){
i+=rLen;
term=term.next;
continue matchHere;
}
break;
}
case Term.REG_I:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
int rLen;
if(sampleOffset<0 || (rLen=sampleOutside-sampleOffset)<0){
break;
}
else if(rLen==0){
term=term.next;
continue matchHere;
}
// don't prevent us from reaching the 'end'
if((i+rLen)>end) break;
if(compareRegionsI(data,sampleOffset,i,rLen,end)){
i+=rLen;
term=term.next;
continue matchHere;
}
break;
}
case Term.REPEAT_0_INF:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
//i+=(cnt=repeat(data,i,end,term.target));
if((cnt=repeat(data,i,end,term.target))<=0){
term=term.next;
continue;
}
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_MIN_INF:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
cnt=repeat(data,i,end,term.target);
if(cnt<term.minCount) break;
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_MIN_MAX:{
//System.out.println("REPEAT, i="+i+", term.minCount="+term.minCount+", term.maxCount="+term.maxCount);
int out1=end;
int out2=i+term.maxCount;
cnt=repeat(data,i,out1<out2? out1: out2,term.target);
if(cnt<term.minCount) break;
i+=cnt;
//branch out the backtracker (that is term.failNext, see Term.make*())
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_REG_MIN_INF:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
//if(sampleOffset<0) throw new Error("register is referred before definition: "+term.memreg);
//if(sampleOutside<0 || sampleOutside<sampleOffset) throw new Error("register is referred within definition: "+term.memreg);
/*@since 1.2*/
int bitset;
if(sampleOffset<0 || (bitset=sampleOutside-sampleOffset)<0){
break;
}
else if(bitset==0){
term=term.next;
continue matchHere;
}
cnt=0;
while(compareRegions(data,i,sampleOffset,bitset,end)){
cnt++;
i+=bitset;
}
if(cnt<term.minCount) break;
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual.regLen=bitset;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.REPEAT_REG_MIN_MAX:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
//if(sampleOffset<0) throw new Error("register is referred before definition: "+term.memreg);
//if(sampleOutside<0 || sampleOutside<sampleOffset) throw new Error("register is referred within definition: "+term.memreg);
/*@since 1.2*/
int bitset;
if(sampleOffset<0 || (bitset=sampleOutside-sampleOffset)<0){
break;
}
else if(bitset==0){
term=term.next;
continue matchHere;
}
cnt=0;
int countBack=term.maxCount;
while(countBack>0 && compareRegions(data,i,sampleOffset,bitset,end)){
cnt++;
i+=bitset;
countBack--;
}
if(cnt<term.minCount) break;
actual.cnt=cnt;
actual.term=term.failNext;
actual.index=i;
actual.regLen=bitset;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.BACKTRACK_0:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>0){
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.BACKTRACK_MIN:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>term.minCount){
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.BACKTRACK_FIND_MIN:{
//System.out.print("<<<[cnt=");
cnt=actual.cnt;
//System.out.print(cnt+", minCnt=");
//System.out.print(term.minCount+", target=");
//System.out.print(term.target+"]");
int minCnt;
if(cnt>(minCnt=term.minCount)){
int start=i+term.distance;
if(start>end){
int exceed=start-end;
cnt-=exceed;
if(cnt<=minCnt) break;
i-=exceed;
start=end;
}
int back=findBack(data,i+term.distance,cnt-minCnt,term.target);
//System.out.print("[back="+back+"]");
if(back<0) break;
//cnt-=back;
//i-=back;
if((cnt-=back)<=minCnt){
i-=back;
if(term.eat)i++;
term=term.next;
continue;
}
i-=back;
actual.cnt=cnt;
actual.index=i;
if(term.eat)i++;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
}
case Term.BACKTRACK_FINDREG_MIN:{
//System.out.print("<<<[cnt=");
cnt=actual.cnt;
//System.out.print(cnt+", minCnt=");
//System.out.print(term.minCount+", target=");
//System.out.print(term.target);
//System.out.print("reg=<"+memregs[term.target.memreg].in+","+memregs[term.target.memreg].out+">]");
int minCnt;
if(cnt>(minCnt=term.minCount)){
int start=i+term.distance;
if(start>end){
int exceed=start-end;
cnt-=exceed;
if(cnt<=minCnt) break;
i-=exceed;
start=end;
}
MemReg mr=memregs[term.target.memreg];
int sampleOff=mr.in;
int sampleLen=mr.out-sampleOff;
//if(sampleOff<0 || sampleLen<0) throw new Error("backreference used before definition: \\"+term.memreg);
//int back=findBackReg(data,i+term.distance,sampleOff,sampleLen,cnt-minCnt,term.target,end);
//if(back<0) break;
/*@since 1.2*/
int back;
if(sampleOff<0 || sampleLen<0){
//the group is not def., as in the case of '(\w+)\1'
//treat as usual BACKTRACK_MIN
cnt--;
i--;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else if(sampleLen==0){
back=1;
}
else{
back=findBackReg(data,i+term.distance,sampleOff,sampleLen,cnt-minCnt,term.target,end);
//System.out.print("[back="+back+"]");
if(back<0) break;
}
cnt-=back;
i-=back;
actual.cnt=cnt;
actual.index=i;
if(term.eat)i+=sampleLen;
actual.term=term;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
}
case Term.BACKTRACK_REG_MIN:
//System.out.println("<<");
cnt=actual.cnt;
if(cnt>term.minCount){
regLen=actual.regLen;
cnt--;
i-=regLen;
actual.cnt=cnt;
actual.index=i;
actual.term=term;
//actual.regLen=regLen;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
else break;
case Term.GROUP_IN:{
memreg=term.memreg;
//memreg=0 is a regex itself; we don't need to handle it
//because regex bounds already are in wOffset and wEnd
if(memreg>0){
//MemReg mr=memregs[memreg];
//saveMemregState((top!=null)? top: defaultEntry,memreg,mr);
//mr.in=i;
memregs[memreg].tmp=i; //assume
}
term=term.next;
continue;
}
case Term.GROUP_OUT:
memreg=term.memreg;
//see above
if(memreg>0){
//if(term.saveState)saveMemregState((top!=null)? top: defaultEntry,memreg,memregs);
MemReg mr=memregs[memreg];
SearchEntry.saveMemregState((top!=null)? top: defaultEntry,memreg,mr);
mr.in=mr.tmp; //commit
mr.out=i;
}
term=term.next;
continue;
case Term.PLOOKBEHIND_IN:{
int tmp=i-term.distance;
if(tmp<offset) break;
//System.out.println("term="+term+", next="+term.next);
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
i=tmp;
le.actual=actual;
le.top=top;
term=term.next;
continue;
}
case Term.INDEPENDENT_IN:
case Term.PLOOKAHEAD_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
term=term.next;
continue;
}
case Term.LOOKBEHIND_CONDITION_OUT:
case Term.LOOKAHEAD_CONDITION_OUT:
case Term.PLOOKAHEAD_OUT:
case Term.PLOOKBEHIND_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
i=le.index;
actual=le.actual;
top=le.top;
term=term.next;
continue;
}
case Term.INDEPENDENT_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
actual=le.actual;
top=le.top;
term=term.next;
continue;
}
case Term.NLOOKBEHIND_IN:{
int tmp=i-term.distance;
if(tmp<offset){
term=term.failNext;
continue;
}
LAEntry le=lookaheads[term.lookaheadId];
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
i=tmp;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.NLOOKAHEAD_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.NLOOKBEHIND_OUT:
case Term.NLOOKAHEAD_OUT:{
LAEntry le=lookaheads[term.lookaheadId];
actual=le.actual;
top=le.top;
break;
}
case Term.LOOKBEHIND_CONDITION_IN:{
int tmp=i-term.distance;
if(tmp<offset){
term=term.failNext;
continue;
}
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
i=tmp;
term=term.next;
continue;
}
case Term.LOOKAHEAD_CONDITION_IN:{
LAEntry le=lookaheads[term.lookaheadId];
le.index=i;
le.actual=actual;
le.top=top;
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
}
case Term.MEMREG_CONDITION:{
MemReg mr=memregs[term.memreg];
int sampleOffset=mr.in;
int sampleOutside=mr.out;
if(sampleOffset>=0 && sampleOutside>=0 && sampleOutside>=sampleOffset){
term=term.next;
}
else{
term=term.failNext;
}
continue;
}
case Term.BRANCH_STORE_CNT_AUX1:
actual.regLen=regLen;
case Term.BRANCH_STORE_CNT:
actual.cnt=cnt;
case Term.BRANCH:
actual.term=term.failNext;
actual.index=i;
actual=(top=actual).on;
if(actual==null){
actual=new SearchEntry();
top.on=actual;
actual.sub=top;
}
term=term.next;
continue;
case Term.SUCCESS:
//System.out.println("success, matchEnd="+matchEnd+", i="+i+", end="+end);
if(!matchEnd || i==end){
this.wOffset=memregs[0].in=wOffset;
this.wEnd=memregs[0].out=i;
this.top=top;
return true;
}
else break;
case Term.CNT_SET_0:
cnt=0;
term=term.next;
continue;
case Term.CNT_INC:
cnt++;
term=term.next;
continue;
case Term.CNT_GT_EQ:
if(cnt>=term.maxCount){
term=term.next;
continue;
}
else break;
case Term.READ_CNT_LT:
cnt=actual.cnt;
if(cnt<term.maxCount){
term=term.next;
continue;
}
else break;
case Term.CRSTORE_CRINC:{
int cntvalue=counters[cntreg=term.cntreg];
SearchEntry.saveCntState((top!=null)? top: defaultEntry,cntreg,cntvalue);
counters[cntreg]=++cntvalue;
term=term.next;
continue;
}
case Term.CR_SET_0:
counters[term.cntreg]=0;
term=term.next;
continue;
case Term.CR_LT:
if(counters[term.cntreg]<term.maxCount){
term=term.next;
continue;
}
else break;
case Term.CR_GT_EQ:
if(counters[term.cntreg]>=term.maxCount){
term=term.next;
continue;
}
else break;
default:
throw new Error("unknown term type: "+term.type);
}
//if(top==null) break matchHere;
if(allowIncomplete && i==end){
//an attempt to implement matchesPrefix()
//not sure it's a good way
//27-04-2002: just as expencted,
//the side effect was found (and POSSIBLY fixed);
//see the case Term.START
return true;
}
if(top==null){
break matchHere;
}
//pop the stack
top=(actual=top).sub;
term=actual.term;
i=actual.index;
//System.out.println("***POP*** : branch to #"+term.instanceNum+" at "+i);
if(actual.isState){
SearchEntry.popState(actual,memregs,counters);
}
}
if(defaultEntry.isState)SearchEntry.popState(defaultEntry,memregs,counters);
term=root;
//wOffset++;
//i=wOffset;
i=++wOffset;
}
this.wOffset=wOffset;
this.top=top;
return false;
}
|
diff --git a/obdalib/reformulation-core/src/test/java/it/unibz/krdb/obda/reformulation/tests/StockExchangeTest.java b/obdalib/reformulation-core/src/test/java/it/unibz/krdb/obda/reformulation/tests/StockExchangeTest.java
index 0283b12dd..5ed9cc667 100644
--- a/obdalib/reformulation-core/src/test/java/it/unibz/krdb/obda/reformulation/tests/StockExchangeTest.java
+++ b/obdalib/reformulation-core/src/test/java/it/unibz/krdb/obda/reformulation/tests/StockExchangeTest.java
@@ -1,103 +1,105 @@
package it.unibz.krdb.obda.reformulation.tests;
import it.unibz.krdb.obda.io.DataManager;
import it.unibz.krdb.obda.model.OBDADataFactory;
import it.unibz.krdb.obda.model.OBDAModel;
import it.unibz.krdb.obda.model.QueryResultSet;
import it.unibz.krdb.obda.model.Statement;
import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl;
import it.unibz.krdb.obda.owlapi.ReformulationPlatformPreferences;
import it.unibz.krdb.obda.owlrefplatform.core.OBDAOWLReformulationPlatform;
import it.unibz.krdb.obda.owlrefplatform.core.OBDAOWLReformulationPlatformFactory;
import it.unibz.krdb.obda.owlrefplatform.core.OBDAOWLReformulationPlatformFactoryImpl;
import java.io.File;
import junit.framework.TestCase;
import org.semanticweb.owl.apibinding.OWLManager;
import org.semanticweb.owl.model.OWLOntology;
import org.semanticweb.owl.model.OWLOntologyManager;
public class StockExchangeTest extends TestCase {
public void test() throws Exception {
String owlfile = "src/test/resources/test/ontologies/scenarios/stockexchange-workbench.owl";
// Loading the OWL file
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntologyFromPhysicalURI((new File(owlfile)).toURI());
// Loading the OBDA data (note, the obda file must be in the same folder as the owl file
OBDADataFactory obdafac = OBDADataFactoryImpl.getInstance();
OBDAModel controller = obdafac.getOBDAModel();
String obdafile = owlfile.substring(0, owlfile.length()-3) + "obda";
DataManager ioManager = new DataManager(controller);
ioManager.loadOBDADataFromURI(new File(obdafile).toURI(),ontology.getURI(),controller.getPrefixManager());
// Creating a new instance of a quonto reasoner
OBDAOWLReformulationPlatformFactory factory = new OBDAOWLReformulationPlatformFactoryImpl();
ReformulationPlatformPreferences p = new ReformulationPlatformPreferences();
factory.setOBDAController(controller);
factory.setPreferenceHolder(p);
OBDAOWLReformulationPlatform reasoner = (OBDAOWLReformulationPlatform) factory.createReasoner(manager);
reasoner.loadOntologies(manager.getOntologies());
+ reasoner.loadOBDAModel(controller);
+ reasoner.setPreferences(p);
// Loading a set of configurations for the reasoner and giving them to quonto
// Properties properties = new Properties();
// properties.load(new FileInputStream(configFile));
// QuontoConfiguration config = new QuontoConfiguration(properties);
// reasoner.setConfiguration(config);
// One time classification call.
reasoner.classify();
// Now we are ready for querying
// The embedded query query
String sparqlstr = "select * FROM etable (\n\t\t\nPREFIX : <http://www.owl-ontologies.com/Ontology1207768242.owl#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> select * where { ?x rdf:type :Address}) t1";
// Getting a prefix for the query
Statement st = reasoner.getStatement();
QueryResultSet r = st.executeQuery(sparqlstr);
int ic = r.getColumCount();
while (r.nextRow()) {
for (int i = 0; i < ic; i++) {
System.out.print(r.getAsString(i+1) + ", ");
}
System.out.println("");
}
r.close();
st.close();
// The embedded query query
sparqlstr = "PREFIX : <http://www.owl-ontologies.com/Ontology1207768242.owl#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> select distinct * where { ?x :hasAddress :getAddressObj-991 }";
// Getting a prefix for the query
st = reasoner.getStatement();
r = st.executeQuery(sparqlstr);
ic = r.getColumCount();
int count = 0;
while (r.nextRow()) {
count +=1;
for (int i = 0; i < ic; i++) {
System.out.print(r.getAsString(i+1) + ", ");
}
System.out.println("");
}
r.close();
st.close();
assertTrue(count == 1);
}
}
| true | true | public void test() throws Exception {
String owlfile = "src/test/resources/test/ontologies/scenarios/stockexchange-workbench.owl";
// Loading the OWL file
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntologyFromPhysicalURI((new File(owlfile)).toURI());
// Loading the OBDA data (note, the obda file must be in the same folder as the owl file
OBDADataFactory obdafac = OBDADataFactoryImpl.getInstance();
OBDAModel controller = obdafac.getOBDAModel();
String obdafile = owlfile.substring(0, owlfile.length()-3) + "obda";
DataManager ioManager = new DataManager(controller);
ioManager.loadOBDADataFromURI(new File(obdafile).toURI(),ontology.getURI(),controller.getPrefixManager());
// Creating a new instance of a quonto reasoner
OBDAOWLReformulationPlatformFactory factory = new OBDAOWLReformulationPlatformFactoryImpl();
ReformulationPlatformPreferences p = new ReformulationPlatformPreferences();
factory.setOBDAController(controller);
factory.setPreferenceHolder(p);
OBDAOWLReformulationPlatform reasoner = (OBDAOWLReformulationPlatform) factory.createReasoner(manager);
reasoner.loadOntologies(manager.getOntologies());
// Loading a set of configurations for the reasoner and giving them to quonto
// Properties properties = new Properties();
// properties.load(new FileInputStream(configFile));
// QuontoConfiguration config = new QuontoConfiguration(properties);
// reasoner.setConfiguration(config);
// One time classification call.
reasoner.classify();
// Now we are ready for querying
// The embedded query query
String sparqlstr = "select * FROM etable (\n\t\t\nPREFIX : <http://www.owl-ontologies.com/Ontology1207768242.owl#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> select * where { ?x rdf:type :Address}) t1";
// Getting a prefix for the query
Statement st = reasoner.getStatement();
QueryResultSet r = st.executeQuery(sparqlstr);
int ic = r.getColumCount();
while (r.nextRow()) {
for (int i = 0; i < ic; i++) {
System.out.print(r.getAsString(i+1) + ", ");
}
System.out.println("");
}
r.close();
st.close();
// The embedded query query
sparqlstr = "PREFIX : <http://www.owl-ontologies.com/Ontology1207768242.owl#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> select distinct * where { ?x :hasAddress :getAddressObj-991 }";
// Getting a prefix for the query
st = reasoner.getStatement();
r = st.executeQuery(sparqlstr);
ic = r.getColumCount();
int count = 0;
while (r.nextRow()) {
count +=1;
for (int i = 0; i < ic; i++) {
System.out.print(r.getAsString(i+1) + ", ");
}
System.out.println("");
}
r.close();
st.close();
assertTrue(count == 1);
}
| public void test() throws Exception {
String owlfile = "src/test/resources/test/ontologies/scenarios/stockexchange-workbench.owl";
// Loading the OWL file
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntologyFromPhysicalURI((new File(owlfile)).toURI());
// Loading the OBDA data (note, the obda file must be in the same folder as the owl file
OBDADataFactory obdafac = OBDADataFactoryImpl.getInstance();
OBDAModel controller = obdafac.getOBDAModel();
String obdafile = owlfile.substring(0, owlfile.length()-3) + "obda";
DataManager ioManager = new DataManager(controller);
ioManager.loadOBDADataFromURI(new File(obdafile).toURI(),ontology.getURI(),controller.getPrefixManager());
// Creating a new instance of a quonto reasoner
OBDAOWLReformulationPlatformFactory factory = new OBDAOWLReformulationPlatformFactoryImpl();
ReformulationPlatformPreferences p = new ReformulationPlatformPreferences();
factory.setOBDAController(controller);
factory.setPreferenceHolder(p);
OBDAOWLReformulationPlatform reasoner = (OBDAOWLReformulationPlatform) factory.createReasoner(manager);
reasoner.loadOntologies(manager.getOntologies());
reasoner.loadOBDAModel(controller);
reasoner.setPreferences(p);
// Loading a set of configurations for the reasoner and giving them to quonto
// Properties properties = new Properties();
// properties.load(new FileInputStream(configFile));
// QuontoConfiguration config = new QuontoConfiguration(properties);
// reasoner.setConfiguration(config);
// One time classification call.
reasoner.classify();
// Now we are ready for querying
// The embedded query query
String sparqlstr = "select * FROM etable (\n\t\t\nPREFIX : <http://www.owl-ontologies.com/Ontology1207768242.owl#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> select * where { ?x rdf:type :Address}) t1";
// Getting a prefix for the query
Statement st = reasoner.getStatement();
QueryResultSet r = st.executeQuery(sparqlstr);
int ic = r.getColumCount();
while (r.nextRow()) {
for (int i = 0; i < ic; i++) {
System.out.print(r.getAsString(i+1) + ", ");
}
System.out.println("");
}
r.close();
st.close();
// The embedded query query
sparqlstr = "PREFIX : <http://www.owl-ontologies.com/Ontology1207768242.owl#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> select distinct * where { ?x :hasAddress :getAddressObj-991 }";
// Getting a prefix for the query
st = reasoner.getStatement();
r = st.executeQuery(sparqlstr);
ic = r.getColumCount();
int count = 0;
while (r.nextRow()) {
count +=1;
for (int i = 0; i < ic; i++) {
System.out.print(r.getAsString(i+1) + ", ");
}
System.out.println("");
}
r.close();
st.close();
assertTrue(count == 1);
}
|
diff --git a/gshell/gshell-admin/src/main/java/org/apache/servicemix/kernel/gshell/admin/internal/AdminServiceImpl.java b/gshell/gshell-admin/src/main/java/org/apache/servicemix/kernel/gshell/admin/internal/AdminServiceImpl.java
index 2e6fa829..9c1ebada 100644
--- a/gshell/gshell-admin/src/main/java/org/apache/servicemix/kernel/gshell/admin/internal/AdminServiceImpl.java
+++ b/gshell/gshell-admin/src/main/java/org/apache/servicemix/kernel/gshell/admin/internal/AdminServiceImpl.java
@@ -1,298 +1,298 @@
/*
* 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.servicemix.kernel.gshell.admin.internal;
import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import org.apache.servicemix.kernel.gshell.admin.AdminService;
import org.apache.servicemix.kernel.gshell.admin.Instance;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.geronimo.gshell.shell.ShellContextHolder;
import org.apache.geronimo.gshell.shell.ShellContext;
import org.osgi.service.prefs.PreferencesService;
import org.osgi.service.prefs.Preferences;
import org.osgi.service.prefs.BackingStoreException;
import org.springframework.beans.factory.InitializingBean;
public class AdminServiceImpl implements AdminService, InitializingBean {
private static final Log LOGGER = LogFactory.getLog(AdminServiceImpl.class);
private PreferencesService preferences;
private Map<String, Instance> instances = new HashMap<String, Instance>();
private int defaultPortStart = 8101;
public PreferencesService getPreferences() {
return preferences;
}
public void setPreferences(PreferencesService preferences) {
this.preferences = preferences;
}
public synchronized void afterPropertiesSet() throws Exception {
try {
Preferences prefs = preferences.getUserPreferences("AdminServiceState");
Preferences child = prefs.node("Instances");
int count = child.getInt("count", 0);
Map<String, Instance> newInstances = new HashMap<String, Instance>();
for (int i = 0; i < count; i++) {
String name = child.get("item." + i + ".name", null);
String loc = child.get("item." + i + ".loc", null);
int pid = child.getInt("item." + i + ".pid", 0);
if (name != null) {
InstanceImpl instance = new InstanceImpl(this, name, loc);
if (pid > 0) {
try {
instance.attach(pid);
} catch (IOException e) {
// Ignore
}
}
newInstances.put(name, instance);
}
}
instances = newInstances;
} catch (Exception e) {
LOGGER.warn("Unable to reload ServiceMix instance list", e);
}
}
public synchronized Instance createInstance(String name, int port, String location) throws Exception {
if (instances.get(name) != null) {
throw new IllegalArgumentException("Instance '" + name + "' already exists");
}
File serviceMixBase = new File(location != null ? location : ("instances/" + name)).getCanonicalFile();
int sshPort = port;
if (sshPort <= 0) {
try {
Preferences prefs = preferences.getUserPreferences("AdminServiceState");
sshPort = prefs.getInt("port", defaultPortStart + 1);
prefs.putInt("port", sshPort + 1);
prefs.flush();
prefs.sync();
} catch (Exception e) {
try {
ServerSocket ss = new ServerSocket(0);
sshPort = ss.getLocalPort();
ss.close();
} catch (Exception t) {
}
}
if (sshPort <= 0) {
sshPort = defaultPortStart;
}
}
println("Creating new instance on port " + sshPort + " at: @|bold " + serviceMixBase + "|");
mkdir(serviceMixBase, "bin");
mkdir(serviceMixBase, "etc");
mkdir(serviceMixBase, "system");
mkdir(serviceMixBase, "deploy");
mkdir(serviceMixBase, "data");
copyResourceToDir(serviceMixBase, "etc/config.properties", true);
copyResourceToDir(serviceMixBase, "etc/org.apache.servicemix.features.cfg", true);
- copyResourceToDir(serviceMixBase, "etc/org.apache.servicemix.users.cfg", true);
+ copyResourceToDir(serviceMixBase, "etc/users.properties", true);
copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.logging.cfg", true);
copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.url.mvn.cfg", true);
copyResourceToDir(serviceMixBase, "etc/startup.properties", true);
copyResourceToDir(serviceMixBase, "etc/system.properties", true);
HashMap<String, String> props = new HashMap<String, String>();
props.put("${servicemix.home}", System.getProperty("servicemix.home"));
props.put("${servicemix.base}", serviceMixBase.getPath());
props.put("${servicemix.sshPort}", Integer.toString(sshPort));
copyFilteredResourceToDir(serviceMixBase, "etc/org.apache.servicemix.shell.cfg", props);
if( System.getProperty("os.name").startsWith("Win") ) {
copyFilteredResourceToDir(serviceMixBase, "bin/servicemix.bat", props);
} else {
copyFilteredResourceToDir(serviceMixBase, "bin/servicemix", props);
chmod(new File(serviceMixBase, "bin/servicemix"), "a+x");
}
Instance instance = new InstanceImpl(this, name, serviceMixBase.toString());
instances.put(name, instance);
saveState();
return instance;
}
public synchronized Instance[] getInstances() {
return instances.values().toArray(new Instance[0]);
}
public synchronized Instance getInstance(String name) {
return instances.get(name);
}
synchronized void forget(String name) {
instances.remove(name);
}
synchronized void saveState() throws IOException, BackingStoreException {
Preferences prefs = preferences.getUserPreferences("AdminServiceState");
Preferences child = prefs.node("Instances");
child.clear();
Instance[] data = getInstances();
child.putInt("count", data.length);
for (int i = 0; i < data.length; i++) {
child.put("item." + i + ".name", data[i].getName());
child.put("item." + i + ".loc", data[i].getLocation());
child.putInt("item." + i + ".pid", data[i].getPid());
}
prefs.flush();
prefs.sync();
}
private void copyResourceToDir(File target, String resource, boolean text) throws Exception {
File outFile = new File(target, resource);
if( !outFile.exists() ) {
println("Creating file: @|bold " + outFile.getPath() + "|");
InputStream is = getClass().getClassLoader().getResourceAsStream("/org/apache/servicemix/kernel/gshell/admin/" + resource);
try {
if( text ) {
// Read it line at a time so that we can use the platform line ending when we write it out.
PrintStream out = new PrintStream(new FileOutputStream(outFile));
try {
Scanner scanner = new Scanner(is);
while (scanner.hasNextLine() ) {
String line = scanner.nextLine();
out.println(line);
}
} finally {
safeClose(out);
}
} else {
// Binary so just write it out the way it came in.
FileOutputStream out = new FileOutputStream(new File(target, resource));
try {
int c=0;
while((c=is.read())>=0) {
out.write(c);
}
} finally {
safeClose(out);
}
}
} finally {
safeClose(is);
}
}
}
private void println(String st) {
ShellContext ctx = ShellContextHolder.get(true);
if (ctx != null) {
ctx.getIo().out.println(st);
} else {
System.out.println(st);
}
}
private void copyFilteredResourceToDir(File target, String resource, HashMap<String, String> props) throws Exception {
File outFile = new File(target, resource);
if( !outFile.exists() ) {
println("Creating file: @|bold "+outFile.getPath()+"|");
InputStream is = getClass().getClassLoader().getResourceAsStream("/org/apache/servicemix/kernel/gshell/admin/" + resource);
try {
// Read it line at a time so that we can use the platform line ending when we write it out.
PrintStream out = new PrintStream(new FileOutputStream(outFile));
try {
Scanner scanner = new Scanner(is);
while (scanner.hasNextLine() ) {
String line = scanner.nextLine();
line = filter(line, props);
out.println(line);
}
} finally {
safeClose(out);
}
} finally {
safeClose(is);
}
}
}
private void safeClose(InputStream is) throws IOException {
if (is == null) {
return;
}
try {
is.close();
} catch (Throwable ignore) {
}
}
private void safeClose(OutputStream is) throws IOException {
if (is == null) {
return;
}
try {
is.close();
} catch (Throwable ignore) {
}
}
private String filter(String line, HashMap<String, String> props) {
for (Map.Entry<String, String> i : props.entrySet()) {
int p1 = line.indexOf(i.getKey());
if( p1 >= 0 ) {
String l1 = line.substring(0, p1);
String l2 = line.substring(p1+i.getKey().length());
line = l1+i.getValue()+l2;
}
}
return line;
}
private void mkdir(File serviceMixBase, String path) {
File file = new File(serviceMixBase, path);
if( !file.exists() ) {
println("Creating dir: @|bold "+file.getPath()+"|");
file.mkdirs();
}
}
private int chmod(File serviceFile, String mode) throws Exception {
ProcessBuilder builder = new ProcessBuilder();
builder.command("chmod", mode, serviceFile.getCanonicalPath());
Process p = builder.start();
// gnodet: Fix SMX4KNL-46: cpu goes to 100% after running the 'admin create' command
// Not sure exactly what happens, but commenting the process io redirection seems
// to work around the problem.
//
//PumpStreamHandler handler = new PumpStreamHandler(io.inputStream, io.outputStream, io.errorStream);
//handler.attach(p);
//handler.start();
int status = p.waitFor();
//handler.stop();
return status;
}
}
| true | true | public synchronized Instance createInstance(String name, int port, String location) throws Exception {
if (instances.get(name) != null) {
throw new IllegalArgumentException("Instance '" + name + "' already exists");
}
File serviceMixBase = new File(location != null ? location : ("instances/" + name)).getCanonicalFile();
int sshPort = port;
if (sshPort <= 0) {
try {
Preferences prefs = preferences.getUserPreferences("AdminServiceState");
sshPort = prefs.getInt("port", defaultPortStart + 1);
prefs.putInt("port", sshPort + 1);
prefs.flush();
prefs.sync();
} catch (Exception e) {
try {
ServerSocket ss = new ServerSocket(0);
sshPort = ss.getLocalPort();
ss.close();
} catch (Exception t) {
}
}
if (sshPort <= 0) {
sshPort = defaultPortStart;
}
}
println("Creating new instance on port " + sshPort + " at: @|bold " + serviceMixBase + "|");
mkdir(serviceMixBase, "bin");
mkdir(serviceMixBase, "etc");
mkdir(serviceMixBase, "system");
mkdir(serviceMixBase, "deploy");
mkdir(serviceMixBase, "data");
copyResourceToDir(serviceMixBase, "etc/config.properties", true);
copyResourceToDir(serviceMixBase, "etc/org.apache.servicemix.features.cfg", true);
copyResourceToDir(serviceMixBase, "etc/org.apache.servicemix.users.cfg", true);
copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.logging.cfg", true);
copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.url.mvn.cfg", true);
copyResourceToDir(serviceMixBase, "etc/startup.properties", true);
copyResourceToDir(serviceMixBase, "etc/system.properties", true);
HashMap<String, String> props = new HashMap<String, String>();
props.put("${servicemix.home}", System.getProperty("servicemix.home"));
props.put("${servicemix.base}", serviceMixBase.getPath());
props.put("${servicemix.sshPort}", Integer.toString(sshPort));
copyFilteredResourceToDir(serviceMixBase, "etc/org.apache.servicemix.shell.cfg", props);
if( System.getProperty("os.name").startsWith("Win") ) {
copyFilteredResourceToDir(serviceMixBase, "bin/servicemix.bat", props);
} else {
copyFilteredResourceToDir(serviceMixBase, "bin/servicemix", props);
chmod(new File(serviceMixBase, "bin/servicemix"), "a+x");
}
Instance instance = new InstanceImpl(this, name, serviceMixBase.toString());
instances.put(name, instance);
saveState();
return instance;
}
| public synchronized Instance createInstance(String name, int port, String location) throws Exception {
if (instances.get(name) != null) {
throw new IllegalArgumentException("Instance '" + name + "' already exists");
}
File serviceMixBase = new File(location != null ? location : ("instances/" + name)).getCanonicalFile();
int sshPort = port;
if (sshPort <= 0) {
try {
Preferences prefs = preferences.getUserPreferences("AdminServiceState");
sshPort = prefs.getInt("port", defaultPortStart + 1);
prefs.putInt("port", sshPort + 1);
prefs.flush();
prefs.sync();
} catch (Exception e) {
try {
ServerSocket ss = new ServerSocket(0);
sshPort = ss.getLocalPort();
ss.close();
} catch (Exception t) {
}
}
if (sshPort <= 0) {
sshPort = defaultPortStart;
}
}
println("Creating new instance on port " + sshPort + " at: @|bold " + serviceMixBase + "|");
mkdir(serviceMixBase, "bin");
mkdir(serviceMixBase, "etc");
mkdir(serviceMixBase, "system");
mkdir(serviceMixBase, "deploy");
mkdir(serviceMixBase, "data");
copyResourceToDir(serviceMixBase, "etc/config.properties", true);
copyResourceToDir(serviceMixBase, "etc/org.apache.servicemix.features.cfg", true);
copyResourceToDir(serviceMixBase, "etc/users.properties", true);
copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.logging.cfg", true);
copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.url.mvn.cfg", true);
copyResourceToDir(serviceMixBase, "etc/startup.properties", true);
copyResourceToDir(serviceMixBase, "etc/system.properties", true);
HashMap<String, String> props = new HashMap<String, String>();
props.put("${servicemix.home}", System.getProperty("servicemix.home"));
props.put("${servicemix.base}", serviceMixBase.getPath());
props.put("${servicemix.sshPort}", Integer.toString(sshPort));
copyFilteredResourceToDir(serviceMixBase, "etc/org.apache.servicemix.shell.cfg", props);
if( System.getProperty("os.name").startsWith("Win") ) {
copyFilteredResourceToDir(serviceMixBase, "bin/servicemix.bat", props);
} else {
copyFilteredResourceToDir(serviceMixBase, "bin/servicemix", props);
chmod(new File(serviceMixBase, "bin/servicemix"), "a+x");
}
Instance instance = new InstanceImpl(this, name, serviceMixBase.toString());
instances.put(name, instance);
saveState();
return instance;
}
|
diff --git a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/service/ReportEngineService.java b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/service/ReportEngineService.java
index f765f743..5c652b63 100644
--- a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/service/ReportEngineService.java
+++ b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/service/ReportEngineService.java
@@ -1,1218 +1,1218 @@
/*************************************************************************************
* Copyright (c) 2004 Actuate Corporation and others.
* 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:
* Actuate Corporation - Initial implementation.
************************************************************************************/
package org.eclipse.birt.report.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import org.apache.axis.AxisFault;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.data.engine.api.IBaseDataSetDesign;
import org.eclipse.birt.data.engine.api.IBaseDataSourceDesign;
import org.eclipse.birt.data.engine.api.IResultMetaData;
import org.eclipse.birt.report.IBirtConstants;
import org.eclipse.birt.report.data.adaptor.api.DataRequestSession;
import org.eclipse.birt.report.data.adaptor.api.DataSessionContext;
import org.eclipse.birt.report.data.adaptor.api.IModelAdaptor;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.HTMLActionHandler;
import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.eclipse.birt.report.engine.api.IDataExtractionTask;
import org.eclipse.birt.report.engine.api.IDataIterator;
import org.eclipse.birt.report.engine.api.IExtractionResults;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IRenderTask;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IResultSetItem;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IRunTask;
import org.eclipse.birt.report.engine.api.IScalarParameterDefn;
import org.eclipse.birt.report.engine.api.PDFRenderContext;
import org.eclipse.birt.report.engine.api.ReportParameterConverter;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.SessionHandle;
import org.eclipse.birt.report.soapengine.api.Column;
import org.eclipse.birt.report.soapengine.api.ResultSet;
import org.eclipse.birt.report.utility.ParameterAccessor;
public class ReportEngineService
{
private static ReportEngineService instance;
/**
* Report engine instance.
*/
private IReportEngine engine = null;
/**
* Static engine config instance.
*/
private EngineConfig config = null;
/**
* Image directory for report images and charts.
*/
private String imageDirectory = null;
/**
* URL accesses images.
*/
private String imageBaseUrl = null;
/**
* Image handler instance.
*/
private HTMLServerImageHandler imageHandler = null;
/**
* Web app context path.
*/
private String contextPath = null;
/**
* Constructor.
*
* @param config
*/
public ReportEngineService( ServletConfig servletConfig )
{
System.setProperty( "RUN_UNDER_ECLIPSE", "false" ); //$NON-NLS-1$ //$NON-NLS-2$
if ( servletConfig == null )
{
return;
}
config = new EngineConfig( );
// Register new image handler
HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig( );
emitterConfig.setActionHandler( new HTMLActionHandler( ) );
imageHandler = new HTMLServerImageHandler( );
emitterConfig.setImageHandler( imageHandler );
config.getEmitterConfigs( ).put( "html", emitterConfig ); //$NON-NLS-1$
// handle resource path
String resourcePath = servletConfig.getServletContext( )
.getInitParameter(
ParameterAccessor.INIT_PARAM_BIRT_RESOURCE_PATH );
boolean isResourceOk = true;
if ( resourcePath == null || resourcePath.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( resourcePath ) )
{
isResourceOk = false;
}
else
{
File resourceFile = new File( resourcePath );
if ( !resourceFile.exists( ) )
{
isResourceOk = resourceFile.mkdirs( );
}
}
if ( isResourceOk )
{
- SessionHandle.setBirtResourcePath( resourcePath );
+ config.setResourcePath( resourcePath );
}
// Prepare image directory.
imageDirectory = servletConfig.getServletContext( ).getInitParameter(
ParameterAccessor.INIT_PARAM_IMAGE_DIR );
if ( imageDirectory == null || imageDirectory.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( imageDirectory ) )
{
imageDirectory = servletConfig.getServletContext( ).getRealPath(
"/report/images" ); //$NON-NLS-1$
}
// Prepare image base url.
imageBaseUrl = "/run?__imageID="; //$NON-NLS-1$
// Prepare log directory.
String logDirectory = servletConfig.getServletContext( )
.getInitParameter( ParameterAccessor.INIT_PARAM_LOG_DIR );
if ( logDirectory == null || logDirectory.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( logDirectory ) )
{
logDirectory = servletConfig.getServletContext( ).getRealPath(
"/logs" ); //$NON-NLS-1$
}
// Prepare log level.
String logLevel = servletConfig.getServletContext( ).getInitParameter(
ParameterAccessor.INIT_PARAM_LOG_LEVEL );
Level level = Level.OFF;
if ( "SEVERE".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.SEVERE;
}
else if ( "WARNING".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.WARNING;
}
else if ( "INFO".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.INFO;
}
else if ( "CONFIG".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.CONFIG;
}
else if ( "FINE".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINE;
}
else if ( "FINER".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINER;
}
else if ( "FINEST".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINEST;
}
else if ( "OFF".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.OFF;
}
config.setLogConfig( logDirectory, level );
// Prepare ScriptLib location
String scriptLibDir = servletConfig.getServletContext( )
.getInitParameter( ParameterAccessor.INIT_PARAM_SCRIPTLIB_DIR );
if ( scriptLibDir == null || scriptLibDir.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( scriptLibDir ) )
{
scriptLibDir = servletConfig.getServletContext( ).getRealPath(
"/scriptlib" ); //$NON-NLS-1$
}
ArrayList jarFileList = new ArrayList( );
if ( scriptLibDir != null )
{
File dir = new File( scriptLibDir );
getAllJarFiles( dir, jarFileList );
}
String scriptlibClassPath = ""; //$NON-NLS-1$
for ( int i = 0; i < jarFileList.size( ); i++ )
scriptlibClassPath += EngineConstants.PROPERTYSEPARATOR
+ ( (File) jarFileList.get( i ) ).getAbsolutePath( );
if ( scriptlibClassPath.startsWith( EngineConstants.PROPERTYSEPARATOR ) )
scriptlibClassPath = scriptlibClassPath
.substring( EngineConstants.PROPERTYSEPARATOR.length( ) );
System.setProperty( EngineConstants.WEBAPP_CLASSPATH_KEY,
scriptlibClassPath );
config.setEngineHome( "" ); //$NON-NLS-1$
}
/**
* Get engine instance.
*
* @return
*/
public static ReportEngineService getInstance( )
{
return instance;
}
/**
* Get engine instance.
*
* @return engine instance
*/
public static void initEngineInstance( ServletConfig servletConfig )
throws BirtException
{
if ( ReportEngineService.instance != null )
{
return;
}
ReportEngineService.instance = new ReportEngineService( servletConfig );
}
/**
* Get all the files under the specified folder (including all the files
* under sub-folders)
*
* @param dir -
* the folder to look into
* @param fileList -
* the fileList to be returned
*/
private void getAllJarFiles( File dir, ArrayList fileList )
{
if ( dir.exists( ) && dir.isDirectory( ) )
{
File[] files = dir.listFiles( );
if ( files == null )
return;
for ( int i = 0; i < files.length; i++ )
{
File file = files[i];
if ( file.isFile( ) )
{
if ( file.getName( ).endsWith( ".jar" ) ) //$NON-NLS-1$
fileList.add( file );
}
else if ( file.isDirectory( ) )
{
getAllJarFiles( file, fileList );
}
}
}
}
/**
* Set Engine context.
*
* @param servletContext
* @param request
*/
synchronized public void setEngineContext( ServletContext servletContext,
HttpServletRequest request )
{
if ( engine == null )
{
IPlatformContext platformContext = new PlatformServletContext(
servletContext );
config.setPlatformContext( platformContext );
try
{
Platform.startup( config );
}
catch ( BirtException e )
{
// TODO remove this output.
e.printStackTrace( );
}
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
engine = factory.createReportEngine( config );
contextPath = request.getContextPath( );
}
}
/**
* Open report design.
*
* @param report
* @return
*/
synchronized public IReportRunnable openReportDesign( String report )
throws EngineException
{
return engine.openReportDesign( report );
}
/**
* Open report design by using the input stream
*
* @param reportStream -
* the input stream
* @return IReportRunnable
* @throws EngineException
*/
synchronized public IReportRunnable openReportDesign(
InputStream reportStream ) throws EngineException
{
return engine.openReportDesign( reportStream );
}
/**
* createGetParameterDefinitionTask.
*
* @param runnable
* @return
*/
public IGetParameterDefinitionTask createGetParameterDefinitionTask(
IReportRunnable runnable )
{
IGetParameterDefinitionTask task = null;
try
{
synchronized ( this.getClass( ) )
{
task = engine.createGetParameterDefinitionTask( runnable );
}
}
catch ( Exception e )
{
}
return task;
}
/**
* Open report document from archive,
*
* @param docName
* the name of the report document
* @param systemId
* the system ID to search the resource in the document,
* generally it is the file name of the report design
* @return the report docuement
*/
public IReportDocument openReportDocument( String systemId, String docName )
{
IReportDocument document = null;
try
{
synchronized ( this.getClass( ) )
{
document = engine.openReportDocument( systemId, docName );
}
}
catch ( Exception e )
{
}
return document;
}
/**
* Render image.
*
* @param imageId
* @param outputStream
* @throws EngineException
*/
public void renderImage( String imageId, OutputStream outputStream )
throws RemoteException
{
assert ( this.imageHandler != null );
try
{
this.imageHandler.getImage( outputStream, this.imageDirectory,
imageId );
}
catch ( EngineException e )
{
AxisFault fault = new AxisFault( );
fault
.setFaultCode( new QName(
"ReportEngineService.renderImage( )" ) ); //$NON-NLS-1$
fault.setFaultString( e.getLocalizedMessage( ) );
throw fault;
}
}
/**
* Create HTML render context.
*
* @param svgFlag
* @param servletPath
* @return
*/
private HTMLRenderContext createHTMLrenderContext( boolean svgFlag,
String servletPath )
{
HTMLRenderContext renderContext = new HTMLRenderContext( );
renderContext.setImageDirectory( imageDirectory );
renderContext.setBaseImageURL( contextPath + imageBaseUrl );
if ( servletPath != null
&& servletPath.length( ) > 0
&& !servletPath
.equalsIgnoreCase( IBirtConstants.SERVLET_PATH_PREVIEW ) )
{
renderContext.setBaseURL( this.contextPath + servletPath );
}
else
{
renderContext.setBaseURL( this.contextPath
+ IBirtConstants.SERVLET_PATH_FRAMESET );
}
renderContext.setSupportedImageFormats( svgFlag
? "PNG;GIF;JPG;BMP;SVG" : "PNG;GIF;JPG;BMP" ); //$NON-NLS-1$ //$NON-NLS-2$
return renderContext;
}
/**
* Create PDF render context.
*
* @return
*/
private PDFRenderContext createPDFrenderContext( )
{
PDFRenderContext renderContext = new PDFRenderContext( );
renderContext.setBaseURL( this.contextPath
+ IBirtConstants.SERVLET_PATH_RUN );
renderContext.setSupportedImageFormats( "PNG;GIF;JPG;BMP" ); //$NON-NLS-1$
return renderContext;
}
/**
* Run and render a report,
*
* @param runnable
* @param outputStream
* @param format
* @param locale
* @param parameters
* @param svgFlag
* @throws IOException
*/
public void runAndRenderReport( HttpServletRequest request,
IReportRunnable runnable, OutputStream outputStream, String format,
Locale locale, Map parameters, boolean masterPage, boolean svgFlag )
throws RemoteException
{
runAndRenderReport( request, runnable, outputStream, format, locale,
parameters, masterPage, svgFlag, null, null, null );
}
/**
* Run and render a report,
*
* @param runnable
* @param outputStream
* @param locale
* @param parameters
* @param svgFlag
* @param activeIds
* @throws IOException
*/
public void runAndRenderReport( HttpServletRequest request,
IReportRunnable runnable, ByteArrayOutputStream outputStream,
Locale locale, Map parameters, boolean masterPage, boolean svgFlag,
List activeIds, HTMLRenderContext htmlRenderContext ) throws RemoteException
{
runAndRenderReport( request, runnable, outputStream,
ParameterAccessor.PARAM_FORMAT_HTML, locale, parameters,
masterPage, svgFlag, Boolean.TRUE, activeIds, htmlRenderContext );
}
synchronized private void runAndRenderReport( HttpServletRequest request,
IReportRunnable runnable, OutputStream outputStream, String format,
Locale locale, Map parameters, boolean masterPage, boolean svgFlag,
Boolean embeddable, List activeIds, HTMLRenderContext htmlRenderContext ) throws RemoteException
{
assert runnable != null;
// Render options
HTMLRenderOption option = new HTMLRenderOption( );
option.setOutputStream( outputStream );
option.setOutputFormat( format );
option.setMasterPageContent( masterPage );
if ( embeddable != null )
{
option.setEmbeddable( embeddable.booleanValue( ) );
}
if ( activeIds != null )
{
option.setInstanceIDs( activeIds );
}
IRunAndRenderTask runAndRenderTask = null;
synchronized ( this.getClass( ) )
{
runAndRenderTask = engine.createRunAndRenderTask( runnable );
}
runAndRenderTask.setLocale( locale );
if ( parameters != null )
{
runAndRenderTask.setParameterValues( parameters );
}
runAndRenderTask.setRenderOption( option );
HashMap context = new HashMap( );
// context.put( DataEngine.DATASET_CACHE_OPTION, Boolean.TRUE );
context.put( "org.eclipse.birt.data.engine.dataset.cache.option",
Boolean.TRUE );
context.put( EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST,
request );
context.put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY,
ReportEngineService.class.getClassLoader( ) );
if ( ParameterAccessor.PARAM_FORMAT_PDF.equalsIgnoreCase( format ) )
{
context.put( EngineConstants.APPCONTEXT_PDF_RENDER_CONTEXT,
createPDFrenderContext( ) );
}
else if ( htmlRenderContext != null )
{
context.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,
htmlRenderContext );
}
else
{
context.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,
createHTMLrenderContext( svgFlag, request
.getServletPath( ) ) );
}
runAndRenderTask.setAppContext( context );
try
{
runAndRenderTask.run( );
}
catch ( BirtException e )
{
AxisFault fault = new AxisFault( );
fault.setFaultCode( new QName(
"ReportEngineService.runAndRenderReport( )" ) ); //$NON-NLS-1$
fault.setFaultString( e.getLocalizedMessage( ) );
throw fault;
}
finally
{
runAndRenderTask.close( );
}
}
/**
* Run report.
*
* @param runnable
* @param archive
* @param documentName
* @param locale
* @param parameters
* @throws RemoteException
*/
public void runReport( HttpServletRequest request,
IReportRunnable runnable, String documentName, Locale locale,
HashMap parameters ) throws RemoteException
{
assert runnable != null;
// Preapre the run report task.
IRunTask runTask = null;
synchronized ( this.getClass( ) )
{
runTask = engine.createRunTask( runnable );
}
runTask.setLocale( locale );
runTask.setParameterValues( parameters );
HashMap context = new HashMap( );
// context.put( DataEngine.DATASET_CACHE_OPTION, Boolean.TRUE );
context.put( "org.eclipse.birt.data.engine.dataset.cache.option",
Boolean.TRUE );
context.put( EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST,
request );
context.put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY,
ReportEngineService.class.getClassLoader( ) );
runTask.setAppContext( context );
// Run report.
try
{
runTask.run( documentName );
}
catch ( BirtException e )
{
// Any Birt exception.
AxisFault fault = new AxisFault( );
fault
.setFaultCode( new QName(
"ReportEngineService.runReport( )" ) ); //$NON-NLS-1$
fault.setFaultString( e.getLocalizedMessage( ) );
throw fault;
}
finally
{
runTask.close( );
}
}
/**
* Render report page.
*
* @param reportDocument
* @param pageNumber
* @param svgFlag
* @return report page content
* @throws RemoteException
*/
public ByteArrayOutputStream renderReport( HttpServletRequest request,
IReportDocument reportDocument, long pageNumber,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale )
throws RemoteException
{
ByteArrayOutputStream out = new ByteArrayOutputStream( );
renderReport( out, request, reportDocument, pageNumber, masterPage,
svgFlag, activeIds, locale );
return out;
}
/**
* Render report page.
*
* @param os
* @param reportDocument
* @param pageNumber
* @param svgFlag
* @return report page content
* @throws RemoteException
*/
public void renderReport( OutputStream os, HttpServletRequest request,
IReportDocument reportDocument, long pageNumber,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale )
throws RemoteException
{
assert reportDocument != null;
assert pageNumber > 0 && pageNumber <= reportDocument.getPageCount( );
OutputStream out = os;
if ( out == null )
out = new ByteArrayOutputStream( );
// Create render task.
IRenderTask renderTask = null;
synchronized ( this.getClass( ) )
{
renderTask = engine.createRenderTask( reportDocument );
}
HashMap context = new HashMap( );
String format = ParameterAccessor.getFormat( request );
if ( format.equalsIgnoreCase( ParameterAccessor.PARAM_FORMAT_PDF ) )
{
context.put( EngineConstants.APPCONTEXT_PDF_RENDER_CONTEXT,
createPDFrenderContext( ) );
}
else
{
context
.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT,
createHTMLrenderContext( svgFlag, request
.getServletPath( ) ) );
}
context.put( EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST,
request );
context.put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY,
ReportEngineService.class.getClassLoader( ) );
renderTask.setAppContext( context );
// Render option
HTMLRenderOption setting = new HTMLRenderOption( );
setting.setOutputStream( out );
if ( format.equalsIgnoreCase( ParameterAccessor.PARAM_FORMAT_PDF ) )
{
setting.setOutputFormat( IBirtConstants.PDF_RENDER_FORMAT );
setting.setActionHandle( new ViewerHTMLActionHandler(
reportDocument, pageNumber, locale, false ) );
}
else
{
setting.setOutputFormat( IBirtConstants.HTML_RENDER_FORMAT );
boolean isEmbeddable = false;
if ( ParameterAccessor.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( request.getServletPath( ) ) )
isEmbeddable = true;
setting.setEmbeddable( isEmbeddable );
setting.setInstanceIDs( activeIds );
setting.setMasterPageContent( masterPage );
setting.setActionHandle( new ViewerHTMLActionHandler(
reportDocument, pageNumber, locale, isEmbeddable ) );
}
renderTask.setRenderOption( setting );
renderTask.setLocale( locale );
// Render designated page.
try
{
if ( format.equalsIgnoreCase( ParameterAccessor.PARAM_FORMAT_PDF ) )
renderTask.render( );
else
{
renderTask.setPageNumber( pageNumber );
renderTask.render( );
}
}
catch ( BirtException e )
{
AxisFault fault = new AxisFault( );
fault.setFaultCode( new QName(
"ReportEngineService.renderReport( )" ) ); //$NON-NLS-1$
fault.setFaultString( e.getLocalizedMessage( ) );
throw fault;
}
catch ( Exception e )
{
AxisFault fault = new AxisFault( );
fault.setFaultCode( new QName(
"ReportEngineService.renderReport( )" ) ); //$NON-NLS-1$
fault.setFaultString( e.getLocalizedMessage( ) );
throw fault;
}
finally
{
renderTask.close( );
}
}
/**
* Get query result sets.
*
* @param document
* @return
* @throws RemoteException
*/
public ResultSet[] getResultSets( IReportDocument document )
throws RemoteException
{
assert document != null;
ResultSet[] resultSetArray = null;
IDataExtractionTask dataTask = null;
synchronized ( this.getClass( ) )
{
dataTask = engine.createDataExtractionTask( document );
}
try
{
List resultSets = dataTask.getResultSetList( );
if ( resultSets != null && resultSets.size( ) > 0 )
{
resultSetArray = new ResultSet[resultSets.size( )];
for ( int k = 0; k < resultSets.size( ); k++ )
{
resultSetArray[k] = new ResultSet( );
IResultSetItem resultSetItem = (IResultSetItem) resultSets
.get( k );
assert resultSetItem != null;
resultSetArray[k].setQueryName( resultSetItem
.getResultSetName( ) );
IResultMetaData metaData = resultSetItem
.getResultMetaData( );
assert metaData != null;
Column[] columnArray = new Column[metaData.getColumnCount( )];
for ( int i = 0; i < metaData.getColumnCount( ); i++ )
{
columnArray[i] = new Column( );
String name = metaData.getColumnName( i );
columnArray[i].setName( name );
String label = metaData.getColumnLabel( i );
if ( label == null || label.length( ) <= 0 )
{
label = name;
}
columnArray[i].setLabel( label );
columnArray[i].setVisibility( new Boolean( true ) );
}
resultSetArray[k].setColumn( columnArray );
}
}
}
catch ( BirtException e )
{
e.printStackTrace( );
AxisFault fault = new AxisFault( );
fault
.setFaultCode( new QName(
"ReportEngineService.getMetaData( )" ) ); //$NON-NLS-1$
fault.setFaultString( e.getLocalizedMessage( ) );
throw fault;
}
catch ( Exception e )
{
e.printStackTrace( );
AxisFault fault = new AxisFault( );
fault
.setFaultCode( new QName(
"ReportEngineService.getMetaData( )" ) ); //$NON-NLS-1$
fault.setFaultString( e.getLocalizedMessage( ) );
throw fault;
}
finally
{
dataTask.close( );
}
return resultSetArray;
}
/**
* Extract data.
*
* @param document
* @param id
* @param columns
* @param filters
* @param locale
* @param outputStream
* @throws RemoteException
*/
public void extractData( IReportDocument document, String resultSetName,
Collection columns, Locale locale, OutputStream outputStream )
throws RemoteException
{
assert document != null;
assert resultSetName != null && resultSetName.length( ) > 0;
assert columns != null && !columns.isEmpty( );
String[] columnNames = new String[columns.size( )];
Iterator iSelectedColumns = columns.iterator( );
for ( int i = 0; iSelectedColumns.hasNext( ); i++ )
{
columnNames[i] = (String) iSelectedColumns.next( );
}
IDataExtractionTask dataTask = null;
IExtractionResults result = null;
IDataIterator iData = null;
try
{
synchronized ( this.getClass( ) )
{
dataTask = engine.createDataExtractionTask( document );
}
dataTask.selectResultSet( resultSetName );
dataTask.selectColumns( columnNames );
dataTask.setLocale( locale );
result = dataTask.extract( );
if ( result != null )
{
iData = result.nextResultIterator( );
if ( iData != null && columnNames.length > 0 )
{
StringBuffer buf = new StringBuffer( );
// Captions
buf.append( columnNames[0] );
for ( int i = 1; i < columnNames.length; i++ )
{
buf.append( ',' ); //$NON-NLS-1$
buf.append( columnNames[i] );
}
buf.append( '\n' );
outputStream.write( buf.toString( ).getBytes( ) );
buf.delete( 0, buf.length( ) );
// Data
while ( iData.next( ) )
{
String value = null;
try
{
value = cvsConvertor( (String) DataTypeUtil
.convert( iData.getValue( columnNames[0] ),
DataType.STRING_TYPE ) );
}
catch ( Exception e )
{
value = null;
}
if ( value != null )
{
buf.append( value );
}
for ( int i = 1; i < columnNames.length; i++ )
{
buf.append( ',' ); //$NON-NLS-1$
try
{
value = cvsConvertor( (String) DataTypeUtil
.convert( iData
.getValue( columnNames[i] ),
DataType.STRING_TYPE ) );
}
catch ( Exception e )
{
value = null;
}
if ( value != null )
{
buf.append( value );
}
}
buf.append( '\n' );
outputStream.write( buf.toString( ).getBytes( ) );
buf.delete( 0, buf.length( ) );
}
}
}
}
catch ( Exception e )
{
AxisFault fault = new AxisFault( );
fault
.setFaultCode( new QName(
"ReportEngineService.extractData( )" ) ); //$NON-NLS-1$
fault.setFaultString( e.getLocalizedMessage( ) );
throw fault;
}
finally
{
if ( iData != null )
{
iData.close( );
}
if ( result != null )
{
result.close( );
}
if ( dataTask != null )
{
dataTask.close( );
}
}
}
/**
* CSV format convertor. Here is the rule.
*
* 1) Fields with embedded commas must be delimited with double-quote
* characters. 2) Fields that contain double quote characters must be
* surounded by double-quotes, and the embedded double-quotes must each be
* represented by a pair of consecutive double quotes. 3) A field that
* contains embedded line-breaks must be surounded by double-quotes. 4)
* Fields with leading or trailing spaces must be delimited with
* double-quote characters.
*
* @param value
* @return
* @throws RemoteException
*/
private String cvsConvertor( String value ) throws RemoteException
{
if ( value == null )
{
return null;
}
value = value.replaceAll( "\"", "\"\"" ); //$NON-NLS-1$ //$NON-NLS-2$
boolean needQuote = false;
needQuote = ( value.indexOf( ',' ) != -1 )
|| ( value.indexOf( '"' ) != -1 ) //$NON-NLS-1$ //$NON-NLS-2$
|| ( value.indexOf( 0x0A ) != -1 )
|| value.startsWith( " " ) || value.endsWith( " " ); //$NON-NLS-1$ //$NON-NLS-2$
value = needQuote ? "\"" + value + "\"" : value; //$NON-NLS-1$ //$NON-NLS-2$
return value;
}
/**
* Prepare the report parameters.
*
* @param request
* @param task
* @param configVars
* @param locale
* @return
*/
public HashMap parseParameters( HttpServletRequest request,
IGetParameterDefinitionTask task, Map configVars, Locale locale )
{
assert task != null;
HashMap params = new HashMap( );
Collection parameterList = task.getParameterDefns( false );
for ( Iterator iter = parameterList.iterator( ); iter.hasNext( ); )
{
IScalarParameterDefn parameterObj = (IScalarParameterDefn) iter
.next( );
String paramValue = null;
Object paramValueObj = null;
// ScalarParameterHandle paramHandle = ( ScalarParameterHandle )
// parameterObj
// .getHandle( );
String paramName = parameterObj.getName( );
String format = parameterObj.getDisplayFormat( );
// Get default value from task
ReportParameterConverter converter = new ReportParameterConverter(
format, locale );
if ( ParameterAccessor.isReportParameterExist( request, paramName ) )
{
// Get value from http request
paramValue = ParameterAccessor.getReportParameter( request,
paramName, paramValue );
paramValueObj = converter.parse( paramValue, parameterObj
.getDataType( ) );
}
else if ( ParameterAccessor.isDesigner( request )
&& configVars.containsKey( paramName ) )
{
// Get value from test config
String configValue = (String) configVars.get( paramName );
ReportParameterConverter cfgConverter = new ReportParameterConverter(
format, Locale.US );
paramValueObj = cfgConverter.parse( configValue, parameterObj
.getDataType( ) );
}
else
{
paramValueObj = task.getDefaultValue( parameterObj.getName( ) );
}
params.put( paramName, paramValueObj );
}
return params;
}
/**
* Check whether missing parameter or not.
*
* @param task
* @param parameters
* @return
*/
public boolean validateParameters( IGetParameterDefinitionTask task,
Map parameters )
{
assert task != null;
assert parameters != null;
boolean missingParameter = false;
Collection parameterList = task.getParameterDefns( false );
for ( Iterator iter = parameterList.iterator( ); iter.hasNext( ); )
{
IScalarParameterDefn parameterObj = (IScalarParameterDefn) iter
.next( );
// ScalarParameterHandle paramHandle = ( ScalarParameterHandle )
// parameterObj
// .getHandle( );
String parameterName = parameterObj.getName( );
Object parameterValue = parameters.get( parameterName );
if ( parameterObj.isHidden( ) )
{
continue;
}
if ( parameterValue == null && !parameterObj.allowNull( ) )
{
missingParameter = true;
break;
}
if ( IScalarParameterDefn.TYPE_STRING == parameterObj.getDataType( ) )
{
String parameterStringValue = (String) parameterValue;
if ( parameterStringValue != null
&& parameterStringValue.length( ) <= 0
&& !parameterObj.allowBlank( ) )
{
missingParameter = true;
break;
}
}
}
return missingParameter;
}
/**
* uses to clear the data cach.
*
* @param dataSet
* the dataset handle
* @throws BirtException
*/
public void clearCache( DataSetHandle dataSet ) throws BirtException
{
DataSessionContext context = new DataSessionContext(
DataSessionContext.MODE_DIRECT_PRESENTATION, dataSet
.getModuleHandle( ), null );
DataRequestSession requestSession = DataRequestSession
.newSession( context );
IModelAdaptor modelAdaptor = requestSession.getModelAdaptor( );
DataSourceHandle dataSource = dataSet.getDataSource( );
IBaseDataSourceDesign sourceDesign = modelAdaptor
.adaptDataSource( dataSource );
IBaseDataSetDesign dataSetDesign = modelAdaptor.adaptDataSet( dataSet );
requestSession.clearCache( sourceDesign, dataSetDesign );
}
}
| true | true | public ReportEngineService( ServletConfig servletConfig )
{
System.setProperty( "RUN_UNDER_ECLIPSE", "false" ); //$NON-NLS-1$ //$NON-NLS-2$
if ( servletConfig == null )
{
return;
}
config = new EngineConfig( );
// Register new image handler
HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig( );
emitterConfig.setActionHandler( new HTMLActionHandler( ) );
imageHandler = new HTMLServerImageHandler( );
emitterConfig.setImageHandler( imageHandler );
config.getEmitterConfigs( ).put( "html", emitterConfig ); //$NON-NLS-1$
// handle resource path
String resourcePath = servletConfig.getServletContext( )
.getInitParameter(
ParameterAccessor.INIT_PARAM_BIRT_RESOURCE_PATH );
boolean isResourceOk = true;
if ( resourcePath == null || resourcePath.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( resourcePath ) )
{
isResourceOk = false;
}
else
{
File resourceFile = new File( resourcePath );
if ( !resourceFile.exists( ) )
{
isResourceOk = resourceFile.mkdirs( );
}
}
if ( isResourceOk )
{
SessionHandle.setBirtResourcePath( resourcePath );
}
// Prepare image directory.
imageDirectory = servletConfig.getServletContext( ).getInitParameter(
ParameterAccessor.INIT_PARAM_IMAGE_DIR );
if ( imageDirectory == null || imageDirectory.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( imageDirectory ) )
{
imageDirectory = servletConfig.getServletContext( ).getRealPath(
"/report/images" ); //$NON-NLS-1$
}
// Prepare image base url.
imageBaseUrl = "/run?__imageID="; //$NON-NLS-1$
// Prepare log directory.
String logDirectory = servletConfig.getServletContext( )
.getInitParameter( ParameterAccessor.INIT_PARAM_LOG_DIR );
if ( logDirectory == null || logDirectory.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( logDirectory ) )
{
logDirectory = servletConfig.getServletContext( ).getRealPath(
"/logs" ); //$NON-NLS-1$
}
// Prepare log level.
String logLevel = servletConfig.getServletContext( ).getInitParameter(
ParameterAccessor.INIT_PARAM_LOG_LEVEL );
Level level = Level.OFF;
if ( "SEVERE".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.SEVERE;
}
else if ( "WARNING".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.WARNING;
}
else if ( "INFO".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.INFO;
}
else if ( "CONFIG".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.CONFIG;
}
else if ( "FINE".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINE;
}
else if ( "FINER".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINER;
}
else if ( "FINEST".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINEST;
}
else if ( "OFF".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.OFF;
}
config.setLogConfig( logDirectory, level );
// Prepare ScriptLib location
String scriptLibDir = servletConfig.getServletContext( )
.getInitParameter( ParameterAccessor.INIT_PARAM_SCRIPTLIB_DIR );
if ( scriptLibDir == null || scriptLibDir.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( scriptLibDir ) )
{
scriptLibDir = servletConfig.getServletContext( ).getRealPath(
"/scriptlib" ); //$NON-NLS-1$
}
ArrayList jarFileList = new ArrayList( );
if ( scriptLibDir != null )
{
File dir = new File( scriptLibDir );
getAllJarFiles( dir, jarFileList );
}
String scriptlibClassPath = ""; //$NON-NLS-1$
for ( int i = 0; i < jarFileList.size( ); i++ )
scriptlibClassPath += EngineConstants.PROPERTYSEPARATOR
+ ( (File) jarFileList.get( i ) ).getAbsolutePath( );
if ( scriptlibClassPath.startsWith( EngineConstants.PROPERTYSEPARATOR ) )
scriptlibClassPath = scriptlibClassPath
.substring( EngineConstants.PROPERTYSEPARATOR.length( ) );
System.setProperty( EngineConstants.WEBAPP_CLASSPATH_KEY,
scriptlibClassPath );
config.setEngineHome( "" ); //$NON-NLS-1$
}
| public ReportEngineService( ServletConfig servletConfig )
{
System.setProperty( "RUN_UNDER_ECLIPSE", "false" ); //$NON-NLS-1$ //$NON-NLS-2$
if ( servletConfig == null )
{
return;
}
config = new EngineConfig( );
// Register new image handler
HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig( );
emitterConfig.setActionHandler( new HTMLActionHandler( ) );
imageHandler = new HTMLServerImageHandler( );
emitterConfig.setImageHandler( imageHandler );
config.getEmitterConfigs( ).put( "html", emitterConfig ); //$NON-NLS-1$
// handle resource path
String resourcePath = servletConfig.getServletContext( )
.getInitParameter(
ParameterAccessor.INIT_PARAM_BIRT_RESOURCE_PATH );
boolean isResourceOk = true;
if ( resourcePath == null || resourcePath.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( resourcePath ) )
{
isResourceOk = false;
}
else
{
File resourceFile = new File( resourcePath );
if ( !resourceFile.exists( ) )
{
isResourceOk = resourceFile.mkdirs( );
}
}
if ( isResourceOk )
{
config.setResourcePath( resourcePath );
}
// Prepare image directory.
imageDirectory = servletConfig.getServletContext( ).getInitParameter(
ParameterAccessor.INIT_PARAM_IMAGE_DIR );
if ( imageDirectory == null || imageDirectory.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( imageDirectory ) )
{
imageDirectory = servletConfig.getServletContext( ).getRealPath(
"/report/images" ); //$NON-NLS-1$
}
// Prepare image base url.
imageBaseUrl = "/run?__imageID="; //$NON-NLS-1$
// Prepare log directory.
String logDirectory = servletConfig.getServletContext( )
.getInitParameter( ParameterAccessor.INIT_PARAM_LOG_DIR );
if ( logDirectory == null || logDirectory.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( logDirectory ) )
{
logDirectory = servletConfig.getServletContext( ).getRealPath(
"/logs" ); //$NON-NLS-1$
}
// Prepare log level.
String logLevel = servletConfig.getServletContext( ).getInitParameter(
ParameterAccessor.INIT_PARAM_LOG_LEVEL );
Level level = Level.OFF;
if ( "SEVERE".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.SEVERE;
}
else if ( "WARNING".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.WARNING;
}
else if ( "INFO".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.INFO;
}
else if ( "CONFIG".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.CONFIG;
}
else if ( "FINE".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINE;
}
else if ( "FINER".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINER;
}
else if ( "FINEST".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.FINEST;
}
else if ( "OFF".equalsIgnoreCase( logLevel ) ) //$NON-NLS-1$
{
level = Level.OFF;
}
config.setLogConfig( logDirectory, level );
// Prepare ScriptLib location
String scriptLibDir = servletConfig.getServletContext( )
.getInitParameter( ParameterAccessor.INIT_PARAM_SCRIPTLIB_DIR );
if ( scriptLibDir == null || scriptLibDir.trim( ).length( ) <= 0
|| ParameterAccessor.isRelativePath( scriptLibDir ) )
{
scriptLibDir = servletConfig.getServletContext( ).getRealPath(
"/scriptlib" ); //$NON-NLS-1$
}
ArrayList jarFileList = new ArrayList( );
if ( scriptLibDir != null )
{
File dir = new File( scriptLibDir );
getAllJarFiles( dir, jarFileList );
}
String scriptlibClassPath = ""; //$NON-NLS-1$
for ( int i = 0; i < jarFileList.size( ); i++ )
scriptlibClassPath += EngineConstants.PROPERTYSEPARATOR
+ ( (File) jarFileList.get( i ) ).getAbsolutePath( );
if ( scriptlibClassPath.startsWith( EngineConstants.PROPERTYSEPARATOR ) )
scriptlibClassPath = scriptlibClassPath
.substring( EngineConstants.PROPERTYSEPARATOR.length( ) );
System.setProperty( EngineConstants.WEBAPP_CLASSPATH_KEY,
scriptlibClassPath );
config.setEngineHome( "" ); //$NON-NLS-1$
}
|
diff --git a/phone/com/android/internal/policy/impl/PhoneWindowManager.java b/phone/com/android/internal/policy/impl/PhoneWindowManager.java
index 2143f52..2f9faae 100755
--- a/phone/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/phone/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -1,2236 +1,2242 @@
/*
* 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.internal.policy.impl;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.IStatusBar;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Rect;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.LocalPowerManager;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Vibrator;
import android.provider.Settings;
import com.android.internal.policy.PolicyManager;
import com.android.internal.telephony.ITelephony;
import android.util.Config;
import android.util.EventLog;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.IWindowManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowOrientationListener;
import android.view.RawInputEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD;
import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_PHONE;
import static android.view.WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
import static android.view.WindowManager.LayoutParams.TYPE_SEARCH_BAR;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
import android.view.WindowManagerImpl;
import android.view.WindowManagerPolicy;
import android.view.WindowManagerPolicy.WindowState;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.media.IAudioService;
import android.media.AudioManager;
/**
* WindowManagerPolicy implementation for the Android phone UI. This
* introduces a new method suffix, Lp, for an internal lock of the
* PhoneWindowManager. This is used to protect some internal state, and
* can be acquired with either thw Lw and Li lock held, so has the restrictions
* of both of those when held.
*/
public class PhoneWindowManager implements WindowManagerPolicy {
static final String TAG = "WindowManager";
static final boolean DEBUG = false;
static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
static final boolean DEBUG_LAYOUT = false;
static final boolean SHOW_STARTING_ANIMATIONS = true;
static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
// wallpaper is at the bottom, though the window manager may move it.
static final int WALLPAPER_LAYER = 2;
static final int APPLICATION_LAYER = 2;
static final int PHONE_LAYER = 3;
static final int SEARCH_BAR_LAYER = 4;
static final int STATUS_BAR_PANEL_LAYER = 5;
// toasts and the plugged-in battery thing
static final int TOAST_LAYER = 6;
static final int STATUS_BAR_LAYER = 7;
// SIM errors and unlock. Not sure if this really should be in a high layer.
static final int PRIORITY_PHONE_LAYER = 8;
// like the ANR / app crashed dialogs
static final int SYSTEM_ALERT_LAYER = 9;
// system-level error dialogs
static final int SYSTEM_ERROR_LAYER = 10;
// on-screen keyboards and other such input method user interfaces go here.
static final int INPUT_METHOD_LAYER = 11;
// on-screen keyboards and other such input method user interfaces go here.
static final int INPUT_METHOD_DIALOG_LAYER = 12;
// the keyguard; nothing on top of these can take focus, since they are
// responsible for power management when displayed.
static final int KEYGUARD_LAYER = 13;
static final int KEYGUARD_DIALOG_LAYER = 14;
// things in here CAN NOT take focus, but are shown on top of everything else.
static final int SYSTEM_OVERLAY_LAYER = 15;
static final int APPLICATION_MEDIA_SUBLAYER = -2;
static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
static final int APPLICATION_PANEL_SUBLAYER = 1;
static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
static final float SLIDE_TOUCH_EVENT_SIZE_LIMIT = 0.6f;
// Debugging: set this to have the system act like there is no hard keyboard.
static final boolean KEYBOARD_ALWAYS_HIDDEN = false;
static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
final Object mLock = new Object();
Context mContext;
IWindowManager mWindowManager;
LocalPowerManager mPowerManager;
Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
// Vibrator pattern for haptic feedback of a long press.
long[] mLongPressVibePattern;
// Vibrator pattern for haptic feedback of virtual key press.
long[] mVirtualKeyVibePattern;
// Vibrator pattern for haptic feedback during boot when safe mode is disabled.
long[] mSafeModeDisabledVibePattern;
// Vibrator pattern for haptic feedback during boot when safe mode is enabled.
long[] mSafeModeEnabledVibePattern;
/** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
boolean mEnableShiftMenuBugReports = false;
boolean mSafeMode;
WindowState mStatusBar = null;
WindowState mKeyguard = null;
KeyguardViewMediator mKeyguardMediator;
GlobalActions mGlobalActions;
boolean mShouldTurnOffOnKeyUp;
RecentApplicationsDialog mRecentAppsDialog;
Handler mHandler;
final IntentFilter mBatteryStatusFilter = new IntentFilter();
boolean mLidOpen;
int mPlugged;
boolean mRegisteredBatteryReceiver;
int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
int mLidOpenRotation;
int mCarDockRotation;
int mDeskDockRotation;
int mCarDockKeepsScreenOn;
int mDeskDockKeepsScreenOn;
boolean mCarDockEnablesAccelerometer;
boolean mDeskDockEnablesAccelerometer;
int mLidKeyboardAccessibility;
int mLidNavigationAccessibility;
boolean mScreenOn = false;
boolean mOrientationSensorEnabled = false;
int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
static final int DEFAULT_ACCELEROMETER_ROTATION = 0;
int mAccelerometerDefault = DEFAULT_ACCELEROMETER_ROTATION;
boolean mHasSoftInput = false;
// The current size of the screen.
int mW, mH;
// During layout, the current screen borders with all outer decoration
// (status bar, input method dock) accounted for.
int mCurLeft, mCurTop, mCurRight, mCurBottom;
// During layout, the frame in which content should be displayed
// to the user, accounting for all screen decoration except for any
// space they deem as available for other content. This is usually
// the same as mCur*, but may be larger if the screen decor has supplied
// content insets.
int mContentLeft, mContentTop, mContentRight, mContentBottom;
// During layout, the current screen borders along with input method
// windows are placed.
int mDockLeft, mDockTop, mDockRight, mDockBottom;
// During layout, the layer at which the doc window is placed.
int mDockLayer;
static final Rect mTmpParentFrame = new Rect();
static final Rect mTmpDisplayFrame = new Rect();
static final Rect mTmpContentFrame = new Rect();
static final Rect mTmpVisibleFrame = new Rect();
WindowState mTopFullscreenOpaqueWindowState;
boolean mForceStatusBar;
boolean mHideLockScreen;
boolean mDismissKeyguard;
boolean mHomePressed;
Intent mHomeIntent;
Intent mCarDockIntent;
Intent mDeskDockIntent;
boolean mSearchKeyPressed;
boolean mConsumeSearchKeyUp;
static final int ENDCALL_HOME = 0x1;
static final int ENDCALL_SLEEPS = 0x2;
static final int DEFAULT_ENDCALL_BEHAVIOR = ENDCALL_SLEEPS;
int mEndcallBehavior;
int mLandscapeRotation = -1;
int mPortraitRotation = -1;
// Nothing to see here, move along...
int mFancyRotationAnimation;
ShortcutManager mShortcutManager;
PowerManager.WakeLock mBroadcastWakeLock;
PowerManager.WakeLock mDockWakeLock;
class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.END_BUTTON_BEHAVIOR), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.ACCELEROMETER_ROTATION), false, this);
resolver.registerContentObserver(Settings.Secure.getUriFor(
Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
"fancy_rotation_anim"), false, this);
update();
}
@Override public void onChange(boolean selfChange) {
update();
try {
mWindowManager.setRotation(USE_LAST_ROTATION, false,
mFancyRotationAnimation);
} catch (RemoteException e) {
// Ignore
}
}
public void update() {
ContentResolver resolver = mContext.getContentResolver();
boolean updateRotation = false;
synchronized (mLock) {
mEndcallBehavior = Settings.System.getInt(resolver,
Settings.System.END_BUTTON_BEHAVIOR, DEFAULT_ENDCALL_BEHAVIOR);
mFancyRotationAnimation = Settings.System.getInt(resolver,
"fancy_rotation_anim", 0) != 0 ? 0x80 : 0;
int accelerometerDefault = Settings.System.getInt(resolver,
Settings.System.ACCELEROMETER_ROTATION, DEFAULT_ACCELEROMETER_ROTATION);
if (mAccelerometerDefault != accelerometerDefault) {
mAccelerometerDefault = accelerometerDefault;
updateOrientationListenerLp();
}
String imId = Settings.Secure.getString(resolver,
Settings.Secure.DEFAULT_INPUT_METHOD);
boolean hasSoftInput = imId != null && imId.length() > 0;
if (mHasSoftInput != hasSoftInput) {
mHasSoftInput = hasSoftInput;
updateRotation = true;
}
}
if (updateRotation) {
updateRotation(0);
}
}
}
class MyOrientationListener extends WindowOrientationListener {
MyOrientationListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int rotation) {
// Send updates based on orientation value
if (localLOGV) Log.v(TAG, "onOrientationChanged, rotation changed to " +rotation);
try {
mWindowManager.setRotation(rotation, false,
mFancyRotationAnimation);
} catch (RemoteException e) {
// Ignore
}
}
}
MyOrientationListener mOrientationListener;
boolean useSensorForOrientationLp(int appOrientation) {
// The app says use the sensor.
if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR) {
return true;
}
// The user preference says we can rotate, and the app is willing to rotate.
if (mAccelerometerDefault != 0 &&
(appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)) {
return true;
}
// We're in a dock that has a rotation affinity, an the app is willing to rotate.
if ((mCarDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_CAR)
|| (mDeskDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_DESK)) {
// Note we override the nosensor flag here.
if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
|| appOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
return true;
}
}
// Else, don't use the sensor.
return false;
}
/*
* We always let the sensor be switched on by default except when
* the user has explicitly disabled sensor based rotation or when the
* screen is switched off.
*/
boolean needSensorRunningLp() {
if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR) {
// If the application has explicitly requested to follow the
// orientation, then we need to turn the sensor or.
return true;
}
if ((mCarDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_CAR) ||
(mDeskDockEnablesAccelerometer && mDockState == Intent.EXTRA_DOCK_STATE_DESK)) {
// enable accelerometer if we are docked in a dock that enables accelerometer
// orientation management,
return true;
}
if (mAccelerometerDefault == 0) {
// If the setting for using the sensor by default is enabled, then
// we will always leave it on. Note that the user could go to
// a window that forces an orientation that does not use the
// sensor and in theory we could turn it off... however, when next
// turning it on we won't have a good value for the current
// orientation for a little bit, which can cause orientation
// changes to lag, so we'd like to keep it always on. (It will
// still be turned off when the screen is off.)
return false;
}
return true;
}
/*
* Various use cases for invoking this function
* screen turning off, should always disable listeners if already enabled
* screen turned on and current app has sensor based orientation, enable listeners
* if not already enabled
* screen turned on and current app does not have sensor orientation, disable listeners if
* already enabled
* screen turning on and current app has sensor based orientation, enable listeners if needed
* screen turning on and current app has nosensor based orientation, do nothing
*/
void updateOrientationListenerLp() {
if (!mOrientationListener.canDetectOrientation()) {
// If sensor is turned off or nonexistent for some reason
return;
}
//Could have been invoked due to screen turning on or off or
//change of the currently visible window's orientation
if (localLOGV) Log.v(TAG, "Screen status="+mScreenOn+
", current orientation="+mCurrentAppOrientation+
", SensorEnabled="+mOrientationSensorEnabled);
boolean disable = true;
if (mScreenOn) {
if (needSensorRunningLp()) {
disable = false;
//enable listener if not already enabled
if (!mOrientationSensorEnabled) {
mOrientationListener.enable();
if(localLOGV) Log.v(TAG, "Enabling listeners");
mOrientationSensorEnabled = true;
}
}
}
//check if sensors need to be disabled
if (disable && mOrientationSensorEnabled) {
mOrientationListener.disable();
if(localLOGV) Log.v(TAG, "Disabling listeners");
mOrientationSensorEnabled = false;
}
}
Runnable mPowerLongPress = new Runnable() {
public void run() {
mShouldTurnOffOnKeyUp = false;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
showGlobalActionsDialog();
}
};
void showGlobalActionsDialog() {
if (mGlobalActions == null) {
mGlobalActions = new GlobalActions(mContext);
}
final boolean keyguardShowing = mKeyguardMediator.isShowingAndNotHidden();
mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
if (keyguardShowing) {
// since it took two seconds of long press to bring this up,
// poke the wake lock so they have some time to see the dialog.
mKeyguardMediator.pokeWakelock();
}
}
boolean isDeviceProvisioned() {
return Settings.Secure.getInt(
mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
}
/**
* When a home-key longpress expires, close other system windows and launch the recent apps
*/
Runnable mHomeLongPress = new Runnable() {
public void run() {
/*
* Eat the longpress so it won't dismiss the recent apps dialog when
* the user lets go of the home key
*/
mHomePressed = false;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
showRecentAppsDialog();
}
};
/**
* Create (if necessary) and launch the recent apps dialog
*/
void showRecentAppsDialog() {
if (mRecentAppsDialog == null) {
mRecentAppsDialog = new RecentApplicationsDialog(mContext);
}
mRecentAppsDialog.show();
}
/** {@inheritDoc} */
public void init(Context context, IWindowManager windowManager,
LocalPowerManager powerManager) {
mContext = context;
mWindowManager = windowManager;
mPowerManager = powerManager;
mKeyguardMediator = new KeyguardViewMediator(context, this, powerManager);
mHandler = new Handler();
mOrientationListener = new MyOrientationListener(mContext);
SettingsObserver settingsObserver = new SettingsObserver(mHandler);
settingsObserver.observe();
mShortcutManager = new ShortcutManager(context, mHandler);
mShortcutManager.observe();
mHomeIntent = new Intent(Intent.ACTION_MAIN, null);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mCarDockIntent = new Intent(Intent.ACTION_MAIN, null);
mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null);
mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mBroadcastWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"PhoneWindowManager.mBroadcastWakeLock");
mDockWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK,
"PhoneWindowManager.mDockWakeLock");
mDockWakeLock.setReferenceCounted(false);
mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
mLidOpenRotation = readRotation(
com.android.internal.R.integer.config_lidOpenRotation);
mCarDockRotation = readRotation(
com.android.internal.R.integer.config_carDockRotation);
mDeskDockRotation = readRotation(
com.android.internal.R.integer.config_deskDockRotation);
mCarDockKeepsScreenOn = mContext.getResources().getInteger(
com.android.internal.R.integer.config_carDockKeepsScreenOn);
mDeskDockKeepsScreenOn = mContext.getResources().getInteger(
com.android.internal.R.integer.config_deskDockKeepsScreenOn);
mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_carDockEnablesAccelerometer);
mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
mLidKeyboardAccessibility = mContext.getResources().getInteger(
com.android.internal.R.integer.config_lidKeyboardAccessibility);
mLidNavigationAccessibility = mContext.getResources().getInteger(
com.android.internal.R.integer.config_lidNavigationAccessibility);
// register for battery events
mBatteryStatusFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mPlugged = 0;
updatePlugged(context.registerReceiver(null, mBatteryStatusFilter));
// register for dock events
context.registerReceiver(mDockReceiver, new IntentFilter(Intent.ACTION_DOCK_EVENT));
mVibrator = new Vibrator();
mLongPressVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_longPressVibePattern);
mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_virtualKeyVibePattern);
mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_safeModeDisabledVibePattern);
mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_safeModeEnabledVibePattern);
}
void updatePlugged(Intent powerIntent) {
if (localLOGV) Log.v(TAG, "New battery status: " + powerIntent.getExtras());
if (powerIntent != null) {
mPlugged = powerIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
if (localLOGV) Log.v(TAG, "PLUGGED: " + mPlugged);
}
}
private int readRotation(int resID) {
try {
int rotation = mContext.getResources().getInteger(resID);
switch (rotation) {
case 0:
return Surface.ROTATION_0;
case 90:
return Surface.ROTATION_90;
case 180:
return Surface.ROTATION_180;
case 270:
return Surface.ROTATION_270;
}
} catch (Resources.NotFoundException e) {
// fall through
}
return -1;
}
/** {@inheritDoc} */
public int checkAddPermission(WindowManager.LayoutParams attrs) {
int type = attrs.type;
if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
|| type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) {
return WindowManagerImpl.ADD_OKAY;
}
String permission = null;
switch (type) {
case TYPE_TOAST:
// XXX right now the app process has complete control over
// this... should introduce a token to let the system
// monitor/control what they are doing.
break;
case TYPE_INPUT_METHOD:
case TYPE_WALLPAPER:
// The window manager will check these.
break;
case TYPE_PHONE:
case TYPE_PRIORITY_PHONE:
case TYPE_SYSTEM_ALERT:
case TYPE_SYSTEM_ERROR:
case TYPE_SYSTEM_OVERLAY:
permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
break;
default:
permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
}
if (permission != null) {
if (mContext.checkCallingOrSelfPermission(permission)
!= PackageManager.PERMISSION_GRANTED) {
return WindowManagerImpl.ADD_PERMISSION_DENIED;
}
}
return WindowManagerImpl.ADD_OKAY;
}
public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
switch (attrs.type) {
case TYPE_SYSTEM_OVERLAY:
case TYPE_TOAST:
// These types of windows can't receive input events.
attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
break;
}
}
void readLidState() {
try {
int sw = mWindowManager.getSwitchState(RawInputEvent.SW_LID);
if (sw >= 0) {
mLidOpen = sw == 0;
}
} catch (RemoteException e) {
// Ignore
}
}
private int determineHiddenState(boolean lidOpen,
int mode, int hiddenValue, int visibleValue) {
switch (mode) {
case 1:
return lidOpen ? visibleValue : hiddenValue;
case 2:
return lidOpen ? hiddenValue : visibleValue;
}
return visibleValue;
}
/** {@inheritDoc} */
public void adjustConfigurationLw(Configuration config) {
readLidState();
final boolean lidOpen = !KEYBOARD_ALWAYS_HIDDEN && mLidOpen;
mPowerManager.setKeyboardVisibility(lidOpen);
config.hardKeyboardHidden = determineHiddenState(lidOpen,
mLidKeyboardAccessibility, Configuration.HARDKEYBOARDHIDDEN_YES,
Configuration.HARDKEYBOARDHIDDEN_NO);
config.navigationHidden = determineHiddenState(lidOpen,
mLidNavigationAccessibility, Configuration.NAVIGATIONHIDDEN_YES,
Configuration.NAVIGATIONHIDDEN_NO);
config.keyboardHidden = (config.hardKeyboardHidden
== Configuration.HARDKEYBOARDHIDDEN_NO || mHasSoftInput)
? Configuration.KEYBOARDHIDDEN_NO
: Configuration.KEYBOARDHIDDEN_YES;
}
public boolean isCheekPressedAgainstScreen(MotionEvent ev) {
if(ev.getSize() > SLIDE_TOUCH_EVENT_SIZE_LIMIT) {
return true;
}
int size = ev.getHistorySize();
for(int i = 0; i < size; i++) {
if(ev.getHistoricalSize(i) > SLIDE_TOUCH_EVENT_SIZE_LIMIT) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public int windowTypeToLayerLw(int type) {
if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
return APPLICATION_LAYER;
}
switch (type) {
case TYPE_STATUS_BAR:
return STATUS_BAR_LAYER;
case TYPE_STATUS_BAR_PANEL:
return STATUS_BAR_PANEL_LAYER;
case TYPE_SEARCH_BAR:
return SEARCH_BAR_LAYER;
case TYPE_PHONE:
return PHONE_LAYER;
case TYPE_KEYGUARD:
return KEYGUARD_LAYER;
case TYPE_KEYGUARD_DIALOG:
return KEYGUARD_DIALOG_LAYER;
case TYPE_SYSTEM_ALERT:
return SYSTEM_ALERT_LAYER;
case TYPE_SYSTEM_ERROR:
return SYSTEM_ERROR_LAYER;
case TYPE_INPUT_METHOD:
return INPUT_METHOD_LAYER;
case TYPE_INPUT_METHOD_DIALOG:
return INPUT_METHOD_DIALOG_LAYER;
case TYPE_SYSTEM_OVERLAY:
return SYSTEM_OVERLAY_LAYER;
case TYPE_PRIORITY_PHONE:
return PRIORITY_PHONE_LAYER;
case TYPE_TOAST:
return TOAST_LAYER;
case TYPE_WALLPAPER:
return WALLPAPER_LAYER;
}
Log.e(TAG, "Unknown window type: " + type);
return APPLICATION_LAYER;
}
/** {@inheritDoc} */
public int subWindowTypeToLayerLw(int type) {
switch (type) {
case TYPE_APPLICATION_PANEL:
case TYPE_APPLICATION_ATTACHED_DIALOG:
return APPLICATION_PANEL_SUBLAYER;
case TYPE_APPLICATION_MEDIA:
return APPLICATION_MEDIA_SUBLAYER;
case TYPE_APPLICATION_MEDIA_OVERLAY:
return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
case TYPE_APPLICATION_SUB_PANEL:
return APPLICATION_SUB_PANEL_SUBLAYER;
}
Log.e(TAG, "Unknown sub-window type: " + type);
return 0;
}
public int getMaxWallpaperLayer() {
return STATUS_BAR_LAYER;
}
public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) {
return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD;
}
public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
return attrs.type != WindowManager.LayoutParams.TYPE_STATUS_BAR
&& attrs.type != WindowManager.LayoutParams.TYPE_WALLPAPER;
}
/** {@inheritDoc} */
public View addStartingWindow(IBinder appToken, String packageName,
int theme, CharSequence nonLocalizedLabel,
int labelRes, int icon) {
if (!SHOW_STARTING_ANIMATIONS) {
return null;
}
if (packageName == null) {
return null;
}
Context context = mContext;
boolean setTheme = false;
//Log.i(TAG, "addStartingWindow " + packageName + ": nonLocalizedLabel="
// + nonLocalizedLabel + " theme=" + Integer.toHexString(theme));
if (theme != 0 || labelRes != 0) {
try {
context = context.createPackageContext(packageName, 0);
if (theme != 0) {
context.setTheme(theme);
setTheme = true;
}
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
if (!setTheme) {
context.setTheme(com.android.internal.R.style.Theme);
}
Window win = PolicyManager.makeNewWindow(context);
if (win.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowDisablePreview, false)) {
return null;
}
Resources r = context.getResources();
win.setTitle(r.getText(labelRes, nonLocalizedLabel));
win.setType(
WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
// Force the window flags: this is a fake window, so it is not really
// touchable or focusable by the user. We also add in the ALT_FOCUSABLE_IM
// flag because we do know that the next window will take input
// focus, so we want to get the IME window up on top of us right away.
win.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
win.setLayout(WindowManager.LayoutParams.FILL_PARENT,
WindowManager.LayoutParams.FILL_PARENT);
final WindowManager.LayoutParams params = win.getAttributes();
params.token = appToken;
params.packageName = packageName;
params.windowAnimations = win.getWindowStyle().getResourceId(
com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
params.setTitle("Starting " + packageName);
try {
WindowManagerImpl wm = (WindowManagerImpl)
context.getSystemService(Context.WINDOW_SERVICE);
View view = win.getDecorView();
if (win.isFloating()) {
// Whoops, there is no way to display an animation/preview
// of such a thing! After all that work... let's skip it.
// (Note that we must do this here because it is in
// getDecorView() where the theme is evaluated... maybe
// we should peek the floating attribute from the theme
// earlier.)
return null;
}
if (localLOGV) Log.v(
TAG, "Adding starting window for " + packageName
+ " / " + appToken + ": "
+ (view.getParent() != null ? view : null));
wm.addView(view, params);
// Only return the view if it was successfully added to the
// window manager... which we can tell by it having a parent.
return view.getParent() != null ? view : null;
} catch (WindowManagerImpl.BadTokenException e) {
// ignore
Log.w(TAG, appToken + " already running, starting window not displayed");
}
return null;
}
/** {@inheritDoc} */
public void removeStartingWindow(IBinder appToken, View window) {
// RuntimeException e = new RuntimeException();
// Log.i(TAG, "remove " + appToken + " " + window, e);
if (localLOGV) Log.v(
TAG, "Removing starting window for " + appToken + ": " + window);
if (window != null) {
WindowManagerImpl wm = (WindowManagerImpl) mContext.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(window);
}
}
/**
* Preflight adding a window to the system.
*
* Currently enforces that three window types are singletons:
* <ul>
* <li>STATUS_BAR_TYPE</li>
* <li>KEYGUARD_TYPE</li>
* </ul>
*
* @param win The window to be added
* @param attrs Information about the window to be added
*
* @return If ok, WindowManagerImpl.ADD_OKAY. If too many singletons, WindowManagerImpl.ADD_MULTIPLE_SINGLETON
*/
public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
switch (attrs.type) {
case TYPE_STATUS_BAR:
if (mStatusBar != null) {
return WindowManagerImpl.ADD_MULTIPLE_SINGLETON;
}
mStatusBar = win;
break;
case TYPE_KEYGUARD:
if (mKeyguard != null) {
return WindowManagerImpl.ADD_MULTIPLE_SINGLETON;
}
mKeyguard = win;
break;
}
return WindowManagerImpl.ADD_OKAY;
}
/** {@inheritDoc} */
public void removeWindowLw(WindowState win) {
if (mStatusBar == win) {
mStatusBar = null;
}
else if (mKeyguard == win) {
mKeyguard = null;
}
}
static final boolean PRINT_ANIM = false;
/** {@inheritDoc} */
public int selectAnimationLw(WindowState win, int transit) {
if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
+ ": transit=" + transit);
if (transit == TRANSIT_PREVIEW_DONE) {
if (win.hasAppShownWindows()) {
if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
return com.android.internal.R.anim.app_starting_exit;
}
}
return 0;
}
public Animation createForceHideEnterAnimation() {
return AnimationUtils.loadAnimation(mContext,
com.android.internal.R.anim.lock_screen_behind_enter);
}
static ITelephony getPhoneInterface() {
return ITelephony.Stub.asInterface(ServiceManager.checkService(Context.TELEPHONY_SERVICE));
}
static IAudioService getAudioInterface() {
return IAudioService.Stub.asInterface(ServiceManager.checkService(Context.AUDIO_SERVICE));
}
boolean keyguardOn() {
return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode();
}
private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
};
/** {@inheritDoc} */
public boolean interceptKeyTi(WindowState win, int code, int metaKeys, boolean down,
int repeatCount, int flags) {
boolean keyguardOn = keyguardOn();
if (false) {
Log.d(TAG, "interceptKeyTi code=" + code + " down=" + down + " repeatCount="
+ repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed);
}
// Clear a pending HOME longpress if the user releases Home
// TODO: This could probably be inside the next bit of logic, but that code
// turned out to be a bit fragile so I'm doing it here explicitly, for now.
if ((code == KeyEvent.KEYCODE_HOME) && !down) {
mHandler.removeCallbacks(mHomeLongPress);
}
// If the HOME button is currently being held, then we do special
// chording with it.
if (mHomePressed) {
// If we have released the home key, and didn't do anything else
// while it was pressed, then it is time to go home!
if (code == KeyEvent.KEYCODE_HOME) {
if (!down) {
mHomePressed = false;
if ((flags&KeyEvent.FLAG_CANCELED) == 0) {
// If an incoming call is ringing, HOME is totally disabled.
// (The user is already on the InCallScreen at this point,
// and his ONLY options are to answer or reject the call.)
boolean incomingRinging = false;
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
incomingRinging = phoneServ.isRinging();
} else {
Log.w(TAG, "Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "RemoteException from getPhoneInterface()", ex);
}
if (incomingRinging) {
Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
} else {
launchHomeFromHotKey();
}
} else {
Log.i(TAG, "Ignoring HOME; event canceled.");
}
}
}
return true;
}
// First we always handle the home key here, so applications
// can never break it, although if keyguard is on, we do let
// it handle it, because that gives us the correct 5 second
// timeout.
if (code == KeyEvent.KEYCODE_HOME) {
// If a system window has focus, then it doesn't make sense
// right now to interact with applications.
WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
if (attrs != null) {
final int type = attrs.type;
if (type == WindowManager.LayoutParams.TYPE_KEYGUARD
|| type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {
// the "app" is keyguard, so give it the key
return false;
}
final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
for (int i=0; i<typeCount; i++) {
if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
// don't do anything, but also don't pass it to the app
return true;
}
}
}
if (down && repeatCount == 0) {
if (!keyguardOn) {
mHandler.postDelayed(mHomeLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
}
mHomePressed = true;
}
return true;
} else if (code == KeyEvent.KEYCODE_MENU) {
// Hijack modified menu keys for debugging features
final int chordBug = KeyEvent.META_SHIFT_ON;
if (down && repeatCount == 0) {
if (mEnableShiftMenuBugReports && (metaKeys & chordBug) == chordBug) {
Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
mContext.sendOrderedBroadcast(intent, null);
return true;
} else if (SHOW_PROCESSES_ON_ALT_MENU &&
(metaKeys & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
Intent service = new Intent();
service.setClassName(mContext, "com.android.server.LoadAverageService");
ContentResolver res = mContext.getContentResolver();
boolean shown = Settings.System.getInt(
res, Settings.System.SHOW_PROCESSES, 0) != 0;
if (!shown) {
mContext.startService(service);
} else {
mContext.stopService(service);
}
Settings.System.putInt(
res, Settings.System.SHOW_PROCESSES, shown ? 0 : 1);
return true;
}
}
} else if (code == KeyEvent.KEYCODE_NOTIFICATION) {
if (down) {
// this key doesn't exist on current hardware, but if a device
// didn't have a touchscreen, it would want one of these to open
// the status bar.
IStatusBar sbs = IStatusBar.Stub.asInterface(ServiceManager.getService("statusbar"));
if (sbs != null) {
try {
sbs.toggle();
} catch (RemoteException e) {
// we're screwed anyway, since it's in this process
throw new RuntimeException(e);
}
}
}
return true;
} else if (code == KeyEvent.KEYCODE_SEARCH) {
if (down) {
if (repeatCount == 0) {
mSearchKeyPressed = true;
}
} else {
mSearchKeyPressed = false;
if (mConsumeSearchKeyUp) {
// Consume the up-event
mConsumeSearchKeyUp = false;
return true;
}
}
}
// Shortcuts are invoked through Search+key, so intercept those here
if (mSearchKeyPressed) {
if (down && repeatCount == 0 && !keyguardOn) {
Intent shortcutIntent = mShortcutManager.getIntent(code, metaKeys);
if (shortcutIntent != null) {
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(shortcutIntent);
/*
* We launched an app, so the up-event of the search key
* should be consumed
*/
mConsumeSearchKeyUp = true;
return true;
}
}
}
return false;
}
/**
* A home key -> launch home action was detected. Take the appropriate action
* given the situation with the keyguard.
*/
void launchHomeFromHotKey() {
if (mKeyguardMediator.isShowingAndNotHidden()) {
// don't launch home if keyguard showing
} else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) {
// when in keyguard restricted mode, must first verify unlock
// before launching home
mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() {
public void onKeyguardExitResult(boolean success) {
if (success) {
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
startDockOrHome();
}
}
});
} else {
// no keyguard stuff to worry about, just launch home!
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
startDockOrHome();
}
}
public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
final int fl = attrs.flags;
if ((fl &
(FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
== (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
contentInset.set(mCurLeft, mCurTop, mW - mCurRight, mH - mCurBottom);
} else {
contentInset.setEmpty();
}
}
/** {@inheritDoc} */
public void beginLayoutLw(int displayWidth, int displayHeight) {
mW = displayWidth;
mH = displayHeight;
mDockLeft = mContentLeft = mCurLeft = 0;
mDockTop = mContentTop = mCurTop = 0;
mDockRight = mContentRight = mCurRight = displayWidth;
mDockBottom = mContentBottom = mCurBottom = displayHeight;
mDockLayer = 0x10000000;
mTopFullscreenOpaqueWindowState = null;
mForceStatusBar = false;
mHideLockScreen = false;
mDismissKeyguard = false;
// decide where the status bar goes ahead of time
if (mStatusBar != null) {
final Rect pf = mTmpParentFrame;
final Rect df = mTmpDisplayFrame;
final Rect vf = mTmpVisibleFrame;
pf.left = df.left = vf.left = 0;
pf.top = df.top = vf.top = 0;
pf.right = df.right = vf.right = displayWidth;
pf.bottom = df.bottom = vf.bottom = displayHeight;
mStatusBar.computeFrameLw(pf, df, vf, vf);
if (mStatusBar.isVisibleLw()) {
// If the status bar is hidden, we don't want to cause
// windows behind it to scroll.
mDockTop = mContentTop = mCurTop = mStatusBar.getFrameLw().bottom;
if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: mDockBottom="
+ mDockBottom + " mContentBottom="
+ mContentBottom + " mCurBottom=" + mCurBottom);
}
}
}
void setAttachedWindowFrames(WindowState win, int fl, int sim,
WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) {
if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
// Here's a special case: if this attached window is a panel that is
// above the dock window, and the window it is attached to is below
// the dock window, then the frames we computed for the window it is
// attached to can not be used because the dock is effectively part
// of the underlying window and the attached window is floating on top
// of the whole thing. So, we ignore the attached window and explicitly
// compute the frames that would be appropriate without the dock.
df.left = cf.left = vf.left = mDockLeft;
df.top = cf.top = vf.top = mDockTop;
df.right = cf.right = vf.right = mDockRight;
df.bottom = cf.bottom = vf.bottom = mDockBottom;
} else {
// The effective display frame of the attached window depends on
// whether it is taking care of insetting its content. If not,
// we need to use the parent's content frame so that the entire
// window is positioned within that content. Otherwise we can use
// the display frame and let the attached window take care of
// positioning its content appropriately.
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
cf.set(attached.getDisplayFrameLw());
} else {
// If the window is resizing, then we want to base the content
// frame on our attached content frame to resize... however,
// things can be tricky if the attached window is NOT in resize
// mode, in which case its content frame will be larger.
// Ungh. So to deal with that, make sure the content frame
// we end up using is not covering the IM dock.
cf.set(attached.getContentFrameLw());
if (attached.getSurfaceLayer() < mDockLayer) {
if (cf.left < mContentLeft) cf.left = mContentLeft;
if (cf.top < mContentTop) cf.top = mContentTop;
if (cf.right > mContentRight) cf.right = mContentRight;
if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
}
}
df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
vf.set(attached.getVisibleFrameLw());
}
// The LAYOUT_IN_SCREEN flag is used to determine whether the attached
// window should be positioned relative to its parent or the entire
// screen.
pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
? attached.getFrameLw() : df);
}
/** {@inheritDoc} */
public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
WindowState attached) {
// we've already done the status bar
if (win == mStatusBar) {
return;
}
if (false) {
if ("com.google.android.youtube".equals(attrs.packageName)
&& attrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
Log.i(TAG, "GOTCHA!");
}
}
final int fl = attrs.flags;
final int sim = attrs.softInputMode;
final Rect pf = mTmpParentFrame;
final Rect df = mTmpDisplayFrame;
final Rect cf = mTmpContentFrame;
final Rect vf = mTmpVisibleFrame;
if (attrs.type == TYPE_INPUT_METHOD) {
pf.left = df.left = cf.left = vf.left = mDockLeft;
pf.top = df.top = cf.top = vf.top = mDockTop;
pf.right = df.right = cf.right = vf.right = mDockRight;
pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom;
// IM dock windows always go to the bottom of the screen.
attrs.gravity = Gravity.BOTTOM;
mDockLayer = win.getSurfaceLayer();
} else {
if ((fl &
(FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
== (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
// This is the case for a normal activity window: we want it
// to cover all of the screen space, and it can take care of
// moving its contents to account for screen decorations that
// intrude into that space.
if (attached != null) {
// If this window is attached to another, our display
// frame is the same as the one we are attached to.
setAttachedWindowFrames(win, fl, sim, attached, true, pf, df, cf, vf);
} else {
pf.left = df.left = 0;
pf.top = df.top = 0;
pf.right = df.right = mW;
pf.bottom = df.bottom = mH;
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
cf.left = mDockLeft;
cf.top = mDockTop;
cf.right = mDockRight;
cf.bottom = mDockBottom;
} else {
cf.left = mContentLeft;
cf.top = mContentTop;
cf.right = mContentRight;
cf.bottom = mContentBottom;
}
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
}
} else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0) {
// A window that has requested to fill the entire screen just
// gets everything, period.
pf.left = df.left = cf.left = 0;
pf.top = df.top = cf.top = 0;
pf.right = df.right = cf.right = mW;
pf.bottom = df.bottom = cf.bottom = mH;
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
} else if (attached != null) {
// A child window should be placed inside of the same visible
// frame that its parent had.
setAttachedWindowFrames(win, fl, sim, attached, false, pf, df, cf, vf);
} else {
// Otherwise, a normal window must be placed inside the content
// of all screen decorations.
pf.left = mContentLeft;
pf.top = mContentTop;
pf.right = mContentRight;
pf.bottom = mContentBottom;
if ((sim & SOFT_INPUT_MASK_ADJUST) != SOFT_INPUT_ADJUST_RESIZE) {
df.left = cf.left = mDockLeft;
df.top = cf.top = mDockTop;
df.right = cf.right = mDockRight;
df.bottom = cf.bottom = mDockBottom;
} else {
df.left = cf.left = mContentLeft;
df.top = cf.top = mContentTop;
df.right = cf.right = mContentRight;
df.bottom = cf.bottom = mContentBottom;
}
vf.left = mCurLeft;
vf.top = mCurTop;
vf.right = mCurRight;
vf.bottom = mCurBottom;
}
}
if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000;
df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
}
if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
+ ": sim=#" + Integer.toHexString(sim)
+ " pf=" + pf.toShortString() + " df=" + df.toShortString()
+ " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
if (false) {
if ("com.google.android.youtube".equals(attrs.packageName)
&& attrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
if (true || localLOGV) Log.v(TAG, "Computing frame of " + win +
": sim=#" + Integer.toHexString(sim)
+ " pf=" + pf.toShortString() + " df=" + df.toShortString()
+ " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
}
}
win.computeFrameLw(pf, df, cf, vf);
if (mTopFullscreenOpaqueWindowState == null &&
win.isVisibleOrBehindKeyguardLw()) {
if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
mForceStatusBar = true;
}
if (attrs.type >= FIRST_APPLICATION_WINDOW
&& attrs.type <= LAST_APPLICATION_WINDOW
&& win.fillsScreenLw(mW, mH, false, false)) {
if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
mTopFullscreenOpaqueWindowState = win;
if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
if (localLOGV) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
mHideLockScreen = true;
}
}
if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0) {
if (localLOGV) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
mDismissKeyguard = true;
}
}
// Dock windows carve out the bottom of the screen, so normal windows
// can't appear underneath them.
if (attrs.type == TYPE_INPUT_METHOD && !win.getGivenInsetsPendingLw()) {
int top = win.getContentFrameLw().top;
top += win.getGivenContentInsetsLw().top;
if (mContentBottom > top) {
mContentBottom = top;
}
top = win.getVisibleFrameLw().top;
top += win.getGivenVisibleInsetsLw().top;
if (mCurBottom > top) {
mCurBottom = top;
}
if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
+ mDockBottom + " mContentBottom="
+ mContentBottom + " mCurBottom=" + mCurBottom);
}
}
/** {@inheritDoc} */
public int finishLayoutLw() {
int changes = 0;
boolean hiding = false;
if (mStatusBar != null) {
if (localLOGV) Log.i(TAG, "force=" + mForceStatusBar
+ " top=" + mTopFullscreenOpaqueWindowState);
if (mForceStatusBar) {
if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
} else if (mTopFullscreenOpaqueWindowState != null) {
//Log.i(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
// + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
//Log.i(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs());
WindowManager.LayoutParams lp =
mTopFullscreenOpaqueWindowState.getAttrs();
boolean hideStatusBar =
(lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
if (hideStatusBar) {
if (DEBUG_LAYOUT) Log.v(TAG, "Hiding status bar");
if (mStatusBar.hideLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
hiding = true;
} else {
if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
}
}
}
// Hide the key guard if a visible window explicitly specifies that it wants to be displayed
// when the screen is locked
if (mKeyguard != null) {
if (localLOGV) Log.v(TAG, "finishLayoutLw::mHideKeyguard="+mHideLockScreen);
if (mDismissKeyguard && !mKeyguardMediator.isSecure()) {
if (mKeyguard.hideLw(false)) {
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
if (mKeyguardMediator.isShowing()) {
mHandler.post(new Runnable() {
public void run() {
mKeyguardMediator.keyguardDone(false, false);
}
});
}
} else if (mHideLockScreen) {
if (mKeyguard.hideLw(false)) {
mKeyguardMediator.setHidden(true);
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
} else {
if (mKeyguard.showLw(false)) {
mKeyguardMediator.setHidden(false);
changes |= FINISH_LAYOUT_REDO_LAYOUT
| FINISH_LAYOUT_REDO_CONFIG
| FINISH_LAYOUT_REDO_WALLPAPER;
}
}
}
if (changes != 0 && hiding) {
IStatusBar sbs = IStatusBar.Stub.asInterface(ServiceManager.getService("statusbar"));
if (sbs != null) {
try {
// Make sure the window shade is hidden.
sbs.deactivate();
} catch (RemoteException e) {
}
}
}
return changes;
}
/** {@inheritDoc} */
public void beginAnimationLw(int displayWidth, int displayHeight) {
}
/** {@inheritDoc} */
public void animatingWindowLw(WindowState win,
WindowManager.LayoutParams attrs) {
}
/** {@inheritDoc} */
public boolean finishAnimationLw() {
return false;
}
/** {@inheritDoc} */
public boolean preprocessInputEventTq(RawInputEvent event) {
switch (event.type) {
case RawInputEvent.EV_SW:
if (event.keycode == RawInputEvent.SW_LID) {
// lid changed state
mLidOpen = event.value == 0;
boolean awakeNow = mKeyguardMediator.doLidChangeTq(mLidOpen);
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
if (awakeNow) {
// If the lid opening and we don't have to keep the
// keyguard up, then we can turn on the screen
// immediately.
mKeyguardMediator.pokeWakelock();
} else if (keyguardIsShowingTq()) {
if (mLidOpen) {
// If we are opening the lid and not hiding the
// keyguard, then we need to have it turn on the
// screen once it is shown.
mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(
KeyEvent.KEYCODE_POWER);
}
} else {
// Light up the keyboard if we are sliding up.
if (mLidOpen) {
mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
LocalPowerManager.BUTTON_EVENT);
} else {
mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
LocalPowerManager.OTHER_EVENT);
}
}
}
}
return false;
}
/** {@inheritDoc} */
public boolean isAppSwitchKeyTqTiLwLi(int keycode) {
return keycode == KeyEvent.KEYCODE_HOME
|| keycode == KeyEvent.KEYCODE_ENDCALL;
}
/** {@inheritDoc} */
public boolean isMovementKeyTi(int keycode) {
switch (keycode) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
return true;
}
return false;
}
/**
* @return Whether a telephone call is in progress right now.
*/
boolean isInCall() {
final ITelephony phone = getPhoneInterface();
if (phone == null) {
Log.w(TAG, "couldn't get ITelephony reference");
return false;
}
try {
return phone.isOffhook();
} catch (RemoteException e) {
Log.w(TAG, "ITelephony.isOffhhook threw RemoteException " + e);
return false;
}
}
/**
* @return Whether music is being played right now.
*/
boolean isMusicActive() {
final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
if (am == null) {
Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
return false;
}
return am.isMusicActive();
}
/**
* Tell the audio service to adjust the volume appropriate to the event.
* @param keycode
*/
void handleVolumeKey(int stream, int keycode) {
final IAudioService audio = getAudioInterface();
if (audio == null) {
Log.w(TAG, "handleVolumeKey: couldn't get IAudioService reference");
return;
}
try {
// since audio is playing, we shouldn't have to hold a wake lock
// during the call, but we do it as a precaution for the rare possibility
// that the music stops right before we call this
mBroadcastWakeLock.acquire();
audio.adjustStreamVolume(stream,
keycode == KeyEvent.KEYCODE_VOLUME_UP
? AudioManager.ADJUST_RAISE
: AudioManager.ADJUST_LOWER,
0);
} catch (RemoteException e) {
Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
} finally {
mBroadcastWakeLock.release();
}
}
static boolean isMediaKey(int code) {
if (code == KeyEvent.KEYCODE_HEADSETHOOK ||
code == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE ||
code == KeyEvent.KEYCODE_MEDIA_STOP ||
code == KeyEvent.KEYCODE_MEDIA_NEXT ||
code == KeyEvent.KEYCODE_MEDIA_PREVIOUS ||
code == KeyEvent.KEYCODE_MEDIA_PREVIOUS ||
code == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) {
return true;
}
return false;
}
/** {@inheritDoc} */
public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
- final boolean keyguardShowing = keyguardIsShowingTq();
+ // If screen is off then we treat the case where the keyguard is open but hidden
+ // the same as if it were open and in front.
+ // This will prevent any keys other than the power button from waking the screen
+ // when the keyguard is hidden by another activity.
+ final boolean keyguardActive = (screenIsOn ?
+ mKeyguardMediator.isShowingAndNotHidden() :
+ mKeyguardMediator.isShowing());
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
- + " screenIsOn=" + screenIsOn + " keyguardShowing=" + keyguardShowing);
+ + " screenIsOn=" + screenIsOn + " keyguardActive=" + keyguardActive);
}
- if (keyguardShowing) {
+ if (keyguardActive) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
if (isInCall()) {
// if the keyguard didn't wake the device, we are in call, and
// it is a volume key, turn on the screen so that the user
// can more easily adjust the in call volume.
mKeyguardMediator.pokeWakelock();
} else if (isMusicActive()) {
// when keyguard is showing and screen off, we need
// to handle the volume key for music here
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
- if (keyguardShowing
+ if (keyguardActive
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
class PassHeadsetKey implements Runnable {
KeyEvent mKeyEvent;
PassHeadsetKey(KeyEvent keyEvent) {
mKeyEvent = keyEvent;
}
public void run() {
if (ActivityManagerNative.isSystemReady()) {
Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
intent.putExtra(Intent.EXTRA_KEY_EVENT, mKeyEvent);
mContext.sendOrderedBroadcast(intent, null, mBroadcastDone,
mHandler, Activity.RESULT_OK, null, null);
}
}
}
BroadcastReceiver mBroadcastDone = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
mBroadcastWakeLock.release();
}
};
BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
updatePlugged(intent);
updateDockKeepingScreenOn();
}
};
BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
Intent.EXTRA_DOCK_STATE_UNDOCKED);
boolean watchBattery = mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
if (watchBattery != mRegisteredBatteryReceiver) {
mRegisteredBatteryReceiver = watchBattery;
if (watchBattery) {
updatePlugged(mContext.registerReceiver(mBatteryReceiver,
mBatteryStatusFilter));
} else {
mContext.unregisterReceiver(mBatteryReceiver);
}
}
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
updateDockKeepingScreenOn();
updateOrientationListenerLp();
}
};
/** {@inheritDoc} */
public boolean isWakeRelMovementTq(int device, int classes,
RawInputEvent event) {
// if it's tagged with one of the wake bits, it wakes up the device
return ((event.flags & (FLAG_WAKE | FLAG_WAKE_DROPPED)) != 0);
}
/** {@inheritDoc} */
public boolean isWakeAbsMovementTq(int device, int classes,
RawInputEvent event) {
// if it's tagged with one of the wake bits, it wakes up the device
return ((event.flags & (FLAG_WAKE | FLAG_WAKE_DROPPED)) != 0);
}
/**
* Given the current state of the world, should this key wake up the device?
*/
protected boolean isWakeKeyTq(RawInputEvent event) {
// There are not key maps for trackball devices, but we'd still
// like to have pressing it wake the device up, so force it here.
int keycode = event.keycode;
int flags = event.flags;
if (keycode == RawInputEvent.BTN_MOUSE) {
flags |= WindowManagerPolicy.FLAG_WAKE;
}
return (flags
& (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
}
/** {@inheritDoc} */
public void screenTurnedOff(int why) {
EventLog.writeEvent(70000, 0);
mKeyguardMediator.onScreenTurnedOff(why);
synchronized (mLock) {
mScreenOn = false;
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void screenTurnedOn() {
EventLog.writeEvent(70000, 1);
mKeyguardMediator.onScreenTurnedOn();
synchronized (mLock) {
mScreenOn = true;
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void enableKeyguard(boolean enabled) {
mKeyguardMediator.setKeyguardEnabled(enabled);
}
/** {@inheritDoc} */
public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
mKeyguardMediator.verifyUnlock(callback);
}
/** {@inheritDoc} */
public boolean keyguardIsShowingTq() {
return mKeyguardMediator.isShowingAndNotHidden();
}
/** {@inheritDoc} */
public boolean inKeyguardRestrictedKeyInputMode() {
return mKeyguardMediator.isInputRestricted();
}
void sendCloseSystemWindows() {
sendCloseSystemWindows(mContext, null);
}
void sendCloseSystemWindows(String reason) {
sendCloseSystemWindows(mContext, reason);
}
static void sendCloseSystemWindows(Context context, String reason) {
if (ActivityManagerNative.isSystemReady()) {
try {
ActivityManagerNative.getDefault().closeSystemDialogs(reason);
} catch (RemoteException e) {
}
}
}
public int rotationForOrientationLw(int orientation, int lastRotation,
boolean displayEnabled) {
if (mPortraitRotation < 0) {
// Initialize the rotation angles for each orientation once.
Display d = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
if (d.getWidth() > d.getHeight()) {
mPortraitRotation = Surface.ROTATION_90;
mLandscapeRotation = Surface.ROTATION_0;
} else {
mPortraitRotation = Surface.ROTATION_0;
mLandscapeRotation = Surface.ROTATION_90;
}
}
synchronized (mLock) {
switch (orientation) {
case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
//always return landscape if orientation set to landscape
return mLandscapeRotation;
case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
//always return portrait if orientation set to portrait
return mPortraitRotation;
}
// case for nosensor meaning ignore sensor and consider only lid
// or orientation sensor disabled
//or case.unspecified
if (mLidOpen) {
return mLidOpenRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
return mCarDockRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
return mDeskDockRotation;
} else {
if (useSensorForOrientationLp(orientation)) {
// If the user has enabled auto rotation by default, do it.
int curRotation = mOrientationListener.getCurrentRotation();
return curRotation >= 0 ? curRotation : lastRotation;
}
return Surface.ROTATION_0;
}
}
}
public boolean detectSafeMode() {
try {
int menuState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_MENU);
int sState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_S);
int dpadState = mWindowManager.getDPadKeycodeState(KeyEvent.KEYCODE_DPAD_CENTER);
int trackballState = mWindowManager.getTrackballScancodeState(RawInputEvent.BTN_MOUSE);
mSafeMode = menuState > 0 || sState > 0 || dpadState > 0 || trackballState > 0;
performHapticFeedbackLw(null, mSafeMode
? HapticFeedbackConstants.SAFE_MODE_ENABLED
: HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
if (mSafeMode) {
Log.i(TAG, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
+ " dpad=" + dpadState + " trackball=" + trackballState + ")");
} else {
Log.i(TAG, "SAFE MODE not enabled");
}
return mSafeMode;
} catch (RemoteException e) {
// Doom! (it's also local)
throw new RuntimeException("window manager dead");
}
}
static long[] getLongIntArray(Resources r, int resid) {
int[] ar = r.getIntArray(resid);
if (ar == null) {
return null;
}
long[] out = new long[ar.length];
for (int i=0; i<ar.length; i++) {
out[i] = ar[i];
}
return out;
}
/** {@inheritDoc} */
public void systemReady() {
// tell the keyguard
mKeyguardMediator.onSystemReady();
android.os.SystemProperties.set("dev.bootcomplete", "1");
synchronized (mLock) {
updateOrientationListenerLp();
}
}
/** {@inheritDoc} */
public void enableScreenAfterBoot() {
readLidState();
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
}
void updateDockKeepingScreenOn() {
if (mPlugged != 0) {
if (localLOGV) Log.v(TAG, "Update: mDockState=" + mDockState
+ " mPlugged=" + mPlugged
+ " mCarDockKeepsScreenOn" + mCarDockKeepsScreenOn
+ " mDeskDockKeepsScreenOn" + mDeskDockKeepsScreenOn);
if (mDockState == Intent.EXTRA_DOCK_STATE_CAR
&& (mPlugged&mCarDockKeepsScreenOn) != 0) {
if (!mDockWakeLock.isHeld()) {
mDockWakeLock.acquire();
}
return;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK
&& (mPlugged&mDeskDockKeepsScreenOn) != 0) {
if (!mDockWakeLock.isHeld()) {
mDockWakeLock.acquire();
}
return;
}
}
if (mDockWakeLock.isHeld()) {
mDockWakeLock.release();
}
}
void updateRotation(int animFlags) {
mPowerManager.setKeyboardVisibility(mLidOpen);
int rotation = Surface.ROTATION_0;
if (mLidOpen) {
rotation = mLidOpenRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
rotation = mCarDockRotation;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
rotation = mDeskDockRotation;
}
//if lid is closed orientation will be portrait
try {
//set orientation on WindowManager
mWindowManager.setRotation(rotation, true,
mFancyRotationAnimation | animFlags);
} catch (RemoteException e) {
// Ignore
}
}
/**
* Return an Intent to launch the currently active dock as home. Returns
* null if the standard home should be launched.
* @return
*/
Intent createHomeDockIntent() {
if (mDockState == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
return null;
}
Intent intent;
if (mDockState == Intent.EXTRA_DOCK_STATE_CAR) {
intent = mCarDockIntent;
} else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
intent = mDeskDockIntent;
} else {
Log.w(TAG, "Unknown dock state: " + mDockState);
return null;
}
ActivityInfo ai = intent.resolveActivityInfo(
mContext.getPackageManager(), PackageManager.GET_META_DATA);
if (ai == null) {
return null;
}
if (ai.metaData != null && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
intent = new Intent(intent);
intent.setClassName(ai.packageName, ai.name);
return intent;
}
return null;
}
void startDockOrHome() {
Intent dock = createHomeDockIntent();
if (dock != null) {
try {
mContext.startActivity(dock);
return;
} catch (ActivityNotFoundException e) {
}
}
mContext.startActivity(mHomeIntent);
}
/**
* goes to the home screen
* @return whether it did anything
*/
boolean goHome() {
if (false) {
// This code always brings home to the front.
try {
ActivityManagerNative.getDefault().stopAppSwitches();
} catch (RemoteException e) {
}
sendCloseSystemWindows();
startDockOrHome();
} else {
// This code brings home to the front or, if it is already
// at the front, puts the device to sleep.
try {
ActivityManagerNative.getDefault().stopAppSwitches();
sendCloseSystemWindows();
Intent dock = createHomeDockIntent();
if (dock != null) {
int result = ActivityManagerNative.getDefault()
.startActivity(null, dock,
dock.resolveTypeIfNeeded(mContext.getContentResolver()),
null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
return false;
}
}
int result = ActivityManagerNative.getDefault()
.startActivity(null, mHomeIntent,
mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
return false;
}
} catch (RemoteException ex) {
// bummer, the activity manager, which is in this process, is dead
}
}
return true;
}
public void setCurrentOrientationLw(int newOrientation) {
synchronized (mLock) {
if (newOrientation != mCurrentAppOrientation) {
mCurrentAppOrientation = newOrientation;
updateOrientationListenerLp();
}
}
}
public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
final boolean hapticsDisabled = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 0;
if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
return false;
}
switch (effectId) {
case HapticFeedbackConstants.LONG_PRESS:
mVibrator.vibrate(mLongPressVibePattern, -1);
return true;
case HapticFeedbackConstants.VIRTUAL_KEY:
mVibrator.vibrate(mVirtualKeyVibePattern, -1);
return true;
case HapticFeedbackConstants.SAFE_MODE_DISABLED:
mVibrator.vibrate(mSafeModeDisabledVibePattern, -1);
return true;
case HapticFeedbackConstants.SAFE_MODE_ENABLED:
mVibrator.vibrate(mSafeModeEnabledVibePattern, -1);
return true;
}
return false;
}
public void keyFeedbackFromInput(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& (event.getFlags()&KeyEvent.FLAG_VIRTUAL_HARD_KEY) != 0) {
performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
}
}
public void screenOnStoppedLw() {
if (!mKeyguardMediator.isShowingAndNotHidden() && mPowerManager.isScreenOn()) {
long curTime = SystemClock.uptimeMillis();
mPowerManager.userActivity(curTime, false, LocalPowerManager.OTHER_EVENT);
}
}
public boolean allowKeyRepeat() {
// disable key repeat when screen is off
return mScreenOn;
}
}
| false | true | public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
final boolean keyguardShowing = keyguardIsShowingTq();
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
+ " screenIsOn=" + screenIsOn + " keyguardShowing=" + keyguardShowing);
}
if (keyguardShowing) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
if (isInCall()) {
// if the keyguard didn't wake the device, we are in call, and
// it is a volume key, turn on the screen so that the user
// can more easily adjust the in call volume.
mKeyguardMediator.pokeWakelock();
} else if (isMusicActive()) {
// when keyguard is showing and screen off, we need
// to handle the volume key for music here
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
if (keyguardShowing
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
| public int interceptKeyTq(RawInputEvent event, boolean screenIsOn) {
int result = ACTION_PASS_TO_USER;
final boolean isWakeKey = isWakeKeyTq(event);
// If screen is off then we treat the case where the keyguard is open but hidden
// the same as if it were open and in front.
// This will prevent any keys other than the power button from waking the screen
// when the keyguard is hidden by another activity.
final boolean keyguardActive = (screenIsOn ?
mKeyguardMediator.isShowingAndNotHidden() :
mKeyguardMediator.isShowing());
if (false) {
Log.d(TAG, "interceptKeyTq event=" + event + " keycode=" + event.keycode
+ " screenIsOn=" + screenIsOn + " keyguardActive=" + keyguardActive);
}
if (keyguardActive) {
if (screenIsOn) {
// when the screen is on, always give the event to the keyguard
result |= ACTION_PASS_TO_USER;
} else {
// otherwise, don't pass it to the user
result &= ~ACTION_PASS_TO_USER;
final boolean isKeyDown =
(event.type == RawInputEvent.EV_KEY) && (event.value != 0);
if (isWakeKey && isKeyDown) {
// tell the mediator about a wake key, it may decide to
// turn on the screen depending on whether the key is
// appropriate.
if (!mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(event.keycode)
&& (event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
if (isInCall()) {
// if the keyguard didn't wake the device, we are in call, and
// it is a volume key, turn on the screen so that the user
// can more easily adjust the in call volume.
mKeyguardMediator.pokeWakelock();
} else if (isMusicActive()) {
// when keyguard is showing and screen off, we need
// to handle the volume key for music here
handleVolumeKey(AudioManager.STREAM_MUSIC, event.keycode);
}
}
}
}
} else if (!screenIsOn) {
// If we are in-call with screen off and keyguard is not showing,
// then handle the volume key ourselves.
// This is necessary because the phone app will disable the keyguard
// when the proximity sensor is in use.
if (isInCall() && event.type == RawInputEvent.EV_KEY &&
(event.keycode == KeyEvent.KEYCODE_VOLUME_DOWN
|| event.keycode == KeyEvent.KEYCODE_VOLUME_UP)) {
result &= ~ACTION_PASS_TO_USER;
handleVolumeKey(AudioManager.STREAM_VOICE_CALL, event.keycode);
}
if (isWakeKey) {
// a wake key has a sole purpose of waking the device; don't pass
// it to the user
result |= ACTION_POKE_USER_ACTIVITY;
result &= ~ACTION_PASS_TO_USER;
}
}
int type = event.type;
int code = event.keycode;
boolean down = event.value != 0;
if (type == RawInputEvent.EV_KEY) {
if (code == KeyEvent.KEYCODE_ENDCALL
|| code == KeyEvent.KEYCODE_POWER) {
if (down) {
boolean handled = false;
// key repeats are generated by the window manager, and we don't see them
// here, so unless the driver is doing something it shouldn't be, we know
// this is the real press event.
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
try {
if (code == KeyEvent.KEYCODE_ENDCALL) {
handled = phoneServ.endCall();
} else if (code == KeyEvent.KEYCODE_POWER && phoneServ.isRinging()) {
// Pressing power during incoming call should silence the ringer
phoneServ.silenceRinger();
handled = true;
}
} catch (RemoteException ex) {
Log.w(TAG, "ITelephony threw RemoteException" + ex);
}
} else {
Log.w(TAG, "!!! Unable to find ITelephony interface !!!");
}
// power button should turn off screen in addition to hanging up the phone
if ((handled && code != KeyEvent.KEYCODE_POWER) || !screenIsOn) {
mShouldTurnOffOnKeyUp = false;
} else {
// only try to turn off the screen if we didn't already hang up
mShouldTurnOffOnKeyUp = true;
mHandler.postDelayed(mPowerLongPress,
ViewConfiguration.getGlobalActionKeyTimeout());
result &= ~ACTION_PASS_TO_USER;
}
} else {
mHandler.removeCallbacks(mPowerLongPress);
if (mShouldTurnOffOnKeyUp) {
mShouldTurnOffOnKeyUp = false;
boolean gohome = (mEndcallBehavior & ENDCALL_HOME) != 0;
boolean sleeps = (mEndcallBehavior & ENDCALL_SLEEPS) != 0;
if (keyguardActive
|| (sleeps && !gohome)
|| (gohome && !goHome() && sleeps)) {
// they must already be on the keyguad or home screen,
// go to sleep instead
Log.d(TAG, "I'm tired mEndcallBehavior=0x"
+ Integer.toHexString(mEndcallBehavior));
result &= ~ACTION_POKE_USER_ACTIVITY;
result |= ACTION_GO_TO_SLEEP;
}
result &= ~ACTION_PASS_TO_USER;
}
}
} else if (isMediaKey(code)) {
// This key needs to be handled even if the screen is off.
// If others need to be handled while it's off, this is a reasonable
// pattern to follow.
if ((result & ACTION_PASS_TO_USER) == 0) {
// Only do this if we would otherwise not pass it to the user. In that
// case, the PhoneWindow class will do the same thing, except it will
// only do it if the showing app doesn't process the key on its own.
KeyEvent keyEvent = new KeyEvent(event.when, event.when,
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code, 0);
mBroadcastWakeLock.acquire();
mHandler.post(new PassHeadsetKey(keyEvent));
}
} else if (code == KeyEvent.KEYCODE_CALL) {
// If an incoming call is ringing, answer it!
// (We handle this key here, rather than in the InCallScreen, to make
// sure we'll respond to the key even if the InCallScreen hasn't come to
// the foreground yet.)
// We answer the call on the DOWN event, to agree with
// the "fallback" behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " CALL key-down while ringing: Answer the call!");
phoneServ.answerRingingCall();
// And *don't* pass this key thru to the current activity
// (which is presumably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "CALL button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "CALL button: RemoteException from getPhoneInterface()", ex);
}
}
} else if ((code == KeyEvent.KEYCODE_VOLUME_UP)
|| (code == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// If an incoming call is ringing, either VOLUME key means
// "silence ringer". We handle these keys here, rather than
// in the InCallScreen, to make sure we'll respond to them
// even if the InCallScreen hasn't come to the foreground yet.
// Look for the DOWN event here, to agree with the "fallback"
// behavior in the InCallScreen.
if (down) {
try {
ITelephony phoneServ = getPhoneInterface();
if (phoneServ != null) {
if (phoneServ.isRinging()) {
Log.i(TAG, "interceptKeyTq:"
+ " VOLUME key-down while ringing: Silence ringer!");
// Silence the ringer. (It's safe to call this
// even if the ringer has already been silenced.)
phoneServ.silenceRinger();
// And *don't* pass this key thru to the current activity
// (which is probably the InCallScreen.)
result &= ~ACTION_PASS_TO_USER;
}
} else {
Log.w(TAG, "VOLUME button: Unable to find ITelephony interface");
}
} catch (RemoteException ex) {
Log.w(TAG, "VOLUME button: RemoteException from getPhoneInterface()", ex);
}
}
}
}
return result;
}
|
diff --git a/src/uk/me/parabola/imgfmt/sys/ImgFS.java b/src/uk/me/parabola/imgfmt/sys/ImgFS.java
index 5539f024..7dbb43b7 100644
--- a/src/uk/me/parabola/imgfmt/sys/ImgFS.java
+++ b/src/uk/me/parabola/imgfmt/sys/ImgFS.java
@@ -1,199 +1,207 @@
/*
* Copyright (C) 2006 Steve Ratcliffe
*
* 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.
*
*
* Author: Steve Ratcliffe
* Create date: 26-Nov-2006
*/
package uk.me.parabola.imgfmt.sys;
import uk.me.parabola.log.Logger;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.nio.channels.FileChannel;
import uk.me.parabola.imgfmt.fs.FileSystem;
import uk.me.parabola.imgfmt.fs.DirectoryEntry;
import uk.me.parabola.imgfmt.fs.ImgChannel;
import uk.me.parabola.imgfmt.FileSystemParam;
import uk.me.parabola.imgfmt.FileExistsException;
/**
* The img file is really a filesystem containing several files.
* It is made up of a header, a directory area and a data area which
* occur in the filesystem in that order.
*
* @author steve
*/
public class ImgFS implements FileSystem {
private static final Logger log = Logger.getLogger(ImgFS.class);
private int blockSize = 512;
private FileChannel file;
// A file system consists of a header, a directory and a data area.
private ImgHeader header;
// There is only one directory that holds all filename and block allocation
// information.
private Directory directory;
// The filesystem is responsible for allocating blocks
private BlockManager blockManager;
/**
* Create an IMG file from its external filesystem name and optionally some
* parameters.
*
* @param filename The filename eg 'gmapsupp.img'
* @param params File system parameters. Can be null.
* @throws FileNotFoundException If the file cannot be created.
*/
public ImgFS(String filename, FileSystemParam params)
throws FileNotFoundException
{
log.info("Creating file system");
RandomAccessFile rafile = new RandomAccessFile(filename, "rw");
+ try {
+ // Set length to zero because if you don't you can get a
+ // map that doesn't work. Not clear why.
+ rafile.setLength(0);
+ } catch (IOException e) {
+ // It doesn't matter that much.
+ log.warn("Could not set file length to zero");
+ }
file = rafile.getChannel();
header = new ImgHeader(file);
header.setDirectoryStartBlock(2); // could be from params
// Set the times.
Date date = new Date();
header.setCreationTime(date);
header.setUpdateTime(date);
// The block manager allocates blocks for files.
blockManager = new BlockManager(blockSize,
header.getDirectoryStartBlock());
directory = new Directory(file, blockManager);
if (params != null)
setParams(params);
// Initialise the directory.
directory.init();
}
/**
* Set various parameters of the file system. Anything that
* has not been set in <tt>params</tt> (ie is zero or null)
* will not have any effect.
*
* @param params A set of parameters.
*/
private void setParams(FileSystemParam params) {
int bs = params.getBlockSize();
if (bs > 0) {
blockSize = bs;
header.setBlockSize(bs);
directory.setBlockSize(bs);
}
String mapdesc = params.getMapDescription();
if (mapdesc != null)
header.setDescription(mapdesc);
}
/**
* Create a new file it must not allready exist.
*
* @param name The file name.
* @return A directory entry for the new file.
*/
public ImgChannel create(String name) throws FileExistsException {
Dirent dir = directory.create(name);
FileNode f = new FileNode(file, blockManager, dir, "w");
return f;
}
/**
* Open a file. The returned file object can be used to read and write the
* underlying file.
*
* @param name The file name to open.
* @param mode Either "r" for read access, "w" for write access or "rw"
* for both read and write.
* @return A file descriptor.
* @throws FileNotFoundException When the file does not exist.
*/
public ImgChannel open(String name, String mode) throws FileNotFoundException {
if (name == null || mode == null)
throw new IllegalArgumentException("null argument");
// Its wrong to do this as this routine should not throw an exception
// when the file exists. Needs lookup().
// if (mode.indexOf('w') >= 0)
// return create(name);
throw new FileNotFoundException("File not found because it isn't implemented yet");
}
/**
* Lookup the file and return a directory entry for it.
*
* @param name The filename to look up.
* @return A directory entry.
* @throws IOException If an error occurs reading the directory.
*/
public DirectoryEntry lookup(String name) throws IOException {
if (name == null)
throw new IllegalArgumentException("null name argument");
throw new IOException("not implemented");
}
/**
* List all the files in the directory.
*
* @return A List of directory entries.
* @throws IOException If an error occurs reading the directory.
*/
public List<DirectoryEntry> list() throws IOException {
throw new IOException("not implemented yet");
}
/**
* Sync with the underlying file. All unwritten data is written out to
* the underlying file.
*
* @throws IOException If an error occurs during the write.
*/
public void sync() throws IOException {
header.sync();
file.position((long) header.getDirectoryStartBlock() * header.getBlockSize());
directory.sync();
}
/**
* Close the filesystem. Any saved data is flushed out. It is better
* to explicitly sync the data out first, to be sure that it has worked.
*/
public void close() {
try {
sync();
} catch (IOException e) {
log.debug("could not sync filesystem");
}
}
}
| true | true | public ImgFS(String filename, FileSystemParam params)
throws FileNotFoundException
{
log.info("Creating file system");
RandomAccessFile rafile = new RandomAccessFile(filename, "rw");
file = rafile.getChannel();
header = new ImgHeader(file);
header.setDirectoryStartBlock(2); // could be from params
// Set the times.
Date date = new Date();
header.setCreationTime(date);
header.setUpdateTime(date);
// The block manager allocates blocks for files.
blockManager = new BlockManager(blockSize,
header.getDirectoryStartBlock());
directory = new Directory(file, blockManager);
if (params != null)
setParams(params);
// Initialise the directory.
directory.init();
}
| public ImgFS(String filename, FileSystemParam params)
throws FileNotFoundException
{
log.info("Creating file system");
RandomAccessFile rafile = new RandomAccessFile(filename, "rw");
try {
// Set length to zero because if you don't you can get a
// map that doesn't work. Not clear why.
rafile.setLength(0);
} catch (IOException e) {
// It doesn't matter that much.
log.warn("Could not set file length to zero");
}
file = rafile.getChannel();
header = new ImgHeader(file);
header.setDirectoryStartBlock(2); // could be from params
// Set the times.
Date date = new Date();
header.setCreationTime(date);
header.setUpdateTime(date);
// The block manager allocates blocks for files.
blockManager = new BlockManager(blockSize,
header.getDirectoryStartBlock());
directory = new Directory(file, blockManager);
if (params != null)
setParams(params);
// Initialise the directory.
directory.init();
}
|
diff --git a/libraries/javalib/java/text/SimpleDateFormat.java b/libraries/javalib/java/text/SimpleDateFormat.java
index 5945f2df1..20e36d22b 100644
--- a/libraries/javalib/java/text/SimpleDateFormat.java
+++ b/libraries/javalib/java/text/SimpleDateFormat.java
@@ -1,390 +1,390 @@
package java.text;
import java.lang.String;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import kaffe.util.DateParser;
import kaffe.util.NotImplemented;
/*
* Java core library component.
*
* Copyright (c) 1997, 1998
* Transvirtual Technologies, Inc. All rights reserved.
*
* See the file "license.terms" for information on usage and redistribution
* of this file.
*/
public class SimpleDateFormat
extends DateFormat
{
private static final long serialVersionUID = 4774881970558875024L;
final private static String DEFAULTPATTERNCHARS = "GyMdkHmsSEDFwWahKz";
private DateFormatSymbols syms;
private String pattern;
public SimpleDateFormat() {
this("", Locale.getDefault());
}
public SimpleDateFormat(String pattern) {
this(pattern, Locale.getDefault());
}
public SimpleDateFormat(String pattern, DateFormatSymbols syms) {
this.syms = syms;
this.pattern = pattern;
this.calendar = new GregorianCalendar();
this.format = new DecimalFormat("0");
}
public SimpleDateFormat(String pattern, java.util.Locale loc) {
this.syms = new DateFormatSymbols(loc);
this.pattern = pattern;
this.calendar = new GregorianCalendar(loc);
this.format = new DecimalFormat("0", loc);
}
public void applyLocalizedPattern(String pattern) {
StringBuffer buf = new StringBuffer();
String locals = syms.getLocalPatternChars();
for (int i = 0; i < pattern.length(); i++) {
char letter = pattern.charAt(i);
int idx = locals.indexOf(letter);
if (idx >= 0) {
buf.append(DEFAULTPATTERNCHARS.charAt(idx));
}
else {
buf.append(letter);
if (letter == '\'') {
do {
i++;
letter = pattern.charAt(i);
buf.append(letter);
} while (letter != '\'');
}
}
}
this.pattern = buf.toString();
}
public void applyPattern(String pattern) {
this.pattern = pattern;
}
public Object clone() {
return (super.clone());
}
public boolean equals(Object obj) {
return (super.equals(obj));
}
public StringBuffer format(Date date, StringBuffer buf, FieldPosition pos) {
calendar.setTime(date);
char[] patt = pattern.toCharArray();
for (int i = 0; i < patt.length; ) {
int plen = 0;
char letter = patt[i];
i++;
if (letter != '\'') {
for (plen++; i < patt.length && patt[i] == letter; plen++, i++);
}
int cpos = buf.length();
int val;
switch (letter) {
case 'G':
val = calendar.get(Calendar.ERA);
buf.append(syms.eras[val]);
if (pos.field == ERA_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'y':
val = calendar.get(Calendar.YEAR);
if (plen < 4) {
val = val % 100;
if (val < 10) {
buf.append('0');
}
}
buf.append(val);
if (pos.field == YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'M':
- val = calendar.get(Calendar.MONTH);
+ val = calendar.get(Calendar.MONTH) + 1;
if (plen < 3) {
if (val < 10 && plen == 2) {
buf.append('0');
}
buf.append(val);
}
else if (plen == 3) {
buf.append(syms.shortMonths[val]);
}
else {
buf.append(syms.months[val]);
}
if (pos.field == MONTH_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'd':
val = calendar.get(Calendar.DAY_OF_MONTH);
if (plen > 1 && val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == DATE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'k':
val = calendar.get(Calendar.HOUR_OF_DAY);
if (val == 0) {
val = 24;
}
buf.append(val);
if (pos.field == HOUR_OF_DAY1_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'H':
val = calendar.get(Calendar.HOUR_OF_DAY);
buf.append(val);
if (pos.field == HOUR_OF_DAY0_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'm':
val = calendar.get(Calendar.MINUTE);
if (val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == MINUTE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 's':
val = calendar.get(Calendar.SECOND);
if (val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == SECOND_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'S':
val = calendar.get(Calendar.MILLISECOND);
buf.append(val);
if (pos.field == MILLISECOND_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'E':
val = calendar.get(Calendar.DAY_OF_WEEK);
if (plen < 4) {
buf.append(syms.shortWeekdays[val]);
}
else {
buf.append(syms.weekdays[val]);
}
if (pos.field == DAY_OF_WEEK_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'D':
val = calendar.get(Calendar.DAY_OF_YEAR);
buf.append(val);
if (pos.field == DAY_OF_YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'F':
val = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
buf.append(val);
break;
case 'w':
val = calendar.get(Calendar.WEEK_OF_YEAR);
buf.append(val);
if (pos.field == WEEK_OF_YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'W':
val = calendar.get(Calendar.WEEK_OF_MONTH);
buf.append(val);
if (pos.field == WEEK_OF_MONTH_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'a':
val = calendar.get(Calendar.AM_PM);
buf.append(syms.amPmStrings[val]);
if (pos.field == AM_PM_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'h':
val = calendar.get(Calendar.HOUR);
if (val == 0) {
val = 12;
}
if ( (plen > 1) && (val < 10) )
buf.append('0');
buf.append(val);
if (pos.field == HOUR1_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'K':
val = calendar.get(Calendar.HOUR);
buf.append(val);
if (pos.field == HOUR0_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'z':
TimeZone zone = calendar.getTimeZone();
String szone = zone.getID();
boolean daylight = zone.inDaylightTime(date);
int j;
for (j = 0; j < syms.zoneStrings.length; j++) {
String[] sel = syms.zoneStrings[j];
if (!szone.equals(sel[0])) {
continue;
}
if (plen < 4) {
if (daylight) {
buf.append(sel[4]);
}
else {
buf.append(sel[2]);
}
}
else {
if (daylight) {
buf.append(sel[3]);
}
else {
buf.append(sel[1]);
}
}
break;
}
// If no matching timezone, put in GMT info.
if (j == syms.zoneStrings.length) {
buf.append("GMT");
int ro = zone.getRawOffset() / 60000;
if (ro < 0) {
ro = Math.abs(ro);
buf.append("-");
}
else {
buf.append("+");
}
buf.append(ro / 60);
buf.append(":");
if (ro % 60 < 10) {
buf.append("0");
}
buf.append(ro % 60);
}
if (pos.field == TIMEZONE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case '\'':
if (patt[i] == '\'') {
buf.append('\'');
i++;
}
else {
while (patt[i] != '\'') {
buf.append(patt[i]);
i++;
}
i++;
}
break;
default:
for (j = 0; j < plen; j++) {
buf.append(letter);
}
break;
}
}
return (buf);
}
public DateFormatSymbols getDateFormatSymbols() {
return (syms);
}
public int hashCode() {
return (super.hashCode());
}
public Date parse(String source, ParsePosition pos) {
try {
return DateParser.parse( source, syms);
}
catch ( ParseException _x) {
return null;
}
}
public void setDateFormatSymbols(DateFormatSymbols syms) {
this.syms = syms;
}
public String toLocalizedPattern() {
StringBuffer buf = new StringBuffer();
String locals = syms.getLocalPatternChars();
for (int i = 0; i < pattern.length(); i++) {
int idx = DEFAULTPATTERNCHARS.indexOf(pattern.charAt(i));
if (idx >= 0) {
buf.append(locals.charAt(idx));
}
else {
buf.append(pattern.charAt(i));
}
}
return (buf.toString());
}
public String toPattern() {
return (pattern);
}
}
| true | true | public StringBuffer format(Date date, StringBuffer buf, FieldPosition pos) {
calendar.setTime(date);
char[] patt = pattern.toCharArray();
for (int i = 0; i < patt.length; ) {
int plen = 0;
char letter = patt[i];
i++;
if (letter != '\'') {
for (plen++; i < patt.length && patt[i] == letter; plen++, i++);
}
int cpos = buf.length();
int val;
switch (letter) {
case 'G':
val = calendar.get(Calendar.ERA);
buf.append(syms.eras[val]);
if (pos.field == ERA_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'y':
val = calendar.get(Calendar.YEAR);
if (plen < 4) {
val = val % 100;
if (val < 10) {
buf.append('0');
}
}
buf.append(val);
if (pos.field == YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'M':
val = calendar.get(Calendar.MONTH);
if (plen < 3) {
if (val < 10 && plen == 2) {
buf.append('0');
}
buf.append(val);
}
else if (plen == 3) {
buf.append(syms.shortMonths[val]);
}
else {
buf.append(syms.months[val]);
}
if (pos.field == MONTH_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'd':
val = calendar.get(Calendar.DAY_OF_MONTH);
if (plen > 1 && val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == DATE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'k':
val = calendar.get(Calendar.HOUR_OF_DAY);
if (val == 0) {
val = 24;
}
buf.append(val);
if (pos.field == HOUR_OF_DAY1_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'H':
val = calendar.get(Calendar.HOUR_OF_DAY);
buf.append(val);
if (pos.field == HOUR_OF_DAY0_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'm':
val = calendar.get(Calendar.MINUTE);
if (val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == MINUTE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 's':
val = calendar.get(Calendar.SECOND);
if (val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == SECOND_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'S':
val = calendar.get(Calendar.MILLISECOND);
buf.append(val);
if (pos.field == MILLISECOND_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'E':
val = calendar.get(Calendar.DAY_OF_WEEK);
if (plen < 4) {
buf.append(syms.shortWeekdays[val]);
}
else {
buf.append(syms.weekdays[val]);
}
if (pos.field == DAY_OF_WEEK_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'D':
val = calendar.get(Calendar.DAY_OF_YEAR);
buf.append(val);
if (pos.field == DAY_OF_YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'F':
val = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
buf.append(val);
break;
case 'w':
val = calendar.get(Calendar.WEEK_OF_YEAR);
buf.append(val);
if (pos.field == WEEK_OF_YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'W':
val = calendar.get(Calendar.WEEK_OF_MONTH);
buf.append(val);
if (pos.field == WEEK_OF_MONTH_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'a':
val = calendar.get(Calendar.AM_PM);
buf.append(syms.amPmStrings[val]);
if (pos.field == AM_PM_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'h':
val = calendar.get(Calendar.HOUR);
if (val == 0) {
val = 12;
}
if ( (plen > 1) && (val < 10) )
buf.append('0');
buf.append(val);
if (pos.field == HOUR1_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'K':
val = calendar.get(Calendar.HOUR);
buf.append(val);
if (pos.field == HOUR0_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'z':
TimeZone zone = calendar.getTimeZone();
String szone = zone.getID();
boolean daylight = zone.inDaylightTime(date);
int j;
for (j = 0; j < syms.zoneStrings.length; j++) {
String[] sel = syms.zoneStrings[j];
if (!szone.equals(sel[0])) {
continue;
}
if (plen < 4) {
if (daylight) {
buf.append(sel[4]);
}
else {
buf.append(sel[2]);
}
}
else {
if (daylight) {
buf.append(sel[3]);
}
else {
buf.append(sel[1]);
}
}
break;
}
// If no matching timezone, put in GMT info.
if (j == syms.zoneStrings.length) {
buf.append("GMT");
int ro = zone.getRawOffset() / 60000;
if (ro < 0) {
ro = Math.abs(ro);
buf.append("-");
}
else {
buf.append("+");
}
buf.append(ro / 60);
buf.append(":");
if (ro % 60 < 10) {
buf.append("0");
}
buf.append(ro % 60);
}
if (pos.field == TIMEZONE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case '\'':
if (patt[i] == '\'') {
buf.append('\'');
i++;
}
else {
while (patt[i] != '\'') {
buf.append(patt[i]);
i++;
}
i++;
}
break;
default:
for (j = 0; j < plen; j++) {
buf.append(letter);
}
break;
}
}
return (buf);
}
| public StringBuffer format(Date date, StringBuffer buf, FieldPosition pos) {
calendar.setTime(date);
char[] patt = pattern.toCharArray();
for (int i = 0; i < patt.length; ) {
int plen = 0;
char letter = patt[i];
i++;
if (letter != '\'') {
for (plen++; i < patt.length && patt[i] == letter; plen++, i++);
}
int cpos = buf.length();
int val;
switch (letter) {
case 'G':
val = calendar.get(Calendar.ERA);
buf.append(syms.eras[val]);
if (pos.field == ERA_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'y':
val = calendar.get(Calendar.YEAR);
if (plen < 4) {
val = val % 100;
if (val < 10) {
buf.append('0');
}
}
buf.append(val);
if (pos.field == YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'M':
val = calendar.get(Calendar.MONTH) + 1;
if (plen < 3) {
if (val < 10 && plen == 2) {
buf.append('0');
}
buf.append(val);
}
else if (plen == 3) {
buf.append(syms.shortMonths[val]);
}
else {
buf.append(syms.months[val]);
}
if (pos.field == MONTH_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'd':
val = calendar.get(Calendar.DAY_OF_MONTH);
if (plen > 1 && val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == DATE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'k':
val = calendar.get(Calendar.HOUR_OF_DAY);
if (val == 0) {
val = 24;
}
buf.append(val);
if (pos.field == HOUR_OF_DAY1_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'H':
val = calendar.get(Calendar.HOUR_OF_DAY);
buf.append(val);
if (pos.field == HOUR_OF_DAY0_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'm':
val = calendar.get(Calendar.MINUTE);
if (val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == MINUTE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 's':
val = calendar.get(Calendar.SECOND);
if (val < 10) {
buf.append('0');
}
buf.append(val);
if (pos.field == SECOND_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'S':
val = calendar.get(Calendar.MILLISECOND);
buf.append(val);
if (pos.field == MILLISECOND_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'E':
val = calendar.get(Calendar.DAY_OF_WEEK);
if (plen < 4) {
buf.append(syms.shortWeekdays[val]);
}
else {
buf.append(syms.weekdays[val]);
}
if (pos.field == DAY_OF_WEEK_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'D':
val = calendar.get(Calendar.DAY_OF_YEAR);
buf.append(val);
if (pos.field == DAY_OF_YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'F':
val = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
buf.append(val);
break;
case 'w':
val = calendar.get(Calendar.WEEK_OF_YEAR);
buf.append(val);
if (pos.field == WEEK_OF_YEAR_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'W':
val = calendar.get(Calendar.WEEK_OF_MONTH);
buf.append(val);
if (pos.field == WEEK_OF_MONTH_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'a':
val = calendar.get(Calendar.AM_PM);
buf.append(syms.amPmStrings[val]);
if (pos.field == AM_PM_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'h':
val = calendar.get(Calendar.HOUR);
if (val == 0) {
val = 12;
}
if ( (plen > 1) && (val < 10) )
buf.append('0');
buf.append(val);
if (pos.field == HOUR1_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'K':
val = calendar.get(Calendar.HOUR);
buf.append(val);
if (pos.field == HOUR0_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case 'z':
TimeZone zone = calendar.getTimeZone();
String szone = zone.getID();
boolean daylight = zone.inDaylightTime(date);
int j;
for (j = 0; j < syms.zoneStrings.length; j++) {
String[] sel = syms.zoneStrings[j];
if (!szone.equals(sel[0])) {
continue;
}
if (plen < 4) {
if (daylight) {
buf.append(sel[4]);
}
else {
buf.append(sel[2]);
}
}
else {
if (daylight) {
buf.append(sel[3]);
}
else {
buf.append(sel[1]);
}
}
break;
}
// If no matching timezone, put in GMT info.
if (j == syms.zoneStrings.length) {
buf.append("GMT");
int ro = zone.getRawOffset() / 60000;
if (ro < 0) {
ro = Math.abs(ro);
buf.append("-");
}
else {
buf.append("+");
}
buf.append(ro / 60);
buf.append(":");
if (ro % 60 < 10) {
buf.append("0");
}
buf.append(ro % 60);
}
if (pos.field == TIMEZONE_FIELD) {
pos.begin = cpos;
pos.end = buf.length();
}
break;
case '\'':
if (patt[i] == '\'') {
buf.append('\'');
i++;
}
else {
while (patt[i] != '\'') {
buf.append(patt[i]);
i++;
}
i++;
}
break;
default:
for (j = 0; j < plen; j++) {
buf.append(letter);
}
break;
}
}
return (buf);
}
|
diff --git a/odata4j-core/src/main/java/org/odata4j/producer/exceptions/ODataException.java b/odata4j-core/src/main/java/org/odata4j/producer/exceptions/ODataException.java
index 224c89f7..1176564e 100644
--- a/odata4j-core/src/main/java/org/odata4j/producer/exceptions/ODataException.java
+++ b/odata4j-core/src/main/java/org/odata4j/producer/exceptions/ODataException.java
@@ -1,86 +1,86 @@
package org.odata4j.producer.exceptions;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.StatusType;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.odata4j.core.ODataConstants;
import org.odata4j.core.OError;
import org.odata4j.format.FormatWriter;
import org.odata4j.format.FormatWriterFactory;
import org.odata4j.producer.ErrorResponse;
@Provider
public class ODataException extends RuntimeException implements ErrorResponse, ExceptionMapper<ODataException> {
private static final long serialVersionUID = 1L;
private StatusType status = Status.INTERNAL_SERVER_ERROR;
@Context
protected UriInfo uriInfo;
@Context
protected HttpHeaders httpHeaders;
public ODataException() {
}
public ODataException(StatusType status) {
this.status = status;
}
public ODataException(StatusType status, String message) {
super(message);
this.status = status;
}
public ODataException(StatusType status, Throwable cause) {
super(cause);
this.status = status;
}
public ODataException(StatusType status, String message, Throwable cause) {
super(message, cause);
this.status = status;
}
public Response toResponse(ODataException exception) {
String format = uriInfo.getQueryParameters().getFirst("$format");
String callback = uriInfo.getQueryParameters().getFirst("$callback");
FormatWriter<ErrorResponse> fw = FormatWriterFactory.getFormatWriter(ErrorResponse.class, httpHeaders.getAcceptableMediaTypes(), format, callback);
StringWriter sw = new StringWriter();
fw.write(uriInfo, sw, exception);
return Response.status(exception.status)
.type(fw.getContentType())
.header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER)
.entity(sw.toString())
.build();
}
public OError getError() {
return new OError() {
public String getMessage() {
return ODataException.this.getMessage() != null ? ODataException.this.getMessage() : status.getReasonPhrase();
}
public String getCode() {
return ODataException.this.getClass().getSimpleName();
}
public String getInnerError() {
StringWriter sw = new StringWriter();
- ODataException.this.getCause().printStackTrace(new PrintWriter(sw));
+ ODataException.this.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
};
}
}
| true | true | public OError getError() {
return new OError() {
public String getMessage() {
return ODataException.this.getMessage() != null ? ODataException.this.getMessage() : status.getReasonPhrase();
}
public String getCode() {
return ODataException.this.getClass().getSimpleName();
}
public String getInnerError() {
StringWriter sw = new StringWriter();
ODataException.this.getCause().printStackTrace(new PrintWriter(sw));
return sw.toString();
}
};
}
| public OError getError() {
return new OError() {
public String getMessage() {
return ODataException.this.getMessage() != null ? ODataException.this.getMessage() : status.getReasonPhrase();
}
public String getCode() {
return ODataException.this.getClass().getSimpleName();
}
public String getInnerError() {
StringWriter sw = new StringWriter();
ODataException.this.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
};
}
|
diff --git a/src/main/java/org/spout/engine/filesystem/WorldFiles.java b/src/main/java/org/spout/engine/filesystem/WorldFiles.java
index d3cc458de..a85f2f1df 100644
--- a/src/main/java/org/spout/engine/filesystem/WorldFiles.java
+++ b/src/main/java/org/spout/engine/filesystem/WorldFiles.java
@@ -1,579 +1,579 @@
/*
* This file is part of Spout.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* Spout is licensed under the SpoutDev License Version 1.
*
* Spout 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Spout 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,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.engine.filesystem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import org.spout.api.Spout;
import org.spout.api.datatable.DataMap;
import org.spout.api.datatable.DatatableMap;
import org.spout.api.datatable.GenericDatatableMap;
import org.spout.api.entity.component.Controller;
import org.spout.api.entity.Entity;
import org.spout.api.entity.component.controller.type.ControllerRegistry;
import org.spout.api.entity.component.controller.type.ControllerType;
import org.spout.api.generator.WorldGenerator;
import org.spout.api.generator.biome.BiomeManager;
import org.spout.api.generator.biome.EmptyBiomeManager;
import org.spout.api.geo.discrete.Point;
import org.spout.api.geo.discrete.Transform;
import org.spout.api.io.store.simple.BinaryFileStore;
import org.spout.api.math.Quaternion;
import org.spout.api.math.Vector3;
import org.spout.api.util.NBTMapper;
import org.spout.api.util.StringMap;
import org.spout.api.util.sanitation.SafeCast;
import org.spout.api.util.sanitation.StringSanitizer;
import org.spout.api.util.typechecker.TypeChecker;
import org.spout.engine.SpoutEngine;
import org.spout.engine.entity.SpoutEntity;
import org.spout.engine.world.FilteredChunk;
import org.spout.engine.world.SpoutChunk;
import org.spout.engine.world.SpoutChunk.PopulationState;
import org.spout.engine.world.SpoutChunkSnapshot;
import org.spout.engine.world.SpoutRegion;
import org.spout.engine.world.SpoutWorld;
import org.spout.engine.world.dynamic.DynamicBlockUpdate;
import org.spout.nbt.ByteArrayTag;
import org.spout.nbt.ByteTag;
import org.spout.nbt.CompoundMap;
import org.spout.nbt.CompoundTag;
import org.spout.nbt.FloatTag;
import org.spout.nbt.IntTag;
import org.spout.nbt.ListTag;
import org.spout.nbt.LongTag;
import org.spout.nbt.ShortArrayTag;
import org.spout.nbt.StringTag;
import org.spout.nbt.Tag;
import org.spout.nbt.stream.NBTInputStream;
import org.spout.nbt.stream.NBTOutputStream;
public class WorldFiles {
private static final TypeChecker<List<? extends FloatTag>> checkerListFloatTag = TypeChecker.tList(FloatTag.class);
private static final TypeChecker<List<? extends CompoundTag>> checkerListCompoundTag = TypeChecker.tList(CompoundTag.class);
private static final byte WORLD_VERSION = 2;
private static final byte ENTITY_VERSION = 1;
private static final byte CHUNK_VERSION = 1;
public static void saveWorldData(SpoutWorld world) {
File worldData = new File(world.getDirectory(), "world.dat");
String generatorName = world.getGenerator().getName();
if (!StringSanitizer.isAlphaNumericUnderscore(generatorName)) {
generatorName = Long.toHexString(System.currentTimeMillis());
Spout.getEngine().getLogger().severe("Generator name " + generatorName + " is not valid, using " + generatorName + " instead");
}
//Save the world item map
world.getItemMap().save();
CompoundMap worldTags = new CompoundMap();
//World Version 1
worldTags.put(new ByteTag("version", WORLD_VERSION));
worldTags.put(new LongTag("seed", world.getSeed()));
worldTags.put(new StringTag("generator", generatorName));
worldTags.put(new LongTag("UUID_lsb", world.getUID().getLeastSignificantBits()));
worldTags.put(new LongTag("UUID_msb", world.getUID().getMostSignificantBits()));
worldTags.put(new ByteArrayTag("extra_data", ((DataMap) world.getDataMap()).getRawMap().compress()));
worldTags.put(new LongTag("age", world.getAge()));
//World version 2
worldTags.put(new ListTag<FloatTag>("spawn_position", FloatTag.class, NBTMapper.transformToNBT(world.getSpawnPoint())));
CompoundTag worldTag = new CompoundTag(world.getName(), worldTags);
NBTOutputStream os = null;
try {
os = new NBTOutputStream(new DataOutputStream(new FileOutputStream(worldData)), false);
os.writeTag(worldTag);
} catch (IOException e) {
Spout.getLogger().log(Level.SEVERE, "Error saving world data for " + world.toString(), e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ignore) {
}
}
}
}
public static SpoutWorld loadWorldFromData(String name, WorldGenerator generator, StringMap global) {
SpoutWorld world = null;
File worldData = new File(new File(SharedFileSystem.WORLDS_DIRECTORY, name), "world.dat");
if (worldData.exists()) {
NBTInputStream is = null;
try {
is = new NBTInputStream(new DataInputStream(new FileInputStream(worldData)), false);
CompoundTag dataTag = (CompoundTag) is.readTag();
CompoundMap map = dataTag.getValue();
byte version = SafeCast.toByte(NBTMapper.toTagValue(map.get("version")), WORLD_VERSION);
switch (version) {
case 1:
world = loadVersionOne(name, generator, global, map);
break;
case 2:
world = loadVersionTwo(name, generator, global, map);
break;
}
} catch (Exception e) {
Spout.getLogger().log(Level.SEVERE, "Error saving load data for " + name, e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
}
return world;
}
/**
* Loads version 2 of the world NBT
* @param name The name of the world
* @param generator The generator of the world
* @param global The global StringMap for the engine
* @param map The CompoundMap of tags from NBT
* @return The newly created SpoutWorld loaded from NBT
*/
private static SpoutWorld loadVersionTwo(String name, WorldGenerator generator, StringMap global, CompoundMap map) {
SpoutWorld world;
//Load the world specific item map
File itemMapFile = new File(new File(SharedFileSystem.WORLDS_DIRECTORY, name), "materials.dat");
BinaryFileStore itemStore = new BinaryFileStore(itemMapFile);
if (itemMapFile.exists()) {
itemStore.load();
}
StringMap itemMap = new StringMap(global, itemStore, 0, Short.MAX_VALUE, name + "ItemMap");
String generatorName = generator.getName();
GenericDatatableMap extraData = new GenericDatatableMap();
long seed = SafeCast.toLong(NBTMapper.toTagValue(map.get("seed")), new Random().nextLong());
String savedGeneratorName = SafeCast.toString(NBTMapper.toTagValue(map.get("generator")), "");
long lsb = SafeCast.toLong(NBTMapper.toTagValue(map.get("UUID_lsb")), new Random().nextLong());
long msb = SafeCast.toLong(NBTMapper.toTagValue(map.get("UUID_msb")), new Random().nextLong());
byte[] extraDataBytes = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("extra_data")), new byte[0]);
extraData.decompress(extraDataBytes);
if (!savedGeneratorName.equals(generatorName)) {
Spout.getLogger().severe("World was saved last with the generator: " + savedGeneratorName + " but is being loaded with: " + generatorName + " MAY CAUSE WORLD CORRUPTION!");
}
long age = SafeCast.toLong(NBTMapper.toTagValue(map.get("age")), 0L);
world = new SpoutWorld(name, Spout.getEngine(), seed, age, generator, new UUID(msb, lsb), itemMap, extraData);
List<? extends FloatTag> spawnPosition = checkerListFloatTag.checkTag(map.get("spawn_position"));
Transform spawn = NBTMapper.nbtToTransform(world, spawnPosition);
world.setSpawnPoint(spawn);
return world;
}
/**
* Loads version 1 of the world NBT
* @param name The name of the world
* @param generator The generator of the world
* @param global The global StringMap for the engine
* @param map The CompoundMap of tags from NBT
* @return The newly created SpoutWorld loaded from NBT
*/
private static SpoutWorld loadVersionOne(String name, WorldGenerator generator, StringMap global, CompoundMap map) {
SpoutWorld world;
//Load the world specific item map
File itemMapFile = new File(new File(SharedFileSystem.WORLDS_DIRECTORY, name), "materials.dat");
BinaryFileStore itemStore = new BinaryFileStore(itemMapFile);
if (itemMapFile.exists()) {
itemStore.load();
}
StringMap itemMap = new StringMap(global, itemStore, 0, Short.MAX_VALUE, name + "ItemMap");
String generatorName = generator.getName();
GenericDatatableMap extraData = new GenericDatatableMap();
long seed = SafeCast.toLong(NBTMapper.toTagValue(map.get("seed")), new Random().nextLong());
String savedGeneratorName = SafeCast.toString(NBTMapper.toTagValue(map.get("generator")), "");
long lsb = SafeCast.toLong(NBTMapper.toTagValue(map.get("UUID_lsb")), new Random().nextLong());
long msb = SafeCast.toLong(NBTMapper.toTagValue(map.get("UUID_msb")), new Random().nextLong());
byte[] extraDataBytes = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("extraData")), new byte[0]);
extraData.decompress(extraDataBytes);
if (!savedGeneratorName.equals(generatorName)) {
Spout.getEngine().getLogger().severe("World was saved last with the generator: " + savedGeneratorName + " but is being loaded with: " + generatorName + " MAY CAUSE WORLD CORRUPTION!");
}
long age = SafeCast.toLong(NBTMapper.toTagValue(map.get("age")), 0L);
world = new SpoutWorld(name, Spout.getEngine(), seed, age, generator, new UUID(msb, lsb), itemMap, extraData);
return world;
}
public static void saveChunk(SpoutWorld world, SpoutChunkSnapshot snapshot, List<DynamicBlockUpdate> blockUpdates, OutputStream dos) {
CompoundMap chunkTags = new CompoundMap();
short[] blocks = snapshot.getBlockIds();
short[] data = snapshot.getBlockData();
//Switch block ids from engine material ids to world specific ids
StringMap global = ((SpoutEngine) Spout.getEngine()).getEngineItemMap();
StringMap itemMap = world.getItemMap();
for (int i = 0; i < blocks.length; i++) {
blocks[i] = (short) global.convertTo(itemMap, blocks[i]);
}
chunkTags.put(new ByteTag("version", CHUNK_VERSION));
chunkTags.put(new ByteTag("format", (byte) 0));
chunkTags.put(new IntTag("x", snapshot.getX()));
chunkTags.put(new IntTag("y", snapshot.getY()));
chunkTags.put(new IntTag("z", snapshot.getZ()));
chunkTags.put(new ByteTag("populationState", snapshot.getPopulationState().getId()));
chunkTags.put(new ShortArrayTag("blocks", blocks));
chunkTags.put(new ShortArrayTag("data", data));
chunkTags.put(new ByteArrayTag("skyLight", snapshot.getSkyLight()));
chunkTags.put(new ByteArrayTag("blockLight", snapshot.getBlockLight()));
chunkTags.put(new CompoundTag("entities", saveEntities(snapshot.getEntities())));
chunkTags.put(saveDynamicUpdates(blockUpdates));
byte[] biomes = snapshot.getBiomeManager().serialize();
if (biomes != null) {
chunkTags.put(new StringTag("biomeManager", snapshot.getBiomeManager().getClass().getCanonicalName()));
chunkTags.put(new ByteArrayTag("biomes", biomes));
}
chunkTags.put(new ByteArrayTag("extraData", ((DataMap)snapshot.getDataMap()).getRawMap().compress()));
CompoundTag chunkCompound = new CompoundTag("chunk", chunkTags);
NBTOutputStream os = null;
try {
os = new NBTOutputStream(dos, false);
os.writeTag(chunkCompound);
} catch (IOException e) {
Spout.getLogger().log(Level.SEVERE, "Error saving chunk {" + snapshot.getX() + ", " + snapshot.getY() + ", " + snapshot + "}", e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ignore) {
}
}
}
}
public static SpoutChunk loadChunk(SpoutRegion r, int x, int y, int z, InputStream dis, ChunkDataForRegion dataForRegion) {
SpoutChunk chunk = null;
NBTInputStream is = null;
try {
if (dis == null) {
//The inputstream is null because no chunk data exists
return chunk;
}
is = new NBTInputStream(dis, false);
CompoundTag chunkTag = (CompoundTag) is.readTag();
CompoundMap map = chunkTag.getValue();
int cx = r.getChunkX() + x;
int cy = r.getChunkY() + y;
int cz = r.getChunkZ() + z;
byte populationState = SafeCast.toGeneric(map.get("populationState"), new ByteTag("", PopulationState.POPULATED.getId()), ByteTag.class).getValue();
short[] blocks = SafeCast.toShortArray(NBTMapper.toTagValue(map.get("blocks")), null);
short[] data = SafeCast.toShortArray(NBTMapper.toTagValue(map.get("data")), null);
byte[] skyLight = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("skyLight")), null);
byte[] blockLight = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("blockLight")), null);
byte[] extraData = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("extraData")), null);
BiomeManager manager = null;
if (map.containsKey("biomes")) {
try {
String biomeManagerClass = (String) map.get("biomeManager").getValue();
byte[] biomes = (byte[]) map.get("biomes").getValue();
@SuppressWarnings("unchecked")
Class<? extends BiomeManager> clazz = (Class<? extends BiomeManager>) Class.forName(biomeManagerClass);
Class<?>[] params = {int.class, int.class, int.class};
manager = clazz.getConstructor(params).newInstance(cx, cy, cz);
manager.deserialize(biomes);
} catch (Exception e) {
Spout.getLogger().severe("Failed to read biome data for chunk");
e.printStackTrace();
}
}
if (manager == null) {
manager = new EmptyBiomeManager(cx, cy, cz);
}
//Convert world block ids to engine material ids
SpoutWorld world = r.getWorld();
StringMap global = ((SpoutEngine) Spout.getEngine()).getEngineItemMap();
StringMap itemMap = world.getItemMap();
for (int i = 0; i < blocks.length; i++) {
blocks[i] = (short) itemMap.convertTo(global, blocks[i]);
}
DatatableMap extraDataMap = new GenericDatatableMap();
extraDataMap.decompress(extraData);
chunk = new FilteredChunk(r.getWorld(), r, cx, cy, cz, PopulationState.byID(populationState), blocks, data, skyLight, blockLight, manager, extraDataMap);
- CompoundMap entityMap = SafeCast.toGeneric(NBTMapper.toTagValue(map.get("entities")), null, CompoundMap.class);
+ CompoundMap entityMap = SafeCast.toGeneric(NBTMapper.toTagValue(map.get("entities")), (CompoundMap) null, CompoundMap.class);
loadEntities(r, entityMap, dataForRegion.loadedEntities);
List<? extends CompoundTag> updateList = checkerListCompoundTag.checkTag(map.get("dynamic_updates"), null);
loadDynamicUpdates(updateList, dataForRegion.loadedUpdates);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
return chunk;
}
private static void loadEntities(SpoutRegion r, CompoundMap map, List<SpoutEntity> loadedEntities) {
if (r != null && map != null) {
for (Tag tag : map) {
SpoutEntity e = loadEntity(r, (CompoundTag) tag);
if (e != null) {
loadedEntities.add(e);
}
}
}
}
private static CompoundMap saveEntities(Set<Entity> entities) {
CompoundMap tagMap = new CompoundMap();
for (Entity e : entities) {
Tag tag = saveEntity((SpoutEntity) e);
if (tag != null) {
tagMap.put(tag);
}
}
return tagMap;
}
private static SpoutEntity loadEntity(SpoutRegion r, CompoundTag tag) {
CompoundMap map = tag.getValue();
@SuppressWarnings("unused")
byte version = SafeCast.toByte(NBTMapper.toTagValue(map.get("version")), (byte) 0);
String name = SafeCast.toString(NBTMapper.toTagValue(map.get("controller")), "");
ControllerType type = ControllerRegistry.get(name);
if (type == null) {
Spout.getEngine().getLogger().log(Level.SEVERE, "No controller type found matching: " + name);
} else if (type.canCreateController()) {
//Read entity
Float pX = SafeCast.toFloat(NBTMapper.toTagValue(map.get("posX")), Float.MAX_VALUE);
Float pY = SafeCast.toFloat(NBTMapper.toTagValue(map.get("posY")), Float.MAX_VALUE);
Float pZ = SafeCast.toFloat(NBTMapper.toTagValue(map.get("posZ")), Float.MAX_VALUE);
if (pX == Float.MAX_VALUE || pY == Float.MAX_VALUE || pZ == Float.MAX_VALUE) {
return null;
}
float sX = SafeCast.toFloat(NBTMapper.toTagValue(map.get("scaleX")), 1.0F);
float sY = SafeCast.toFloat(NBTMapper.toTagValue(map.get("scaleY")), 1.0F);
float sZ = SafeCast.toFloat(NBTMapper.toTagValue(map.get("scaleZ")), 1.0F);
float qX = SafeCast.toFloat(NBTMapper.toTagValue(map.get("quatX")), 0.0F);
float qY = SafeCast.toFloat(NBTMapper.toTagValue(map.get("quatY")), 0.0F);
float qZ = SafeCast.toFloat(NBTMapper.toTagValue(map.get("quatZ")), 0.0F);
float qW = SafeCast.toFloat(NBTMapper.toTagValue(map.get("quatW")), 1.0F);
long msb = SafeCast.toLong(NBTMapper.toTagValue(map.get("UUID_msb")), new Random().nextLong());
long lsb = SafeCast.toLong(NBTMapper.toTagValue(map.get("UUID_lsb")), new Random().nextLong());
UUID uid = new UUID(msb, lsb);
int view = SafeCast.toInt(NBTMapper.toTagValue(map.get("view")), 0);
boolean observer = SafeCast.toGeneric(NBTMapper.toTagValue(map.get("observer")), new ByteTag("", (byte) 0), ByteTag.class).getBooleanValue();
//Setup controller
Controller controller = type.createController();
try {
boolean controllerDataExists = SafeCast.toGeneric(NBTMapper.toTagValue(map.get("controller_data_exists")), new ByteTag("", (byte) 0), ByteTag.class).getBooleanValue();
if (controllerDataExists) {
byte[] data = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("controller_data")), new byte[0]);
DatatableMap dataMap = ((DataMap) controller.data()).getRawMap();
dataMap.decompress(data);
}
} catch (Exception error) {
Spout.getEngine().getLogger().log(Level.SEVERE, "Unable to load the controller for the type: " + type.getName(), error);
}
//Setup entity
Transform t = new Transform(new Point(r != null ? r.getWorld() : null, pX, pY, pZ), new Quaternion(qX, qY, qZ, qW, false), new Vector3(sX, sY, sZ));
SpoutEntity e = new SpoutEntity((SpoutEngine) Spout.getEngine(), t, controller, view, uid, false);
e.setObserver(observer);
return e;
} else {
Spout.getEngine().getLogger().log(Level.SEVERE, "Unable to create controller for the type: " + type.getName());
}
return null;
}
private static Tag saveEntity(SpoutEntity e) {
if (!e.getController().isSavable() || e.isDead()) {
return null;
}
CompoundMap map = new CompoundMap();
map.put(new ByteTag("version", ENTITY_VERSION));
map.put(new StringTag("controller", e.getController().getType().getName()));
//Write entity
map.put(new FloatTag("posX", e.getPosition().getX()));
map.put(new FloatTag("posY", e.getPosition().getY()));
map.put(new FloatTag("posZ", e.getPosition().getZ()));
map.put(new FloatTag("scaleX", e.getScale().getX()));
map.put(new FloatTag("scaleY", e.getScale().getY()));
map.put(new FloatTag("scaleZ", e.getScale().getZ()));
map.put(new FloatTag("quatX", e.getRotation().getX()));
map.put(new FloatTag("quatY", e.getRotation().getY()));
map.put(new FloatTag("quatZ", e.getRotation().getZ()));
map.put(new FloatTag("quatW", e.getRotation().getW()));
map.put(new LongTag("UUID_msb", e.getUID().getMostSignificantBits()));
map.put(new LongTag("UUID_lsb", e.getUID().getLeastSignificantBits()));
map.put(new IntTag("view", e.getViewDistance()));
map.put(new ByteTag("observer", e.isObserverLive()));
//Write controller
try {
//Call onSave
e.getController().onSave();
//Serialize data
DatatableMap dataMap = ((DataMap) e.getController().data()).getRawMap();
if (!dataMap.isEmpty()) {
map.put(new ByteTag("controller_data_exists", true));
map.put(new ByteArrayTag("controller_data", dataMap.compress()));
} else {
map.put(new ByteTag("controller_data_exists", false));
}
} catch (Exception error) {
Spout.getEngine().getLogger().log(Level.SEVERE, "Unable to write the controller information for the type: " + e.getController().getType(), error);
}
CompoundTag tag = new CompoundTag("entity_" + e.getId(), map);
return tag;
}
private static ListTag<CompoundTag> saveDynamicUpdates(List<DynamicBlockUpdate> updates) {
List<CompoundTag> list = new ArrayList<CompoundTag>(updates.size());
for (DynamicBlockUpdate update : updates) {
CompoundTag tag = saveDynamicUpdate(update);
if (tag != null) {
list.add(tag);
}
}
return new ListTag<CompoundTag>("dynamic_updates", CompoundTag.class, list);
}
private static CompoundTag saveDynamicUpdate(DynamicBlockUpdate update) {
CompoundMap map = new CompoundMap();
map.put(new IntTag("packed", update.getPacked()));
map.put(new LongTag("nextUpdate", update.getNextUpdate()));
map.put(new LongTag("queuedTime", update.getQueuedTime()));
map.put(new IntTag("data", update.getData()));
return new CompoundTag("update", map);
}
private static void loadDynamicUpdates(List<? extends CompoundTag> list, List<DynamicBlockUpdate> loadedUpdates) {
if (list == null) {
return;
}
for (CompoundTag compoundTag : list) {
DynamicBlockUpdate update = loadDynamicUpdate(compoundTag);
if (update == null) {
continue;
}
loadedUpdates.add(update);
}
}
private static DynamicBlockUpdate loadDynamicUpdate(CompoundTag compoundTag) {
final CompoundMap map = compoundTag.getValue();
final int packed = SafeCast.toInt(NBTMapper.toTagValue(map.get("packed")), -1);
if (packed < 0) {
return null;
}
final long nextUpdate = SafeCast.toLong(NBTMapper.toTagValue(map.get("nextUpdate")), -1L);
if (nextUpdate < 0) {
return null;
}
final long queuedTime = SafeCast.toLong(NBTMapper.toTagValue(map.get("queuedTime")), -1L);
final int data = SafeCast.toInt(NBTMapper.toTagValue(map.get("data")), 0);
return new DynamicBlockUpdate(packed, nextUpdate, queuedTime, data, null);
}
}
| true | true | public static SpoutChunk loadChunk(SpoutRegion r, int x, int y, int z, InputStream dis, ChunkDataForRegion dataForRegion) {
SpoutChunk chunk = null;
NBTInputStream is = null;
try {
if (dis == null) {
//The inputstream is null because no chunk data exists
return chunk;
}
is = new NBTInputStream(dis, false);
CompoundTag chunkTag = (CompoundTag) is.readTag();
CompoundMap map = chunkTag.getValue();
int cx = r.getChunkX() + x;
int cy = r.getChunkY() + y;
int cz = r.getChunkZ() + z;
byte populationState = SafeCast.toGeneric(map.get("populationState"), new ByteTag("", PopulationState.POPULATED.getId()), ByteTag.class).getValue();
short[] blocks = SafeCast.toShortArray(NBTMapper.toTagValue(map.get("blocks")), null);
short[] data = SafeCast.toShortArray(NBTMapper.toTagValue(map.get("data")), null);
byte[] skyLight = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("skyLight")), null);
byte[] blockLight = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("blockLight")), null);
byte[] extraData = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("extraData")), null);
BiomeManager manager = null;
if (map.containsKey("biomes")) {
try {
String biomeManagerClass = (String) map.get("biomeManager").getValue();
byte[] biomes = (byte[]) map.get("biomes").getValue();
@SuppressWarnings("unchecked")
Class<? extends BiomeManager> clazz = (Class<? extends BiomeManager>) Class.forName(biomeManagerClass);
Class<?>[] params = {int.class, int.class, int.class};
manager = clazz.getConstructor(params).newInstance(cx, cy, cz);
manager.deserialize(biomes);
} catch (Exception e) {
Spout.getLogger().severe("Failed to read biome data for chunk");
e.printStackTrace();
}
}
if (manager == null) {
manager = new EmptyBiomeManager(cx, cy, cz);
}
//Convert world block ids to engine material ids
SpoutWorld world = r.getWorld();
StringMap global = ((SpoutEngine) Spout.getEngine()).getEngineItemMap();
StringMap itemMap = world.getItemMap();
for (int i = 0; i < blocks.length; i++) {
blocks[i] = (short) itemMap.convertTo(global, blocks[i]);
}
DatatableMap extraDataMap = new GenericDatatableMap();
extraDataMap.decompress(extraData);
chunk = new FilteredChunk(r.getWorld(), r, cx, cy, cz, PopulationState.byID(populationState), blocks, data, skyLight, blockLight, manager, extraDataMap);
CompoundMap entityMap = SafeCast.toGeneric(NBTMapper.toTagValue(map.get("entities")), null, CompoundMap.class);
loadEntities(r, entityMap, dataForRegion.loadedEntities);
List<? extends CompoundTag> updateList = checkerListCompoundTag.checkTag(map.get("dynamic_updates"), null);
loadDynamicUpdates(updateList, dataForRegion.loadedUpdates);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
return chunk;
}
| public static SpoutChunk loadChunk(SpoutRegion r, int x, int y, int z, InputStream dis, ChunkDataForRegion dataForRegion) {
SpoutChunk chunk = null;
NBTInputStream is = null;
try {
if (dis == null) {
//The inputstream is null because no chunk data exists
return chunk;
}
is = new NBTInputStream(dis, false);
CompoundTag chunkTag = (CompoundTag) is.readTag();
CompoundMap map = chunkTag.getValue();
int cx = r.getChunkX() + x;
int cy = r.getChunkY() + y;
int cz = r.getChunkZ() + z;
byte populationState = SafeCast.toGeneric(map.get("populationState"), new ByteTag("", PopulationState.POPULATED.getId()), ByteTag.class).getValue();
short[] blocks = SafeCast.toShortArray(NBTMapper.toTagValue(map.get("blocks")), null);
short[] data = SafeCast.toShortArray(NBTMapper.toTagValue(map.get("data")), null);
byte[] skyLight = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("skyLight")), null);
byte[] blockLight = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("blockLight")), null);
byte[] extraData = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("extraData")), null);
BiomeManager manager = null;
if (map.containsKey("biomes")) {
try {
String biomeManagerClass = (String) map.get("biomeManager").getValue();
byte[] biomes = (byte[]) map.get("biomes").getValue();
@SuppressWarnings("unchecked")
Class<? extends BiomeManager> clazz = (Class<? extends BiomeManager>) Class.forName(biomeManagerClass);
Class<?>[] params = {int.class, int.class, int.class};
manager = clazz.getConstructor(params).newInstance(cx, cy, cz);
manager.deserialize(biomes);
} catch (Exception e) {
Spout.getLogger().severe("Failed to read biome data for chunk");
e.printStackTrace();
}
}
if (manager == null) {
manager = new EmptyBiomeManager(cx, cy, cz);
}
//Convert world block ids to engine material ids
SpoutWorld world = r.getWorld();
StringMap global = ((SpoutEngine) Spout.getEngine()).getEngineItemMap();
StringMap itemMap = world.getItemMap();
for (int i = 0; i < blocks.length; i++) {
blocks[i] = (short) itemMap.convertTo(global, blocks[i]);
}
DatatableMap extraDataMap = new GenericDatatableMap();
extraDataMap.decompress(extraData);
chunk = new FilteredChunk(r.getWorld(), r, cx, cy, cz, PopulationState.byID(populationState), blocks, data, skyLight, blockLight, manager, extraDataMap);
CompoundMap entityMap = SafeCast.toGeneric(NBTMapper.toTagValue(map.get("entities")), (CompoundMap) null, CompoundMap.class);
loadEntities(r, entityMap, dataForRegion.loadedEntities);
List<? extends CompoundTag> updateList = checkerListCompoundTag.checkTag(map.get("dynamic_updates"), null);
loadDynamicUpdates(updateList, dataForRegion.loadedUpdates);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
return chunk;
}
|
diff --git a/src/com/android/gallery3d/app/PhotoDataAdapter.java b/src/com/android/gallery3d/app/PhotoDataAdapter.java
index fd3a7cf73..bee014911 100644
--- a/src/com/android/gallery3d/app/PhotoDataAdapter.java
+++ b/src/com/android/gallery3d/app/PhotoDataAdapter.java
@@ -1,1133 +1,1137 @@
/*
* 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.gallery3d.app;
import android.graphics.Bitmap;
import android.graphics.BitmapRegionDecoder;
import android.os.Handler;
import android.os.Message;
import com.android.gallery3d.common.BitmapUtils;
import com.android.gallery3d.common.Utils;
import com.android.gallery3d.data.ContentListener;
import com.android.gallery3d.data.LocalMediaItem;
import com.android.gallery3d.data.MediaItem;
import com.android.gallery3d.data.MediaObject;
import com.android.gallery3d.data.MediaSet;
import com.android.gallery3d.data.Path;
import com.android.gallery3d.glrenderer.TiledTexture;
import com.android.gallery3d.ui.PhotoView;
import com.android.gallery3d.ui.ScreenNail;
import com.android.gallery3d.ui.SynchronizedHandler;
import com.android.gallery3d.ui.TileImageViewAdapter;
import com.android.gallery3d.ui.TiledScreenNail;
import com.android.gallery3d.util.Future;
import com.android.gallery3d.util.FutureListener;
import com.android.gallery3d.util.MediaSetUtils;
import com.android.gallery3d.util.ThreadPool;
import com.android.gallery3d.util.ThreadPool.Job;
import com.android.gallery3d.util.ThreadPool.JobContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class PhotoDataAdapter implements PhotoPage.Model {
@SuppressWarnings("unused")
private static final String TAG = "PhotoDataAdapter";
private static final int MSG_LOAD_START = 1;
private static final int MSG_LOAD_FINISH = 2;
private static final int MSG_RUN_OBJECT = 3;
private static final int MSG_UPDATE_IMAGE_REQUESTS = 4;
private static final int MIN_LOAD_COUNT = 16;
private static final int DATA_CACHE_SIZE = 256;
private static final int SCREEN_NAIL_MAX = PhotoView.SCREEN_NAIL_MAX;
private static final int IMAGE_CACHE_SIZE = 2 * SCREEN_NAIL_MAX + 1;
private static final int BIT_SCREEN_NAIL = 1;
private static final int BIT_FULL_IMAGE = 2;
// sImageFetchSeq is the fetching sequence for images.
// We want to fetch the current screennail first (offset = 0), the next
// screennail (offset = +1), then the previous screennail (offset = -1) etc.
// After all the screennail are fetched, we fetch the full images (only some
// of them because of we don't want to use too much memory).
private static ImageFetch[] sImageFetchSeq;
private static class ImageFetch {
int indexOffset;
int imageBit;
public ImageFetch(int offset, int bit) {
indexOffset = offset;
imageBit = bit;
}
}
static {
int k = 0;
sImageFetchSeq = new ImageFetch[1 + (IMAGE_CACHE_SIZE - 1) * 2 + 3];
sImageFetchSeq[k++] = new ImageFetch(0, BIT_SCREEN_NAIL);
for (int i = 1; i < IMAGE_CACHE_SIZE; ++i) {
sImageFetchSeq[k++] = new ImageFetch(i, BIT_SCREEN_NAIL);
sImageFetchSeq[k++] = new ImageFetch(-i, BIT_SCREEN_NAIL);
}
sImageFetchSeq[k++] = new ImageFetch(0, BIT_FULL_IMAGE);
sImageFetchSeq[k++] = new ImageFetch(1, BIT_FULL_IMAGE);
sImageFetchSeq[k++] = new ImageFetch(-1, BIT_FULL_IMAGE);
}
private final TileImageViewAdapter mTileProvider = new TileImageViewAdapter();
// PhotoDataAdapter caches MediaItems (data) and ImageEntries (image).
//
// The MediaItems are stored in the mData array, which has DATA_CACHE_SIZE
// entries. The valid index range are [mContentStart, mContentEnd). We keep
// mContentEnd - mContentStart <= DATA_CACHE_SIZE, so we can use
// (i % DATA_CACHE_SIZE) as index to the array.
//
// The valid MediaItem window size (mContentEnd - mContentStart) may be
// smaller than DATA_CACHE_SIZE because we only update the window and reload
// the MediaItems when there are significant changes to the window position
// (>= MIN_LOAD_COUNT).
private final MediaItem mData[] = new MediaItem[DATA_CACHE_SIZE];
private int mContentStart = 0;
private int mContentEnd = 0;
// The ImageCache is a Path-to-ImageEntry map. It only holds the
// ImageEntries in the range of [mActiveStart, mActiveEnd). We also keep
// mActiveEnd - mActiveStart <= IMAGE_CACHE_SIZE. Besides, the
// [mActiveStart, mActiveEnd) range must be contained within
// the [mContentStart, mContentEnd) range.
private HashMap<Path, ImageEntry> mImageCache =
new HashMap<Path, ImageEntry>();
private int mActiveStart = 0;
private int mActiveEnd = 0;
// mCurrentIndex is the "center" image the user is viewing. The change of
// mCurrentIndex triggers the data loading and image loading.
private int mCurrentIndex;
// mChanges keeps the version number (of MediaItem) about the images. If any
// of the version number changes, we notify the view. This is used after a
// database reload or mCurrentIndex changes.
private final long mChanges[] = new long[IMAGE_CACHE_SIZE];
// mPaths keeps the corresponding Path (of MediaItem) for the images. This
// is used to determine the item movement.
private final Path mPaths[] = new Path[IMAGE_CACHE_SIZE];
private final Handler mMainHandler;
private final ThreadPool mThreadPool;
private final PhotoView mPhotoView;
private final MediaSet mSource;
private ReloadTask mReloadTask;
private long mSourceVersion = MediaObject.INVALID_DATA_VERSION;
private int mSize = 0;
private Path mItemPath;
private int mCameraIndex;
private boolean mIsPanorama;
private boolean mIsStaticCamera;
private boolean mIsActive;
private boolean mNeedFullImage;
private int mFocusHintDirection = FOCUS_HINT_NEXT;
private Path mFocusHintPath = null;
public interface DataListener extends LoadingListener {
public void onPhotoChanged(int index, Path item);
}
private DataListener mDataListener;
private final SourceListener mSourceListener = new SourceListener();
private final TiledTexture.Uploader mUploader;
// The path of the current viewing item will be stored in mItemPath.
// If mItemPath is not null, mCurrentIndex is only a hint for where we
// can find the item. If mItemPath is null, then we use the mCurrentIndex to
// find the image being viewed. cameraIndex is the index of the camera
// preview. If cameraIndex < 0, there is no camera preview.
public PhotoDataAdapter(AbstractGalleryActivity activity, PhotoView view,
MediaSet mediaSet, Path itemPath, int indexHint, int cameraIndex,
boolean isPanorama, boolean isStaticCamera) {
mSource = Utils.checkNotNull(mediaSet);
mPhotoView = Utils.checkNotNull(view);
mItemPath = Utils.checkNotNull(itemPath);
mCurrentIndex = indexHint;
mCameraIndex = cameraIndex;
mIsPanorama = isPanorama;
mIsStaticCamera = isStaticCamera;
mThreadPool = activity.getThreadPool();
mNeedFullImage = true;
Arrays.fill(mChanges, MediaObject.INVALID_DATA_VERSION);
mUploader = new TiledTexture.Uploader(activity.getGLRoot());
mMainHandler = new SynchronizedHandler(activity.getGLRoot()) {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_RUN_OBJECT:
((Runnable) message.obj).run();
return;
case MSG_LOAD_START: {
if (mDataListener != null) {
mDataListener.onLoadingStarted();
}
return;
}
case MSG_LOAD_FINISH: {
if (mDataListener != null) {
mDataListener.onLoadingFinished(false);
}
return;
}
case MSG_UPDATE_IMAGE_REQUESTS: {
updateImageRequests();
return;
}
default: throw new AssertionError();
}
}
};
updateSlidingWindow();
}
private MediaItem getItemInternal(int index) {
if (index < 0 || index >= mSize) return null;
if (index >= mContentStart && index < mContentEnd) {
return mData[index % DATA_CACHE_SIZE];
}
return null;
}
private long getVersion(int index) {
MediaItem item = getItemInternal(index);
if (item == null) return MediaObject.INVALID_DATA_VERSION;
return item.getDataVersion();
}
private Path getPath(int index) {
MediaItem item = getItemInternal(index);
if (item == null) return null;
return item.getPath();
}
private void fireDataChange() {
// First check if data actually changed.
boolean changed = false;
for (int i = -SCREEN_NAIL_MAX; i <= SCREEN_NAIL_MAX; ++i) {
long newVersion = getVersion(mCurrentIndex + i);
if (mChanges[i + SCREEN_NAIL_MAX] != newVersion) {
mChanges[i + SCREEN_NAIL_MAX] = newVersion;
changed = true;
}
}
if (!changed) return;
// Now calculate the fromIndex array. fromIndex represents the item
// movement. It records the index where the picture come from. The
// special value Integer.MAX_VALUE means it's a new picture.
final int N = IMAGE_CACHE_SIZE;
int fromIndex[] = new int[N];
// Remember the old path array.
Path oldPaths[] = new Path[N];
System.arraycopy(mPaths, 0, oldPaths, 0, N);
// Update the mPaths array.
for (int i = 0; i < N; ++i) {
mPaths[i] = getPath(mCurrentIndex + i - SCREEN_NAIL_MAX);
}
// Calculate the fromIndex array.
for (int i = 0; i < N; i++) {
Path p = mPaths[i];
if (p == null) {
fromIndex[i] = Integer.MAX_VALUE;
continue;
}
// Try to find the same path in the old array
int j;
for (j = 0; j < N; j++) {
if (oldPaths[j] == p) {
break;
}
}
fromIndex[i] = (j < N) ? j - SCREEN_NAIL_MAX : Integer.MAX_VALUE;
}
mPhotoView.notifyDataChange(fromIndex, -mCurrentIndex,
mSize - 1 - mCurrentIndex);
}
public void setDataListener(DataListener listener) {
mDataListener = listener;
}
private void updateScreenNail(Path path, Future<ScreenNail> future) {
ImageEntry entry = mImageCache.get(path);
ScreenNail screenNail = future.get();
if (entry == null || entry.screenNailTask != future) {
if (screenNail != null) screenNail.recycle();
return;
}
entry.screenNailTask = null;
// Combine the ScreenNails if we already have a BitmapScreenNail
if (entry.screenNail instanceof TiledScreenNail) {
TiledScreenNail original = (TiledScreenNail) entry.screenNail;
screenNail = original.combine(screenNail);
}
if (screenNail == null) {
entry.failToLoad = true;
} else {
entry.failToLoad = false;
entry.screenNail = screenNail;
}
for (int i = -SCREEN_NAIL_MAX; i <= SCREEN_NAIL_MAX; ++i) {
if (path == getPath(mCurrentIndex + i)) {
if (i == 0) updateTileProvider(entry);
mPhotoView.notifyImageChange(i);
break;
}
}
updateImageRequests();
updateScreenNailUploadQueue();
}
private void updateFullImage(Path path, Future<BitmapRegionDecoder> future) {
ImageEntry entry = mImageCache.get(path);
if (entry == null || entry.fullImageTask != future) {
BitmapRegionDecoder fullImage = future.get();
if (fullImage != null) fullImage.recycle();
return;
}
entry.fullImageTask = null;
entry.fullImage = future.get();
if (entry.fullImage != null) {
if (path == getPath(mCurrentIndex)) {
updateTileProvider(entry);
mPhotoView.notifyImageChange(0);
}
}
updateImageRequests();
}
@Override
public void resume() {
mIsActive = true;
TiledTexture.prepareResources();
mSource.addContentListener(mSourceListener);
updateImageCache();
updateImageRequests();
mReloadTask = new ReloadTask();
mReloadTask.start();
fireDataChange();
}
@Override
public void pause() {
mIsActive = false;
mReloadTask.terminate();
mReloadTask = null;
mSource.removeContentListener(mSourceListener);
for (ImageEntry entry : mImageCache.values()) {
if (entry.fullImageTask != null) entry.fullImageTask.cancel();
if (entry.screenNailTask != null) entry.screenNailTask.cancel();
if (entry.screenNail != null) entry.screenNail.recycle();
}
mImageCache.clear();
mTileProvider.clear();
mUploader.clear();
TiledTexture.freeResources();
}
private MediaItem getItem(int index) {
if (index < 0 || index >= mSize || !mIsActive) return null;
Utils.assertTrue(index >= mActiveStart && index < mActiveEnd);
if (index >= mContentStart && index < mContentEnd) {
return mData[index % DATA_CACHE_SIZE];
}
return null;
}
private void updateCurrentIndex(int index) {
if (mCurrentIndex == index) return;
mCurrentIndex = index;
updateSlidingWindow();
MediaItem item = mData[index % DATA_CACHE_SIZE];
mItemPath = item == null ? null : item.getPath();
updateImageCache();
updateImageRequests();
updateTileProvider();
if (mDataListener != null) {
mDataListener.onPhotoChanged(index, mItemPath);
}
fireDataChange();
}
private void uploadScreenNail(int offset) {
int index = mCurrentIndex + offset;
if (index < mActiveStart || index >= mActiveEnd) return;
MediaItem item = getItem(index);
if (item == null) return;
ImageEntry e = mImageCache.get(item.getPath());
if (e == null) return;
ScreenNail s = e.screenNail;
if (s instanceof TiledScreenNail) {
TiledTexture t = ((TiledScreenNail) s).getTexture();
if (t != null && !t.isReady()) mUploader.addTexture(t);
}
}
private void updateScreenNailUploadQueue() {
mUploader.clear();
uploadScreenNail(0);
for (int i = 1; i < IMAGE_CACHE_SIZE; ++i) {
uploadScreenNail(i);
uploadScreenNail(-i);
}
}
@Override
public void moveTo(int index) {
updateCurrentIndex(index);
}
@Override
public ScreenNail getScreenNail(int offset) {
int index = mCurrentIndex + offset;
if (index < 0 || index >= mSize || !mIsActive) return null;
Utils.assertTrue(index >= mActiveStart && index < mActiveEnd);
MediaItem item = getItem(index);
if (item == null) return null;
ImageEntry entry = mImageCache.get(item.getPath());
if (entry == null) return null;
// Create a default ScreenNail if the real one is not available yet,
// except for camera that a black screen is better than a gray tile.
if (entry.screenNail == null && !isCamera(offset)) {
entry.screenNail = newPlaceholderScreenNail(item);
if (offset == 0) updateTileProvider(entry);
}
return entry.screenNail;
}
@Override
public void getImageSize(int offset, PhotoView.Size size) {
MediaItem item = getItem(mCurrentIndex + offset);
if (item == null) {
size.width = 0;
size.height = 0;
} else {
size.width = item.getWidth();
size.height = item.getHeight();
}
}
@Override
public int getImageRotation(int offset) {
MediaItem item = getItem(mCurrentIndex + offset);
return (item == null) ? 0 : item.getFullImageRotation();
}
@Override
public void setNeedFullImage(boolean enabled) {
mNeedFullImage = enabled;
mMainHandler.sendEmptyMessage(MSG_UPDATE_IMAGE_REQUESTS);
}
@Override
public boolean isCamera(int offset) {
return mCurrentIndex + offset == mCameraIndex;
}
@Override
public boolean isPanorama(int offset) {
return isCamera(offset) && mIsPanorama;
}
@Override
public boolean isStaticCamera(int offset) {
return isCamera(offset) && mIsStaticCamera;
}
@Override
public boolean isVideo(int offset) {
MediaItem item = getItem(mCurrentIndex + offset);
return (item == null)
? false
: item.getMediaType() == MediaItem.MEDIA_TYPE_VIDEO;
}
@Override
public boolean isDeletable(int offset) {
MediaItem item = getItem(mCurrentIndex + offset);
return (item == null)
? false
: (item.getSupportedOperations() & MediaItem.SUPPORT_DELETE) != 0;
}
@Override
public int getLoadingState(int offset) {
ImageEntry entry = mImageCache.get(getPath(mCurrentIndex + offset));
if (entry == null) return LOADING_INIT;
if (entry.failToLoad) return LOADING_FAIL;
if (entry.screenNail != null) return LOADING_COMPLETE;
return LOADING_INIT;
}
@Override
public ScreenNail getScreenNail() {
return getScreenNail(0);
}
@Override
public int getImageHeight() {
return mTileProvider.getImageHeight();
}
@Override
public int getImageWidth() {
return mTileProvider.getImageWidth();
}
@Override
public int getLevelCount() {
return mTileProvider.getLevelCount();
}
@Override
public Bitmap getTile(int level, int x, int y, int tileSize) {
return mTileProvider.getTile(level, x, y, tileSize);
}
@Override
public boolean isEmpty() {
return mSize == 0;
}
@Override
public int getCurrentIndex() {
return mCurrentIndex;
}
@Override
public MediaItem getMediaItem(int offset) {
int index = mCurrentIndex + offset;
if (index >= mContentStart && index < mContentEnd) {
return mData[index % DATA_CACHE_SIZE];
}
return null;
}
@Override
public void setCurrentPhoto(Path path, int indexHint) {
if (mItemPath == path) return;
mItemPath = path;
mCurrentIndex = indexHint;
updateSlidingWindow();
updateImageCache();
fireDataChange();
// We need to reload content if the path doesn't match.
MediaItem item = getMediaItem(0);
if (item != null && item.getPath() != path) {
if (mReloadTask != null) mReloadTask.notifyDirty();
}
}
@Override
public void setFocusHintDirection(int direction) {
mFocusHintDirection = direction;
}
@Override
public void setFocusHintPath(Path path) {
mFocusHintPath = path;
}
private void updateTileProvider() {
ImageEntry entry = mImageCache.get(getPath(mCurrentIndex));
if (entry == null) { // in loading
mTileProvider.clear();
} else {
updateTileProvider(entry);
}
}
private void updateTileProvider(ImageEntry entry) {
ScreenNail screenNail = entry.screenNail;
BitmapRegionDecoder fullImage = entry.fullImage;
if (screenNail != null) {
if (fullImage != null) {
mTileProvider.setScreenNail(screenNail,
fullImage.getWidth(), fullImage.getHeight());
mTileProvider.setRegionDecoder(fullImage);
} else {
int width = screenNail.getWidth();
int height = screenNail.getHeight();
mTileProvider.setScreenNail(screenNail, width, height);
}
} else {
mTileProvider.clear();
}
}
private void updateSlidingWindow() {
// 1. Update the image window
int start = Utils.clamp(mCurrentIndex - IMAGE_CACHE_SIZE / 2,
0, Math.max(0, mSize - IMAGE_CACHE_SIZE));
int end = Math.min(mSize, start + IMAGE_CACHE_SIZE);
if (mActiveStart == start && mActiveEnd == end) return;
mActiveStart = start;
mActiveEnd = end;
// 2. Update the data window
start = Utils.clamp(mCurrentIndex - DATA_CACHE_SIZE / 2,
0, Math.max(0, mSize - DATA_CACHE_SIZE));
end = Math.min(mSize, start + DATA_CACHE_SIZE);
if (mContentStart > mActiveStart || mContentEnd < mActiveEnd
|| Math.abs(start - mContentStart) > MIN_LOAD_COUNT) {
for (int i = mContentStart; i < mContentEnd; ++i) {
if (i < start || i >= end) {
mData[i % DATA_CACHE_SIZE] = null;
}
}
mContentStart = start;
mContentEnd = end;
if (mReloadTask != null) mReloadTask.notifyDirty();
}
}
private void updateImageRequests() {
if (!mIsActive) return;
int currentIndex = mCurrentIndex;
MediaItem item = mData[currentIndex % DATA_CACHE_SIZE];
if (item == null || item.getPath() != mItemPath) {
// current item mismatch - don't request image
return;
}
// 1. Find the most wanted request and start it (if not already started).
Future<?> task = null;
for (int i = 0; i < sImageFetchSeq.length; i++) {
int offset = sImageFetchSeq[i].indexOffset;
int bit = sImageFetchSeq[i].imageBit;
if (bit == BIT_FULL_IMAGE && !mNeedFullImage) continue;
task = startTaskIfNeeded(currentIndex + offset, bit);
if (task != null) break;
}
// 2. Cancel everything else.
for (ImageEntry entry : mImageCache.values()) {
if (entry.screenNailTask != null && entry.screenNailTask != task) {
entry.screenNailTask.cancel();
entry.screenNailTask = null;
entry.requestedScreenNail = MediaObject.INVALID_DATA_VERSION;
}
if (entry.fullImageTask != null && entry.fullImageTask != task) {
entry.fullImageTask.cancel();
entry.fullImageTask = null;
entry.requestedFullImage = MediaObject.INVALID_DATA_VERSION;
}
}
}
private class ScreenNailJob implements Job<ScreenNail> {
private MediaItem mItem;
public ScreenNailJob(MediaItem item) {
mItem = item;
}
@Override
public ScreenNail run(JobContext jc) {
// We try to get a ScreenNail first, if it fails, we fallback to get
// a Bitmap and then wrap it in a BitmapScreenNail instead.
ScreenNail s = mItem.getScreenNail();
if (s != null) return s;
// If this is a temporary item, don't try to get its bitmap because
// it won't be available. We will get its bitmap after a data reload.
if (isTemporaryItem(mItem)) {
return newPlaceholderScreenNail(mItem);
}
Bitmap bitmap = mItem.requestImage(MediaItem.TYPE_THUMBNAIL).run(jc);
if (jc.isCancelled()) return null;
if (bitmap != null) {
bitmap = BitmapUtils.rotateBitmap(bitmap,
mItem.getRotation() - mItem.getFullImageRotation(), true);
}
return bitmap == null ? null : new TiledScreenNail(bitmap);
}
}
private class FullImageJob implements Job<BitmapRegionDecoder> {
private MediaItem mItem;
public FullImageJob(MediaItem item) {
mItem = item;
}
@Override
public BitmapRegionDecoder run(JobContext jc) {
if (isTemporaryItem(mItem)) {
return null;
}
return mItem.requestLargeImage().run(jc);
}
}
// Returns true if we think this is a temporary item created by Camera. A
// temporary item is an image or a video whose data is still being
// processed, but an incomplete entry is created first in MediaProvider, so
// we can display them (in grey tile) even if they are not saved to disk
// yet. When the image or video data is actually saved, we will get
// notification from MediaProvider, reload data, and show the actual image
// or video data.
private boolean isTemporaryItem(MediaItem mediaItem) {
// Must have camera to create a temporary item.
if (mCameraIndex < 0) return false;
// Must be an item in camera roll.
if (!(mediaItem instanceof LocalMediaItem)) return false;
LocalMediaItem item = (LocalMediaItem) mediaItem;
if (item.getBucketId() != MediaSetUtils.CAMERA_BUCKET_ID) return false;
// Must have no size, but must have width and height information
if (item.getSize() != 0) return false;
if (item.getWidth() == 0) return false;
if (item.getHeight() == 0) return false;
// Must be created in the last 10 seconds.
if (item.getDateInMs() - System.currentTimeMillis() > 10000) return false;
return true;
}
// Create a default ScreenNail when a ScreenNail is needed, but we don't yet
// have one available (because the image data is still being saved, or the
// Bitmap is still being loaded.
private ScreenNail newPlaceholderScreenNail(MediaItem item) {
int width = item.getWidth();
int height = item.getHeight();
return new TiledScreenNail(width, height);
}
// Returns the task if we started the task or the task is already started.
private Future<?> startTaskIfNeeded(int index, int which) {
if (index < mActiveStart || index >= mActiveEnd) return null;
ImageEntry entry = mImageCache.get(getPath(index));
if (entry == null) return null;
MediaItem item = mData[index % DATA_CACHE_SIZE];
Utils.assertTrue(item != null);
long version = item.getDataVersion();
if (which == BIT_SCREEN_NAIL && entry.screenNailTask != null
&& entry.requestedScreenNail == version) {
return entry.screenNailTask;
} else if (which == BIT_FULL_IMAGE && entry.fullImageTask != null
&& entry.requestedFullImage == version) {
return entry.fullImageTask;
}
if (which == BIT_SCREEN_NAIL && entry.requestedScreenNail != version) {
entry.requestedScreenNail = version;
entry.screenNailTask = mThreadPool.submit(
new ScreenNailJob(item),
new ScreenNailListener(item));
// request screen nail
return entry.screenNailTask;
}
if (which == BIT_FULL_IMAGE && entry.requestedFullImage != version
&& (item.getSupportedOperations()
& MediaItem.SUPPORT_FULL_IMAGE) != 0) {
entry.requestedFullImage = version;
entry.fullImageTask = mThreadPool.submit(
new FullImageJob(item),
new FullImageListener(item));
// request full image
return entry.fullImageTask;
}
return null;
}
private void updateImageCache() {
HashSet<Path> toBeRemoved = new HashSet<Path>(mImageCache.keySet());
for (int i = mActiveStart; i < mActiveEnd; ++i) {
MediaItem item = mData[i % DATA_CACHE_SIZE];
if (item == null) continue;
Path path = item.getPath();
ImageEntry entry = mImageCache.get(path);
toBeRemoved.remove(path);
if (entry != null) {
if (Math.abs(i - mCurrentIndex) > 1) {
if (entry.fullImageTask != null) {
entry.fullImageTask.cancel();
entry.fullImageTask = null;
}
entry.fullImage = null;
entry.requestedFullImage = MediaObject.INVALID_DATA_VERSION;
}
if (entry.requestedScreenNail != item.getDataVersion()) {
// This ScreenNail is outdated, we want to update it if it's
// still a placeholder.
if (entry.screenNail instanceof TiledScreenNail) {
TiledScreenNail s = (TiledScreenNail) entry.screenNail;
s.updatePlaceholderSize(
item.getWidth(), item.getHeight());
}
}
} else {
entry = new ImageEntry();
mImageCache.put(path, entry);
}
}
// Clear the data and requests for ImageEntries outside the new window.
for (Path path : toBeRemoved) {
ImageEntry entry = mImageCache.remove(path);
if (entry.fullImageTask != null) entry.fullImageTask.cancel();
if (entry.screenNailTask != null) entry.screenNailTask.cancel();
if (entry.screenNail != null) entry.screenNail.recycle();
}
updateScreenNailUploadQueue();
}
private class FullImageListener
implements Runnable, FutureListener<BitmapRegionDecoder> {
private final Path mPath;
private Future<BitmapRegionDecoder> mFuture;
public FullImageListener(MediaItem item) {
mPath = item.getPath();
}
@Override
public void onFutureDone(Future<BitmapRegionDecoder> future) {
mFuture = future;
mMainHandler.sendMessage(
mMainHandler.obtainMessage(MSG_RUN_OBJECT, this));
}
@Override
public void run() {
updateFullImage(mPath, mFuture);
}
}
private class ScreenNailListener
implements Runnable, FutureListener<ScreenNail> {
private final Path mPath;
private Future<ScreenNail> mFuture;
public ScreenNailListener(MediaItem item) {
mPath = item.getPath();
}
@Override
public void onFutureDone(Future<ScreenNail> future) {
mFuture = future;
mMainHandler.sendMessage(
mMainHandler.obtainMessage(MSG_RUN_OBJECT, this));
}
@Override
public void run() {
updateScreenNail(mPath, mFuture);
}
}
private static class ImageEntry {
public BitmapRegionDecoder fullImage;
public ScreenNail screenNail;
public Future<ScreenNail> screenNailTask;
public Future<BitmapRegionDecoder> fullImageTask;
public long requestedScreenNail = MediaObject.INVALID_DATA_VERSION;
public long requestedFullImage = MediaObject.INVALID_DATA_VERSION;
public boolean failToLoad = false;
}
private class SourceListener implements ContentListener {
@Override
public void onContentDirty() {
if (mReloadTask != null) mReloadTask.notifyDirty();
}
}
private <T> T executeAndWait(Callable<T> callable) {
FutureTask<T> task = new FutureTask<T>(callable);
mMainHandler.sendMessage(
mMainHandler.obtainMessage(MSG_RUN_OBJECT, task));
try {
return task.get();
} catch (InterruptedException e) {
return null;
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
private static class UpdateInfo {
public long version;
public boolean reloadContent;
public Path target;
public int indexHint;
public int contentStart;
public int contentEnd;
public int size;
public ArrayList<MediaItem> items;
}
private class GetUpdateInfo implements Callable<UpdateInfo> {
private boolean needContentReload() {
for (int i = mContentStart, n = mContentEnd; i < n; ++i) {
if (mData[i % DATA_CACHE_SIZE] == null) return true;
}
MediaItem current = mData[mCurrentIndex % DATA_CACHE_SIZE];
return current == null || current.getPath() != mItemPath;
}
@Override
public UpdateInfo call() throws Exception {
// TODO: Try to load some data in first update
UpdateInfo info = new UpdateInfo();
info.version = mSourceVersion;
info.reloadContent = needContentReload();
info.target = mItemPath;
info.indexHint = mCurrentIndex;
info.contentStart = mContentStart;
info.contentEnd = mContentEnd;
info.size = mSize;
return info;
}
}
private class UpdateContent implements Callable<Void> {
UpdateInfo mUpdateInfo;
public UpdateContent(UpdateInfo updateInfo) {
mUpdateInfo = updateInfo;
}
@Override
public Void call() throws Exception {
UpdateInfo info = mUpdateInfo;
mSourceVersion = info.version;
if (info.size != mSize) {
mSize = info.size;
if (mContentEnd > mSize) mContentEnd = mSize;
if (mActiveEnd > mSize) mActiveEnd = mSize;
}
mCurrentIndex = info.indexHint;
updateSlidingWindow();
if (info.items != null) {
int start = Math.max(info.contentStart, mContentStart);
int end = Math.min(info.contentStart + info.items.size(), mContentEnd);
int dataIndex = start % DATA_CACHE_SIZE;
for (int i = start; i < end; ++i) {
mData[dataIndex] = info.items.get(i - info.contentStart);
if (++dataIndex == DATA_CACHE_SIZE) dataIndex = 0;
}
}
// update mItemPath
MediaItem current = mData[mCurrentIndex % DATA_CACHE_SIZE];
mItemPath = current == null ? null : current.getPath();
updateImageCache();
updateTileProvider();
updateImageRequests();
if (mDataListener != null) {
mDataListener.onPhotoChanged(mCurrentIndex, mItemPath);
}
fireDataChange();
return null;
}
}
private class ReloadTask extends Thread {
private volatile boolean mActive = true;
private volatile boolean mDirty = true;
private boolean mIsLoading = false;
private void updateLoading(boolean loading) {
if (mIsLoading == loading) return;
mIsLoading = loading;
mMainHandler.sendEmptyMessage(loading ? MSG_LOAD_START : MSG_LOAD_FINISH);
}
@Override
public void run() {
while (mActive) {
synchronized (this) {
if (!mDirty && mActive) {
updateLoading(false);
Utils.waitWithoutInterrupt(this);
continue;
}
}
mDirty = false;
UpdateInfo info = executeAndWait(new GetUpdateInfo());
updateLoading(true);
long version = mSource.reload();
if (info.version != version) {
info.reloadContent = true;
info.size = mSource.getMediaItemCount();
+ int start = Utils.clamp(info.indexHint - DATA_CACHE_SIZE / 2,
+ 0, Math.max(0, info.size - DATA_CACHE_SIZE));
+ info.contentStart = start;
+ info.contentEnd = Math.min(info.size, start + DATA_CACHE_SIZE);
}
if (!info.reloadContent) continue;
info.items = mSource.getMediaItem(
info.contentStart, info.contentEnd);
int index = MediaSet.INDEX_NOT_FOUND;
// First try to focus on the given hint path if there is one.
if (mFocusHintPath != null) {
index = findIndexOfPathInCache(info, mFocusHintPath);
mFocusHintPath = null;
}
// Otherwise try to see if the currently focused item can be found.
if (index == MediaSet.INDEX_NOT_FOUND) {
MediaItem item = findCurrentMediaItem(info);
if (item != null && item.getPath() == info.target) {
index = info.indexHint;
} else {
index = findIndexOfTarget(info);
}
}
// The image has been deleted. Focus on the next image (keep
// mCurrentIndex unchanged) or the previous image (decrease
// mCurrentIndex by 1). In page mode we want to see the next
// image, so we focus on the next one. In film mode we want the
// later images to shift left to fill the empty space, so we
// focus on the previous image (so it will not move). In any
// case the index needs to be limited to [0, mSize).
if (index == MediaSet.INDEX_NOT_FOUND) {
index = info.indexHint;
int focusHintDirection = mFocusHintDirection;
if (index == (mCameraIndex + 1)) {
focusHintDirection = FOCUS_HINT_NEXT;
}
if (focusHintDirection == FOCUS_HINT_PREVIOUS
&& index > 0) {
index--;
}
}
// Don't change index if mSize == 0
- if (mSize > 0) {
- if (index >= mSize) index = mSize - 1;
+ if (info.size > 0) {
+ if (index >= info.size) index = info.size - 1;
}
info.indexHint = index;
executeAndWait(new UpdateContent(info));
}
}
public synchronized void notifyDirty() {
mDirty = true;
notifyAll();
}
public synchronized void terminate() {
mActive = false;
notifyAll();
}
private MediaItem findCurrentMediaItem(UpdateInfo info) {
ArrayList<MediaItem> items = info.items;
int index = info.indexHint - info.contentStart;
return index < 0 || index >= items.size() ? null : items.get(index);
}
private int findIndexOfTarget(UpdateInfo info) {
if (info.target == null) return info.indexHint;
ArrayList<MediaItem> items = info.items;
// First, try to find the item in the data just loaded
if (items != null) {
int i = findIndexOfPathInCache(info, info.target);
if (i != MediaSet.INDEX_NOT_FOUND) return i;
}
// Not found, find it in mSource.
return mSource.getIndexOfItem(info.target, info.indexHint);
}
private int findIndexOfPathInCache(UpdateInfo info, Path path) {
ArrayList<MediaItem> items = info.items;
for (int i = 0, n = items.size(); i < n; ++i) {
MediaItem item = items.get(i);
if (item != null && item.getPath() == path) {
return i + info.contentStart;
}
}
return MediaSet.INDEX_NOT_FOUND;
}
}
}
| false | true | public void run() {
while (mActive) {
synchronized (this) {
if (!mDirty && mActive) {
updateLoading(false);
Utils.waitWithoutInterrupt(this);
continue;
}
}
mDirty = false;
UpdateInfo info = executeAndWait(new GetUpdateInfo());
updateLoading(true);
long version = mSource.reload();
if (info.version != version) {
info.reloadContent = true;
info.size = mSource.getMediaItemCount();
}
if (!info.reloadContent) continue;
info.items = mSource.getMediaItem(
info.contentStart, info.contentEnd);
int index = MediaSet.INDEX_NOT_FOUND;
// First try to focus on the given hint path if there is one.
if (mFocusHintPath != null) {
index = findIndexOfPathInCache(info, mFocusHintPath);
mFocusHintPath = null;
}
// Otherwise try to see if the currently focused item can be found.
if (index == MediaSet.INDEX_NOT_FOUND) {
MediaItem item = findCurrentMediaItem(info);
if (item != null && item.getPath() == info.target) {
index = info.indexHint;
} else {
index = findIndexOfTarget(info);
}
}
// The image has been deleted. Focus on the next image (keep
// mCurrentIndex unchanged) or the previous image (decrease
// mCurrentIndex by 1). In page mode we want to see the next
// image, so we focus on the next one. In film mode we want the
// later images to shift left to fill the empty space, so we
// focus on the previous image (so it will not move). In any
// case the index needs to be limited to [0, mSize).
if (index == MediaSet.INDEX_NOT_FOUND) {
index = info.indexHint;
int focusHintDirection = mFocusHintDirection;
if (index == (mCameraIndex + 1)) {
focusHintDirection = FOCUS_HINT_NEXT;
}
if (focusHintDirection == FOCUS_HINT_PREVIOUS
&& index > 0) {
index--;
}
}
// Don't change index if mSize == 0
if (mSize > 0) {
if (index >= mSize) index = mSize - 1;
}
info.indexHint = index;
executeAndWait(new UpdateContent(info));
}
}
| public void run() {
while (mActive) {
synchronized (this) {
if (!mDirty && mActive) {
updateLoading(false);
Utils.waitWithoutInterrupt(this);
continue;
}
}
mDirty = false;
UpdateInfo info = executeAndWait(new GetUpdateInfo());
updateLoading(true);
long version = mSource.reload();
if (info.version != version) {
info.reloadContent = true;
info.size = mSource.getMediaItemCount();
int start = Utils.clamp(info.indexHint - DATA_CACHE_SIZE / 2,
0, Math.max(0, info.size - DATA_CACHE_SIZE));
info.contentStart = start;
info.contentEnd = Math.min(info.size, start + DATA_CACHE_SIZE);
}
if (!info.reloadContent) continue;
info.items = mSource.getMediaItem(
info.contentStart, info.contentEnd);
int index = MediaSet.INDEX_NOT_FOUND;
// First try to focus on the given hint path if there is one.
if (mFocusHintPath != null) {
index = findIndexOfPathInCache(info, mFocusHintPath);
mFocusHintPath = null;
}
// Otherwise try to see if the currently focused item can be found.
if (index == MediaSet.INDEX_NOT_FOUND) {
MediaItem item = findCurrentMediaItem(info);
if (item != null && item.getPath() == info.target) {
index = info.indexHint;
} else {
index = findIndexOfTarget(info);
}
}
// The image has been deleted. Focus on the next image (keep
// mCurrentIndex unchanged) or the previous image (decrease
// mCurrentIndex by 1). In page mode we want to see the next
// image, so we focus on the next one. In film mode we want the
// later images to shift left to fill the empty space, so we
// focus on the previous image (so it will not move). In any
// case the index needs to be limited to [0, mSize).
if (index == MediaSet.INDEX_NOT_FOUND) {
index = info.indexHint;
int focusHintDirection = mFocusHintDirection;
if (index == (mCameraIndex + 1)) {
focusHintDirection = FOCUS_HINT_NEXT;
}
if (focusHintDirection == FOCUS_HINT_PREVIOUS
&& index > 0) {
index--;
}
}
// Don't change index if mSize == 0
if (info.size > 0) {
if (index >= info.size) index = info.size - 1;
}
info.indexHint = index;
executeAndWait(new UpdateContent(info));
}
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/YankOperation.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/YankOperation.java
index 3621c0f5..2dc7d960 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/YankOperation.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/YankOperation.java
@@ -1,50 +1,50 @@
package net.sourceforge.vrapper.vim.commands;
import net.sourceforge.vrapper.utils.ContentType;
import net.sourceforge.vrapper.utils.Position;
import net.sourceforge.vrapper.utils.TextRange;
import net.sourceforge.vrapper.utils.VimUtils;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.modes.NormalMode;
import net.sourceforge.vrapper.vim.register.RegisterContent;
import net.sourceforge.vrapper.vim.register.StringRegisterContent;
public class YankOperation extends SimpleTextOperation {
public static final YankOperation INSTANCE = new YankOperation();
private YankOperation() { /* NOP */ }
@Override
public void execute(EditorAdaptor editorAdaptor, TextRange region, ContentType contentType) {
doIt(editorAdaptor, region, contentType);
}
public TextOperation repetition() {
return null;
}
public static void doIt(EditorAdaptor editorAdaptor, TextRange range, ContentType contentType) {
String text = editorAdaptor.getModelContent().getText(range.getLeftBound().getModelOffset(), range.getModelLength());
//if we're expecting lines and this text doesn't end in a newline,
//manually append a newline to the end
//(this to handle yanking the last line of a file)
if (contentType == ContentType.LINES && (text.length() == 0 || ! VimUtils.isNewLine(text.substring(text.length()-1)))) {
text += editorAdaptor.getConfiguration().getNewLine();
}
RegisterContent content = new StringRegisterContent(contentType, text);
editorAdaptor.getRegisterManager().getActiveRegister().setContent(content);
if (contentType == ContentType.LINES && NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
//if this is line-wise, move cursor to first line in selection but keep stickyColumn
int lineNo = editorAdaptor.getModelContent().getLineInformationOfOffset(range.getLeftBound().getModelOffset()).getNumber();
- Position stickyPosition = editorAdaptor.getCursorService().stickyColumnAtViewLine(lineNo);
+ Position stickyPosition = editorAdaptor.getCursorService().stickyColumnAtModelLine(lineNo);
editorAdaptor.getCursorService().setPosition(stickyPosition, true);
}
else {
//move cursor to beginning of selection
editorAdaptor.getCursorService().setPosition(range.getLeftBound(), true);
}
}
}
| true | true | public static void doIt(EditorAdaptor editorAdaptor, TextRange range, ContentType contentType) {
String text = editorAdaptor.getModelContent().getText(range.getLeftBound().getModelOffset(), range.getModelLength());
//if we're expecting lines and this text doesn't end in a newline,
//manually append a newline to the end
//(this to handle yanking the last line of a file)
if (contentType == ContentType.LINES && (text.length() == 0 || ! VimUtils.isNewLine(text.substring(text.length()-1)))) {
text += editorAdaptor.getConfiguration().getNewLine();
}
RegisterContent content = new StringRegisterContent(contentType, text);
editorAdaptor.getRegisterManager().getActiveRegister().setContent(content);
if (contentType == ContentType.LINES && NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
//if this is line-wise, move cursor to first line in selection but keep stickyColumn
int lineNo = editorAdaptor.getModelContent().getLineInformationOfOffset(range.getLeftBound().getModelOffset()).getNumber();
Position stickyPosition = editorAdaptor.getCursorService().stickyColumnAtViewLine(lineNo);
editorAdaptor.getCursorService().setPosition(stickyPosition, true);
}
else {
//move cursor to beginning of selection
editorAdaptor.getCursorService().setPosition(range.getLeftBound(), true);
}
}
| public static void doIt(EditorAdaptor editorAdaptor, TextRange range, ContentType contentType) {
String text = editorAdaptor.getModelContent().getText(range.getLeftBound().getModelOffset(), range.getModelLength());
//if we're expecting lines and this text doesn't end in a newline,
//manually append a newline to the end
//(this to handle yanking the last line of a file)
if (contentType == ContentType.LINES && (text.length() == 0 || ! VimUtils.isNewLine(text.substring(text.length()-1)))) {
text += editorAdaptor.getConfiguration().getNewLine();
}
RegisterContent content = new StringRegisterContent(contentType, text);
editorAdaptor.getRegisterManager().getActiveRegister().setContent(content);
if (contentType == ContentType.LINES && NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
//if this is line-wise, move cursor to first line in selection but keep stickyColumn
int lineNo = editorAdaptor.getModelContent().getLineInformationOfOffset(range.getLeftBound().getModelOffset()).getNumber();
Position stickyPosition = editorAdaptor.getCursorService().stickyColumnAtModelLine(lineNo);
editorAdaptor.getCursorService().setPosition(stickyPosition, true);
}
else {
//move cursor to beginning of selection
editorAdaptor.getCursorService().setPosition(range.getLeftBound(), true);
}
}
|
diff --git a/branches/sng/GeoBeagle/di/com/google/code/geobeagle/data/GeocacheFactory.java b/branches/sng/GeoBeagle/di/com/google/code/geobeagle/data/GeocacheFactory.java
index ab9acc69..2003546a 100644
--- a/branches/sng/GeoBeagle/di/com/google/code/geobeagle/data/GeocacheFactory.java
+++ b/branches/sng/GeoBeagle/di/com/google/code/geobeagle/data/GeocacheFactory.java
@@ -1,98 +1,100 @@
/*
** 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.code.geobeagle.data;
import com.google.code.geobeagle.data.GeocacheFactory.Source.SourceFactory;
import android.os.Parcel;
import android.os.Parcelable;
public class GeocacheFactory {
public static class CreateGeocacheFromParcel implements Parcelable.Creator<Geocache> {
private final GeocacheFromParcelFactory mGeocacheFromParcelFactory = new GeocacheFromParcelFactory(
new GeocacheFactory());
public Geocache createFromParcel(Parcel in) {
return mGeocacheFromParcelFactory.create(in);
}
public Geocache[] newArray(int size) {
return new Geocache[size];
}
}
public static enum Source {
GPX(0), MY_LOCATION(1), WEB_URL(2);
public static class SourceFactory {
private final Source mSources[] = new Source[values().length];
public SourceFactory() {
for (Source source : values())
mSources[source.mIx] = source;
}
public Source fromInt(int i) {
return mSources[i];
}
}
private final int mIx;
Source(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
public static enum Provider {
ATLAS_QUEST(0), GROUNDSPEAK(1), MY_LOCATION(-1);
private final int mIx;
Provider(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
private static SourceFactory mSourceFactory;
public GeocacheFactory() {
mSourceFactory = new SourceFactory();
}
public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName) {
if (id.length() < 2) {
// ID is missing for waypoints imported from the browser; create a
// new id
// from the time.
id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis());
}
+ if (name == null)
+ name = "";
return new Geocache(id, name, latitude, longitude, sourceType, sourceName);
}
public Source sourceFromInt(int sourceIx) {
return mSourceFactory.fromInt(sourceIx);
}
}
| true | true | public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName) {
if (id.length() < 2) {
// ID is missing for waypoints imported from the browser; create a
// new id
// from the time.
id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis());
}
return new Geocache(id, name, latitude, longitude, sourceType, sourceName);
}
| public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName) {
if (id.length() < 2) {
// ID is missing for waypoints imported from the browser; create a
// new id
// from the time.
id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis());
}
if (name == null)
name = "";
return new Geocache(id, name, latitude, longitude, sourceType, sourceName);
}
|
diff --git a/src/com/wolflink289/bukkit/worldregions/util/TimeUtil.java b/src/com/wolflink289/bukkit/worldregions/util/TimeUtil.java
index 475755a..35b53b2 100644
--- a/src/com/wolflink289/bukkit/worldregions/util/TimeUtil.java
+++ b/src/com/wolflink289/bukkit/worldregions/util/TimeUtil.java
@@ -1,140 +1,141 @@
package com.wolflink289.bukkit.worldregions.util;
public class TimeUtil {
// Constructor
private TimeUtil() {
}
// Methods
/**
* Convert ticks to a human readable HH:MM:SS time format.
*
* @param ticks the ticks to convert.
* @return a human readable time format.
*/
static public String ticksAsReadable(int ticks) {
int tc = (int) Math.floor(ticks / 20d);
int s = tc % 60;
int m = ((int) Math.floor(tc / 60d)) % 60;
int h = (int) Math.floor(tc / 60d / 60d);
if (h > 0) {
return pad(h, 1) + ":" + pad(m, 2) + ":" + pad(s, 2);
} else {
return pad(m, 1) + ":" + pad(s, 2);
}
}
/**
* Convert a human readable HH:MM:SS time format to ticks.
*
* @param hrtf the human readable time format.
* @return the time in ticks.
*/
static public int readableAsTicks(String hrtf) {
String[] split = hrtf.split(":");
int h = 0;
int m;
int s;
int i = 0;
if (split.length == 3) h = Integer.parseInt(split[i++]);
m = Integer.parseInt(split[i++]);
s = Integer.parseInt(split[i]);
return (h * 60 * 60 + m * 60 + s) * 20;
}
/**
* Convert ticks into the 24-hour time format.
*
* @param ticks the ticks to convert.
* @return the ticks in a 24-hour time format.
*/
static public String cticksAsTime(int ticks) {
int hours = (int) Math.floor(ticks / 1000d);
int mins = (int) Math.ceil((ticks % 1000) / 1000 * 60);
return pad(hours, 2) + ":" + pad(mins, 2);
}
/**
* Convert a time format into Minecraft day cycle ticks. <br>
* Supported formats:
* 15:00 (24 hour)
* 6:31PM (12 hour, requires (AM or PM))
* 16800 (ticks)
*
* @param str the string to convert.
* @return the time in ticks.
* @throws NumberFormatException
*/
static public int timeAsCticks(String str) {
// Ticks
try {
int ticks = Integer.parseInt(str);
if (ticks < 0 || ticks > 24000) throw new RuntimeException("Ticks range from 0 to 24000.");
return ticks;
} catch (NumberFormatException ex) {
// Ignore and continue
} catch (RuntimeException ex) {
throw new NumberFormatException(ex.getMessage());
}
// 12h
str = str.toLowerCase();
if (str.endsWith("am") || str.endsWith("pm")) {
boolean pm = str.endsWith("pm");
str = str.substring(0, str.length() - 2);
String[] split = str.split(":");
int hours = 0;
int mins = 0;
try {
hours = Integer.parseInt(split[0].trim());
mins = Integer.parseInt(split[1].trim());
} catch (Exception ex) {
throw new NumberFormatException("Invalid time.");
}
if (hours < 1 || hours > 12) throw new NumberFormatException("Hours in 12-hour time range from 1 to 12");
if (mins < 0 || mins > 59) throw new NumberFormatException("Minutes range from 0 to 59");
+ if (hours == 12) pm = !pm;
if (pm) hours += 12;
return (hours * 1000) + (1000 / 60 * mins);
} else {
// 24h
String[] split = str.split(":");
int hours = 0;
int mins = 0;
try {
hours = Integer.parseInt(split[0].trim());
mins = Integer.parseInt(split[1].trim());
} catch (Exception ex) {
throw new NumberFormatException("Invalid time.");
}
if (hours < 0 || hours > 23) throw new NumberFormatException("Hours in 24-hour time range from 0 to 23");
if (mins < 0 || mins > 59) throw new NumberFormatException("Minutes range from 0 to 59");
return (hours * 1000) + (1000 / 60 * mins);
}
}
// Utility in a utility
static private String pad(long number, int padding) {
String padded = String.valueOf(number);
while (padded.length() < padding) {
padded = "0" + padded;
}
return padded;
}
}
| true | true | static public int timeAsCticks(String str) {
// Ticks
try {
int ticks = Integer.parseInt(str);
if (ticks < 0 || ticks > 24000) throw new RuntimeException("Ticks range from 0 to 24000.");
return ticks;
} catch (NumberFormatException ex) {
// Ignore and continue
} catch (RuntimeException ex) {
throw new NumberFormatException(ex.getMessage());
}
// 12h
str = str.toLowerCase();
if (str.endsWith("am") || str.endsWith("pm")) {
boolean pm = str.endsWith("pm");
str = str.substring(0, str.length() - 2);
String[] split = str.split(":");
int hours = 0;
int mins = 0;
try {
hours = Integer.parseInt(split[0].trim());
mins = Integer.parseInt(split[1].trim());
} catch (Exception ex) {
throw new NumberFormatException("Invalid time.");
}
if (hours < 1 || hours > 12) throw new NumberFormatException("Hours in 12-hour time range from 1 to 12");
if (mins < 0 || mins > 59) throw new NumberFormatException("Minutes range from 0 to 59");
if (pm) hours += 12;
return (hours * 1000) + (1000 / 60 * mins);
} else {
// 24h
String[] split = str.split(":");
int hours = 0;
int mins = 0;
try {
hours = Integer.parseInt(split[0].trim());
mins = Integer.parseInt(split[1].trim());
} catch (Exception ex) {
throw new NumberFormatException("Invalid time.");
}
if (hours < 0 || hours > 23) throw new NumberFormatException("Hours in 24-hour time range from 0 to 23");
if (mins < 0 || mins > 59) throw new NumberFormatException("Minutes range from 0 to 59");
return (hours * 1000) + (1000 / 60 * mins);
}
}
| static public int timeAsCticks(String str) {
// Ticks
try {
int ticks = Integer.parseInt(str);
if (ticks < 0 || ticks > 24000) throw new RuntimeException("Ticks range from 0 to 24000.");
return ticks;
} catch (NumberFormatException ex) {
// Ignore and continue
} catch (RuntimeException ex) {
throw new NumberFormatException(ex.getMessage());
}
// 12h
str = str.toLowerCase();
if (str.endsWith("am") || str.endsWith("pm")) {
boolean pm = str.endsWith("pm");
str = str.substring(0, str.length() - 2);
String[] split = str.split(":");
int hours = 0;
int mins = 0;
try {
hours = Integer.parseInt(split[0].trim());
mins = Integer.parseInt(split[1].trim());
} catch (Exception ex) {
throw new NumberFormatException("Invalid time.");
}
if (hours < 1 || hours > 12) throw new NumberFormatException("Hours in 12-hour time range from 1 to 12");
if (mins < 0 || mins > 59) throw new NumberFormatException("Minutes range from 0 to 59");
if (hours == 12) pm = !pm;
if (pm) hours += 12;
return (hours * 1000) + (1000 / 60 * mins);
} else {
// 24h
String[] split = str.split(":");
int hours = 0;
int mins = 0;
try {
hours = Integer.parseInt(split[0].trim());
mins = Integer.parseInt(split[1].trim());
} catch (Exception ex) {
throw new NumberFormatException("Invalid time.");
}
if (hours < 0 || hours > 23) throw new NumberFormatException("Hours in 24-hour time range from 0 to 23");
if (mins < 0 || mins > 59) throw new NumberFormatException("Minutes range from 0 to 59");
return (hours * 1000) + (1000 / 60 * mins);
}
}
|
diff --git a/src/main/java/me/captainbern/animationlib/utils/refs/PacketRef.java b/src/main/java/me/captainbern/animationlib/utils/refs/PacketRef.java
index b11720e..bfc94f9 100644
--- a/src/main/java/me/captainbern/animationlib/utils/refs/PacketRef.java
+++ b/src/main/java/me/captainbern/animationlib/utils/refs/PacketRef.java
@@ -1,15 +1,15 @@
package me.captainbern.animationlib.utils.refs;
import com.google.common.collect.BiMap;
import me.captainbern.animationlib.reflection.ClassTemplate;
import me.captainbern.animationlib.reflection.NMSClassTemplate;
public class PacketRef {
public static final ClassTemplate<Object> protocol = NMSClassTemplate.create("EnumProtocol");
public static BiMap getServerPacketRegistry(){
- return (BiMap) protocol.getField("h").get(null);
+ return (BiMap) protocol.getField("h").get(protocol.newInstance());
}
}
| true | true | public static BiMap getServerPacketRegistry(){
return (BiMap) protocol.getField("h").get(null);
}
| public static BiMap getServerPacketRegistry(){
return (BiMap) protocol.getField("h").get(protocol.newInstance());
}
|
diff --git a/src/main/java/net/countercraft/movecraft/utils/MapUpdateManager.java b/src/main/java/net/countercraft/movecraft/utils/MapUpdateManager.java
index 5bb12d8..de94fdf 100644
--- a/src/main/java/net/countercraft/movecraft/utils/MapUpdateManager.java
+++ b/src/main/java/net/countercraft/movecraft/utils/MapUpdateManager.java
@@ -1,517 +1,517 @@
/*
* This file is part of Movecraft.
*
* Movecraft 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.
*
* Movecraft 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 Movecraft. If not, see <http://www.gnu.org/licenses/>.
*/
package net.countercraft.movecraft.utils;
import net.countercraft.movecraft.Movecraft;
import net.countercraft.movecraft.config.Settings;
import net.countercraft.movecraft.craft.Craft;
import net.countercraft.movecraft.craft.CraftManager;
import net.countercraft.movecraft.items.StorageChestItem;
import net.countercraft.movecraft.localisation.I18nSupport;
import net.countercraft.movecraft.utils.datastructures.InventoryTransferHolder;
import net.countercraft.movecraft.utils.datastructures.SignTransferHolder;
import net.countercraft.movecraft.utils.datastructures.StorageCrateTransferHolder;
import net.countercraft.movecraft.utils.datastructures.TransferData;
import net.minecraft.server.v1_7_R1.ChunkCoordIntPair;
import net.minecraft.server.v1_7_R1.Material;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.v1_7_R1.CraftChunk;
import org.bukkit.craftbukkit.v1_7_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_7_R1.util.CraftMagicNumbers;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import org.testng.collections.Lists;
import java.util.*;
import java.util.logging.Level;
public class MapUpdateManager extends BukkitRunnable {
private final HashMap<World, ArrayList<MapUpdateCommand>> updates = new HashMap<World, ArrayList<MapUpdateCommand>>();
private final HashMap<World, ArrayList<EntityUpdateCommand>> entityUpdates = new HashMap<World, ArrayList<EntityUpdateCommand>>();
private MapUpdateManager() {
}
public static MapUpdateManager getInstance() {
return MapUpdateManagerHolder.INSTANCE;
}
private static class MapUpdateManagerHolder {
private static final MapUpdateManager INSTANCE = new MapUpdateManager();
}
private void updateBlock(MapUpdateCommand m, ArrayList<Chunk> chunkList, World w, Map<MovecraftLocation, TransferData> dataMap, Set<net.minecraft.server.v1_7_R1.Chunk> chunks, Set<Chunk> cmChunks, boolean placeDispensers) {
MovecraftLocation workingL = m.getNewBlockLocation();
int x = workingL.getX();
int y = workingL.getY();
int z = workingL.getZ();
Chunk chunk=null;
// Calculate chunk if necessary, check list of chunks already loaded first
boolean foundChunk=false;
for (Chunk testChunk : chunkList) {
int sx=x>>4;
int sz=z>>4;
if((testChunk.getX()==sx)&&(testChunk.getZ()==sz)) {
foundChunk=true;
chunk=testChunk;
}
}
if(!foundChunk) {
chunk = w.getBlockAt( x, y, z ).getChunk();
chunkList.add(chunk);
}
net.minecraft.server.v1_7_R1.Chunk c = null;
Chunk cmC = null;
if(Settings.CompatibilityMode) {
cmC = chunk;
} else {
c = ( ( CraftChunk ) chunk ).getHandle();
}
//get the inner-chunk index of the block to change
//modify the block in the chunk
int newTypeID = m.getTypeID();
if(newTypeID==23 && !placeDispensers) {
newTypeID=1;
}
TransferData transferData = dataMap.get( workingL );
byte data;
if ( transferData != null ) {
data = transferData.getData();
} else {
data = 0;
}
int origType=w.getBlockAt( x, y, z ).getTypeId();
byte origData=w.getBlockAt( x, y, z ).getData();
boolean success = false;
//don't blank out block if it's already air, or if blocktype will not be changed
if(Settings.CompatibilityMode) {
if((origType!=0)&&(origType!=newTypeID)) {
w.getBlockAt( x, y, z ).setTypeIdAndData( 0, (byte) 0, false );
}
if(origType!=newTypeID || origData!=data) {
w.getBlockAt( x, y, z ).setTypeIdAndData( newTypeID, data, false );
}
if ( !cmChunks.contains( cmC ) ) {
cmChunks.add( cmC );
}
} else {
if((origType!=0)&&(origType!=newTypeID)) {
c.a( x & 15, y, z & 15, CraftMagicNumbers.getBlock(0), 0 );
}
if(origType!=newTypeID || origData!=data) {
success = c.a( x & 15, y, z & 15, CraftMagicNumbers.getBlock(newTypeID), data );
} else {
success=true;
}
if ( !success ) {
w.getBlockAt( x, y, z ).setTypeIdAndData( newTypeID, data, false );
}
if ( !chunks.contains( c ) ) {
chunks.add( c );
}
}
}
public void run() {
if ( updates.isEmpty() ) return;
long startTime=System.currentTimeMillis();
for ( World w : updates.keySet() ) {
if ( w != null ) {
List<MapUpdateCommand> updatesInWorld = updates.get( w );
List<EntityUpdateCommand> entityUpdatesInWorld = entityUpdates.get( w );
Map<MovecraftLocation, List<EntityUpdateCommand>> entityMap = new HashMap<MovecraftLocation, List<EntityUpdateCommand>>();
Map<MovecraftLocation, TransferData> dataMap = new HashMap<MovecraftLocation, TransferData>();
Set<net.minecraft.server.v1_7_R1.Chunk> chunks = null;
Set<Chunk> cmChunks = null;
if(Settings.CompatibilityMode) {
cmChunks = new HashSet<Chunk>();
} else {
chunks = new HashSet<net.minecraft.server.v1_7_R1.Chunk>();
}
ArrayList<Player> unupdatedPlayers=new ArrayList<Player>(Arrays.asList(Movecraft.getInstance().getServer().getOnlinePlayers()));
// Preprocessing
for ( MapUpdateCommand c : updatesInWorld ) {
MovecraftLocation l;
if(c!=null)
l = c.getOldBlockLocation();
else
l = null;
if ( l != null ) {
TransferData blockDataPacket = getBlockDataPacket( w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState(), c.getRotation() );
if ( blockDataPacket != null ) {
dataMap.put( c.getNewBlockLocation(), blockDataPacket );
}
//remove dispensers and replace them with stone blocks to prevent firing during ship reconstruction
if(w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getTypeId()==23) {
w.getBlockAt( l.getX(), l.getY(), l.getZ() ).setTypeIdAndData( 1, (byte) 0, false );
}
}
}
// track the blocks that entities will be standing on to move them smoothly with the craft
if(entityUpdatesInWorld!=null) {
for( EntityUpdateCommand i : entityUpdatesInWorld) {
if(i!=null) {
MovecraftLocation entityLoc=new MovecraftLocation(i.getNewLocation().getBlockX(), i.getNewLocation().getBlockY()-1, i.getNewLocation().getBlockZ());
if(!entityMap.containsKey(entityLoc)) {
List<EntityUpdateCommand> entUpdateList=new ArrayList<EntityUpdateCommand>();
entUpdateList.add(i);
entityMap.put(entityLoc, entUpdateList);
} else {
List<EntityUpdateCommand> entUpdateList=entityMap.get(entityLoc);
entUpdateList.add(i);
}
}
}
}
ArrayList<Chunk> chunkList = new ArrayList<Chunk>();
boolean isFirstChunk=true;
final int[] fragileBlocks = new int[]{ 26, 29, 33, 34, 50, 52, 54, 55, 63, 64, 65, 68, 69, 70, 71, 72, 75, 76, 77, 93, 94, 96, 131, 132, 143, 147, 148, 149, 150, 151, 171, 323, 324, 330, 331, 356, 404 };
Arrays.sort(fragileBlocks);
// Perform core block updates, don't do "fragiles" yet. Don't do Dispensers yet either
for ( MapUpdateCommand m : updatesInWorld ) {
if(m!=null) {
boolean isFragile=(Arrays.binarySearch(fragileBlocks,m.getTypeID())>=0);
if(!isFragile) {
// a TypeID less than 0 indicates an explosion
if(m.getTypeID()<0) {
float explosionPower=m.getTypeID();
explosionPower=0.0F-explosionPower/100.0F;
- w.createExplosion(m.getNewBlockLocation().getX(), m.getNewBlockLocation().getY(), m.getNewBlockLocation().getZ(), explosionPower);
+ w.createExplosion(m.getNewBlockLocation().getX()+0.5, m.getNewBlockLocation().getY()+0.5, m.getNewBlockLocation().getZ()+0.5, explosionPower);
} else {
updateBlock(m, chunkList, w, dataMap, chunks, cmChunks, false);
}
}
// if the block you just updated had any entities on it, move them. If they are moving, add in their motion to the craft motion
if( entityMap.containsKey(m.getNewBlockLocation()) ) {
List<EntityUpdateCommand> mapUpdateList=entityMap.get(m.getNewBlockLocation());
for(EntityUpdateCommand entityUpdate : mapUpdateList) {
Entity entity=entityUpdate.getEntity();
Vector pVel=new Vector(entity.getVelocity().getX(),0.0,entity.getVelocity().getZ());
if( pVel.getX()==0.0 && entity.getVelocity().getZ()==0.0 ) {
Location newLoc=entityUpdate.getNewLocation();
// if they have gone through the floor, move them up one block
double decimalY=newLoc.getY()-Math.floor(newLoc.getY());
if(decimalY>0.40) {
newLoc.setY( Math.ceil( newLoc.getY() ) );
}
entity.teleport(entityUpdate.getNewLocation());
} else {
Location craftMove=entityUpdate.getNewLocation().subtract(entityUpdate.getOldLocation());
entity.teleport(entity.getLocation().add(craftMove));
}
entity.setVelocity(pVel);
}
entityMap.remove(m.getNewBlockLocation());
}
}
}
// Fix redstone and other "fragiles"
for ( MapUpdateCommand i : updatesInWorld ) {
if(i!=null) {
boolean isFragile=(Arrays.binarySearch(fragileBlocks,i.getTypeID())>=0);
if(isFragile) {
updateBlock(i, chunkList, w, dataMap, chunks, cmChunks, false);
}
}
}
for ( MapUpdateCommand i : updatesInWorld ) {
if(i!=null) {
// Put Dispensers back in now that the ship is reconstructed
if(i.getTypeID()==23) {
updateBlock(i, chunkList, w, dataMap, chunks, cmChunks, true);
}
// if a bed was moved, check to see if any spawn points need to be updated
if(i.getTypeID()==26) {
Iterator<Player> iter=unupdatedPlayers.iterator();
while (iter.hasNext()) {
Player p=iter.next();
if(p!=null) {
if(p.getBedSpawnLocation()!=null) {
MovecraftLocation spawnLoc=MathUtils.bukkit2MovecraftLoc( p.getBedSpawnLocation() );
// is the spawn point within 1 block of where the bed used to be?
boolean foundSpawn=false;
if(i.getOldBlockLocation().getX()-spawnLoc.getX()<=1 && i.getOldBlockLocation().getX()-spawnLoc.getX()>=-1) {
if(i.getOldBlockLocation().getZ()-spawnLoc.getZ()<=1 && i.getOldBlockLocation().getZ()-spawnLoc.getZ()>=-1) {
foundSpawn=true;
}
}
if(foundSpawn) {
Location newSpawnLoc = new Location( w, i.getNewBlockLocation().getX(), i.getNewBlockLocation().getY(), i.getNewBlockLocation().getZ() );
p.setBedSpawnLocation(newSpawnLoc, true);
iter.remove();
}
}
}
}
}
}
}
// Restore block specific information
for ( MovecraftLocation l : dataMap.keySet() ) {
try {
TransferData transferData = dataMap.get( l );
if ( transferData instanceof SignTransferHolder ) {
SignTransferHolder signData = ( SignTransferHolder ) transferData;
Sign sign = ( Sign ) w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState();
for ( int i = 0; i < signData.getLines().length; i++ ) {
sign.setLine( i, signData.getLines()[i] );
}
sign.update( true );
} else if ( transferData instanceof StorageCrateTransferHolder ) {
Inventory inventory = Bukkit.createInventory( null, 27, String.format( I18nSupport.getInternationalisedString( "Item - Storage Crate name" ) ) );
inventory.setContents( ( ( StorageCrateTransferHolder ) transferData ).getInvetory() );
StorageChestItem.setInventoryOfCrateAtLocation( inventory, l, w );
} else if ( transferData instanceof InventoryTransferHolder ) {
InventoryTransferHolder invData = ( InventoryTransferHolder ) transferData;
InventoryHolder inventoryHolder = ( InventoryHolder ) w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState();
inventoryHolder.getInventory().setContents( invData.getInvetory() );
}
w.getBlockAt( l.getX(), l.getY(), l.getZ() ).setData( transferData.getData() );
} catch ( Exception e ) {
Movecraft.getInstance().getLogger().log( Level.SEVERE, "Severe error in map updater" );
}
}
if(Settings.CompatibilityMode) {
// todo: lighting stuff here
} else {
for ( net.minecraft.server.v1_7_R1.Chunk c : chunks ) {
c.initLighting();
ChunkCoordIntPair ccip = new ChunkCoordIntPair( c.locX, c.locZ ); // changed from c.x to c.locX and c.locZ
for ( Player p : w.getPlayers() ) {
List<ChunkCoordIntPair> chunkCoordIntPairQueue = ( List<ChunkCoordIntPair> ) ( ( CraftPlayer ) p ).getHandle().chunkCoordIntPairQueue;
if ( !chunkCoordIntPairQueue.contains( ccip ) )
chunkCoordIntPairQueue.add( ccip );
}
}
}
if(CraftManager.getInstance().getCraftsInWorld(w)!=null) {
// clean up dropped items that are fragile block types on or below all crafts. They are likely garbage left on the ground from the block movements
for(Craft cleanCraft : CraftManager.getInstance().getCraftsInWorld(w)) {
Iterator<Entity> i=w.getEntities().iterator();
while (i.hasNext()) {
Entity eTest=i.next();
if (eTest.getTicksLived()<100 && eTest.getType()==org.bukkit.entity.EntityType.DROPPED_ITEM) {
int adjX=eTest.getLocation().getBlockX()-cleanCraft.getMinX();
int adjZ=eTest.getLocation().getBlockZ()-cleanCraft.getMinZ();
int[][][] hb=cleanCraft.getHitBox();
if(adjX>=-1 && adjX<=hb.length) {
if(adjX<0) {
adjX=0;
}
if(adjX>=hb.length) {
adjX=hb.length-1;
}
if(adjZ>-1 && adjZ<=hb[adjX].length) {
Item it=(Item)eTest;
if(Arrays.binarySearch(fragileBlocks,it.getItemStack().getTypeId())>=0) {
eTest.remove();
}
}
}
}
}
}
// and set all crafts that were updated to not processing, and move any spawn points that were on a block that was moved
for ( MapUpdateCommand c : updatesInWorld ) {
if(c!=null) {
Craft craft=c.getCraft();
if(craft!=null) {
if(!craft.isNotProcessing()) {
craft.setProcessing(false);
}
}
}
}
}
}
}
updates.clear();
entityUpdates.clear();
long endTime=System.currentTimeMillis();
// Movecraft.getInstance().getLogger().log( Level.INFO, "Map update took (ms): "+(endTime-startTime));
}
public boolean addWorldUpdate( World w, MapUpdateCommand[] mapUpdates, EntityUpdateCommand[] eUpdates) {
ArrayList<MapUpdateCommand> get = updates.get( w );
if ( get != null ) {
updates.remove( w );
} else {
get = new ArrayList<MapUpdateCommand>();
}
ArrayList<MapUpdateCommand> tempSet = new ArrayList<MapUpdateCommand>();
for ( MapUpdateCommand m : mapUpdates ) {
if ( setContainsConflict( get, m ) ) {
return true;
} else {
tempSet.add( m );
}
}
get.addAll( tempSet );
updates.put( w, get );
//now do entity updates
if(eUpdates!=null) {
ArrayList<EntityUpdateCommand> eGet = entityUpdates.get( w );
if ( eGet != null ) {
entityUpdates.remove( w );
} else {
eGet = new ArrayList<EntityUpdateCommand>();
}
ArrayList<EntityUpdateCommand> tempEUpdates = new ArrayList<EntityUpdateCommand>();
for(EntityUpdateCommand e : eUpdates) {
tempEUpdates.add(e);
}
eGet.addAll( tempEUpdates );
entityUpdates.put(w, eGet);
}
return false;
}
private boolean setContainsConflict( ArrayList<MapUpdateCommand> set, MapUpdateCommand c ) {
for ( MapUpdateCommand command : set ) {
if ( command.getNewBlockLocation().equals( c.getNewBlockLocation() ) ) {
return true;
}
}
return false;
}
private boolean arrayContains( int[] oA, int o ) {
for ( int testO : oA ) {
if ( testO == o ) {
return true;
}
}
return false;
}
private TransferData getBlockDataPacket( BlockState s, Rotation r ) {
if ( BlockUtils.blockHasNoData( s.getTypeId() ) ) {
return null;
}
byte data = s.getRawData();
if ( BlockUtils.blockRequiresRotation( s.getTypeId() ) && r != Rotation.NONE ) {
data = BlockUtils.rotate( data, s.getTypeId(), r );
}
switch ( s.getTypeId() ) {
case 23:
case 54:
case 61:
case 62:
case 117:
// Data and Inventory
if(( ( InventoryHolder ) s ).getInventory().getSize()==54) {
Movecraft.getInstance().getLogger().log( Level.SEVERE, "ERROR: Double chest detected. This is not supported." );
throw new IllegalArgumentException("INVALID BLOCK");
}
ItemStack[] contents = ( ( InventoryHolder ) s ).getInventory().getContents().clone();
( ( InventoryHolder ) s ).getInventory().clear();
return new InventoryTransferHolder( data, contents );
case 68:
case 63:
// Data and sign lines
return new SignTransferHolder( data, ( ( Sign ) s ).getLines() );
case 33:
MovecraftLocation l = MathUtils.bukkit2MovecraftLoc( s.getLocation() );
Inventory i = StorageChestItem.getInventoryOfCrateAtLocation( l, s.getWorld() );
if ( i != null ) {
StorageChestItem.removeInventoryAtLocation( s.getWorld(), l );
return new StorageCrateTransferHolder( data, i.getContents() );
} else {
return new TransferData( data );
}
default:
return new TransferData( data );
}
}
}
| true | true | public void run() {
if ( updates.isEmpty() ) return;
long startTime=System.currentTimeMillis();
for ( World w : updates.keySet() ) {
if ( w != null ) {
List<MapUpdateCommand> updatesInWorld = updates.get( w );
List<EntityUpdateCommand> entityUpdatesInWorld = entityUpdates.get( w );
Map<MovecraftLocation, List<EntityUpdateCommand>> entityMap = new HashMap<MovecraftLocation, List<EntityUpdateCommand>>();
Map<MovecraftLocation, TransferData> dataMap = new HashMap<MovecraftLocation, TransferData>();
Set<net.minecraft.server.v1_7_R1.Chunk> chunks = null;
Set<Chunk> cmChunks = null;
if(Settings.CompatibilityMode) {
cmChunks = new HashSet<Chunk>();
} else {
chunks = new HashSet<net.minecraft.server.v1_7_R1.Chunk>();
}
ArrayList<Player> unupdatedPlayers=new ArrayList<Player>(Arrays.asList(Movecraft.getInstance().getServer().getOnlinePlayers()));
// Preprocessing
for ( MapUpdateCommand c : updatesInWorld ) {
MovecraftLocation l;
if(c!=null)
l = c.getOldBlockLocation();
else
l = null;
if ( l != null ) {
TransferData blockDataPacket = getBlockDataPacket( w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState(), c.getRotation() );
if ( blockDataPacket != null ) {
dataMap.put( c.getNewBlockLocation(), blockDataPacket );
}
//remove dispensers and replace them with stone blocks to prevent firing during ship reconstruction
if(w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getTypeId()==23) {
w.getBlockAt( l.getX(), l.getY(), l.getZ() ).setTypeIdAndData( 1, (byte) 0, false );
}
}
}
// track the blocks that entities will be standing on to move them smoothly with the craft
if(entityUpdatesInWorld!=null) {
for( EntityUpdateCommand i : entityUpdatesInWorld) {
if(i!=null) {
MovecraftLocation entityLoc=new MovecraftLocation(i.getNewLocation().getBlockX(), i.getNewLocation().getBlockY()-1, i.getNewLocation().getBlockZ());
if(!entityMap.containsKey(entityLoc)) {
List<EntityUpdateCommand> entUpdateList=new ArrayList<EntityUpdateCommand>();
entUpdateList.add(i);
entityMap.put(entityLoc, entUpdateList);
} else {
List<EntityUpdateCommand> entUpdateList=entityMap.get(entityLoc);
entUpdateList.add(i);
}
}
}
}
ArrayList<Chunk> chunkList = new ArrayList<Chunk>();
boolean isFirstChunk=true;
final int[] fragileBlocks = new int[]{ 26, 29, 33, 34, 50, 52, 54, 55, 63, 64, 65, 68, 69, 70, 71, 72, 75, 76, 77, 93, 94, 96, 131, 132, 143, 147, 148, 149, 150, 151, 171, 323, 324, 330, 331, 356, 404 };
Arrays.sort(fragileBlocks);
// Perform core block updates, don't do "fragiles" yet. Don't do Dispensers yet either
for ( MapUpdateCommand m : updatesInWorld ) {
if(m!=null) {
boolean isFragile=(Arrays.binarySearch(fragileBlocks,m.getTypeID())>=0);
if(!isFragile) {
// a TypeID less than 0 indicates an explosion
if(m.getTypeID()<0) {
float explosionPower=m.getTypeID();
explosionPower=0.0F-explosionPower/100.0F;
w.createExplosion(m.getNewBlockLocation().getX(), m.getNewBlockLocation().getY(), m.getNewBlockLocation().getZ(), explosionPower);
} else {
updateBlock(m, chunkList, w, dataMap, chunks, cmChunks, false);
}
}
// if the block you just updated had any entities on it, move them. If they are moving, add in their motion to the craft motion
if( entityMap.containsKey(m.getNewBlockLocation()) ) {
List<EntityUpdateCommand> mapUpdateList=entityMap.get(m.getNewBlockLocation());
for(EntityUpdateCommand entityUpdate : mapUpdateList) {
Entity entity=entityUpdate.getEntity();
Vector pVel=new Vector(entity.getVelocity().getX(),0.0,entity.getVelocity().getZ());
if( pVel.getX()==0.0 && entity.getVelocity().getZ()==0.0 ) {
Location newLoc=entityUpdate.getNewLocation();
// if they have gone through the floor, move them up one block
double decimalY=newLoc.getY()-Math.floor(newLoc.getY());
if(decimalY>0.40) {
newLoc.setY( Math.ceil( newLoc.getY() ) );
}
entity.teleport(entityUpdate.getNewLocation());
} else {
Location craftMove=entityUpdate.getNewLocation().subtract(entityUpdate.getOldLocation());
entity.teleport(entity.getLocation().add(craftMove));
}
entity.setVelocity(pVel);
}
entityMap.remove(m.getNewBlockLocation());
}
}
}
// Fix redstone and other "fragiles"
for ( MapUpdateCommand i : updatesInWorld ) {
if(i!=null) {
boolean isFragile=(Arrays.binarySearch(fragileBlocks,i.getTypeID())>=0);
if(isFragile) {
updateBlock(i, chunkList, w, dataMap, chunks, cmChunks, false);
}
}
}
for ( MapUpdateCommand i : updatesInWorld ) {
if(i!=null) {
// Put Dispensers back in now that the ship is reconstructed
if(i.getTypeID()==23) {
updateBlock(i, chunkList, w, dataMap, chunks, cmChunks, true);
}
// if a bed was moved, check to see if any spawn points need to be updated
if(i.getTypeID()==26) {
Iterator<Player> iter=unupdatedPlayers.iterator();
while (iter.hasNext()) {
Player p=iter.next();
if(p!=null) {
if(p.getBedSpawnLocation()!=null) {
MovecraftLocation spawnLoc=MathUtils.bukkit2MovecraftLoc( p.getBedSpawnLocation() );
// is the spawn point within 1 block of where the bed used to be?
boolean foundSpawn=false;
if(i.getOldBlockLocation().getX()-spawnLoc.getX()<=1 && i.getOldBlockLocation().getX()-spawnLoc.getX()>=-1) {
if(i.getOldBlockLocation().getZ()-spawnLoc.getZ()<=1 && i.getOldBlockLocation().getZ()-spawnLoc.getZ()>=-1) {
foundSpawn=true;
}
}
if(foundSpawn) {
Location newSpawnLoc = new Location( w, i.getNewBlockLocation().getX(), i.getNewBlockLocation().getY(), i.getNewBlockLocation().getZ() );
p.setBedSpawnLocation(newSpawnLoc, true);
iter.remove();
}
}
}
}
}
}
}
// Restore block specific information
for ( MovecraftLocation l : dataMap.keySet() ) {
try {
TransferData transferData = dataMap.get( l );
if ( transferData instanceof SignTransferHolder ) {
SignTransferHolder signData = ( SignTransferHolder ) transferData;
Sign sign = ( Sign ) w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState();
for ( int i = 0; i < signData.getLines().length; i++ ) {
sign.setLine( i, signData.getLines()[i] );
}
sign.update( true );
} else if ( transferData instanceof StorageCrateTransferHolder ) {
Inventory inventory = Bukkit.createInventory( null, 27, String.format( I18nSupport.getInternationalisedString( "Item - Storage Crate name" ) ) );
inventory.setContents( ( ( StorageCrateTransferHolder ) transferData ).getInvetory() );
StorageChestItem.setInventoryOfCrateAtLocation( inventory, l, w );
} else if ( transferData instanceof InventoryTransferHolder ) {
InventoryTransferHolder invData = ( InventoryTransferHolder ) transferData;
InventoryHolder inventoryHolder = ( InventoryHolder ) w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState();
inventoryHolder.getInventory().setContents( invData.getInvetory() );
}
w.getBlockAt( l.getX(), l.getY(), l.getZ() ).setData( transferData.getData() );
} catch ( Exception e ) {
Movecraft.getInstance().getLogger().log( Level.SEVERE, "Severe error in map updater" );
}
}
if(Settings.CompatibilityMode) {
// todo: lighting stuff here
} else {
for ( net.minecraft.server.v1_7_R1.Chunk c : chunks ) {
c.initLighting();
ChunkCoordIntPair ccip = new ChunkCoordIntPair( c.locX, c.locZ ); // changed from c.x to c.locX and c.locZ
for ( Player p : w.getPlayers() ) {
List<ChunkCoordIntPair> chunkCoordIntPairQueue = ( List<ChunkCoordIntPair> ) ( ( CraftPlayer ) p ).getHandle().chunkCoordIntPairQueue;
if ( !chunkCoordIntPairQueue.contains( ccip ) )
chunkCoordIntPairQueue.add( ccip );
}
}
}
if(CraftManager.getInstance().getCraftsInWorld(w)!=null) {
// clean up dropped items that are fragile block types on or below all crafts. They are likely garbage left on the ground from the block movements
for(Craft cleanCraft : CraftManager.getInstance().getCraftsInWorld(w)) {
Iterator<Entity> i=w.getEntities().iterator();
while (i.hasNext()) {
Entity eTest=i.next();
if (eTest.getTicksLived()<100 && eTest.getType()==org.bukkit.entity.EntityType.DROPPED_ITEM) {
int adjX=eTest.getLocation().getBlockX()-cleanCraft.getMinX();
int adjZ=eTest.getLocation().getBlockZ()-cleanCraft.getMinZ();
int[][][] hb=cleanCraft.getHitBox();
if(adjX>=-1 && adjX<=hb.length) {
if(adjX<0) {
adjX=0;
}
if(adjX>=hb.length) {
adjX=hb.length-1;
}
if(adjZ>-1 && adjZ<=hb[adjX].length) {
Item it=(Item)eTest;
if(Arrays.binarySearch(fragileBlocks,it.getItemStack().getTypeId())>=0) {
eTest.remove();
}
}
}
}
}
}
// and set all crafts that were updated to not processing, and move any spawn points that were on a block that was moved
for ( MapUpdateCommand c : updatesInWorld ) {
if(c!=null) {
Craft craft=c.getCraft();
if(craft!=null) {
if(!craft.isNotProcessing()) {
craft.setProcessing(false);
}
}
}
}
}
}
}
updates.clear();
entityUpdates.clear();
long endTime=System.currentTimeMillis();
// Movecraft.getInstance().getLogger().log( Level.INFO, "Map update took (ms): "+(endTime-startTime));
}
| public void run() {
if ( updates.isEmpty() ) return;
long startTime=System.currentTimeMillis();
for ( World w : updates.keySet() ) {
if ( w != null ) {
List<MapUpdateCommand> updatesInWorld = updates.get( w );
List<EntityUpdateCommand> entityUpdatesInWorld = entityUpdates.get( w );
Map<MovecraftLocation, List<EntityUpdateCommand>> entityMap = new HashMap<MovecraftLocation, List<EntityUpdateCommand>>();
Map<MovecraftLocation, TransferData> dataMap = new HashMap<MovecraftLocation, TransferData>();
Set<net.minecraft.server.v1_7_R1.Chunk> chunks = null;
Set<Chunk> cmChunks = null;
if(Settings.CompatibilityMode) {
cmChunks = new HashSet<Chunk>();
} else {
chunks = new HashSet<net.minecraft.server.v1_7_R1.Chunk>();
}
ArrayList<Player> unupdatedPlayers=new ArrayList<Player>(Arrays.asList(Movecraft.getInstance().getServer().getOnlinePlayers()));
// Preprocessing
for ( MapUpdateCommand c : updatesInWorld ) {
MovecraftLocation l;
if(c!=null)
l = c.getOldBlockLocation();
else
l = null;
if ( l != null ) {
TransferData blockDataPacket = getBlockDataPacket( w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState(), c.getRotation() );
if ( blockDataPacket != null ) {
dataMap.put( c.getNewBlockLocation(), blockDataPacket );
}
//remove dispensers and replace them with stone blocks to prevent firing during ship reconstruction
if(w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getTypeId()==23) {
w.getBlockAt( l.getX(), l.getY(), l.getZ() ).setTypeIdAndData( 1, (byte) 0, false );
}
}
}
// track the blocks that entities will be standing on to move them smoothly with the craft
if(entityUpdatesInWorld!=null) {
for( EntityUpdateCommand i : entityUpdatesInWorld) {
if(i!=null) {
MovecraftLocation entityLoc=new MovecraftLocation(i.getNewLocation().getBlockX(), i.getNewLocation().getBlockY()-1, i.getNewLocation().getBlockZ());
if(!entityMap.containsKey(entityLoc)) {
List<EntityUpdateCommand> entUpdateList=new ArrayList<EntityUpdateCommand>();
entUpdateList.add(i);
entityMap.put(entityLoc, entUpdateList);
} else {
List<EntityUpdateCommand> entUpdateList=entityMap.get(entityLoc);
entUpdateList.add(i);
}
}
}
}
ArrayList<Chunk> chunkList = new ArrayList<Chunk>();
boolean isFirstChunk=true;
final int[] fragileBlocks = new int[]{ 26, 29, 33, 34, 50, 52, 54, 55, 63, 64, 65, 68, 69, 70, 71, 72, 75, 76, 77, 93, 94, 96, 131, 132, 143, 147, 148, 149, 150, 151, 171, 323, 324, 330, 331, 356, 404 };
Arrays.sort(fragileBlocks);
// Perform core block updates, don't do "fragiles" yet. Don't do Dispensers yet either
for ( MapUpdateCommand m : updatesInWorld ) {
if(m!=null) {
boolean isFragile=(Arrays.binarySearch(fragileBlocks,m.getTypeID())>=0);
if(!isFragile) {
// a TypeID less than 0 indicates an explosion
if(m.getTypeID()<0) {
float explosionPower=m.getTypeID();
explosionPower=0.0F-explosionPower/100.0F;
w.createExplosion(m.getNewBlockLocation().getX()+0.5, m.getNewBlockLocation().getY()+0.5, m.getNewBlockLocation().getZ()+0.5, explosionPower);
} else {
updateBlock(m, chunkList, w, dataMap, chunks, cmChunks, false);
}
}
// if the block you just updated had any entities on it, move them. If they are moving, add in their motion to the craft motion
if( entityMap.containsKey(m.getNewBlockLocation()) ) {
List<EntityUpdateCommand> mapUpdateList=entityMap.get(m.getNewBlockLocation());
for(EntityUpdateCommand entityUpdate : mapUpdateList) {
Entity entity=entityUpdate.getEntity();
Vector pVel=new Vector(entity.getVelocity().getX(),0.0,entity.getVelocity().getZ());
if( pVel.getX()==0.0 && entity.getVelocity().getZ()==0.0 ) {
Location newLoc=entityUpdate.getNewLocation();
// if they have gone through the floor, move them up one block
double decimalY=newLoc.getY()-Math.floor(newLoc.getY());
if(decimalY>0.40) {
newLoc.setY( Math.ceil( newLoc.getY() ) );
}
entity.teleport(entityUpdate.getNewLocation());
} else {
Location craftMove=entityUpdate.getNewLocation().subtract(entityUpdate.getOldLocation());
entity.teleport(entity.getLocation().add(craftMove));
}
entity.setVelocity(pVel);
}
entityMap.remove(m.getNewBlockLocation());
}
}
}
// Fix redstone and other "fragiles"
for ( MapUpdateCommand i : updatesInWorld ) {
if(i!=null) {
boolean isFragile=(Arrays.binarySearch(fragileBlocks,i.getTypeID())>=0);
if(isFragile) {
updateBlock(i, chunkList, w, dataMap, chunks, cmChunks, false);
}
}
}
for ( MapUpdateCommand i : updatesInWorld ) {
if(i!=null) {
// Put Dispensers back in now that the ship is reconstructed
if(i.getTypeID()==23) {
updateBlock(i, chunkList, w, dataMap, chunks, cmChunks, true);
}
// if a bed was moved, check to see if any spawn points need to be updated
if(i.getTypeID()==26) {
Iterator<Player> iter=unupdatedPlayers.iterator();
while (iter.hasNext()) {
Player p=iter.next();
if(p!=null) {
if(p.getBedSpawnLocation()!=null) {
MovecraftLocation spawnLoc=MathUtils.bukkit2MovecraftLoc( p.getBedSpawnLocation() );
// is the spawn point within 1 block of where the bed used to be?
boolean foundSpawn=false;
if(i.getOldBlockLocation().getX()-spawnLoc.getX()<=1 && i.getOldBlockLocation().getX()-spawnLoc.getX()>=-1) {
if(i.getOldBlockLocation().getZ()-spawnLoc.getZ()<=1 && i.getOldBlockLocation().getZ()-spawnLoc.getZ()>=-1) {
foundSpawn=true;
}
}
if(foundSpawn) {
Location newSpawnLoc = new Location( w, i.getNewBlockLocation().getX(), i.getNewBlockLocation().getY(), i.getNewBlockLocation().getZ() );
p.setBedSpawnLocation(newSpawnLoc, true);
iter.remove();
}
}
}
}
}
}
}
// Restore block specific information
for ( MovecraftLocation l : dataMap.keySet() ) {
try {
TransferData transferData = dataMap.get( l );
if ( transferData instanceof SignTransferHolder ) {
SignTransferHolder signData = ( SignTransferHolder ) transferData;
Sign sign = ( Sign ) w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState();
for ( int i = 0; i < signData.getLines().length; i++ ) {
sign.setLine( i, signData.getLines()[i] );
}
sign.update( true );
} else if ( transferData instanceof StorageCrateTransferHolder ) {
Inventory inventory = Bukkit.createInventory( null, 27, String.format( I18nSupport.getInternationalisedString( "Item - Storage Crate name" ) ) );
inventory.setContents( ( ( StorageCrateTransferHolder ) transferData ).getInvetory() );
StorageChestItem.setInventoryOfCrateAtLocation( inventory, l, w );
} else if ( transferData instanceof InventoryTransferHolder ) {
InventoryTransferHolder invData = ( InventoryTransferHolder ) transferData;
InventoryHolder inventoryHolder = ( InventoryHolder ) w.getBlockAt( l.getX(), l.getY(), l.getZ() ).getState();
inventoryHolder.getInventory().setContents( invData.getInvetory() );
}
w.getBlockAt( l.getX(), l.getY(), l.getZ() ).setData( transferData.getData() );
} catch ( Exception e ) {
Movecraft.getInstance().getLogger().log( Level.SEVERE, "Severe error in map updater" );
}
}
if(Settings.CompatibilityMode) {
// todo: lighting stuff here
} else {
for ( net.minecraft.server.v1_7_R1.Chunk c : chunks ) {
c.initLighting();
ChunkCoordIntPair ccip = new ChunkCoordIntPair( c.locX, c.locZ ); // changed from c.x to c.locX and c.locZ
for ( Player p : w.getPlayers() ) {
List<ChunkCoordIntPair> chunkCoordIntPairQueue = ( List<ChunkCoordIntPair> ) ( ( CraftPlayer ) p ).getHandle().chunkCoordIntPairQueue;
if ( !chunkCoordIntPairQueue.contains( ccip ) )
chunkCoordIntPairQueue.add( ccip );
}
}
}
if(CraftManager.getInstance().getCraftsInWorld(w)!=null) {
// clean up dropped items that are fragile block types on or below all crafts. They are likely garbage left on the ground from the block movements
for(Craft cleanCraft : CraftManager.getInstance().getCraftsInWorld(w)) {
Iterator<Entity> i=w.getEntities().iterator();
while (i.hasNext()) {
Entity eTest=i.next();
if (eTest.getTicksLived()<100 && eTest.getType()==org.bukkit.entity.EntityType.DROPPED_ITEM) {
int adjX=eTest.getLocation().getBlockX()-cleanCraft.getMinX();
int adjZ=eTest.getLocation().getBlockZ()-cleanCraft.getMinZ();
int[][][] hb=cleanCraft.getHitBox();
if(adjX>=-1 && adjX<=hb.length) {
if(adjX<0) {
adjX=0;
}
if(adjX>=hb.length) {
adjX=hb.length-1;
}
if(adjZ>-1 && adjZ<=hb[adjX].length) {
Item it=(Item)eTest;
if(Arrays.binarySearch(fragileBlocks,it.getItemStack().getTypeId())>=0) {
eTest.remove();
}
}
}
}
}
}
// and set all crafts that were updated to not processing, and move any spawn points that were on a block that was moved
for ( MapUpdateCommand c : updatesInWorld ) {
if(c!=null) {
Craft craft=c.getCraft();
if(craft!=null) {
if(!craft.isNotProcessing()) {
craft.setProcessing(false);
}
}
}
}
}
}
}
updates.clear();
entityUpdates.clear();
long endTime=System.currentTimeMillis();
// Movecraft.getInstance().getLogger().log( Level.INFO, "Map update took (ms): "+(endTime-startTime));
}
|
diff --git a/execution/src/main/java/org/springframework/batch/execution/facade/SimpleJobExecutorFacade.java b/execution/src/main/java/org/springframework/batch/execution/facade/SimpleJobExecutorFacade.java
index a1084b3ff..9d5f3095f 100644
--- a/execution/src/main/java/org/springframework/batch/execution/facade/SimpleJobExecutorFacade.java
+++ b/execution/src/main/java/org/springframework/batch/execution/facade/SimpleJobExecutorFacade.java
@@ -1,217 +1,217 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* 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.springframework.batch.execution.facade;
import java.util.Iterator;
import java.util.Properties;
import org.springframework.batch.core.configuration.JobConfiguration;
import org.springframework.batch.core.configuration.JobConfigurationLocator;
import org.springframework.batch.core.configuration.NoSuchJobConfigurationException;
import org.springframework.batch.core.domain.JobExecution;
import org.springframework.batch.core.domain.JobInstance;
import org.springframework.batch.core.executor.JobExecutor;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.runtime.JobExecutionRegistry;
import org.springframework.batch.core.runtime.JobIdentifier;
import org.springframework.batch.execution.job.DefaultJobExecutor;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.batch.repeat.RepeatContext;
import org.springframework.batch.statistics.StatisticsProvider;
import org.springframework.util.Assert;
/**
* <p>
* Simple implementation of (@link {@link JobExecutorFacade}).
*
* <p>
* A {@link JobIdentifier} will be used to uniquely identify the job by the
* repository. Once the job is obtained, the {@link JobExecutor} will be used to
* run the job.
* </p>
*
* @author Lucas Ward
* @author Dave Syer
*
*/
public class SimpleJobExecutorFacade implements JobExecutorFacade, StatisticsProvider {
private JobExecutor jobExecutor;
private JobRepository jobRepository;
private JobExecutionRegistry jobExecutionRegistry = new VolatileJobExecutionRegistry();
// there is no sensible default for this
private JobConfigurationLocator jobConfigurationLocator;
private int running = 0;
private Object mutex = new Object();
/**
* Public accessor for the running property.
*
* @return the running
*/
public boolean isRunning() {
synchronized (mutex) {
return running > 0;
}
}
public SimpleJobExecutorFacade() {
jobExecutor = new DefaultJobExecutor();
}
/**
* Setter for the job execution registry. The default should be adequate so
* this setter method is mainly used for testing.
* @param jobExecutionRegistry the jobExecutionRegistry to set
*/
public void setJobExecutionRegistry(JobExecutionRegistry jobExecutionRegistry) {
this.jobExecutionRegistry = jobExecutionRegistry;
}
/**
* Setter for injection of {@link JobConfigurationLocator}.
*
* @param jobConfigurationLocator the jobConfigurationLocator to set
*/
public void setJobConfigurationLocator(JobConfigurationLocator jobConfigurationLocator) {
this.jobConfigurationLocator = jobConfigurationLocator;
}
/**
* Locates a {@link JobConfiguration} by using the name of the provided
* {@link JobIdentifier} and the {@link JobConfigurationLocator}.
*
* @see org.springframework.batch.execution.facade.JobExecutorFacade#start(org.springframework.batch.execution.common.domain.JobConfiguration,
* org.springframework.batch.core.runtime.JobIdentifier)
*
* @throws IllegalArgumentException if the runtime information is null or
* its name is null
* @throws IllegalStateException if the {@link JobConfigurationLocator} does
* not contain a {@link JobConfiguration} with the name provided.
* @throws IllegalStateException if the {@link JobExecutor} is null
* @throws IllegalStateException if the {@link JobConfigurationLocator} is
* null
*
*/
public ExitStatus start(JobIdentifier jobRuntimeInformation) throws NoSuchJobConfigurationException {
Assert.notNull(jobRuntimeInformation, "JobRuntimeInformation must not be null.");
Assert.notNull(jobRuntimeInformation.getName(), "JobRuntimeInformation name must not be null.");
Assert.state(!jobExecutionRegistry.isRegistered(jobRuntimeInformation),
"A job with this JobRuntimeInformation is already executing in this container");
Assert.state(jobExecutor != null, "JobExecutor must be provided.");
Assert.state(jobConfigurationLocator != null, "JobConfigurationLocator must be provided.");
JobConfiguration jobConfiguration = jobConfigurationLocator
.getJobConfiguration(jobRuntimeInformation.getName());
final JobInstance job = jobRepository.findOrCreateJob(jobConfiguration, jobRuntimeInformation);
- JobExecution jobExecutionContext = jobExecutionRegistry.register(job);
+ JobExecution jobExecution = jobExecutionRegistry.register(job);
ExitStatus exitStatus = ExitStatus.FAILED;
try {
synchronized (mutex) {
running++;
}
- exitStatus = jobExecutor.run(jobConfiguration, jobExecutionContext);
+ exitStatus = jobExecutor.run(jobConfiguration, jobExecution);
}
finally {
synchronized (mutex) {
// assume execution is synchronous so when we get to here we are
// not running any more
running--;
}
jobExecutionRegistry.unregister(jobRuntimeInformation);
}
return exitStatus;
}
/*
* (non-Javadoc)
* @see org.springframework.batch.container.BatchContainer#stop(org.springframework.batch.container.common.runtime.JobRuntimeInformation)
*/
public void stop(JobIdentifier runtimeInformation) throws NoSuchJobExecutionException {
JobExecution jobExecutionContext = jobExecutionRegistry.get(runtimeInformation);
if (jobExecutionContext == null) {
throw new NoSuchJobExecutionException("No such Job is executing: [" + runtimeInformation + "]");
}
for (Iterator iter = jobExecutionContext.getStepContexts().iterator(); iter.hasNext();) {
RepeatContext context = (RepeatContext) iter.next();
context.setTerminateOnly();
}
;
for (Iterator iter = jobExecutionContext.getChunkContexts().iterator(); iter.hasNext();) {
RepeatContext context = (RepeatContext) iter.next();
context.setTerminateOnly();
}
}
/**
* Setter for {@link JobExecutor}.
*
* @param jobExecutor
*/
public void setJobExecutor(JobExecutor jobExecutor) {
this.jobExecutor = jobExecutor;
}
/**
* Setter for {@link JobRepository}.
*
* @param jobRepository
*/
public void setJobRepository(JobRepository jobRepository) {
this.jobRepository = jobRepository;
}
/**
* @return a read-only view of the state of the running jobs.
*/
public Properties getStatistics() {
int i = 0;
Properties props = new Properties();
for (Iterator iter = jobExecutionRegistry.findAll().iterator(); iter.hasNext();) {
JobExecution element = (JobExecution) iter.next();
i++;
String runtime = "job" + i;
props.setProperty(runtime, "" + element.getJobIdentifier());
int j = 0;
for (Iterator iterator = element.getStepContexts().iterator(); iterator.hasNext();) {
RepeatContext context = (RepeatContext) iterator.next();
j++;
props.setProperty(runtime + ".step" + j, "" + context);
}
j = 0;
for (Iterator iterator = element.getChunkContexts().iterator(); iterator.hasNext();) {
RepeatContext context = (RepeatContext) iterator.next();
j++;
props.setProperty(runtime + ".chunk" + j, "" + context);
}
}
return props;
}
}
| false | true | public ExitStatus start(JobIdentifier jobRuntimeInformation) throws NoSuchJobConfigurationException {
Assert.notNull(jobRuntimeInformation, "JobRuntimeInformation must not be null.");
Assert.notNull(jobRuntimeInformation.getName(), "JobRuntimeInformation name must not be null.");
Assert.state(!jobExecutionRegistry.isRegistered(jobRuntimeInformation),
"A job with this JobRuntimeInformation is already executing in this container");
Assert.state(jobExecutor != null, "JobExecutor must be provided.");
Assert.state(jobConfigurationLocator != null, "JobConfigurationLocator must be provided.");
JobConfiguration jobConfiguration = jobConfigurationLocator
.getJobConfiguration(jobRuntimeInformation.getName());
final JobInstance job = jobRepository.findOrCreateJob(jobConfiguration, jobRuntimeInformation);
JobExecution jobExecutionContext = jobExecutionRegistry.register(job);
ExitStatus exitStatus = ExitStatus.FAILED;
try {
synchronized (mutex) {
running++;
}
exitStatus = jobExecutor.run(jobConfiguration, jobExecutionContext);
}
finally {
synchronized (mutex) {
// assume execution is synchronous so when we get to here we are
// not running any more
running--;
}
jobExecutionRegistry.unregister(jobRuntimeInformation);
}
return exitStatus;
}
| public ExitStatus start(JobIdentifier jobRuntimeInformation) throws NoSuchJobConfigurationException {
Assert.notNull(jobRuntimeInformation, "JobRuntimeInformation must not be null.");
Assert.notNull(jobRuntimeInformation.getName(), "JobRuntimeInformation name must not be null.");
Assert.state(!jobExecutionRegistry.isRegistered(jobRuntimeInformation),
"A job with this JobRuntimeInformation is already executing in this container");
Assert.state(jobExecutor != null, "JobExecutor must be provided.");
Assert.state(jobConfigurationLocator != null, "JobConfigurationLocator must be provided.");
JobConfiguration jobConfiguration = jobConfigurationLocator
.getJobConfiguration(jobRuntimeInformation.getName());
final JobInstance job = jobRepository.findOrCreateJob(jobConfiguration, jobRuntimeInformation);
JobExecution jobExecution = jobExecutionRegistry.register(job);
ExitStatus exitStatus = ExitStatus.FAILED;
try {
synchronized (mutex) {
running++;
}
exitStatus = jobExecutor.run(jobConfiguration, jobExecution);
}
finally {
synchronized (mutex) {
// assume execution is synchronous so when we get to here we are
// not running any more
running--;
}
jobExecutionRegistry.unregister(jobRuntimeInformation);
}
return exitStatus;
}
|
diff --git a/org.openscada.core.client/src/org/openscada/core/client/AutoReconnectController.java b/org.openscada.core.client/src/org/openscada/core/client/AutoReconnectController.java
index b82cfda91..9c30e1eac 100644
--- a/org.openscada.core.client/src/org/openscada/core/client/AutoReconnectController.java
+++ b/org.openscada.core.client/src/org/openscada/core/client/AutoReconnectController.java
@@ -1,229 +1,233 @@
/*
* This file is part of the OpenSCADA project
* Copyright (C) 2006-2009 inavare GmbH (http://inavare.com)
*
* 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 (at your option) 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 org.openscada.core.client;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openscada.utils.concurrent.NamedThreadFactory;
/**
* A automatic reconnect controller which keeps connection in the requested state
* <p>
* In order to use the reconnect controller put the connection in the constructor and call {@link #connect()}.
*
* <pre><code>
* Connection connection = ...;
* AutoReconnectController controller = new AutoReconnectController ( connection );
* controller.connect ();
* </code></pre>
* <p>
* Note that if you do not hold an instance to the auto reconnect controller it will be garbage collected
* and the connection state will no longer be monitored.
* @since 0.12
* @author Jens Reimann
*
*/
public class AutoReconnectController implements ConnectionStateListener
{
private static Logger logger = Logger.getLogger ( AutoReconnectController.class );
private static final long DEFAULT_RECONNECT_DELAY = Long.getLong ( "openscada.default.reconnect.delay", 10 * 1000 );
private final Connection connection;
private boolean connect;
private final long reconnectDelay;
private final ScheduledThreadPoolExecutor executor;
private long lastTimestamp;
private ConnectionState state;
private boolean checkScheduled;
/**
* Create a new reconnect controller for the provided connection using the default reconnect delay
* @param connection the connection to manage
*/
public AutoReconnectController ( final Connection connection )
{
this ( connection, DEFAULT_RECONNECT_DELAY );
}
/**
* Create a new reconnect controller for the provided connection
* @param connection the connection to manage
* @param reconnectDelay the minimum delay between reconnect attempts
*/
public AutoReconnectController ( final Connection connection, long reconnectDelay )
{
this.connection = connection;
this.reconnectDelay = reconnectDelay;
if ( this.connection == null )
{
throw new NullPointerException ( "'connection' must not be null" );
}
if ( reconnectDelay <= 0 )
{
reconnectDelay = DEFAULT_RECONNECT_DELAY;
}
this.connection.addConnectionStateListener ( this );
final ThreadFactory threadFactory = new NamedThreadFactory ( "AutoReconnect/" + connection.getConnectionInformation () );
this.executor = new ScheduledThreadPoolExecutor ( 1, threadFactory );
}
@Override
protected void finalize () throws Throwable
{
logger.debug ( "Finalized" );
if ( this.executor != null )
{
this.executor.shutdownNow ();
}
super.finalize ();
}
public synchronized void connect ()
{
logger.debug ( "Request to connect" );
if ( this.connect == true )
{
return;
}
this.connect = true;
// we want that now!
this.lastTimestamp = 0;
triggerUpdate ( this.connection.getState () );
}
public synchronized void disconnect ()
{
logger.debug ( "Request to disconnect" );
if ( this.connect == false )
{
return;
}
this.connect = false;
// we want that now!
this.lastTimestamp = 0;
triggerUpdate ( this.connection.getState () );
}
public void stateChange ( final Connection connection, final ConnectionState state, final Throwable error )
{
logger.info ( String.format ( "State change: %s", state ), error );
triggerUpdate ( state );
}
private synchronized void triggerUpdate ( final ConnectionState state )
{
this.state = state;
if ( !this.checkScheduled )
{
this.checkScheduled = true;
this.executor.execute ( new Runnable () {
public void run ()
{
performUpdate ( state );
}
} );
}
}
private void performUpdate ( final ConnectionState state )
{
logger.debug ( "Performing update: " + state );
final long now = System.currentTimeMillis ();
final long diff = now - this.lastTimestamp;
logger.debug ( String.format ( "Last action: %s, diff: %s, delay: %s", this.lastTimestamp, diff, this.reconnectDelay ) );
if ( diff > this.reconnectDelay )
{
performCheckNow ();
}
else
{
final long delay = this.reconnectDelay - diff;
logger.info ( String.format ( "Delaying next check by %s milliseconds", delay ) );
this.executor.schedule ( new Runnable () {
public void run ()
{
performCheckNow ();
}
}, delay, TimeUnit.MILLISECONDS );
}
this.lastTimestamp = System.currentTimeMillis ();
}
private void performCheckNow ()
{
+ ConnectionState currentState;
+ boolean connect;
synchronized ( this )
{
+ currentState = this.state;
+ connect = this.connect;
this.checkScheduled = false;
}
- logger.debug ( String.format ( "Performing state check: %s (request: %s)", this.state, this.connect ) );
+ logger.debug ( String.format ( "Performing state check: %s (request: %s)", currentState, connect ) );
- switch ( this.state )
+ switch ( currentState )
{
case CLOSED:
- if ( this.connect )
+ if ( connect )
{
logger.info ( "Trigger connect" );
this.connection.connect ();
}
break;
case LOOKUP:
case CONNECTING:
case CONNECTED:
case BOUND:
- if ( !this.connect )
+ if ( !connect )
{
logger.info ( "Trigger disconnect" );
this.connection.disconnect ();
}
break;
default:
logger.info ( "Do nothing" );
break;
}
}
}
| false | true | private void performCheckNow ()
{
synchronized ( this )
{
this.checkScheduled = false;
}
logger.debug ( String.format ( "Performing state check: %s (request: %s)", this.state, this.connect ) );
switch ( this.state )
{
case CLOSED:
if ( this.connect )
{
logger.info ( "Trigger connect" );
this.connection.connect ();
}
break;
case LOOKUP:
case CONNECTING:
case CONNECTED:
case BOUND:
if ( !this.connect )
{
logger.info ( "Trigger disconnect" );
this.connection.disconnect ();
}
break;
default:
logger.info ( "Do nothing" );
break;
}
}
| private void performCheckNow ()
{
ConnectionState currentState;
boolean connect;
synchronized ( this )
{
currentState = this.state;
connect = this.connect;
this.checkScheduled = false;
}
logger.debug ( String.format ( "Performing state check: %s (request: %s)", currentState, connect ) );
switch ( currentState )
{
case CLOSED:
if ( connect )
{
logger.info ( "Trigger connect" );
this.connection.connect ();
}
break;
case LOOKUP:
case CONNECTING:
case CONNECTED:
case BOUND:
if ( !connect )
{
logger.info ( "Trigger disconnect" );
this.connection.disconnect ();
}
break;
default:
logger.info ( "Do nothing" );
break;
}
}
|
diff --git a/dao-hibernate/src/main/java/org/apache/ode/daohib/bpel/CriteriaBuilder.java b/dao-hibernate/src/main/java/org/apache/ode/daohib/bpel/CriteriaBuilder.java
index 837c106b9..851dcf51b 100644
--- a/dao-hibernate/src/main/java/org/apache/ode/daohib/bpel/CriteriaBuilder.java
+++ b/dao-hibernate/src/main/java/org/apache/ode/daohib/bpel/CriteriaBuilder.java
@@ -1,428 +1,428 @@
/*
* 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.ode.daohib.bpel;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.bpel.common.BpelEventFilter;
import org.apache.ode.bpel.common.Filter;
import org.apache.ode.bpel.common.InstanceFilter;
import org.apache.ode.utils.ISO8601DateParser;
import org.apache.ode.utils.RelativeDateParser;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
/**
* Class used for converting "filter" objects into Hibernate
* {@link org.hibernate.Criteria} objects.
*/
class CriteriaBuilder {
static final Log __log = LogFactory.getLog(CriteriaBuilder.class);
/**
* Build a HQL query from an instance filter.
* @param filter filter
*/
Query buildHQLQuery(Session session, InstanceFilter filter) {
Map<String, Object> parameters = new HashMap<String, Object>();
StringBuffer query = new StringBuffer();
query.append("select pi from HProcessInstance as pi left join fetch pi.fault ");
if (filter != null) {
// Building each clause
ArrayList<String> clauses = new ArrayList<String>();
// iid filter
if ( filter.getIidFilter() != null ) {
StringBuffer filters = new StringBuffer();
List<String> iids = filter.getIidFilter();
for (int m = 0; m < iids.size(); m++) {
filters.append(" pi.id = :iid").append(m);
parameters.put("iid" + m, iids.get(m));
if (m < iids.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters + ")");
}
// pid filter
if (filter.getPidFilter() != null) {
StringBuffer filters = new StringBuffer();
List<String> pids = filter.getPidFilter();
String cmp;
if (filter.arePidsNegative()) {
cmp = " != ";
} else {
cmp = " = ";
}
for (int m = 0; m < pids.size(); m++) {
- filters.append(" pi.process.id ").append(cmp).append(" :pid").append(m);
+ filters.append(" pi.process.processId ").append(cmp).append(" :pid").append(m);
parameters.put("pid" + m, pids.get(m));
if (m < pids.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters + ")");
}
// name filter
if (filter.getNameFilter() != null) {
clauses.add(" pi.process.typeName like :pname");
parameters.put("pname", filter.getNameFilter().replaceAll("\\*", "%"));
}
// name space filter
if (filter.getNamespaceFilter() != null) {
clauses.add(" pi.process.typeNamespace like :pnamespace");
parameters.put("pnamespace", filter.getNamespaceFilter().replaceAll("\\*", "%"));
}
// started filter
if (filter.getStartedDateFilter() != null) {
for ( String ds : filter.getStartedDateFilter() ) {
// named parameters not needed as date is parsed and is hence not
// prone to HQL injections
clauses.add(" pi.created " + dateFilter(ds));
}
}
// last-active filter
if (filter.getLastActiveDateFilter() != null) {
for ( String ds : filter.getLastActiveDateFilter() ) {
// named parameters not needed as date is parsed and is hence not
// prone to HQL injections
clauses.add(" pi.lastActiveTime " + dateFilter(ds));
}
}
// status filter
if (filter.getStatusFilter() != null) {
StringBuffer filters = new StringBuffer();
List<Short> states = filter.convertFilterState();
for (int m = 0; m < states.size(); m++) {
filters.append(" pi.state = :pstate").append(m);
parameters.put("pstate" + m, states.get(m));
if (m < states.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters.toString() + ")");
}
// $property filter
if (filter.getPropertyValuesFilter() != null) {
Map<String,String> props = filter.getPropertyValuesFilter();
// join to correlation sets
query.append(" inner join pi.correlationSets as cs");
int i = 0;
for (String propKey : props.keySet()) {
i++;
// join to props for each prop
query.append(" inner join cs.properties as csp"+i);
// add clause for prop key and value
// spaces have to be escaped, might be better handled in InstanceFilter
String value = props.get(propKey).replaceAll(" ", " ");
if (propKey.startsWith("{")) {
String namespace = propKey.substring(1, propKey.lastIndexOf("}"));
clauses.add(" csp" + i + ".name = :cspname" + i +
" and csp" + i + ".namespace = :cspnamespace" + i +
" and csp" + i + ".value = :cspvalue" + i);
parameters.put("cspname" + i, propKey.substring(propKey.lastIndexOf("}") + 1, propKey.length()));
parameters.put("cspnamespace" + i, namespace);
parameters.put("cspvalue" + i, value);
} else {
clauses.add(" csp" + i + ".name = :cspname" + i +
" and csp" + i + ".value = :cspvalue" + i);
parameters.put("cspname" + i, propKey);
parameters.put("cspvalue" + i, value);
}
}
}
// order by
StringBuffer orderby = new StringBuffer("");
if (filter.getOrders() != null) {
orderby.append(" order by");
List<String> orders = filter.getOrders();
for (int m = 0; m < orders.size(); m++) {
String field = orders.get(m);
String ord = " asc";
if (field.startsWith("-")) {
ord = " desc";
}
String fieldName = " pi.id";
if (field.endsWith("name")) {
fieldName = " pi.process.typeName";
}
if (field.endsWith("namespace")) {
fieldName = " pi.process.typeNamespace";
}
if ( field.endsWith("version")) {
fieldName = " pi.process.version";
}
if ( field.endsWith("status")) {
fieldName = " pi.state";
}
if ( field.endsWith("started")) {
fieldName = " pi.created";
}
if ( field.endsWith("last-active")) {
fieldName = " pi.lastActiveTime";
}
orderby.append(fieldName + ord);
if (m < orders.size() - 1) orderby.append(", ");
}
}
// Preparing the statement
if (clauses.size() > 0) {
query.append(" where");
for (int m = 0; m < clauses.size(); m++) {
query.append(clauses.get(m));
if (m < clauses.size() - 1) query.append(" and");
}
}
query.append(orderby);
}
if (__log.isDebugEnabled()) {
__log.debug(query.toString());
}
Query q = session.createQuery(query.toString());
for (String p : parameters.keySet()) {
q.setParameter(p, parameters.get(p));
}
if (filter.getLimit() != 0) {
q.setMaxResults(filter.getLimit());
}
return q;
}
private static String dateFilter(String filter) {
String date = Filter.getDateWithoutOp(filter);
String op = filter.substring(0,filter.indexOf(date));
Date dt = null;
try {
dt = ISO8601DateParser.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Timestamp ts = new Timestamp(dt.getTime());
return op + " '" + ts.toString() + "'";
}
/**
* Build a Hibernate {@link Criteria} from an instance filter.
* @param crit target (destination) criteria
* @param filter filter
*/
void buildCriteria(Criteria crit, InstanceFilter filter) {
Criteria processCrit = crit.createCriteria("process");
// Filtering on PID
List<String> pids = filter.getPidFilter();
if (pids != null && pids.size() > 0) {
Disjunction disj = Restrictions.disjunction();
for (String pid: pids) {
if( !filter.arePidsNegative() ) {
disj.add(Restrictions.eq("processId", pid));
} else {
disj.add(Restrictions.ne("processId", pid));
}
}
processCrit.add(disj);
}
List<String> iids = filter.getIidFilter();
if (iids != null && iids.size() > 0) {
Disjunction disj = Restrictions.disjunction();
for (String iid: iids) {
disj.add(Restrictions.eq("id", new Long(iid)));
}
crit.add(disj);
}
// Filtering on name and namespace
if (filter.getNameFilter() != null) {
processCrit.add(Restrictions.like("typeName", filter.getNameFilter().replaceAll("\\*", "%")));
}
if (filter.getNamespaceFilter() != null) {
processCrit.add(Restrictions.like("typeNamespace", filter.getNamespaceFilter().replaceAll("\\*", "%")));
}
// Specific filter for status (using a disjunction between possible statuses)
if (filter.getStatusFilter() != null) {
List<Short> statuses = filter.convertFilterState();
Disjunction disj = Restrictions.disjunction();
for (short status : statuses) {
disj.add(Restrictions.eq("state", status));
}
crit.add(disj);
}
// Specific filter for started and last active dates.
if (filter.getStartedDateFilter() != null) {
for (String sdf : filter.getStartedDateFilter()) {
addFilterOnPrefixedDate(crit, sdf, "created");
}
}
if (filter.getLastActiveDateFilter() != null) {
for (String ladf : filter.getLastActiveDateFilter()) {
addFilterOnPrefixedDate(crit, ladf, "lastActiveTime");
}
}
// Specific filter for correlation properties
if (filter.getPropertyValuesFilter() != null) {
Criteria propCrit = crit.createCriteria("correlationSets").createCriteria("properties");
for (Map.Entry<String, String> corValue : filter.getPropertyValuesFilter().entrySet()) {
String propName = (String)corValue.getKey();
if (propName.startsWith("{")) {
String namespace = propName.substring(1, propName.lastIndexOf("}"));
propName = propName.substring(propName.lastIndexOf("}") + 1, propName.length());
propCrit.add(Restrictions.eq("name", propName))
.add(Restrictions.eq("namespace", namespace))
.add(Restrictions.eq("value", corValue.getValue()));
} else {
propCrit.add(Restrictions.eq("name", corValue.getKey()))
.add(Restrictions.eq("value", corValue.getValue()));
}
}
}
// Ordering
if (filter.orders != null) {
for (String key : filter.orders) {
boolean ascending = true;
String orderKey = key;
if (key.startsWith("+") || key.startsWith("-")) {
orderKey = key.substring(1, key.length());
if (key.startsWith("-")) ascending = false;
}
if ("name".equals(orderKey)) {
if (ascending) processCrit.addOrder(Property.forName("typeName").asc());
else processCrit.addOrder(Property.forName("typeName").desc());
} else if ("namespace".equals(orderKey)) {
if (ascending) processCrit.addOrder(Property.forName("typeNamespace").asc());
else processCrit.addOrder(Property.forName("typeNamespace").desc());
} else if ("pid".equals(orderKey)) {
if (ascending) processCrit.addOrder(Property.forName("processId").asc());
else processCrit.addOrder(Property.forName("processId").desc());
} else if ("version".equals(orderKey)) {
if (ascending) processCrit.addOrder(Property.forName("version").asc());
else processCrit.addOrder(Property.forName("version").desc());
} else if ("status".equals(orderKey)) {
if (ascending) crit.addOrder(Property.forName("state").asc());
else crit.addOrder(Property.forName("state").desc());
} else if ("started".equals(orderKey)) {
if (ascending) crit.addOrder(Property.forName("created").asc());
else crit.addOrder(Property.forName("created").desc());
} else if ("last-active".equals(orderKey)) {
if (ascending) crit.addOrder(Property.forName("lastActiveTime").asc());
else crit.addOrder(Property.forName("lastActiveTime").desc());
}
}
}
if (filter.getLimit() > 0) crit.setMaxResults(filter.getLimit());
}
/**
* Build criteria for an event filter.
* @param crit target criteria
* @param efilter event filter
*/
void buildCriteria(Criteria crit, BpelEventFilter efilter) {
if (efilter.getTypeFilter() != null)
crit.add(Restrictions.like("type", efilter.getTypeFilter().replace('*','%')));
// Specific filter for started and last active dates.
if (efilter.getTimestampFilter() != null) {
for (Filter.Restriction<Date> sdf : efilter.getTimestampFilter()) {
addFilterOnPrefixedDate(crit, sdf.op, sdf.value, "tstamp");
}
}
if (efilter.limit > 0) crit.setMaxResults(efilter.limit);
}
void addScopeFilter(Criteria crit, String scopeId) {
crit.add(Restrictions.eq("",scopeId));
}
static void addFilterOnPrefixedDate(Criteria crit, String prefixedDate, String dateAttribute) {
Date realDate = null;
try {
realDate = parseDateExpression(getDateWithoutOp(prefixedDate));
} catch (ParseException e) {
// Never occurs, the deploy date format is pre-validated by the filter
}
addFilterOnPrefixedDate(crit,prefixedDate,realDate,dateAttribute);
}
private static Date parseDateExpression(String date) throws ParseException {
if( date.toLowerCase().startsWith("-") && date.length() > 1 ) {
return RelativeDateParser.parseRelativeDate(date.substring(1));
} else {
return ISO8601DateParser.parse(date);
}
}
static void addFilterOnPrefixedDate(Criteria crit, String op, Date date, String dateAttribute) {
if (op.startsWith("=")) {
crit.add(Restrictions.eq(dateAttribute, date));
} else if (op.startsWith("<=")) {
crit.add(Restrictions.le(dateAttribute, date));
} else if (op.startsWith(">=")) {
crit.add(Restrictions.ge(dateAttribute, date));
} else if (op.startsWith("<")) {
crit.add(Restrictions.lt(dateAttribute, date));
} else if (op.startsWith(">")) {
crit.add(Restrictions.gt(dateAttribute, date));
}
}
private static String getDateWithoutOp(String ddf) {
return Filter.getDateWithoutOp(ddf);
}
}
| true | true | Query buildHQLQuery(Session session, InstanceFilter filter) {
Map<String, Object> parameters = new HashMap<String, Object>();
StringBuffer query = new StringBuffer();
query.append("select pi from HProcessInstance as pi left join fetch pi.fault ");
if (filter != null) {
// Building each clause
ArrayList<String> clauses = new ArrayList<String>();
// iid filter
if ( filter.getIidFilter() != null ) {
StringBuffer filters = new StringBuffer();
List<String> iids = filter.getIidFilter();
for (int m = 0; m < iids.size(); m++) {
filters.append(" pi.id = :iid").append(m);
parameters.put("iid" + m, iids.get(m));
if (m < iids.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters + ")");
}
// pid filter
if (filter.getPidFilter() != null) {
StringBuffer filters = new StringBuffer();
List<String> pids = filter.getPidFilter();
String cmp;
if (filter.arePidsNegative()) {
cmp = " != ";
} else {
cmp = " = ";
}
for (int m = 0; m < pids.size(); m++) {
filters.append(" pi.process.id ").append(cmp).append(" :pid").append(m);
parameters.put("pid" + m, pids.get(m));
if (m < pids.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters + ")");
}
// name filter
if (filter.getNameFilter() != null) {
clauses.add(" pi.process.typeName like :pname");
parameters.put("pname", filter.getNameFilter().replaceAll("\\*", "%"));
}
// name space filter
if (filter.getNamespaceFilter() != null) {
clauses.add(" pi.process.typeNamespace like :pnamespace");
parameters.put("pnamespace", filter.getNamespaceFilter().replaceAll("\\*", "%"));
}
// started filter
if (filter.getStartedDateFilter() != null) {
for ( String ds : filter.getStartedDateFilter() ) {
// named parameters not needed as date is parsed and is hence not
// prone to HQL injections
clauses.add(" pi.created " + dateFilter(ds));
}
}
// last-active filter
if (filter.getLastActiveDateFilter() != null) {
for ( String ds : filter.getLastActiveDateFilter() ) {
// named parameters not needed as date is parsed and is hence not
// prone to HQL injections
clauses.add(" pi.lastActiveTime " + dateFilter(ds));
}
}
// status filter
if (filter.getStatusFilter() != null) {
StringBuffer filters = new StringBuffer();
List<Short> states = filter.convertFilterState();
for (int m = 0; m < states.size(); m++) {
filters.append(" pi.state = :pstate").append(m);
parameters.put("pstate" + m, states.get(m));
if (m < states.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters.toString() + ")");
}
// $property filter
if (filter.getPropertyValuesFilter() != null) {
Map<String,String> props = filter.getPropertyValuesFilter();
// join to correlation sets
query.append(" inner join pi.correlationSets as cs");
int i = 0;
for (String propKey : props.keySet()) {
i++;
// join to props for each prop
query.append(" inner join cs.properties as csp"+i);
// add clause for prop key and value
// spaces have to be escaped, might be better handled in InstanceFilter
String value = props.get(propKey).replaceAll(" ", " ");
if (propKey.startsWith("{")) {
String namespace = propKey.substring(1, propKey.lastIndexOf("}"));
clauses.add(" csp" + i + ".name = :cspname" + i +
" and csp" + i + ".namespace = :cspnamespace" + i +
" and csp" + i + ".value = :cspvalue" + i);
parameters.put("cspname" + i, propKey.substring(propKey.lastIndexOf("}") + 1, propKey.length()));
parameters.put("cspnamespace" + i, namespace);
parameters.put("cspvalue" + i, value);
} else {
clauses.add(" csp" + i + ".name = :cspname" + i +
" and csp" + i + ".value = :cspvalue" + i);
parameters.put("cspname" + i, propKey);
parameters.put("cspvalue" + i, value);
}
}
}
// order by
StringBuffer orderby = new StringBuffer("");
if (filter.getOrders() != null) {
orderby.append(" order by");
List<String> orders = filter.getOrders();
for (int m = 0; m < orders.size(); m++) {
String field = orders.get(m);
String ord = " asc";
if (field.startsWith("-")) {
ord = " desc";
}
String fieldName = " pi.id";
if (field.endsWith("name")) {
fieldName = " pi.process.typeName";
}
if (field.endsWith("namespace")) {
fieldName = " pi.process.typeNamespace";
}
if ( field.endsWith("version")) {
fieldName = " pi.process.version";
}
if ( field.endsWith("status")) {
fieldName = " pi.state";
}
if ( field.endsWith("started")) {
fieldName = " pi.created";
}
if ( field.endsWith("last-active")) {
fieldName = " pi.lastActiveTime";
}
orderby.append(fieldName + ord);
if (m < orders.size() - 1) orderby.append(", ");
}
}
// Preparing the statement
if (clauses.size() > 0) {
query.append(" where");
for (int m = 0; m < clauses.size(); m++) {
query.append(clauses.get(m));
if (m < clauses.size() - 1) query.append(" and");
}
}
query.append(orderby);
}
if (__log.isDebugEnabled()) {
__log.debug(query.toString());
}
Query q = session.createQuery(query.toString());
for (String p : parameters.keySet()) {
q.setParameter(p, parameters.get(p));
}
if (filter.getLimit() != 0) {
q.setMaxResults(filter.getLimit());
}
return q;
}
| Query buildHQLQuery(Session session, InstanceFilter filter) {
Map<String, Object> parameters = new HashMap<String, Object>();
StringBuffer query = new StringBuffer();
query.append("select pi from HProcessInstance as pi left join fetch pi.fault ");
if (filter != null) {
// Building each clause
ArrayList<String> clauses = new ArrayList<String>();
// iid filter
if ( filter.getIidFilter() != null ) {
StringBuffer filters = new StringBuffer();
List<String> iids = filter.getIidFilter();
for (int m = 0; m < iids.size(); m++) {
filters.append(" pi.id = :iid").append(m);
parameters.put("iid" + m, iids.get(m));
if (m < iids.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters + ")");
}
// pid filter
if (filter.getPidFilter() != null) {
StringBuffer filters = new StringBuffer();
List<String> pids = filter.getPidFilter();
String cmp;
if (filter.arePidsNegative()) {
cmp = " != ";
} else {
cmp = " = ";
}
for (int m = 0; m < pids.size(); m++) {
filters.append(" pi.process.processId ").append(cmp).append(" :pid").append(m);
parameters.put("pid" + m, pids.get(m));
if (m < pids.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters + ")");
}
// name filter
if (filter.getNameFilter() != null) {
clauses.add(" pi.process.typeName like :pname");
parameters.put("pname", filter.getNameFilter().replaceAll("\\*", "%"));
}
// name space filter
if (filter.getNamespaceFilter() != null) {
clauses.add(" pi.process.typeNamespace like :pnamespace");
parameters.put("pnamespace", filter.getNamespaceFilter().replaceAll("\\*", "%"));
}
// started filter
if (filter.getStartedDateFilter() != null) {
for ( String ds : filter.getStartedDateFilter() ) {
// named parameters not needed as date is parsed and is hence not
// prone to HQL injections
clauses.add(" pi.created " + dateFilter(ds));
}
}
// last-active filter
if (filter.getLastActiveDateFilter() != null) {
for ( String ds : filter.getLastActiveDateFilter() ) {
// named parameters not needed as date is parsed and is hence not
// prone to HQL injections
clauses.add(" pi.lastActiveTime " + dateFilter(ds));
}
}
// status filter
if (filter.getStatusFilter() != null) {
StringBuffer filters = new StringBuffer();
List<Short> states = filter.convertFilterState();
for (int m = 0; m < states.size(); m++) {
filters.append(" pi.state = :pstate").append(m);
parameters.put("pstate" + m, states.get(m));
if (m < states.size() - 1) filters.append(" or");
}
clauses.add(" (" + filters.toString() + ")");
}
// $property filter
if (filter.getPropertyValuesFilter() != null) {
Map<String,String> props = filter.getPropertyValuesFilter();
// join to correlation sets
query.append(" inner join pi.correlationSets as cs");
int i = 0;
for (String propKey : props.keySet()) {
i++;
// join to props for each prop
query.append(" inner join cs.properties as csp"+i);
// add clause for prop key and value
// spaces have to be escaped, might be better handled in InstanceFilter
String value = props.get(propKey).replaceAll(" ", " ");
if (propKey.startsWith("{")) {
String namespace = propKey.substring(1, propKey.lastIndexOf("}"));
clauses.add(" csp" + i + ".name = :cspname" + i +
" and csp" + i + ".namespace = :cspnamespace" + i +
" and csp" + i + ".value = :cspvalue" + i);
parameters.put("cspname" + i, propKey.substring(propKey.lastIndexOf("}") + 1, propKey.length()));
parameters.put("cspnamespace" + i, namespace);
parameters.put("cspvalue" + i, value);
} else {
clauses.add(" csp" + i + ".name = :cspname" + i +
" and csp" + i + ".value = :cspvalue" + i);
parameters.put("cspname" + i, propKey);
parameters.put("cspvalue" + i, value);
}
}
}
// order by
StringBuffer orderby = new StringBuffer("");
if (filter.getOrders() != null) {
orderby.append(" order by");
List<String> orders = filter.getOrders();
for (int m = 0; m < orders.size(); m++) {
String field = orders.get(m);
String ord = " asc";
if (field.startsWith("-")) {
ord = " desc";
}
String fieldName = " pi.id";
if (field.endsWith("name")) {
fieldName = " pi.process.typeName";
}
if (field.endsWith("namespace")) {
fieldName = " pi.process.typeNamespace";
}
if ( field.endsWith("version")) {
fieldName = " pi.process.version";
}
if ( field.endsWith("status")) {
fieldName = " pi.state";
}
if ( field.endsWith("started")) {
fieldName = " pi.created";
}
if ( field.endsWith("last-active")) {
fieldName = " pi.lastActiveTime";
}
orderby.append(fieldName + ord);
if (m < orders.size() - 1) orderby.append(", ");
}
}
// Preparing the statement
if (clauses.size() > 0) {
query.append(" where");
for (int m = 0; m < clauses.size(); m++) {
query.append(clauses.get(m));
if (m < clauses.size() - 1) query.append(" and");
}
}
query.append(orderby);
}
if (__log.isDebugEnabled()) {
__log.debug(query.toString());
}
Query q = session.createQuery(query.toString());
for (String p : parameters.keySet()) {
q.setParameter(p, parameters.get(p));
}
if (filter.getLimit() != 0) {
q.setMaxResults(filter.getLimit());
}
return q;
}
|
diff --git a/exchange2/src/com/android/exchange/adapter/ProvisionParser.java b/exchange2/src/com/android/exchange/adapter/ProvisionParser.java
index de30111..0825f74 100644
--- a/exchange2/src/com/android/exchange/adapter/ProvisionParser.java
+++ b/exchange2/src/com/android/exchange/adapter/ProvisionParser.java
@@ -1,616 +1,616 @@
/* 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.exchange.adapter;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.res.Resources;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import com.android.emailcommon.provider.Policy;
import com.android.exchange.EasSyncService;
import com.android.exchange.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Parse the result of the Provision command
*/
public class ProvisionParser extends Parser {
private final EasSyncService mService;
private Policy mPolicy = null;
private String mSecuritySyncKey = null;
private boolean mRemoteWipe = false;
private boolean mIsSupportable = true;
private boolean smimeRequired = false;
private final Resources mResources;
public ProvisionParser(InputStream in, EasSyncService service) throws IOException {
super(in);
mService = service;
mResources = service.mContext.getResources();
}
public Policy getPolicy() {
return mPolicy;
}
public String getSecuritySyncKey() {
return mSecuritySyncKey;
}
public void setSecuritySyncKey(String securitySyncKey) {
mSecuritySyncKey = securitySyncKey;
}
public boolean getRemoteWipe() {
return mRemoteWipe;
}
public boolean hasSupportablePolicySet() {
return (mPolicy != null) && mIsSupportable;
}
public void clearUnsupportablePolicies() {
mIsSupportable = true;
mPolicy.mProtocolPoliciesUnsupported = null;
}
private void addPolicyString(StringBuilder sb, int res) {
sb.append(mResources.getString(res));
sb.append(Policy.POLICY_STRING_DELIMITER);
}
/**
* Complete setup of a Policy; we normalize it first (removing inconsistencies, etc.) and then
* generate the tokenized "protocol policies enforced" string. Note that unsupported policies
* must have been added prior to calling this method (this is only a possibility with wbxml
* policy documents, as all versions of the OS support the policies in xml documents).
*/
private void setPolicy(Policy policy) {
policy.normalize();
StringBuilder sb = new StringBuilder();
if (policy.mDontAllowAttachments) {
addPolicyString(sb, R.string.policy_dont_allow_attachments);
}
if (policy.mRequireManualSyncWhenRoaming) {
addPolicyString(sb, R.string.policy_require_manual_sync_roaming);
}
policy.mProtocolPoliciesEnforced = sb.toString();
mPolicy = policy;
}
private boolean deviceSupportsEncryption() {
DevicePolicyManager dpm = (DevicePolicyManager)
mService.mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
int status = dpm.getStorageEncryptionStatus();
return status != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
}
private void parseProvisionDocWbxml() throws IOException {
Policy policy = new Policy();
ArrayList<Integer> unsupportedList = new ArrayList<Integer>();
boolean passwordEnabled = false;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
boolean tagIsSupported = true;
int res = 0;
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordEnabled = true;
if (policy.mPasswordMode == Policy.PASSWORD_MODE_NONE) {
policy.mPasswordMode = Policy.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
policy.mPasswordMinLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
policy.mPasswordMode = Policy.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
policy.mMaxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
policy.mPasswordMaxFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
policy.mPasswordExpirationDays = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
policy.mPasswordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_CAMERA:
policy.mDontAllowCamera = (getValueInt() == 0);
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
tagIsSupported = false;
switch(tag) {
case Tags.PROVISION_ALLOW_STORAGE_CARD:
res = R.string.policy_dont_allow_storage_cards;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
res = R.string.policy_dont_allow_unsigned_apps;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
res = R.string.policy_dont_allow_unsigned_installers;
break;
case Tags.PROVISION_ALLOW_WIFI:
res = R.string.policy_dont_allow_wifi;
break;
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
res = R.string.policy_dont_allow_text_messaging;
break;
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
res = R.string.policy_dont_allow_pop_imap;
break;
case Tags.PROVISION_ALLOW_IRDA:
res = R.string.policy_dont_allow_irda;
break;
case Tags.PROVISION_ALLOW_HTML_EMAIL:
res = R.string.policy_dont_allow_html;
policy.mDontAllowHtml = true;
break;
case Tags.PROVISION_ALLOW_BROWSER:
res = R.string.policy_dont_allow_browser;
break;
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
res = R.string.policy_dont_allow_consumer_email;
break;
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
res = R.string.policy_dont_allow_internet_sharing;
break;
}
if (res > 0) {
unsupportedList.add(res);
}
}
break;
case Tags.PROVISION_ATTACHMENTS_ENABLED:
policy.mDontAllowAttachments = getValueInt() != 1;
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_bluetooth_restricted);
}
break;
// We may now support device (internal) encryption; we'll check this capability
// below with the call to SecurityPolicy.isSupported()
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
if (getValueInt() == 1) {
if (!deviceSupportsEncryption()) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_require_encryption);
} else {
policy.mRequireEncryption = true;
}
}
break;
// Note that DEVICE_ENCRYPTION_ENABLED refers to SD card encryption, which the OS
// does not yet support.
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
if (getValueInt() == 1) {
log("Policy requires SD card encryption");
// Let's see if this can be supported on our device...
if (deviceSupportsEncryption()) {
StorageManager sm = (StorageManager)mService.mContext.getSystemService(
Context.STORAGE_SERVICE);
// NOTE: Private API!
// Go through volumes; if ANY are removable, we can't support this
// policy.
StorageVolume[] volumeList = sm.getVolumeList();
for (StorageVolume volume: volumeList) {
if (volume.isRemovable()) {
tagIsSupported = false;
- log("Removable: " + volume.getDescription());
+ log("Removable: " + volume.getDescription(mService.mContext));
break; // Break only from the storage volume loop
} else {
- log("Not Removable: " + volume.getDescription());
+ log("Not Removable: " + volume.getDescription(mService.mContext));
}
}
if (tagIsSupported) {
// If this policy is requested, we MUST also require encryption
log("Device supports SD card encryption");
policy.mRequireEncryption = true;
break;
}
} else {
log("Device doesn't support encryption; failing");
tagIsSupported = false;
}
// If we fall through, we can't support the policy
unsupportedList.add(R.string.policy_require_sd_encryption);
}
break;
// Note this policy; we enforce it in ExchangeService
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
policy.mRequireManualSyncWhenRoaming = getValueInt() == 1;
break;
// We are allowed to accept policies, regardless of value of this tag
// TODO: When we DO support a recovery password, we need to store the value in
// the account (so we know to utilize it)
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
// Read, but ignore, value
policy.mPasswordRecoveryEnabled = getValueInt() == 1;
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
if (getValueInt() == 1) {
tagIsSupported = false;
if (!smimeRequired) {
unsupportedList.add(R.string.policy_require_smime);
smimeRequired = true;
}
}
break;
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
int max = getValueInt();
if (max > 0) {
policy.mMaxAttachmentSize = max;
}
break;
// Complex characters are supported
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
policy.mPasswordComplexChars = getValueInt();
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
tagIsSupported = false;
if (tag == Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST) {
unsupportedList.add(R.string.policy_app_blacklist);
} else {
unsupportedList.add(R.string.policy_app_whitelist);
}
}
break;
// We accept calendar age, since we never ask for more than two weeks, and that's
// the most restrictive policy
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
policy.mMaxCalendarLookback = getValueInt();
break;
// We handle max email lookback
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
policy.mMaxEmailLookback = getValueInt();
break;
// We currently reject these next two policies
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
max = Integer.parseInt(value);
if (tag == Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE) {
policy.mMaxTextTruncationSize = max;
unsupportedList.add(R.string.policy_text_truncation);
} else {
policy.mMaxHtmlTruncationSize = max;
unsupportedList.add(R.string.policy_html_truncation);
}
tagIsSupported = false;
}
break;
default:
skipTag();
}
if (!tagIsSupported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
// Make sure policy settings are valid; password not enabled trumps other password settings
if (!passwordEnabled) {
policy.mPasswordMode = Policy.PASSWORD_MODE_NONE;
}
if (!unsupportedList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int res: unsupportedList) {
addPolicyString(sb, res);
}
policy.mProtocolPoliciesUnsupported = sb.toString();
}
setPolicy(policy);
}
/**
* Return whether or not either of the application list tags specifies any applications
* @param endTag the tag whose children we're walking through
* @return whether any applications were specified (by name or by hash)
* @throws IOException
*/
private boolean specifiesApplications(int endTag) throws IOException {
boolean specifiesApplications = false;
while (nextTag(endTag) != END) {
switch (tag) {
case Tags.PROVISION_APPLICATION_NAME:
case Tags.PROVISION_HASH:
specifiesApplications = true;
break;
default:
skipTag();
}
}
return specifiesApplications;
}
/*package*/ void parseProvisionDocXml(String doc) throws IOException {
Policy policy = new Policy();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new ByteArrayInputStream(doc.getBytes()), "UTF-8");
int type = parser.getEventType();
if (type == XmlPullParser.START_DOCUMENT) {
type = parser.next();
if (type == XmlPullParser.START_TAG) {
String tagName = parser.getName();
if (tagName.equals("wap-provisioningdoc")) {
parseWapProvisioningDoc(parser, policy);
}
}
}
} catch (XmlPullParserException e) {
throw new IOException();
}
setPolicy(policy);
}
/**
* Return true if password is required; otherwise false.
*/
private boolean parseSecurityPolicy(XmlPullParser parser, Policy policy)
throws XmlPullParserException, IOException {
boolean passwordRequired = true;
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String tagName = parser.getName();
if (tagName.equals("parm")) {
String name = parser.getAttributeValue(null, "name");
if (name.equals("4131")) {
String value = parser.getAttributeValue(null, "value");
if (value.equals("1")) {
passwordRequired = false;
}
}
}
}
}
return passwordRequired;
}
private void parseCharacteristic(XmlPullParser parser, Policy policy)
throws XmlPullParserException, IOException {
boolean enforceInactivityTimer = true;
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
if (parser.getName().equals("parm")) {
String name = parser.getAttributeValue(null, "name");
String value = parser.getAttributeValue(null, "value");
if (name.equals("AEFrequencyValue")) {
if (enforceInactivityTimer) {
if (value.equals("0")) {
policy.mMaxScreenLockTime = 1;
} else {
policy.mMaxScreenLockTime = 60*Integer.parseInt(value);
}
}
} else if (name.equals("AEFrequencyType")) {
// "0" here means we don't enforce an inactivity timeout
if (value.equals("0")) {
enforceInactivityTimer = false;
}
} else if (name.equals("DeviceWipeThreshold")) {
policy.mPasswordMaxFails = Integer.parseInt(value);
} else if (name.equals("CodewordFrequency")) {
// Ignore; has no meaning for us
} else if (name.equals("MinimumPasswordLength")) {
policy.mPasswordMinLength = Integer.parseInt(value);
} else if (name.equals("PasswordComplexity")) {
if (value.equals("0")) {
policy.mPasswordMode = Policy.PASSWORD_MODE_STRONG;
} else {
policy.mPasswordMode = Policy.PASSWORD_MODE_SIMPLE;
}
}
}
}
}
}
private void parseRegistry(XmlPullParser parser, Policy policy)
throws XmlPullParserException, IOException {
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("characteristic")) {
parseCharacteristic(parser, policy);
}
}
}
}
private void parseWapProvisioningDoc(XmlPullParser parser, Policy policy)
throws XmlPullParserException, IOException {
while (true) {
int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName().equals("wap-provisioningdoc")) {
break;
} else if (type == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("characteristic")) {
String atype = parser.getAttributeValue(null, "type");
if (atype.equals("SecurityPolicy")) {
// If a password isn't required, stop here
if (!parseSecurityPolicy(parser, policy)) {
return;
}
} else if (atype.equals("Registry")) {
parseRegistry(parser, policy);
return;
}
}
}
}
}
private void parseProvisionData() throws IOException {
while (nextTag(Tags.PROVISION_DATA) != END) {
if (tag == Tags.PROVISION_EAS_PROVISION_DOC) {
parseProvisionDocWbxml();
} else {
skipTag();
}
}
}
private void parsePolicy() throws IOException {
String policyType = null;
while (nextTag(Tags.PROVISION_POLICY) != END) {
switch (tag) {
case Tags.PROVISION_POLICY_TYPE:
policyType = getValue();
mService.userLog("Policy type: ", policyType);
break;
case Tags.PROVISION_POLICY_KEY:
mSecuritySyncKey = getValue();
break;
case Tags.PROVISION_STATUS:
mService.userLog("Policy status: ", getValue());
break;
case Tags.PROVISION_DATA:
if (policyType.equalsIgnoreCase(EasSyncService.EAS_2_POLICY_TYPE)) {
// Parse the old style XML document
parseProvisionDocXml(getValue());
} else {
// Parse the newer WBXML data
parseProvisionData();
}
break;
default:
skipTag();
}
}
}
private void parsePolicies() throws IOException {
while (nextTag(Tags.PROVISION_POLICIES) != END) {
if (tag == Tags.PROVISION_POLICY) {
parsePolicy();
} else {
skipTag();
}
}
}
private void parseDeviceInformation() throws IOException {
while (nextTag(Tags.SETTINGS_DEVICE_INFORMATION) != END) {
if (tag == Tags.SETTINGS_STATUS) {
mService.userLog("DeviceInformation status: " + getValue());
} else {
skipTag();
}
}
}
@Override
public boolean parse() throws IOException {
boolean res = false;
if (nextTag(START_DOCUMENT) != Tags.PROVISION_PROVISION) {
throw new IOException();
}
while (nextTag(START_DOCUMENT) != END_DOCUMENT) {
switch (tag) {
case Tags.PROVISION_STATUS:
int status = getValueInt();
mService.userLog("Provision status: ", status);
res = (status == 1);
break;
case Tags.SETTINGS_DEVICE_INFORMATION:
parseDeviceInformation();
break;
case Tags.PROVISION_POLICIES:
parsePolicies();
break;
case Tags.PROVISION_REMOTE_WIPE:
// Indicate remote wipe command received
mRemoteWipe = true;
break;
default:
skipTag();
}
}
return res;
}
}
| false | true | private void parseProvisionDocWbxml() throws IOException {
Policy policy = new Policy();
ArrayList<Integer> unsupportedList = new ArrayList<Integer>();
boolean passwordEnabled = false;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
boolean tagIsSupported = true;
int res = 0;
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordEnabled = true;
if (policy.mPasswordMode == Policy.PASSWORD_MODE_NONE) {
policy.mPasswordMode = Policy.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
policy.mPasswordMinLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
policy.mPasswordMode = Policy.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
policy.mMaxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
policy.mPasswordMaxFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
policy.mPasswordExpirationDays = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
policy.mPasswordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_CAMERA:
policy.mDontAllowCamera = (getValueInt() == 0);
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
tagIsSupported = false;
switch(tag) {
case Tags.PROVISION_ALLOW_STORAGE_CARD:
res = R.string.policy_dont_allow_storage_cards;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
res = R.string.policy_dont_allow_unsigned_apps;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
res = R.string.policy_dont_allow_unsigned_installers;
break;
case Tags.PROVISION_ALLOW_WIFI:
res = R.string.policy_dont_allow_wifi;
break;
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
res = R.string.policy_dont_allow_text_messaging;
break;
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
res = R.string.policy_dont_allow_pop_imap;
break;
case Tags.PROVISION_ALLOW_IRDA:
res = R.string.policy_dont_allow_irda;
break;
case Tags.PROVISION_ALLOW_HTML_EMAIL:
res = R.string.policy_dont_allow_html;
policy.mDontAllowHtml = true;
break;
case Tags.PROVISION_ALLOW_BROWSER:
res = R.string.policy_dont_allow_browser;
break;
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
res = R.string.policy_dont_allow_consumer_email;
break;
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
res = R.string.policy_dont_allow_internet_sharing;
break;
}
if (res > 0) {
unsupportedList.add(res);
}
}
break;
case Tags.PROVISION_ATTACHMENTS_ENABLED:
policy.mDontAllowAttachments = getValueInt() != 1;
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_bluetooth_restricted);
}
break;
// We may now support device (internal) encryption; we'll check this capability
// below with the call to SecurityPolicy.isSupported()
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
if (getValueInt() == 1) {
if (!deviceSupportsEncryption()) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_require_encryption);
} else {
policy.mRequireEncryption = true;
}
}
break;
// Note that DEVICE_ENCRYPTION_ENABLED refers to SD card encryption, which the OS
// does not yet support.
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
if (getValueInt() == 1) {
log("Policy requires SD card encryption");
// Let's see if this can be supported on our device...
if (deviceSupportsEncryption()) {
StorageManager sm = (StorageManager)mService.mContext.getSystemService(
Context.STORAGE_SERVICE);
// NOTE: Private API!
// Go through volumes; if ANY are removable, we can't support this
// policy.
StorageVolume[] volumeList = sm.getVolumeList();
for (StorageVolume volume: volumeList) {
if (volume.isRemovable()) {
tagIsSupported = false;
log("Removable: " + volume.getDescription());
break; // Break only from the storage volume loop
} else {
log("Not Removable: " + volume.getDescription());
}
}
if (tagIsSupported) {
// If this policy is requested, we MUST also require encryption
log("Device supports SD card encryption");
policy.mRequireEncryption = true;
break;
}
} else {
log("Device doesn't support encryption; failing");
tagIsSupported = false;
}
// If we fall through, we can't support the policy
unsupportedList.add(R.string.policy_require_sd_encryption);
}
break;
// Note this policy; we enforce it in ExchangeService
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
policy.mRequireManualSyncWhenRoaming = getValueInt() == 1;
break;
// We are allowed to accept policies, regardless of value of this tag
// TODO: When we DO support a recovery password, we need to store the value in
// the account (so we know to utilize it)
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
// Read, but ignore, value
policy.mPasswordRecoveryEnabled = getValueInt() == 1;
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
if (getValueInt() == 1) {
tagIsSupported = false;
if (!smimeRequired) {
unsupportedList.add(R.string.policy_require_smime);
smimeRequired = true;
}
}
break;
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
int max = getValueInt();
if (max > 0) {
policy.mMaxAttachmentSize = max;
}
break;
// Complex characters are supported
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
policy.mPasswordComplexChars = getValueInt();
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
tagIsSupported = false;
if (tag == Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST) {
unsupportedList.add(R.string.policy_app_blacklist);
} else {
unsupportedList.add(R.string.policy_app_whitelist);
}
}
break;
// We accept calendar age, since we never ask for more than two weeks, and that's
// the most restrictive policy
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
policy.mMaxCalendarLookback = getValueInt();
break;
// We handle max email lookback
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
policy.mMaxEmailLookback = getValueInt();
break;
// We currently reject these next two policies
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
max = Integer.parseInt(value);
if (tag == Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE) {
policy.mMaxTextTruncationSize = max;
unsupportedList.add(R.string.policy_text_truncation);
} else {
policy.mMaxHtmlTruncationSize = max;
unsupportedList.add(R.string.policy_html_truncation);
}
tagIsSupported = false;
}
break;
default:
skipTag();
}
if (!tagIsSupported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
// Make sure policy settings are valid; password not enabled trumps other password settings
if (!passwordEnabled) {
policy.mPasswordMode = Policy.PASSWORD_MODE_NONE;
}
if (!unsupportedList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int res: unsupportedList) {
addPolicyString(sb, res);
}
policy.mProtocolPoliciesUnsupported = sb.toString();
}
setPolicy(policy);
}
| private void parseProvisionDocWbxml() throws IOException {
Policy policy = new Policy();
ArrayList<Integer> unsupportedList = new ArrayList<Integer>();
boolean passwordEnabled = false;
while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) {
boolean tagIsSupported = true;
int res = 0;
switch (tag) {
case Tags.PROVISION_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
passwordEnabled = true;
if (policy.mPasswordMode == Policy.PASSWORD_MODE_NONE) {
policy.mPasswordMode = Policy.PASSWORD_MODE_SIMPLE;
}
}
break;
case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH:
policy.mPasswordMinLength = getValueInt();
break;
case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED:
if (getValueInt() == 1) {
policy.mPasswordMode = Policy.PASSWORD_MODE_STRONG;
}
break;
case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK:
// EAS gives us seconds, which is, happily, what the PolicySet requires
policy.mMaxScreenLockTime = getValueInt();
break;
case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS:
policy.mPasswordMaxFails = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION:
policy.mPasswordExpirationDays = getValueInt();
break;
case Tags.PROVISION_DEVICE_PASSWORD_HISTORY:
policy.mPasswordHistory = getValueInt();
break;
case Tags.PROVISION_ALLOW_CAMERA:
policy.mDontAllowCamera = (getValueInt() == 0);
break;
case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD:
// Ignore this unless there's any MSFT documentation for what this means
// Hint: I haven't seen any that's more specific than "simple"
getValue();
break;
// The following policies, if false, can't be supported at the moment
case Tags.PROVISION_ALLOW_STORAGE_CARD:
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
case Tags.PROVISION_ALLOW_WIFI:
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
case Tags.PROVISION_ALLOW_IRDA:
case Tags.PROVISION_ALLOW_HTML_EMAIL:
case Tags.PROVISION_ALLOW_BROWSER:
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
if (getValueInt() == 0) {
tagIsSupported = false;
switch(tag) {
case Tags.PROVISION_ALLOW_STORAGE_CARD:
res = R.string.policy_dont_allow_storage_cards;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS:
res = R.string.policy_dont_allow_unsigned_apps;
break;
case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES:
res = R.string.policy_dont_allow_unsigned_installers;
break;
case Tags.PROVISION_ALLOW_WIFI:
res = R.string.policy_dont_allow_wifi;
break;
case Tags.PROVISION_ALLOW_TEXT_MESSAGING:
res = R.string.policy_dont_allow_text_messaging;
break;
case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL:
res = R.string.policy_dont_allow_pop_imap;
break;
case Tags.PROVISION_ALLOW_IRDA:
res = R.string.policy_dont_allow_irda;
break;
case Tags.PROVISION_ALLOW_HTML_EMAIL:
res = R.string.policy_dont_allow_html;
policy.mDontAllowHtml = true;
break;
case Tags.PROVISION_ALLOW_BROWSER:
res = R.string.policy_dont_allow_browser;
break;
case Tags.PROVISION_ALLOW_CONSUMER_EMAIL:
res = R.string.policy_dont_allow_consumer_email;
break;
case Tags.PROVISION_ALLOW_INTERNET_SHARING:
res = R.string.policy_dont_allow_internet_sharing;
break;
}
if (res > 0) {
unsupportedList.add(res);
}
}
break;
case Tags.PROVISION_ATTACHMENTS_ENABLED:
policy.mDontAllowAttachments = getValueInt() != 1;
break;
// Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed
case Tags.PROVISION_ALLOW_BLUETOOTH:
if (getValueInt() != 2) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_bluetooth_restricted);
}
break;
// We may now support device (internal) encryption; we'll check this capability
// below with the call to SecurityPolicy.isSupported()
case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION:
if (getValueInt() == 1) {
if (!deviceSupportsEncryption()) {
tagIsSupported = false;
unsupportedList.add(R.string.policy_require_encryption);
} else {
policy.mRequireEncryption = true;
}
}
break;
// Note that DEVICE_ENCRYPTION_ENABLED refers to SD card encryption, which the OS
// does not yet support.
case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED:
if (getValueInt() == 1) {
log("Policy requires SD card encryption");
// Let's see if this can be supported on our device...
if (deviceSupportsEncryption()) {
StorageManager sm = (StorageManager)mService.mContext.getSystemService(
Context.STORAGE_SERVICE);
// NOTE: Private API!
// Go through volumes; if ANY are removable, we can't support this
// policy.
StorageVolume[] volumeList = sm.getVolumeList();
for (StorageVolume volume: volumeList) {
if (volume.isRemovable()) {
tagIsSupported = false;
log("Removable: " + volume.getDescription(mService.mContext));
break; // Break only from the storage volume loop
} else {
log("Not Removable: " + volume.getDescription(mService.mContext));
}
}
if (tagIsSupported) {
// If this policy is requested, we MUST also require encryption
log("Device supports SD card encryption");
policy.mRequireEncryption = true;
break;
}
} else {
log("Device doesn't support encryption; failing");
tagIsSupported = false;
}
// If we fall through, we can't support the policy
unsupportedList.add(R.string.policy_require_sd_encryption);
}
break;
// Note this policy; we enforce it in ExchangeService
case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING:
policy.mRequireManualSyncWhenRoaming = getValueInt() == 1;
break;
// We are allowed to accept policies, regardless of value of this tag
// TODO: When we DO support a recovery password, we need to store the value in
// the account (so we know to utilize it)
case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED:
// Read, but ignore, value
policy.mPasswordRecoveryEnabled = getValueInt() == 1;
break;
// The following policies, if true, can't be supported at the moment
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES:
case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM:
case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM:
if (getValueInt() == 1) {
tagIsSupported = false;
if (!smimeRequired) {
unsupportedList.add(R.string.policy_require_smime);
smimeRequired = true;
}
}
break;
case Tags.PROVISION_MAX_ATTACHMENT_SIZE:
int max = getValueInt();
if (max > 0) {
policy.mMaxAttachmentSize = max;
}
break;
// Complex characters are supported
case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS:
policy.mPasswordComplexChars = getValueInt();
break;
// The following policies are moot; they allow functionality that we don't support
case Tags.PROVISION_ALLOW_DESKTOP_SYNC:
case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION:
case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS:
case Tags.PROVISION_ALLOW_REMOTE_DESKTOP:
skipTag();
break;
// We don't handle approved/unapproved application lists
case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST:
case Tags.PROVISION_APPROVED_APPLICATION_LIST:
// Parse and throw away the content
if (specifiesApplications(tag)) {
tagIsSupported = false;
if (tag == Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST) {
unsupportedList.add(R.string.policy_app_blacklist);
} else {
unsupportedList.add(R.string.policy_app_whitelist);
}
}
break;
// We accept calendar age, since we never ask for more than two weeks, and that's
// the most restrictive policy
case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER:
policy.mMaxCalendarLookback = getValueInt();
break;
// We handle max email lookback
case Tags.PROVISION_MAX_EMAIL_AGE_FILTER:
policy.mMaxEmailLookback = getValueInt();
break;
// We currently reject these next two policies
case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE:
case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE:
String value = getValue();
// -1 indicates no required truncation
if (!value.equals("-1")) {
max = Integer.parseInt(value);
if (tag == Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE) {
policy.mMaxTextTruncationSize = max;
unsupportedList.add(R.string.policy_text_truncation);
} else {
policy.mMaxHtmlTruncationSize = max;
unsupportedList.add(R.string.policy_html_truncation);
}
tagIsSupported = false;
}
break;
default:
skipTag();
}
if (!tagIsSupported) {
log("Policy not supported: " + tag);
mIsSupportable = false;
}
}
// Make sure policy settings are valid; password not enabled trumps other password settings
if (!passwordEnabled) {
policy.mPasswordMode = Policy.PASSWORD_MODE_NONE;
}
if (!unsupportedList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (int res: unsupportedList) {
addPolicyString(sb, res);
}
policy.mProtocolPoliciesUnsupported = sb.toString();
}
setPolicy(policy);
}
|
diff --git a/ttools/src/main/uk/ac/starlink/ttools/lint/StreamHandler.java b/ttools/src/main/uk/ac/starlink/ttools/lint/StreamHandler.java
index b675a5cab..eb9acf3fc 100644
--- a/ttools/src/main/uk/ac/starlink/ttools/lint/StreamHandler.java
+++ b/ttools/src/main/uk/ac/starlink/ttools/lint/StreamHandler.java
@@ -1,177 +1,177 @@
package uk.ac.starlink.ttools.lint;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import org.xml.sax.Locator;
import uk.ac.starlink.util.Base64InputStream;
import uk.ac.starlink.util.Compression;
import uk.ac.starlink.util.PipeReaderThread;
import uk.ac.starlink.util.URLUtils;
/**
* Handler for STREAM elements.
*
* @author Mark Taylor (Starlink)
* @since 8 Apr 2005
*/
public class StreamHandler extends ElementHandler {
private PipeReaderThread pipeReader_;
private OutputStream dataSink_;
public void startElement() {
/* Get and check href and encoding attributes. */
String href = getAttribute( "href" );
String encoding = getAttribute( "encoding" );
- if ( href == null || href.trim().length() == 0 &&
+ if ( ( href == null || href.trim().length() == 0 ) &&
! "base64".equals( encoding ) ) {
warning( this + " has no href but encoding is not base64" );
}
ElementHandler parent = getAncestry().getParent();
if ( parent instanceof StreamingHandler ) {
final StreamingHandler streamer = (StreamingHandler) parent;
/* If we have the data specified by URL, feed the resulting
* decoded input stream to the stream consumer directly. */
if ( href != null ) {
Locator locator = getContext().getLocator();
String systemId = locator == null ? null
: locator.getSystemId();
URL url = URLUtils.makeURL( systemId, href );
if ( url != null ) {
InputStream in = null;
try {
in = url.openStream();
in = new BufferedInputStream( in );
in = decodeStream( in );
streamer.feed( in );
}
catch ( IOException e ) {
warning( "Read error for external stream " + e );
}
finally {
if ( in != null ) {
try {
in.close();
}
catch ( IOException e ) {
// ignore.
}
}
}
}
else {
error( "Can't make sense of href '" + href + "'" );
}
}
/* Otherwise, we must expect the data to appear in the STREAM
* element's content. Set up reader which will be fed bytes
* from this handler's characters() method during the parse. */
else {
try {
pipeReader_ = new PipeReaderThread() {
protected void doReading( InputStream in )
throws IOException {
in = new BufferedInputStream( in );
in = decodeStream( in );
streamer.feed( in );
}
};
pipeReader_.start();
dataSink_ = new BufferedOutputStream( pipeReader_
.getOutputStream() );
}
catch ( IOException e ) {
error( "Trouble with STREAM content - can't validate" );
pipeReader_ = null;
dataSink_ = null;
}
}
}
else {
error( "Illegal parent of STREAM " + parent );
}
}
public void characters( char[] ch, int start, int leng ) {
/* Deal with any character content of the element by writing them
* to the consumer stream we've set up. */
if ( dataSink_ != null ) {
try {
for ( int i = 0; i < leng; i++ ) {
dataSink_.write( ch[ start++ ] );
}
}
catch ( IOException e ) {
// Ignore - it will be picked up by finishReading if it's
// important.
}
}
else {
error( "Unexpected content of STREAM " +
"(stream with href should be empty)" );
}
}
public void endElement() {
/* Tidy up the consumer stream. */
if ( dataSink_ != null ) {
assert pipeReader_ != null;
try {
dataSink_.close();
pipeReader_.finishReading();
}
catch ( IOException e ) {
error( "Streaming error " + e );
}
dataSink_ = null;
pipeReader_ = null;
}
}
/**
* Decode the binary data stream in accordance with the encoding attribute
* on this element.
*
* @param in raw input stream
* @return decoded input stream
*/
private InputStream decodeStream( InputStream in ) throws IOException {
String encoding = getAttribute( "encoding" );
if ( encoding == null ||
encoding.equals( "none" ) ||
encoding.trim().length() == 0 ) {
return in;
}
else if ( encoding.equals( "base64" ) ) {
return new Base64InputStream( in );
}
else if ( encoding.equals( "gzip" ) ) {
return new GZIPInputStream( in );
}
else if ( encoding.equals( "dynamic" ) ) {
warning( "Parser can't interpret dynamic stream " +
"encodings properly - sorry" );
/* Pass it to the Compression class, which will probably be able
* to work out the correct compression type based on content.
* This shirks the validation though. */
return Compression.decompressStatic( in );
}
else {
error( "Unknown encoding type '" + encoding + "' (assume none)" );
return in;
}
}
}
| true | true | public void startElement() {
/* Get and check href and encoding attributes. */
String href = getAttribute( "href" );
String encoding = getAttribute( "encoding" );
if ( href == null || href.trim().length() == 0 &&
! "base64".equals( encoding ) ) {
warning( this + " has no href but encoding is not base64" );
}
ElementHandler parent = getAncestry().getParent();
if ( parent instanceof StreamingHandler ) {
final StreamingHandler streamer = (StreamingHandler) parent;
/* If we have the data specified by URL, feed the resulting
* decoded input stream to the stream consumer directly. */
if ( href != null ) {
Locator locator = getContext().getLocator();
String systemId = locator == null ? null
: locator.getSystemId();
URL url = URLUtils.makeURL( systemId, href );
if ( url != null ) {
InputStream in = null;
try {
in = url.openStream();
in = new BufferedInputStream( in );
in = decodeStream( in );
streamer.feed( in );
}
catch ( IOException e ) {
warning( "Read error for external stream " + e );
}
finally {
if ( in != null ) {
try {
in.close();
}
catch ( IOException e ) {
// ignore.
}
}
}
}
else {
error( "Can't make sense of href '" + href + "'" );
}
}
/* Otherwise, we must expect the data to appear in the STREAM
* element's content. Set up reader which will be fed bytes
* from this handler's characters() method during the parse. */
else {
try {
pipeReader_ = new PipeReaderThread() {
protected void doReading( InputStream in )
throws IOException {
in = new BufferedInputStream( in );
in = decodeStream( in );
streamer.feed( in );
}
};
pipeReader_.start();
dataSink_ = new BufferedOutputStream( pipeReader_
.getOutputStream() );
}
catch ( IOException e ) {
error( "Trouble with STREAM content - can't validate" );
pipeReader_ = null;
dataSink_ = null;
}
}
}
else {
error( "Illegal parent of STREAM " + parent );
}
}
| public void startElement() {
/* Get and check href and encoding attributes. */
String href = getAttribute( "href" );
String encoding = getAttribute( "encoding" );
if ( ( href == null || href.trim().length() == 0 ) &&
! "base64".equals( encoding ) ) {
warning( this + " has no href but encoding is not base64" );
}
ElementHandler parent = getAncestry().getParent();
if ( parent instanceof StreamingHandler ) {
final StreamingHandler streamer = (StreamingHandler) parent;
/* If we have the data specified by URL, feed the resulting
* decoded input stream to the stream consumer directly. */
if ( href != null ) {
Locator locator = getContext().getLocator();
String systemId = locator == null ? null
: locator.getSystemId();
URL url = URLUtils.makeURL( systemId, href );
if ( url != null ) {
InputStream in = null;
try {
in = url.openStream();
in = new BufferedInputStream( in );
in = decodeStream( in );
streamer.feed( in );
}
catch ( IOException e ) {
warning( "Read error for external stream " + e );
}
finally {
if ( in != null ) {
try {
in.close();
}
catch ( IOException e ) {
// ignore.
}
}
}
}
else {
error( "Can't make sense of href '" + href + "'" );
}
}
/* Otherwise, we must expect the data to appear in the STREAM
* element's content. Set up reader which will be fed bytes
* from this handler's characters() method during the parse. */
else {
try {
pipeReader_ = new PipeReaderThread() {
protected void doReading( InputStream in )
throws IOException {
in = new BufferedInputStream( in );
in = decodeStream( in );
streamer.feed( in );
}
};
pipeReader_.start();
dataSink_ = new BufferedOutputStream( pipeReader_
.getOutputStream() );
}
catch ( IOException e ) {
error( "Trouble with STREAM content - can't validate" );
pipeReader_ = null;
dataSink_ = null;
}
}
}
else {
error( "Illegal parent of STREAM " + parent );
}
}
|
diff --git a/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/LuceneRequestProcessor.java b/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/LuceneRequestProcessor.java
index d435a644..0d4bcaed 100644
--- a/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/LuceneRequestProcessor.java
+++ b/contentconnector/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/search/LuceneRequestProcessor.java
@@ -1,489 +1,492 @@
package com.gentics.cr.lucene.search;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Vector;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import com.gentics.cr.CRConfig;
import com.gentics.cr.CRError;
import com.gentics.cr.CRRequest;
import com.gentics.cr.CRResolvableBean;
import com.gentics.cr.RequestProcessor;
import com.gentics.cr.configuration.GenericConfiguration;
import com.gentics.cr.exceptions.CRException;
import com.gentics.cr.lucene.indexaccessor.IndexAccessor;
import com.gentics.cr.lucene.indexer.index.LuceneAnalyzerFactory;
import com.gentics.cr.lucene.indexer.index.LuceneIndexLocation;
import com.gentics.cr.lucene.search.highlight.AdvancedContentHighlighter;
import com.gentics.cr.lucene.search.highlight.ContentHighlighter;
import com.gentics.cr.lucene.search.query.CRQueryParserFactory;
import com.gentics.cr.monitoring.MonitorFactory;
import com.gentics.cr.monitoring.UseCase;
import com.gentics.cr.util.generics.Lists;
/**
*
* Last changed: $Date: 2010-04-01 15:25:54 +0200 (Do, 01 Apr 2010) $
* @version $Revision: 545 $
* @author $Author: [email protected] $
*
*/
public class LuceneRequestProcessor extends RequestProcessor {
protected static Logger log = Logger.getLogger(LuceneRequestProcessor.class);
protected static Logger ext_log = Logger.getLogger(LuceneRequestProcessor.class);
private CRSearcher searcher = null;
protected String name=null;
private boolean getStoredAttributes = false;
/**
* init CRMetaResolvableBean with or without parsed_query
*/
private boolean showParsedQuery = false;
private static final String SCORE_ATTRIBUTE_KEY = "SCOREATTRIBUTE";
private static final String GET_STORED_ATTRIBUTE_KEY = "GETSTOREDATTRIBUTES";
private Hashtable<String,ContentHighlighter> highlighters;
private static final String SEARCH_COUNT_KEY = "SEARCHCOUNT";
private static final String ID_ATTRIBUTE_KEY = "idAttribute";
/**
* Key where to find the total hits of the search in the metaresolvable.
* Metaresolvable has to be enabled => LuceneRequestProcessor.META_RESOLVABLE_KEY
*/
public static final String META_HITS_KEY = "totalhits";
/**
* Key where to find the start position of the search in the metaresolvable.
* Metaresolvable has to be enabled => LuceneRequestProcessor.META_RESOLVABLE_KEY
*/
public static final String META_START_KEY = "start";
/**
* TODO
*/
public static final String META_COUNT_KEY = "count";
/**
* TODO
*/
public static final String META_QUERY_KEY = "query";
/**
* TODO
*/
public static final String META_MAXSCORE_KEY = "maxscore";
/**
* Key where to find the query used for highlighting the content. Usually this is the
* searchqery without the permissions and meta search informations.
* If this is not set, the requestFilter (default query) will be used
*/
public static final String HIGHLIGHT_QUERY_KEY = "highlightquery";
/**
* Configuration key for the attributes to be searched when no explizit
* attribute is given in the query.
*/
public static final String SEARCHED_ATTRIBUTES_KEY = "searchedAttributes";
/**
* Key to store the parsed query in the meta resolvable.
*/
public static final String PARSED_QUERY_KEY = "parsed_query";
/**
* Key to configure if CRMetaResolvableBean should contain parsed_query
*
*
*/
private static final String SHOW_PARSED_QUERY_KEY = "showparsedquery";
/**
* Create new instance of LuceneRequestProcessor.
* @param config
* @throws CRException
*/
public LuceneRequestProcessor(final CRConfig config) throws CRException {
super(config);
this.name = config.getName();
this.searcher = new CRSearcher(config);
getStoredAttributes = Boolean.parseBoolean(
(String) config.get(GET_STORED_ATTRIBUTE_KEY));
highlighters = ContentHighlighter.getTransformerTable(
(GenericConfiguration) config);
showParsedQuery = Boolean.parseBoolean(
(String) this.config.get(SHOW_PARSED_QUERY_KEY));
}
/**
* Converts a generic List to a List of Field.
* @param l - generic list
* @return list of vectors, null in case l was null, Vector<Field> with size
* null if l.size() was 0
*/
private static List<Field> toFieldList(final List<Fieldable> l) {
if (l == null) {
return null;
} else if (l.size() > 0) {
return Lists.toSpecialList(l, Field.class);
} else {
return new Vector<Field>(0);
}
}
/**
* This returns a collection of CRResolvableBeans containing the IDATTRIBUTE
* and all STORED ATTRIBUTES of the Lucene Documents.
* @param request - CRRequest containing the query in RequestFilter
* @param doNavigation - if set to true there will be generated explanation
* output to the explanation logger of CRSearcher
* @return search result as Collection of CRResolvableBean
* @throws CRException
*/
public final Collection<CRResolvableBean> getObjects(final CRRequest request, final boolean doNavigation)
throws CRException {
UseCase ucGetObjects = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")");
/**
* search preparations (instantiate/validate all needed variables)
*/
UseCase ucPrepareSearch = startUseCase("LuceneRequestProcessor.getObjects(" + name + ")#prepareSearch");
ArrayList<CRResolvableBean> result = new ArrayList<CRResolvableBean>();
int count = getCount(request);
int start = getStart(request);
ucPrepareSearch.stop();
/** * search preparations */
/**
* Get results
*/
long indexSearchStartTime = System.currentTimeMillis();
UseCase ucSearch = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")#search");
HashMap<String, Object> searchResult = null;
try {
searchResult = this.searcher.search(request.getRequestFilter(), getSearchedAttributes(), count, start,
doNavigation, request.getSortArray(), request);
} catch (IOException ex) {
log.error("Error while getting search results from index.");
throw new CRException(ex);
}
ucSearch.stop();
log.debug("Search in Index took " + (System.currentTimeMillis() - indexSearchStartTime) + "ms");
/** * Get results */
if (log.isDebugEnabled()) {
if(searchResult != null) {
for (Object res : searchResult.values()) {
if (res instanceof LinkedHashMap) {
- LinkedHashMap<Document, Float> documents =
- (LinkedHashMap<Document, Float>) res;
+ LinkedHashMap<?, ?> documents =
+ (LinkedHashMap<?, ?>) res;
if (documents != null) {
- for (Entry<Document, Float> entry
+ for (Entry<?, ?> entry
: documents.entrySet()) {
- Document doc = entry.getKey();
- if (doc != null) {
- log.debug("LuceneRequestProcessor.getObjects: "
- + doc.getField("contentid").toString());
+ Object object = entry.getKey();
+ if(object instanceof Document) {
+ Document doc = (Document) object;
+ if (doc != null) {
+ log.debug("LuceneRequestProcessor.getObjects: "
+ + doc.getField("contentid").toString());
+ }
}
}
}
}
}
} else {
log.debug("No results found.");
}
}
/**
* process search
*/
UseCase ucProcessSearch = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")#processSearch");
if (searchResult != null) {
Query parsedQuery = (Query) searchResult.get(CRSearcher.RESULT_QUERY_KEY);
result = processMetaData(result, searchResult, parsedQuery, request, start, count);
result = processSearchResolvables(result, searchResult, parsedQuery, request);
} else {
// searchresult is null - we don't want to proceed - we want to throw an error
result = null;
}
ucProcessSearch.stop();
/** * process search */
ucGetObjects.stop();
return result;
}
/**
* Start a usecase.
* @param message Use the specified message as description.
* @return Instantiated usecase
*/
private UseCase startUseCase(final String message) {
return MonitorFactory.startUseCase(message);
}
/**
* Get count (number of items to return) from request and validate it. Fall back to config count if not set.
* @param request Request to get the count of.
* @return count integer
* @throws CRException If cound can not be determined
*/
private int getCount(final CRRequest request) throws CRException {
int count = request.getCount();
//IF COUNT IS NOT SET IN THE REQUEST, USE DEFAULT VALUE LOADED FROM
//CONFIG
if (count <= 0) {
String cstring = (String) this.config.get(SEARCH_COUNT_KEY);
if (cstring != null) {
count = new Integer(cstring);
}
}
if (count <= 0) {
String message = "Default count is lower or equal to 0! This will "
+ "result in an error. Overthink your config (insert rp."
+ "<number>.searchcount=<value> in your properties file)!";
log.error(message);
throw new CRException(new CRError("Error", message));
}
return count;
}
/**
* Get the start position from the request.
* @param request request to get the start position from.
* @return return a position great than 0
* @throws CRException if start < 0 an error is thrown
*/
private int getStart(final CRRequest request) throws CRException {
int start = request.getStart();
if (start < 0) {
String message = "Bad request: start is lower than 0!";
log.error(message);
throw new CRException(new CRError("Error", message));
}
return start;
}
/**
* Create a metadata bean using the provided arguments (contentid: 10001).
* @param result List of resolvables to add it to
* @param searchResult List of searchresults to use for metadata object
* @param parsedQuery query used to fetch the results
* @param request CRRequest
* @param start start position
* @param count number of items to return
* @return list of results with added metadata bean
*/
private ArrayList<CRResolvableBean> processMetaData(final ArrayList<CRResolvableBean> result,
final HashMap<String, Object> searchResult, final Query parsedQuery, final CRRequest request,
final int start, final int count) {
UseCase ucProcessSearchMeta =
startUseCase("LuceneRequestProcessor.getObjects(" + name + ")#processSearch.Metaresolvables");
Object metaKey = request.get(META_RESOLVABLE_KEY);
if (metaKey != null && (Boolean) metaKey) {
final CRResolvableBean metaBean;
if (showParsedQuery) {
metaBean = new CRMetaResolvableBean(
searchResult, request, parsedQuery, start, count);
} else {
metaBean = new CRMetaResolvableBean(
searchResult, request, start, count);
}
result.add(metaBean);
}
ucProcessSearchMeta.stop();
return result;
}
/**
* do the actual search, parse the highlight query and process all documents.
* @param result List to store the resulting documents in
* @param searchResult Actual searchresults from Searcher
* @param parsedQuery query to use for storing with the documents
* @param request needed for highlighting the query
* @return list of results containing all documents
*/
private ArrayList<CRResolvableBean> processSearchResolvables(final ArrayList<CRResolvableBean> result,
final HashMap<String, Object> searchResult, Query parsedQuery, final CRRequest request) {
UseCase ucProcessSearchResolvables =
startUseCase("LuceneRequestProcessor.getObjects(" + name + ")#processSearch.Resolvables");
LinkedHashMap<Document, Float> docs =
objectToLinkedHashMapDocuments(searchResult.get(CRSearcher.RESULT_RESULT_KEY));
LuceneIndexLocation idsLocation = LuceneIndexLocation.getIndexLocation(this.config);
IndexAccessor indexAccessor = idsLocation.getAccessor();
IndexReader reader = null;
try {
reader = indexAccessor.getReader(false);
parseHighlightQuery(request, reader, parsedQuery);
processDocuments(docs, result, reader, parsedQuery);
} catch (IOException e) {
log.error("Cannot get Index reader for highlighting", e);
} finally {
indexAccessor.release(reader, false);
}
ucProcessSearchResolvables.stop();
return result;
}
/**
* Parse the highlight query with the analyzer/parser provided by the config.
* @param request CRRequest used to get the parser instance
* @param reader IndexReader for rewriting the parsedQuery
* @param parsedQuery query for parsed query.
* @return highlighted query
* @throws IOException if rewriting the query goes wrong this exception is thrown
*/
private Query parseHighlightQuery(final CRRequest request, final IndexReader reader,
Query parsedQuery) throws IOException {
//PARSE HIGHLIGHT QUERY
Object highlightQuery = request.get(HIGHLIGHT_QUERY_KEY);
if (highlightQuery != null) {
Analyzer analyzer = LuceneAnalyzerFactory.createAnalyzer((GenericConfiguration) this.config);
QueryParser parser =
CRQueryParserFactory.getConfiguredParser(getSearchedAttributes(), analyzer, request, config);
try {
parsedQuery = parser.parse((String) highlightQuery);
parsedQuery = parsedQuery.rewrite(reader);
} catch (ParseException e) {
log.error("Error while parsing hightlight query", e);
}
}
return parsedQuery;
}
/**
* Perform highlighting for one document.
* @param crBean bean to check if we need to highlight something and set the highlighting afterwards.
* @param doc document to get the document id for the highligther
* @param parsedQuery rewritten Query
* @param reader prepared index Reader
*/
private void doHighlighting(final CRResolvableBean crBean, final Document doc,
final Query parsedQuery, final IndexReader reader) {
//IF HIGHLIGHTERS ARE CONFIGURED => DO HIGHLIGHTNING
if (highlighters != null) {
UseCase ucProcessSearchHighlight = MonitorFactory.startUseCase("LuceneRequestProcessor." + "getObjects("
+ name + ")#processSearch.Highlight");
long s2 = System.currentTimeMillis();
for (Entry<String, ContentHighlighter> contentHighlighter : highlighters.entrySet()) {
ContentHighlighter highligther = contentHighlighter.getValue();
String att = contentHighlighter.getKey();
//IF crBean matches the highlighters rule => highlight
if (highligther.match(crBean)) {
String ret = null;
if (highligther instanceof AdvancedContentHighlighter) {
AdvancedContentHighlighter advancedHighlighter = (AdvancedContentHighlighter) highligther;
int documentId = Integer.parseInt(doc.get("id"));
ret = advancedHighlighter.highlight(parsedQuery, reader, documentId, att);
} else {
ret = highligther.highlight((String) crBean.get(att), parsedQuery);
}
if (ret != null && !"".equals(ret)) {
crBean.set(att, ret);
}
}
}
log.debug("Highlighters took " + (System.currentTimeMillis() - s2) + "ms");
ucProcessSearchHighlight.stop();
}
}
private void processDocuments(LinkedHashMap<Document, Float> docs, final ArrayList<CRResolvableBean> result,
final IndexReader reader, final Query parsedQuery) {
String scoreAttribute = (String) config.get(SCORE_ATTRIBUTE_KEY);
//PROCESS RESULT
if (docs != null) {
String idAttribute = (String) this.config.get(ID_ATTRIBUTE_KEY);
for (Entry<Document, Float> entry : docs.entrySet()) {
Document doc = entry.getKey();
Float score = entry.getValue();
CRResolvableBean crBean = new CRResolvableBean(doc.get(idAttribute));
if (getStoredAttributes) {
for (Field field : toFieldList(doc.getFields())) {
if (field.isStored()) {
if (field.isBinary()) {
crBean.set(field.name(), field.getBinaryValue());
} else {
crBean.set(field.name(), field.stringValue());
}
}
}
}
if (scoreAttribute != null && !"".equals(scoreAttribute)) {
crBean.set(scoreAttribute, score);
}
//DO HIGHLIGHTING
doHighlighting(crBean, doc, parsedQuery, reader);
ext_log.debug("Found " + crBean.getContentid() + " with score " + score.toString());
result.add(crBean);
}
}
}
/**
* TODO javadoc.
* @param obj TODO javadoc
* @return TODO javadoc
*/
@SuppressWarnings("unchecked")
private LinkedHashMap<Document, Float> objectToLinkedHashMapDocuments(
final Object obj) {
return (LinkedHashMap<Document, Float>) obj;
}
/**
* @return the attributes to search in from the condfig.
*/
private String[] getSearchedAttributes() {
String sa = (String) this.config.get(SEARCHED_ATTRIBUTES_KEY);
String[] ret = null;
if (sa != null) {
ret = sa.split(",");
}
return ret;
}
@Override
public void finalize() {
}
}
| false | true | public final Collection<CRResolvableBean> getObjects(final CRRequest request, final boolean doNavigation)
throws CRException {
UseCase ucGetObjects = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")");
/**
* search preparations (instantiate/validate all needed variables)
*/
UseCase ucPrepareSearch = startUseCase("LuceneRequestProcessor.getObjects(" + name + ")#prepareSearch");
ArrayList<CRResolvableBean> result = new ArrayList<CRResolvableBean>();
int count = getCount(request);
int start = getStart(request);
ucPrepareSearch.stop();
/** * search preparations */
/**
* Get results
*/
long indexSearchStartTime = System.currentTimeMillis();
UseCase ucSearch = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")#search");
HashMap<String, Object> searchResult = null;
try {
searchResult = this.searcher.search(request.getRequestFilter(), getSearchedAttributes(), count, start,
doNavigation, request.getSortArray(), request);
} catch (IOException ex) {
log.error("Error while getting search results from index.");
throw new CRException(ex);
}
ucSearch.stop();
log.debug("Search in Index took " + (System.currentTimeMillis() - indexSearchStartTime) + "ms");
/** * Get results */
if (log.isDebugEnabled()) {
if(searchResult != null) {
for (Object res : searchResult.values()) {
if (res instanceof LinkedHashMap) {
LinkedHashMap<Document, Float> documents =
(LinkedHashMap<Document, Float>) res;
if (documents != null) {
for (Entry<Document, Float> entry
: documents.entrySet()) {
Document doc = entry.getKey();
if (doc != null) {
log.debug("LuceneRequestProcessor.getObjects: "
+ doc.getField("contentid").toString());
}
}
}
}
}
} else {
log.debug("No results found.");
}
}
/**
* process search
*/
UseCase ucProcessSearch = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")#processSearch");
if (searchResult != null) {
Query parsedQuery = (Query) searchResult.get(CRSearcher.RESULT_QUERY_KEY);
result = processMetaData(result, searchResult, parsedQuery, request, start, count);
result = processSearchResolvables(result, searchResult, parsedQuery, request);
} else {
// searchresult is null - we don't want to proceed - we want to throw an error
result = null;
}
ucProcessSearch.stop();
/** * process search */
ucGetObjects.stop();
return result;
}
| public final Collection<CRResolvableBean> getObjects(final CRRequest request, final boolean doNavigation)
throws CRException {
UseCase ucGetObjects = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")");
/**
* search preparations (instantiate/validate all needed variables)
*/
UseCase ucPrepareSearch = startUseCase("LuceneRequestProcessor.getObjects(" + name + ")#prepareSearch");
ArrayList<CRResolvableBean> result = new ArrayList<CRResolvableBean>();
int count = getCount(request);
int start = getStart(request);
ucPrepareSearch.stop();
/** * search preparations */
/**
* Get results
*/
long indexSearchStartTime = System.currentTimeMillis();
UseCase ucSearch = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")#search");
HashMap<String, Object> searchResult = null;
try {
searchResult = this.searcher.search(request.getRequestFilter(), getSearchedAttributes(), count, start,
doNavigation, request.getSortArray(), request);
} catch (IOException ex) {
log.error("Error while getting search results from index.");
throw new CRException(ex);
}
ucSearch.stop();
log.debug("Search in Index took " + (System.currentTimeMillis() - indexSearchStartTime) + "ms");
/** * Get results */
if (log.isDebugEnabled()) {
if(searchResult != null) {
for (Object res : searchResult.values()) {
if (res instanceof LinkedHashMap) {
LinkedHashMap<?, ?> documents =
(LinkedHashMap<?, ?>) res;
if (documents != null) {
for (Entry<?, ?> entry
: documents.entrySet()) {
Object object = entry.getKey();
if(object instanceof Document) {
Document doc = (Document) object;
if (doc != null) {
log.debug("LuceneRequestProcessor.getObjects: "
+ doc.getField("contentid").toString());
}
}
}
}
}
}
} else {
log.debug("No results found.");
}
}
/**
* process search
*/
UseCase ucProcessSearch = startUseCase("LuceneRequestProcessor." + "getObjects(" + name + ")#processSearch");
if (searchResult != null) {
Query parsedQuery = (Query) searchResult.get(CRSearcher.RESULT_QUERY_KEY);
result = processMetaData(result, searchResult, parsedQuery, request, start, count);
result = processSearchResolvables(result, searchResult, parsedQuery, request);
} else {
// searchresult is null - we don't want to proceed - we want to throw an error
result = null;
}
ucProcessSearch.stop();
/** * process search */
ucGetObjects.stop();
return result;
}
|
diff --git a/src/main/java/edu/unsw/cse/comp9323/group1/controllers/CourseDetailController.java b/src/main/java/edu/unsw/cse/comp9323/group1/controllers/CourseDetailController.java
index a231a7c..0a34c47 100644
--- a/src/main/java/edu/unsw/cse/comp9323/group1/controllers/CourseDetailController.java
+++ b/src/main/java/edu/unsw/cse/comp9323/group1/controllers/CourseDetailController.java
@@ -1,96 +1,96 @@
package edu.unsw.cse.comp9323.group1.controllers;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import edu.unsw.cse.comp9323.group1.DAOs.CourseDAO;
import edu.unsw.cse.comp9323.group1.DAOs.RatingDAO;
import edu.unsw.cse.comp9323.group1.DAOs.SurveyDAO;
import edu.unsw.cse.comp9323.group1.models.Course;
import edu.unsw.cse.comp9323.group1.models.Survey;
@Controller
@RequestMapping("/courseDetail")
public class CourseDetailController {
@RequestMapping(method = RequestMethod.GET)
public String getCourseDetail(@RequestParam("courseName") String courseName,@RequestParam("studentId") String studentId, ModelMap model) throws UnsupportedEncodingException, URISyntaxException, HttpException {
CourseDAO crsDAO = new CourseDAO();
Course course = new Course();
course = crsDAO.getCourseByName(courseName);
SurveyDAO surveyDAO = new SurveyDAO();
List<Survey> allSurveys = new ArrayList<Survey>();
allSurveys = surveyDAO.getAllAvailableSurvey();
/*
* get spesifically for the current courseID
*/
List<Survey> listOfSurveys = surveyDAO.getSurveyWithCourseId(courseName);
/*
* filter the result before show it to view
*/
List<Survey> returnSurveys = new ArrayList<Survey>();
Iterator<Survey> listOfSurveysItr = listOfSurveys.iterator();
while(listOfSurveysItr.hasNext()){
String surveyIdRslt = (String)listOfSurveysItr.next().getId();
Iterator<Survey> allSurveysItr = allSurveys.iterator();
while(allSurveysItr.hasNext()){
Survey surveyTemp = allSurveysItr.next();
if(surveyIdRslt.equals(surveyTemp.getId())){
returnSurveys.add(surveyTemp);
}
}
}
RatingDAO ratingDAO = new RatingDAO();
int overallRatingCourse = ratingDAO.getOverAllRating(courseName);
HashMap <String, Integer> userRatingsCourse = new HashMap <String, Integer>();
userRatingsCourse = ratingDAO.getUserRating(studentId, courseName);
model.addAttribute("UniReputationRating", 0);
model.addAttribute("UniTeachingRating", 0);
model.addAttribute("UniResearchRating", 0);
model.addAttribute("UniAdminRating", 0);
model.addAttribute("LectureNotesRating", 0);
Iterator it = userRatingsCourse.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey().toString().equalsIgnoreCase("reputation")){
model.addAttribute("UniReputationRating", Integer.parseInt(pairs.getValue().toString()));
System.out.println(">>>>>>>> reputation sets");
}else if(pairs.getKey().toString().equalsIgnoreCase("teaching")){
model.addAttribute("UniTeachingRating", Integer.parseInt(pairs.getValue().toString()));
}else if(pairs.getKey().toString().equalsIgnoreCase("research")){
model.addAttribute("UniResearchRating", Integer.parseInt(pairs.getValue().toString()));
}else if(pairs.getKey().toString().equalsIgnoreCase("admin")){
model.addAttribute("UniAdminRating", Integer.parseInt(pairs.getValue().toString()));
- }else if(pairs.getKey().toString().equalsIgnoreCase("campus")){
+ }else if(pairs.getKey().toString().equalsIgnoreCase("lecturenotes")){
model.addAttribute("LectureNotesRating", Integer.parseInt(pairs.getValue().toString()));
}
//System.out.println(pairs.getKey().toString() + " = " + pairs.getValue());
//System.out.println(model.get("UniReputationRating"));
System.out.println("ENDDD");
it.remove(); // avoids a ConcurrentModificationException
}
model.addAttribute("OverallRating", overallRatingCourse);
model.addAttribute("allSurveys", returnSurveys);
model.addAttribute("course", course);
model.addAttribute("studentId", studentId);
return "courseDetail";
}
}
| true | true | public String getCourseDetail(@RequestParam("courseName") String courseName,@RequestParam("studentId") String studentId, ModelMap model) throws UnsupportedEncodingException, URISyntaxException, HttpException {
CourseDAO crsDAO = new CourseDAO();
Course course = new Course();
course = crsDAO.getCourseByName(courseName);
SurveyDAO surveyDAO = new SurveyDAO();
List<Survey> allSurveys = new ArrayList<Survey>();
allSurveys = surveyDAO.getAllAvailableSurvey();
/*
* get spesifically for the current courseID
*/
List<Survey> listOfSurveys = surveyDAO.getSurveyWithCourseId(courseName);
/*
* filter the result before show it to view
*/
List<Survey> returnSurveys = new ArrayList<Survey>();
Iterator<Survey> listOfSurveysItr = listOfSurveys.iterator();
while(listOfSurveysItr.hasNext()){
String surveyIdRslt = (String)listOfSurveysItr.next().getId();
Iterator<Survey> allSurveysItr = allSurveys.iterator();
while(allSurveysItr.hasNext()){
Survey surveyTemp = allSurveysItr.next();
if(surveyIdRslt.equals(surveyTemp.getId())){
returnSurveys.add(surveyTemp);
}
}
}
RatingDAO ratingDAO = new RatingDAO();
int overallRatingCourse = ratingDAO.getOverAllRating(courseName);
HashMap <String, Integer> userRatingsCourse = new HashMap <String, Integer>();
userRatingsCourse = ratingDAO.getUserRating(studentId, courseName);
model.addAttribute("UniReputationRating", 0);
model.addAttribute("UniTeachingRating", 0);
model.addAttribute("UniResearchRating", 0);
model.addAttribute("UniAdminRating", 0);
model.addAttribute("LectureNotesRating", 0);
Iterator it = userRatingsCourse.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey().toString().equalsIgnoreCase("reputation")){
model.addAttribute("UniReputationRating", Integer.parseInt(pairs.getValue().toString()));
System.out.println(">>>>>>>> reputation sets");
}else if(pairs.getKey().toString().equalsIgnoreCase("teaching")){
model.addAttribute("UniTeachingRating", Integer.parseInt(pairs.getValue().toString()));
}else if(pairs.getKey().toString().equalsIgnoreCase("research")){
model.addAttribute("UniResearchRating", Integer.parseInt(pairs.getValue().toString()));
}else if(pairs.getKey().toString().equalsIgnoreCase("admin")){
model.addAttribute("UniAdminRating", Integer.parseInt(pairs.getValue().toString()));
}else if(pairs.getKey().toString().equalsIgnoreCase("campus")){
model.addAttribute("LectureNotesRating", Integer.parseInt(pairs.getValue().toString()));
}
//System.out.println(pairs.getKey().toString() + " = " + pairs.getValue());
//System.out.println(model.get("UniReputationRating"));
System.out.println("ENDDD");
it.remove(); // avoids a ConcurrentModificationException
}
model.addAttribute("OverallRating", overallRatingCourse);
model.addAttribute("allSurveys", returnSurveys);
model.addAttribute("course", course);
model.addAttribute("studentId", studentId);
return "courseDetail";
}
| public String getCourseDetail(@RequestParam("courseName") String courseName,@RequestParam("studentId") String studentId, ModelMap model) throws UnsupportedEncodingException, URISyntaxException, HttpException {
CourseDAO crsDAO = new CourseDAO();
Course course = new Course();
course = crsDAO.getCourseByName(courseName);
SurveyDAO surveyDAO = new SurveyDAO();
List<Survey> allSurveys = new ArrayList<Survey>();
allSurveys = surveyDAO.getAllAvailableSurvey();
/*
* get spesifically for the current courseID
*/
List<Survey> listOfSurveys = surveyDAO.getSurveyWithCourseId(courseName);
/*
* filter the result before show it to view
*/
List<Survey> returnSurveys = new ArrayList<Survey>();
Iterator<Survey> listOfSurveysItr = listOfSurveys.iterator();
while(listOfSurveysItr.hasNext()){
String surveyIdRslt = (String)listOfSurveysItr.next().getId();
Iterator<Survey> allSurveysItr = allSurveys.iterator();
while(allSurveysItr.hasNext()){
Survey surveyTemp = allSurveysItr.next();
if(surveyIdRslt.equals(surveyTemp.getId())){
returnSurveys.add(surveyTemp);
}
}
}
RatingDAO ratingDAO = new RatingDAO();
int overallRatingCourse = ratingDAO.getOverAllRating(courseName);
HashMap <String, Integer> userRatingsCourse = new HashMap <String, Integer>();
userRatingsCourse = ratingDAO.getUserRating(studentId, courseName);
model.addAttribute("UniReputationRating", 0);
model.addAttribute("UniTeachingRating", 0);
model.addAttribute("UniResearchRating", 0);
model.addAttribute("UniAdminRating", 0);
model.addAttribute("LectureNotesRating", 0);
Iterator it = userRatingsCourse.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey().toString().equalsIgnoreCase("reputation")){
model.addAttribute("UniReputationRating", Integer.parseInt(pairs.getValue().toString()));
System.out.println(">>>>>>>> reputation sets");
}else if(pairs.getKey().toString().equalsIgnoreCase("teaching")){
model.addAttribute("UniTeachingRating", Integer.parseInt(pairs.getValue().toString()));
}else if(pairs.getKey().toString().equalsIgnoreCase("research")){
model.addAttribute("UniResearchRating", Integer.parseInt(pairs.getValue().toString()));
}else if(pairs.getKey().toString().equalsIgnoreCase("admin")){
model.addAttribute("UniAdminRating", Integer.parseInt(pairs.getValue().toString()));
}else if(pairs.getKey().toString().equalsIgnoreCase("lecturenotes")){
model.addAttribute("LectureNotesRating", Integer.parseInt(pairs.getValue().toString()));
}
//System.out.println(pairs.getKey().toString() + " = " + pairs.getValue());
//System.out.println(model.get("UniReputationRating"));
System.out.println("ENDDD");
it.remove(); // avoids a ConcurrentModificationException
}
model.addAttribute("OverallRating", overallRatingCourse);
model.addAttribute("allSurveys", returnSurveys);
model.addAttribute("course", course);
model.addAttribute("studentId", studentId);
return "courseDetail";
}
|
Subsets and Splits