diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/ar/com/jolisper/enumerable/core/Reduce.java b/src/ar/com/jolisper/enumerable/core/Reduce.java
index e791ba3..06da23a 100644
--- a/src/ar/com/jolisper/enumerable/core/Reduce.java
+++ b/src/ar/com/jolisper/enumerable/core/Reduce.java
@@ -1,20 +1,20 @@
package ar.com.jolisper.enumerable.core;
import java.util.List;
public abstract class Reduce<ResultType, CollectionType> {
- public Object reduce(ResultType initValue, List<? extends CollectionType> collection) {
+ public ResultType reduce(ResultType initValue, List<? extends CollectionType> collection) {
ResultType result = initValue;
for ( CollectionType element : collection ) {
result = logic( result , element );
}
return result;
}
protected abstract ResultType logic(ResultType result, CollectionType element);
}
| true | true | public Object reduce(ResultType initValue, List<? extends CollectionType> collection) {
ResultType result = initValue;
for ( CollectionType element : collection ) {
result = logic( result , element );
}
return result;
}
| public ResultType reduce(ResultType initValue, List<? extends CollectionType> collection) {
ResultType result = initValue;
for ( CollectionType element : collection ) {
result = logic( result , element );
}
return result;
}
|
diff --git a/src/org/apache/xalan/xsltc/trax/Util.java b/src/org/apache/xalan/xsltc/trax/Util.java
index a4d9f1b1..91f751f3 100644
--- a/src/org/apache/xalan/xsltc/trax/Util.java
+++ b/src/org/apache/xalan/xsltc/trax/Util.java
@@ -1,167 +1,164 @@
/*
* @(#)$Id$
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001-2003 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) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Santiago Pericas-Geertsen
*
*/
package org.apache.xalan.xsltc.trax;
import java.io.InputStream;
import java.io.Reader;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import org.apache.xalan.xsltc.compiler.XSLTC;
import org.apache.xalan.xsltc.compiler.util.ErrorMsg;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public final class Util {
public static String baseName(String name) {
return org.apache.xalan.xsltc.compiler.util.Util.baseName(name);
}
public static String noExtName(String name) {
return org.apache.xalan.xsltc.compiler.util.Util.noExtName(name);
}
public static String toJavaName(String name) {
return org.apache.xalan.xsltc.compiler.util.Util.toJavaName(name);
}
/**
* Creates a SAX2 InputSource object from a TrAX Source object
*/
public static InputSource getInputSource(XSLTC xsltc, Source source)
throws TransformerConfigurationException
{
InputSource input = null;
- String systemId = source.getSystemId();
- if (systemId == null) {
- systemId = "";
- }
+ String systemId = source.getSystemId();
try {
// Try to get InputSource from SAXSource input
if (source instanceof SAXSource) {
final SAXSource sax = (SAXSource)source;
input = sax.getInputSource();
// Pass the SAX parser to the compiler
xsltc.setXMLReader(sax.getXMLReader());
}
// handle DOMSource
else if (source instanceof DOMSource) {
final DOMSource domsrc = (DOMSource)source;
final Document dom = (Document)domsrc.getNode();
final DOM2SAX dom2sax = new DOM2SAX(dom);
xsltc.setXMLReader(dom2sax);
// Try to get SAX InputSource from DOM Source.
input = SAXSource.sourceToInputSource(source);
if (input == null){
input = new InputSource(domsrc.getSystemId());
}
}
// Try to get InputStream or Reader from StreamSource
else if (source instanceof StreamSource) {
final StreamSource stream = (StreamSource)source;
final InputStream istream = stream.getInputStream();
final Reader reader = stream.getReader();
// Create InputSource from Reader or InputStream in Source
if (istream != null) {
input = new InputSource(istream);
}
else if (reader != null) {
input = new InputSource(reader);
}
else {
input = new InputSource(systemId);
}
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
throw new TransformerConfigurationException(err.toString());
}
input.setSystemId(systemId);
}
catch (NullPointerException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR,
"TransformerFactory.newTemplates()");
throw new TransformerConfigurationException(err.toString());
}
catch (SecurityException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
throw new TransformerConfigurationException(err.toString());
}
return input;
}
}
| true | true | public static InputSource getInputSource(XSLTC xsltc, Source source)
throws TransformerConfigurationException
{
InputSource input = null;
String systemId = source.getSystemId();
if (systemId == null) {
systemId = "";
}
try {
// Try to get InputSource from SAXSource input
if (source instanceof SAXSource) {
final SAXSource sax = (SAXSource)source;
input = sax.getInputSource();
// Pass the SAX parser to the compiler
xsltc.setXMLReader(sax.getXMLReader());
}
// handle DOMSource
else if (source instanceof DOMSource) {
final DOMSource domsrc = (DOMSource)source;
final Document dom = (Document)domsrc.getNode();
final DOM2SAX dom2sax = new DOM2SAX(dom);
xsltc.setXMLReader(dom2sax);
// Try to get SAX InputSource from DOM Source.
input = SAXSource.sourceToInputSource(source);
if (input == null){
input = new InputSource(domsrc.getSystemId());
}
}
// Try to get InputStream or Reader from StreamSource
else if (source instanceof StreamSource) {
final StreamSource stream = (StreamSource)source;
final InputStream istream = stream.getInputStream();
final Reader reader = stream.getReader();
// Create InputSource from Reader or InputStream in Source
if (istream != null) {
input = new InputSource(istream);
}
else if (reader != null) {
input = new InputSource(reader);
}
else {
input = new InputSource(systemId);
}
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
throw new TransformerConfigurationException(err.toString());
}
input.setSystemId(systemId);
}
catch (NullPointerException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR,
"TransformerFactory.newTemplates()");
throw new TransformerConfigurationException(err.toString());
}
catch (SecurityException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
throw new TransformerConfigurationException(err.toString());
}
return input;
}
| public static InputSource getInputSource(XSLTC xsltc, Source source)
throws TransformerConfigurationException
{
InputSource input = null;
String systemId = source.getSystemId();
try {
// Try to get InputSource from SAXSource input
if (source instanceof SAXSource) {
final SAXSource sax = (SAXSource)source;
input = sax.getInputSource();
// Pass the SAX parser to the compiler
xsltc.setXMLReader(sax.getXMLReader());
}
// handle DOMSource
else if (source instanceof DOMSource) {
final DOMSource domsrc = (DOMSource)source;
final Document dom = (Document)domsrc.getNode();
final DOM2SAX dom2sax = new DOM2SAX(dom);
xsltc.setXMLReader(dom2sax);
// Try to get SAX InputSource from DOM Source.
input = SAXSource.sourceToInputSource(source);
if (input == null){
input = new InputSource(domsrc.getSystemId());
}
}
// Try to get InputStream or Reader from StreamSource
else if (source instanceof StreamSource) {
final StreamSource stream = (StreamSource)source;
final InputStream istream = stream.getInputStream();
final Reader reader = stream.getReader();
// Create InputSource from Reader or InputStream in Source
if (istream != null) {
input = new InputSource(istream);
}
else if (reader != null) {
input = new InputSource(reader);
}
else {
input = new InputSource(systemId);
}
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
throw new TransformerConfigurationException(err.toString());
}
input.setSystemId(systemId);
}
catch (NullPointerException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR,
"TransformerFactory.newTemplates()");
throw new TransformerConfigurationException(err.toString());
}
catch (SecurityException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
throw new TransformerConfigurationException(err.toString());
}
return input;
}
|
diff --git a/xwords4/android/XWords4/src/org/eehouse/android/xw4/GamesList.java b/xwords4/android/XWords4/src/org/eehouse/android/xw4/GamesList.java
index 60b08e681..ff1677320 100644
--- a/xwords4/android/XWords4/src/org/eehouse/android/xw4/GamesList.java
+++ b/xwords4/android/XWords4/src/org/eehouse/android/xw4/GamesList.java
@@ -1,1131 +1,1131 @@
/* -*- compile-command: "cd ../../../../../; ant debug install"; -*- */
/*
* Copyright 2009 - 2012 by Eric House ([email protected]). All
* rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.eehouse.android.xw4;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.io.File;
import java.util.Date;
// import android.telephony.PhoneStateListener;
// import android.telephony.TelephonyManager;
import junit.framework.Assert;
import org.eehouse.android.xw4.jni.*;
public class GamesList extends XWExpandableListActivity
implements DBUtils.DBChangeListener,
GameListAdapter.LoadItemCB,
DictImportActivity.DownloadFinishedListener {
private static final int WARN_NODICT = DlgDelegate.DIALOG_LAST + 1;
private static final int WARN_NODICT_SUBST = WARN_NODICT + 1;
private static final int SHOW_SUBST = WARN_NODICT + 2;
private static final int GET_NAME = WARN_NODICT + 3;
private static final int RENAME_GAME = WARN_NODICT + 4;
private static final int NEW_GROUP = WARN_NODICT + 5;
private static final int RENAME_GROUP = WARN_NODICT + 6;
private static final int CHANGE_GROUP = WARN_NODICT + 7;
private static final int WARN_NODICT_NEW = WARN_NODICT + 8;
private static final String SAVE_ROWID = "SAVE_ROWID";
private static final String SAVE_GROUPID = "SAVE_GROUPID";
private static final String SAVE_DICTNAMES = "SAVE_DICTNAMES";
private static final String RELAYIDS_EXTRA = "relayids";
private static final String GAMEID_EXTRA = "gameid";
private static final String REMATCH_ROWID_EXTRA = "rowid";
private static final int NEW_NET_GAME_ACTION = 1;
private static final int RESET_GAME_ACTION = 2;
private static final int DELETE_GAME_ACTION = 3;
private static final int SYNC_MENU_ACTION = 4;
private static final int NEW_FROM_ACTION = 5;
private static final int DELETE_GROUP_ACTION = 6;
private static final int[] DEBUGITEMS = { R.id.gamel_menu_loaddb
, R.id.gamel_menu_storedb
, R.id.gamel_menu_checkupdates
};
private static boolean s_firstShown = false;
private GameListAdapter m_adapter;
private String m_missingDict;
private String m_missingDictName;
private long m_missingDictRowId = DBUtils.ROWID_NOTFOUND;
private String[] m_sameLangDicts;
private int m_missingDictLang;
private long m_rowid;
private long m_groupid;
private String m_nameField;
private NetLaunchInfo m_netLaunchInfo;
private GameNamer m_namer;
@Override
protected Dialog onCreateDialog( int id )
{
DialogInterface.OnClickListener lstnr;
DialogInterface.OnClickListener lstnr2;
LinearLayout layout;
Dialog dialog = super.onCreateDialog( id );
if ( null == dialog ) {
AlertDialog.Builder ab;
switch ( id ) {
case WARN_NODICT:
case WARN_NODICT_NEW:
case WARN_NODICT_SUBST:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
// no name, so user must pick
if ( null == m_missingDictName ) {
DictsActivity.launchAndDownload( GamesList.this,
m_missingDictLang );
} else {
DictImportActivity
.downloadDictInBack( GamesList.this,
m_missingDictLang,
m_missingDictName,
GamesList.this );
}
}
};
String message;
String langName =
DictLangCache.getLangName( this, m_missingDictLang );
String gameName = GameUtils.getName( this, m_rowid );
if ( WARN_NODICT == id ) {
message = getString( R.string.no_dictf,
gameName, langName );
} else if ( WARN_NODICT_NEW == id ) {
message =
getString( R.string.invite_dict_missing_body_nonamef,
null, m_missingDictName, langName );
} else {
message = getString( R.string.no_dict_substf,
gameName, m_missingDictName,
langName );
}
ab = new AlertDialog.Builder( this )
.setTitle( R.string.no_dict_title )
.setMessage( message )
.setPositiveButton( R.string.button_cancel, null )
.setNegativeButton( R.string.button_download, lstnr )
;
if ( WARN_NODICT_SUBST == id ) {
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
showDialog( SHOW_SUBST );
}
};
ab.setNeutralButton( R.string.button_substdict, lstnr );
}
dialog = ab.create();
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case SHOW_SUBST:
m_sameLangDicts =
DictLangCache.getHaveLangCounts( this, m_missingDictLang );
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg,
int which ) {
int pos = ((AlertDialog)dlg).getListView().
getCheckedItemPosition();
String dict = m_sameLangDicts[pos];
dict = DictLangCache.stripCount( dict );
if ( GameUtils.replaceDicts( GamesList.this,
m_missingDictRowId,
m_missingDictName,
dict ) ) {
launchGameIf();
}
}
};
dialog = new AlertDialog.Builder( this )
.setTitle( R.string.subst_dict_title )
.setPositiveButton( R.string.button_substdict, lstnr )
.setNegativeButton( R.string.button_cancel, null )
.setSingleChoiceItems( m_sameLangDicts, 0, null )
.create();
// Force destruction so onCreateDialog() will get
// called next time and we can insert a different
// list. There seems to be no way to change the list
// inside onPrepareDialog().
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case RENAME_GAME:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.setName( GamesList.this, m_rowid, name );
m_adapter.invalName( m_rowid );
}
};
dialog = buildNamerDlg( GameUtils.getName( this, m_rowid ),
R.string.rename_label,
R.string.game_rename_title,
lstnr, RENAME_GAME );
break;
case RENAME_GROUP:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.setGroupName( GamesList.this, m_groupid,
name );
m_adapter.inval( m_rowid );
onContentChanged();
}
};
dialog = buildNamerDlg( m_adapter.groupName( m_groupid ),
R.string.rename_group_label,
- R.string.game_rename_group_title,
+ R.string.game_name_group_title,
lstnr, RENAME_GROUP );
break;
case NEW_GROUP:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.addGroup( GamesList.this, name );
// m_adapter.inval();
onContentChanged();
}
};
dialog = buildNamerDlg( "", R.string.newgroup_label,
- R.string.game_rename_title,
+ R.string.game_name_group_title,
lstnr, RENAME_GROUP );
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case CHANGE_GROUP:
final long startGroup = DBUtils.getGroupForGame( this, m_rowid );
final int[] selItem = {-1}; // hack!!!!
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlgi, int item ) {
selItem[0] = item;
AlertDialog dlg = (AlertDialog)dlgi;
Button btn =
dlg.getButton( AlertDialog.BUTTON_POSITIVE );
long newGroup = m_adapter.getGroupIDFor( item );
btn.setEnabled( newGroup != startGroup );
}
};
lstnr2 = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
Assert.assertTrue( -1 != selItem[0] );
long gid = m_adapter.getGroupIDFor( selItem[0] );
DBUtils.moveGame( GamesList.this, m_rowid, gid );
onContentChanged();
}
};
String[] groups = m_adapter.groupNames();
int curGroupPos = m_adapter.getGroupPosition( startGroup );
String name = GameUtils.getName( this, m_rowid );
dialog = new AlertDialog.Builder( this )
.setTitle( getString( R.string.change_groupf, name ) )
.setSingleChoiceItems( groups, curGroupPos, lstnr )
.setPositiveButton( R.string.button_move, lstnr2 )
.setNegativeButton( R.string.button_cancel, null )
.create();
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case GET_NAME:
layout =
(LinearLayout)Utils.inflate( this, R.layout.dflt_name );
final EditText etext =
(EditText)layout.findViewById( R.id.name_edit );
etext.setText( CommonPrefs.getDefaultPlayerName( this, 0,
true ) );
dialog = new AlertDialog.Builder( this )
.setTitle( R.string.default_name_title )
.setMessage( R.string.default_name_message )
.setPositiveButton( R.string.button_ok, null )
.setView( layout )
.create();
dialog.setOnDismissListener(new DialogInterface.
OnDismissListener() {
public void onDismiss( DialogInterface dlg ) {
String name = etext.getText().toString();
if ( 0 == name.length() ) {
name = CommonPrefs.
getDefaultPlayerName( GamesList.this,
0, true );
}
CommonPrefs.setDefaultPlayerName( GamesList.this,
name );
}
});
break;
default:
// just drop it; super.onCreateDialog likely failed
break;
}
}
return dialog;
} // onCreateDialog
@Override protected void onPrepareDialog( int id, Dialog dialog )
{
super.onPrepareDialog( id, dialog );
if ( CHANGE_GROUP == id ) {
((AlertDialog)dialog).getButton( AlertDialog.BUTTON_POSITIVE )
.setEnabled( false );
}
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate( savedInstanceState );
// scary, but worth playing with:
// Assert.assertTrue( isTaskRoot() );
getBundledData( savedInstanceState );
setContentView(R.layout.game_list);
registerForContextMenu( getExpandableListView() );
DBUtils.setDBChangeListener( this );
boolean isUpgrade = Utils.firstBootThisVersion( this );
if ( isUpgrade && !s_firstShown ) {
FirstRunDialog.show( this );
s_firstShown = true;
}
PreferenceManager.setDefaultValues( this, R.xml.xwprefs, isUpgrade );
// setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
Button newGameB = (Button)findViewById(R.id.new_game);
newGameB.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick( View v ) {
// addGame( false );
startNewGameActivity();
// showNotAgainDlg( R.string.not_again_newgame,
// R.string.key_notagain_newgame );
}
});
newGameB = (Button)findViewById(R.id.new_group);
newGameB.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick( View v ) {
showDialog( NEW_GROUP );
}
});
String field = CommonPrefs.getSummaryField( this );
long[] positions = XWPrefs.getGroupPositions( this );
m_adapter = new GameListAdapter( this, getExpandableListView(),
new Handler(), this, positions,
field );
setListAdapter( m_adapter );
m_adapter.expandGroups( getExpandableListView() );
NetUtils.informOfDeaths( this );
Intent intent = getIntent();
startFirstHasDict( intent );
startNewNetGame( intent );
startHasGameID( intent );
startHasRowID( intent );
askDefaultNameIf();
} // onCreate
@Override
// called when we're brought to the front (probably as a result of
// notification)
protected void onNewIntent( Intent intent )
{
super.onNewIntent( intent );
Assert.assertNotNull( intent );
invalRelayIDs( intent.getStringArrayExtra( RELAYIDS_EXTRA ) );
startFirstHasDict( intent );
startNewNetGame( intent );
startHasGameID( intent );
startHasRowID( intent );
}
@Override
protected void onStart()
{
super.onStart();
boolean hide = CommonPrefs.getHideIntro( this );
int hereOrGone = hide ? View.GONE : View.VISIBLE;
for ( int id : new int[]{ R.id.empty_games_list,
R.id.new_buttons } ) {
View view = findViewById( id );
view.setVisibility( hereOrGone );
}
View empty = findViewById( R.id.empty_list_msg );
empty.setVisibility( hide ? View.VISIBLE : View.GONE );
getExpandableListView().setEmptyView( hide? empty : null );
// TelephonyManager mgr =
// (TelephonyManager)getSystemService( Context.TELEPHONY_SERVICE );
// m_phoneStateListener = new XWPhoneStateListener();
// mgr.listen( m_phoneStateListener,
// PhoneStateListener.LISTEN_DATA_CONNECTION_STATE );
}
@Override
protected void onStop()
{
// TelephonyManager mgr =
// (TelephonyManager)getSystemService( Context.TELEPHONY_SERVICE );
// mgr.listen( m_phoneStateListener, PhoneStateListener.LISTEN_NONE );
// m_phoneStateListener = null;
long[] positions = m_adapter.getPositions();
XWPrefs.setGroupPositions( this, positions );
super.onStop();
}
@Override
protected void onDestroy()
{
DBUtils.clearDBChangeListener( this );
super.onDestroy();
}
@Override
protected void onSaveInstanceState( Bundle outState )
{
super.onSaveInstanceState( outState );
outState.putLong( SAVE_ROWID, m_rowid );
outState.putLong( SAVE_GROUPID, m_groupid );
outState.putString( SAVE_DICTNAMES, m_missingDictName );
if ( null != m_netLaunchInfo ) {
m_netLaunchInfo.putSelf( outState );
}
}
private void getBundledData( Bundle bundle )
{
if ( null != bundle ) {
m_rowid = bundle.getLong( SAVE_ROWID );
m_groupid = bundle.getLong( SAVE_GROUPID );
m_netLaunchInfo = new NetLaunchInfo( bundle );
m_missingDictName = bundle.getString( SAVE_DICTNAMES );
}
}
@Override
public void onWindowFocusChanged( boolean hasFocus )
{
super.onWindowFocusChanged( hasFocus );
if ( hasFocus ) {
updateField();
}
}
// DBUtils.DBChangeListener interface
public void gameSaved( final long rowid, final boolean countChanged )
{
post( new Runnable() {
public void run() {
if ( countChanged ) {
onContentChanged();
} else {
m_adapter.inval( rowid );
}
}
} );
}
// GameListAdapter.LoadItemCB interface
public void itemClicked( long rowid, GameSummary summary )
{
// We need a way to let the user get back to the basic-config
// dialog in case it was dismissed. That way it to check for
// an empty room name.
if ( summary.conType == CommsAddrRec.CommsConnType.COMMS_CONN_RELAY
&& summary.roomName.length() == 0 ) {
// If it's unconfigured and of the type RelayGameActivity
// can handle send it there, otherwise use the full-on
// config.
Class clazz;
if ( RelayGameActivity.isSimpleGame( summary ) ) {
clazz = RelayGameActivity.class;
} else {
clazz = GameConfig.class;
}
GameUtils.doConfig( this, rowid, clazz );
} else {
if ( checkWarnNoDict( rowid ) ) {
launchGame( rowid );
}
}
}
// BTService.MultiEventListener interface
@Override
public void eventOccurred( MultiService.MultiEvent event,
final Object ... args )
{
switch( event ) {
case HOST_PONGED:
post( new Runnable() {
public void run() {
DbgUtils.showf( GamesList.this,
"Pong from %s", args[0].toString() );
}
});
break;
default:
super.eventOccurred( event, args );
break;
}
}
// DlgDelegate.DlgClickNotify interface
@Override
public void dlgButtonClicked( int id, int which )
{
if ( AlertDialog.BUTTON_POSITIVE == which ) {
switch( id ) {
case NEW_NET_GAME_ACTION:
if ( checkWarnNoDict( m_netLaunchInfo ) ) {
makeNewNetGameIf();
}
break;
case RESET_GAME_ACTION:
GameUtils.resetGame( this, m_rowid );
onContentChanged(); // required because position may change
break;
case DELETE_GAME_ACTION:
GameUtils.deleteGame( this, m_rowid, true );
break;
case SYNC_MENU_ACTION:
doSyncMenuitem();
break;
case NEW_FROM_ACTION:
long newid = GameUtils.dupeGame( GamesList.this, m_rowid );
if ( null != m_adapter ) {
m_adapter.inval( newid );
}
break;
case DELETE_GROUP_ACTION:
GameUtils.deleteGroup( this, m_groupid );
onContentChanged();
break;
default:
Assert.fail();
}
}
}
@Override
public void onContentChanged()
{
super.onContentChanged();
if ( null != m_adapter ) {
m_adapter.expandGroups( getExpandableListView() );
}
}
@Override
public void onCreateContextMenu( ContextMenu menu, View view,
ContextMenuInfo menuInfo )
{
ExpandableListView.ExpandableListContextMenuInfo info
= (ExpandableListView.ExpandableListContextMenuInfo)menuInfo;
long packedPos = info.packedPosition;
int childPos = ExpandableListView.getPackedPositionChild( packedPos );
String name;
if ( 0 <= childPos ) { // game case
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.games_list_item_menu, menu );
long rowid = m_adapter.getRowIDFor( packedPos );
name = GameUtils.getName( this, rowid );
} else { // group case
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.games_list_group_menu, menu );
int pos = ExpandableListView.getPackedPositionGroup( packedPos );
name = m_adapter.groupNames()[pos];
if ( 0 == pos ) {
Utils.setItemEnabled( menu, R.id.list_group_moveup, false );
}
if ( pos + 1 == m_adapter.getGroupCount() ) {
Utils.setItemEnabled( menu, R.id.list_group_movedown, false );
}
if ( XWPrefs.getDefaultNewGameGroup( this )
== m_adapter.getGroupIDFor( pos ) ) {
Utils.setItemEnabled( menu, R.id.list_group_default, false );
Utils.setItemEnabled( menu, R.id.list_group_delete, false );
}
}
menu.setHeaderTitle( getString( R.string.game_item_menu_titlef,
name ) );
}
@Override
public boolean onContextItemSelected( MenuItem item )
{
ExpandableListContextMenuInfo info;
try {
info = (ExpandableListContextMenuInfo)item.getMenuInfo();
} catch (ClassCastException cce) {
DbgUtils.loge( cce );
return false;
}
long packedPos = info.packedPosition;
int childPos = ExpandableListView.getPackedPositionChild( packedPos );
int groupPos = ExpandableListView.getPackedPositionGroup(packedPos);
int menuID = item.getItemId();
boolean handled;
if ( 0 <= childPos ) {
long rowid = m_adapter.getRowIDFor( groupPos, childPos );
handled = handleGameMenuItem( menuID, rowid );
} else {
handled = handleGroupMenuItem( menuID, groupPos );
}
return handled;
} // onContextItemSelected
@Override
public boolean onCreateOptionsMenu( Menu menu )
{
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.games_list_menu, menu );
return true;
}
@Override
public boolean onPrepareOptionsMenu( Menu menu )
{
boolean visible = XWPrefs.getDebugEnabled( this );
for ( int id : DEBUGITEMS ) {
MenuItem item = menu.findItem( id );
item.setVisible( visible );
}
if ( visible && !DBUtils.gameDBExists( this ) ) {
MenuItem item = menu.findItem( R.id.gamel_menu_loaddb );
item.setVisible( false );
}
return super.onPrepareOptionsMenu( menu );
}
public boolean onOptionsItemSelected( MenuItem item )
{
boolean handled = true;
Intent intent;
switch (item.getItemId()) {
case R.id.gamel_menu_newgame:
startNewGameActivity();
break;
case R.id.gamel_menu_newgroup:
showDialog( NEW_GROUP );
break;
case R.id.gamel_menu_dicts:
intent = new Intent( this, DictsActivity.class );
startActivity( intent );
break;
case R.id.gamel_menu_checkmoves:
showNotAgainDlgThen( R.string.not_again_sync,
R.string.key_notagain_sync,
SYNC_MENU_ACTION );
break;
case R.id.gamel_menu_checkupdates:
UpdateCheckReceiver.checkVersions( this, true );
break;
case R.id.gamel_menu_prefs:
Utils.launchSettings( this );
break;
case R.id.gamel_menu_about:
showAboutDialog();
break;
case R.id.gamel_menu_email:
Utils.emailAuthor( this );
break;
case R.id.gamel_menu_loaddb:
DBUtils.loadDB( this );
onContentChanged();
break;
case R.id.gamel_menu_storedb:
DBUtils.saveDB( this );
break;
// case R.id.gamel_menu_view_hidden:
// Utils.notImpl( this );
// break;
default:
handled = false;
}
return handled;
}
// DictImportActivity.DownloadFinishedListener interface
public void downloadFinished( String name, final boolean success )
{
post( new Runnable() {
public void run() {
boolean madeGame = false;
if ( success ) {
madeGame = makeNewNetGameIf() || launchGameIf();
}
if ( ! madeGame ) {
int id = success ? R.string.download_done
: R.string.download_failed;
Utils.showToast( GamesList.this, id );
}
}
} );
}
private boolean handleGameMenuItem( int menuID, long rowid )
{
boolean handled = true;
DialogInterface.OnClickListener lstnr;
m_rowid = rowid;
if ( R.id.list_item_delete == menuID ) {
showConfirmThen( R.string.confirm_delete, R.string.button_delete,
DELETE_GAME_ACTION );
} else {
if ( checkWarnNoDict( m_rowid ) ) {
switch ( menuID ) {
case R.id.list_item_reset:
showConfirmThen( R.string.confirm_reset,
R.string.button_reset, RESET_GAME_ACTION );
break;
case R.id.list_item_config:
GameUtils.doConfig( this, m_rowid, GameConfig.class );
break;
case R.id.list_item_rename:
showDialog( RENAME_GAME );
break;
case R.id.list_item_move:
if ( 1 >= m_adapter.getGroupCount() ) {
showOKOnlyDialog( R.string.no_move_onegroup );
} else {
showDialog( CHANGE_GROUP );
}
break;
case R.id.list_item_new_from:
showNotAgainDlgThen( R.string.not_again_newfrom,
R.string.key_notagain_newfrom,
NEW_FROM_ACTION );
break;
case R.id.list_item_copy:
GameSummary summary = DBUtils.getSummary( this, m_rowid );
if ( summary.inNetworkGame() ) {
showOKOnlyDialog( R.string.no_copy_network );
} else {
byte[] stream = GameUtils.savedGame( this, m_rowid );
GameLock lock = GameUtils.saveNewGame( this, stream );
DBUtils.saveSummary( this, lock, summary );
lock.unlock();
}
break;
// These require some notion of predictable sort order.
// Maybe put off until I'm using a db?
// case R.id.list_item_hide:
// case R.id.list_item_move_up:
// case R.id.list_item_move_down:
// case R.id.list_item_move_to_top:
// case R.id.list_item_move_to_bottom:
// Utils.notImpl( this );
// break;
default:
handled = false;
break;
}
}
}
return handled;
} // handleGameMenuItem
private boolean handleGroupMenuItem( int menuID, int groupPos )
{
boolean handled = true;
m_groupid = m_adapter.getGroupIDFor( groupPos );
switch ( menuID ) {
case R.id.list_group_delete:
if ( m_groupid == XWPrefs.getDefaultNewGameGroup( this ) ) {
showOKOnlyDialog( R.string.cannot_delete_default_group );
} else {
String msg = getString( R.string.group_confirm_del );
int nGames = m_adapter.getChildrenCount( groupPos );
if ( 0 < nGames ) {
msg += getString( R.string.group_confirm_delf, nGames );
}
showConfirmThen( msg, DELETE_GROUP_ACTION );
}
break;
case R.id.list_group_rename:
showDialog( RENAME_GROUP );
break;
case R.id.list_group_default:
XWPrefs.setDefaultNewGameGroup( this, m_groupid );
break;
case R.id.list_group_moveup:
if ( m_adapter.moveGroup( m_groupid, -1 ) ) {
onContentChanged();
}
break;
case R.id.list_group_movedown:
if ( m_adapter.moveGroup( m_groupid, 1 ) ) {
onContentChanged();
}
break;
default:
handled = false;
}
return handled;
}
private boolean checkWarnNoDict( NetLaunchInfo nli )
{
// check that we have the dict required
boolean haveDict;
if ( null == nli.dict ) { // can only test for language support
String[] dicts = DictLangCache.getHaveLang( this, nli.lang );
haveDict = 0 < dicts.length;
if ( haveDict ) {
// Just pick one -- good enough for the period when
// users aren't using new clients that include the
// dict name.
nli.dict = dicts[0];
}
} else {
haveDict =
DictLangCache.haveDict( this, nli.lang, nli.dict );
}
if ( !haveDict ) {
m_netLaunchInfo = nli;
m_missingDictLang = nli.lang;
m_missingDictName = nli.dict;
showDialog( WARN_NODICT_NEW );
}
return haveDict;
}
private boolean checkWarnNoDict( long rowid )
{
String[][] missingNames = new String[1][];
int[] missingLang = new int[1];
boolean hasDicts =
GameUtils.gameDictsHere( this, rowid, missingNames, missingLang );
if ( !hasDicts ) {
m_missingDictLang = missingLang[0];
if ( 0 < missingNames[0].length ) {
m_missingDictName = missingNames[0][0];
} else {
m_missingDictName = null;
}
m_missingDictRowId = rowid;
if ( 0 == DictLangCache.getLangCount( this, m_missingDictLang ) ) {
showDialog( WARN_NODICT );
} else if ( null != m_missingDictName ) {
showDialog( WARN_NODICT_SUBST );
} else {
String dict =
DictLangCache.getHaveLang( this, m_missingDictLang)[0];
if ( GameUtils.replaceDicts( this, m_missingDictRowId,
null, dict ) ) {
launchGameIf();
}
}
}
return hasDicts;
}
private void invalRelayIDs( String[] relayIDs )
{
if ( null != relayIDs ) {
for ( String relayID : relayIDs ) {
long[] rowids = DBUtils.getRowIDsFor( this, relayID );
if ( null != rowids ) {
for ( long rowid : rowids ) {
m_adapter.inval( rowid );
}
}
}
}
}
// Launch the first of these for which there's a dictionary
// present.
private void startFirstHasDict( String[] relayIDs )
{
if ( null != relayIDs ) {
outer:
for ( String relayID : relayIDs ) {
long[] rowids = DBUtils.getRowIDsFor( this, relayID );
if ( null != rowids ) {
for ( long rowid : rowids ) {
if ( GameUtils.gameDictsHere( this, rowid ) ) {
launchGame( rowid );
break outer;
}
}
}
}
}
}
private void startFirstHasDict( Intent intent )
{
if ( null != intent ) {
String[] relayIDs = intent.getStringArrayExtra( RELAYIDS_EXTRA );
startFirstHasDict( relayIDs );
}
}
private void startNewGameActivity()
{
startActivity( new Intent( this, NewGameActivity.class ) );
}
private void startNewNetGame( NetLaunchInfo nli )
{
Date create = DBUtils.getMostRecentCreate( this, nli );
if ( null == create ) {
if ( checkWarnNoDict( nli ) ) {
makeNewNetGame( nli );
}
} else {
String msg = getString( R.string.dup_game_queryf,
create.toString() );
m_netLaunchInfo = nli;
showConfirmThen( msg, NEW_NET_GAME_ACTION );
}
} // startNewNetGame
private void startNewNetGame( Intent intent )
{
NetLaunchInfo nli = null;
if ( MultiService.isMissingDictIntent( intent ) ) {
nli = new NetLaunchInfo( intent );
} else {
Uri data = intent.getData();
if ( null != data ) {
nli = new NetLaunchInfo( this, data );
}
}
if ( null != nli && nli.isValid() ) {
startNewNetGame( nli );
}
} // startNewNetGame
private void startHasGameID( int gameID )
{
long[] rowids = DBUtils.getRowIDsFor( this, gameID );
if ( null != rowids && 0 < rowids.length ) {
launchGame( rowids[0] );
}
}
private void startHasGameID( Intent intent )
{
int gameID = intent.getIntExtra( GAMEID_EXTRA, 0 );
if ( 0 != gameID ) {
startHasGameID( gameID );
}
}
private void startHasRowID( Intent intent )
{
long rowid = intent.getLongExtra( REMATCH_ROWID_EXTRA, -1 );
if ( -1 != rowid ) {
// this will juggle if the preference is set
long newid = GameUtils.dupeGame( this, rowid );
launchGame( newid );
}
}
private void askDefaultNameIf()
{
if ( null == CommonPrefs.getDefaultPlayerName( this, 0, false ) ) {
String name = CommonPrefs.getDefaultPlayerName( this, 0, true );
CommonPrefs.setDefaultPlayerName( GamesList.this, name );
showDialog( GET_NAME );
}
}
private void updateField()
{
String newField = CommonPrefs.getSummaryField( this );
if ( m_adapter.setField( newField ) ) {
// The adapter should be able to decide whether full
// content change is required. PENDING
onContentChanged();
}
}
private Dialog buildNamerDlg( String curname, int labelID, int titleID,
DialogInterface.OnClickListener lstnr,
int dlgID )
{
m_namer = (GameNamer)Utils.inflate( this, R.layout.rename_game );
m_namer.setName( curname );
m_namer.setLabel( labelID );
Dialog dialog = new AlertDialog.Builder( this )
.setTitle( titleID )
.setNegativeButton( R.string.button_cancel, null )
.setPositiveButton( R.string.button_ok, lstnr )
.setView( m_namer )
.create();
Utils.setRemoveOnDismiss( this, dialog, dlgID );
return dialog;
}
private boolean makeNewNetGameIf()
{
boolean madeGame = null != m_netLaunchInfo;
if ( madeGame ) {
makeNewNetGame( m_netLaunchInfo );
m_netLaunchInfo = null;
}
return madeGame;
}
private boolean launchGameIf()
{
boolean madeGame = DBUtils.ROWID_NOTFOUND != m_missingDictRowId;
if ( madeGame ) {
GameUtils.launchGame( this, m_missingDictRowId );
m_missingDictRowId = DBUtils.ROWID_NOTFOUND;
}
return madeGame;
}
private void launchGame( long rowid, boolean invited )
{
GameUtils.launchGame( this, rowid, invited );
}
private void launchGame( long rowid )
{
launchGame( rowid, false );
}
private void makeNewNetGame( NetLaunchInfo info )
{
long rowid = GameUtils.makeNewNetGame( this, info );
launchGame( rowid, true );
}
public static void onGameDictDownload( Context context, Intent intent )
{
intent.setClass( context, GamesList.class );
context.startActivity( intent );
}
private static Intent makeSelfIntent( Context context )
{
Intent intent = new Intent( context, GamesList.class );
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK );
return intent;
}
public static Intent makeRelayIdsIntent( Context context,
String[] relayIDs )
{
Intent intent = makeSelfIntent( context );
intent.putExtra( RELAYIDS_EXTRA, relayIDs );
return intent;
}
public static Intent makeGameIDIntent( Context context, int gameID )
{
Intent intent = makeSelfIntent( context );
intent.putExtra( GAMEID_EXTRA, gameID );
return intent;
}
public static Intent makeRematchIntent( Context context, CurGameInfo gi,
long rowid )
{
Intent intent = makeSelfIntent( context );
if ( CurGameInfo.DeviceRole.SERVER_STANDALONE == gi.serverRole ) {
intent.putExtra( REMATCH_ROWID_EXTRA, rowid );
} else {
Utils.notImpl( context );
}
return intent;
}
public static void openGame( Context context, Uri data )
{
Intent intent = makeSelfIntent( context );
intent.setData( data );
context.startActivity( intent );
}
}
| false | true | protected Dialog onCreateDialog( int id )
{
DialogInterface.OnClickListener lstnr;
DialogInterface.OnClickListener lstnr2;
LinearLayout layout;
Dialog dialog = super.onCreateDialog( id );
if ( null == dialog ) {
AlertDialog.Builder ab;
switch ( id ) {
case WARN_NODICT:
case WARN_NODICT_NEW:
case WARN_NODICT_SUBST:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
// no name, so user must pick
if ( null == m_missingDictName ) {
DictsActivity.launchAndDownload( GamesList.this,
m_missingDictLang );
} else {
DictImportActivity
.downloadDictInBack( GamesList.this,
m_missingDictLang,
m_missingDictName,
GamesList.this );
}
}
};
String message;
String langName =
DictLangCache.getLangName( this, m_missingDictLang );
String gameName = GameUtils.getName( this, m_rowid );
if ( WARN_NODICT == id ) {
message = getString( R.string.no_dictf,
gameName, langName );
} else if ( WARN_NODICT_NEW == id ) {
message =
getString( R.string.invite_dict_missing_body_nonamef,
null, m_missingDictName, langName );
} else {
message = getString( R.string.no_dict_substf,
gameName, m_missingDictName,
langName );
}
ab = new AlertDialog.Builder( this )
.setTitle( R.string.no_dict_title )
.setMessage( message )
.setPositiveButton( R.string.button_cancel, null )
.setNegativeButton( R.string.button_download, lstnr )
;
if ( WARN_NODICT_SUBST == id ) {
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
showDialog( SHOW_SUBST );
}
};
ab.setNeutralButton( R.string.button_substdict, lstnr );
}
dialog = ab.create();
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case SHOW_SUBST:
m_sameLangDicts =
DictLangCache.getHaveLangCounts( this, m_missingDictLang );
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg,
int which ) {
int pos = ((AlertDialog)dlg).getListView().
getCheckedItemPosition();
String dict = m_sameLangDicts[pos];
dict = DictLangCache.stripCount( dict );
if ( GameUtils.replaceDicts( GamesList.this,
m_missingDictRowId,
m_missingDictName,
dict ) ) {
launchGameIf();
}
}
};
dialog = new AlertDialog.Builder( this )
.setTitle( R.string.subst_dict_title )
.setPositiveButton( R.string.button_substdict, lstnr )
.setNegativeButton( R.string.button_cancel, null )
.setSingleChoiceItems( m_sameLangDicts, 0, null )
.create();
// Force destruction so onCreateDialog() will get
// called next time and we can insert a different
// list. There seems to be no way to change the list
// inside onPrepareDialog().
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case RENAME_GAME:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.setName( GamesList.this, m_rowid, name );
m_adapter.invalName( m_rowid );
}
};
dialog = buildNamerDlg( GameUtils.getName( this, m_rowid ),
R.string.rename_label,
R.string.game_rename_title,
lstnr, RENAME_GAME );
break;
case RENAME_GROUP:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.setGroupName( GamesList.this, m_groupid,
name );
m_adapter.inval( m_rowid );
onContentChanged();
}
};
dialog = buildNamerDlg( m_adapter.groupName( m_groupid ),
R.string.rename_group_label,
R.string.game_rename_group_title,
lstnr, RENAME_GROUP );
break;
case NEW_GROUP:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.addGroup( GamesList.this, name );
// m_adapter.inval();
onContentChanged();
}
};
dialog = buildNamerDlg( "", R.string.newgroup_label,
R.string.game_rename_title,
lstnr, RENAME_GROUP );
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case CHANGE_GROUP:
final long startGroup = DBUtils.getGroupForGame( this, m_rowid );
final int[] selItem = {-1}; // hack!!!!
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlgi, int item ) {
selItem[0] = item;
AlertDialog dlg = (AlertDialog)dlgi;
Button btn =
dlg.getButton( AlertDialog.BUTTON_POSITIVE );
long newGroup = m_adapter.getGroupIDFor( item );
btn.setEnabled( newGroup != startGroup );
}
};
lstnr2 = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
Assert.assertTrue( -1 != selItem[0] );
long gid = m_adapter.getGroupIDFor( selItem[0] );
DBUtils.moveGame( GamesList.this, m_rowid, gid );
onContentChanged();
}
};
String[] groups = m_adapter.groupNames();
int curGroupPos = m_adapter.getGroupPosition( startGroup );
String name = GameUtils.getName( this, m_rowid );
dialog = new AlertDialog.Builder( this )
.setTitle( getString( R.string.change_groupf, name ) )
.setSingleChoiceItems( groups, curGroupPos, lstnr )
.setPositiveButton( R.string.button_move, lstnr2 )
.setNegativeButton( R.string.button_cancel, null )
.create();
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case GET_NAME:
layout =
(LinearLayout)Utils.inflate( this, R.layout.dflt_name );
final EditText etext =
(EditText)layout.findViewById( R.id.name_edit );
etext.setText( CommonPrefs.getDefaultPlayerName( this, 0,
true ) );
dialog = new AlertDialog.Builder( this )
.setTitle( R.string.default_name_title )
.setMessage( R.string.default_name_message )
.setPositiveButton( R.string.button_ok, null )
.setView( layout )
.create();
dialog.setOnDismissListener(new DialogInterface.
OnDismissListener() {
public void onDismiss( DialogInterface dlg ) {
String name = etext.getText().toString();
if ( 0 == name.length() ) {
name = CommonPrefs.
getDefaultPlayerName( GamesList.this,
0, true );
}
CommonPrefs.setDefaultPlayerName( GamesList.this,
name );
}
});
break;
default:
// just drop it; super.onCreateDialog likely failed
break;
}
}
return dialog;
} // onCreateDialog
| protected Dialog onCreateDialog( int id )
{
DialogInterface.OnClickListener lstnr;
DialogInterface.OnClickListener lstnr2;
LinearLayout layout;
Dialog dialog = super.onCreateDialog( id );
if ( null == dialog ) {
AlertDialog.Builder ab;
switch ( id ) {
case WARN_NODICT:
case WARN_NODICT_NEW:
case WARN_NODICT_SUBST:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
// no name, so user must pick
if ( null == m_missingDictName ) {
DictsActivity.launchAndDownload( GamesList.this,
m_missingDictLang );
} else {
DictImportActivity
.downloadDictInBack( GamesList.this,
m_missingDictLang,
m_missingDictName,
GamesList.this );
}
}
};
String message;
String langName =
DictLangCache.getLangName( this, m_missingDictLang );
String gameName = GameUtils.getName( this, m_rowid );
if ( WARN_NODICT == id ) {
message = getString( R.string.no_dictf,
gameName, langName );
} else if ( WARN_NODICT_NEW == id ) {
message =
getString( R.string.invite_dict_missing_body_nonamef,
null, m_missingDictName, langName );
} else {
message = getString( R.string.no_dict_substf,
gameName, m_missingDictName,
langName );
}
ab = new AlertDialog.Builder( this )
.setTitle( R.string.no_dict_title )
.setMessage( message )
.setPositiveButton( R.string.button_cancel, null )
.setNegativeButton( R.string.button_download, lstnr )
;
if ( WARN_NODICT_SUBST == id ) {
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
showDialog( SHOW_SUBST );
}
};
ab.setNeutralButton( R.string.button_substdict, lstnr );
}
dialog = ab.create();
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case SHOW_SUBST:
m_sameLangDicts =
DictLangCache.getHaveLangCounts( this, m_missingDictLang );
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg,
int which ) {
int pos = ((AlertDialog)dlg).getListView().
getCheckedItemPosition();
String dict = m_sameLangDicts[pos];
dict = DictLangCache.stripCount( dict );
if ( GameUtils.replaceDicts( GamesList.this,
m_missingDictRowId,
m_missingDictName,
dict ) ) {
launchGameIf();
}
}
};
dialog = new AlertDialog.Builder( this )
.setTitle( R.string.subst_dict_title )
.setPositiveButton( R.string.button_substdict, lstnr )
.setNegativeButton( R.string.button_cancel, null )
.setSingleChoiceItems( m_sameLangDicts, 0, null )
.create();
// Force destruction so onCreateDialog() will get
// called next time and we can insert a different
// list. There seems to be no way to change the list
// inside onPrepareDialog().
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case RENAME_GAME:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.setName( GamesList.this, m_rowid, name );
m_adapter.invalName( m_rowid );
}
};
dialog = buildNamerDlg( GameUtils.getName( this, m_rowid ),
R.string.rename_label,
R.string.game_rename_title,
lstnr, RENAME_GAME );
break;
case RENAME_GROUP:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.setGroupName( GamesList.this, m_groupid,
name );
m_adapter.inval( m_rowid );
onContentChanged();
}
};
dialog = buildNamerDlg( m_adapter.groupName( m_groupid ),
R.string.rename_group_label,
R.string.game_name_group_title,
lstnr, RENAME_GROUP );
break;
case NEW_GROUP:
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
String name = m_namer.getName();
DBUtils.addGroup( GamesList.this, name );
// m_adapter.inval();
onContentChanged();
}
};
dialog = buildNamerDlg( "", R.string.newgroup_label,
R.string.game_name_group_title,
lstnr, RENAME_GROUP );
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case CHANGE_GROUP:
final long startGroup = DBUtils.getGroupForGame( this, m_rowid );
final int[] selItem = {-1}; // hack!!!!
lstnr = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlgi, int item ) {
selItem[0] = item;
AlertDialog dlg = (AlertDialog)dlgi;
Button btn =
dlg.getButton( AlertDialog.BUTTON_POSITIVE );
long newGroup = m_adapter.getGroupIDFor( item );
btn.setEnabled( newGroup != startGroup );
}
};
lstnr2 = new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dlg, int item ) {
Assert.assertTrue( -1 != selItem[0] );
long gid = m_adapter.getGroupIDFor( selItem[0] );
DBUtils.moveGame( GamesList.this, m_rowid, gid );
onContentChanged();
}
};
String[] groups = m_adapter.groupNames();
int curGroupPos = m_adapter.getGroupPosition( startGroup );
String name = GameUtils.getName( this, m_rowid );
dialog = new AlertDialog.Builder( this )
.setTitle( getString( R.string.change_groupf, name ) )
.setSingleChoiceItems( groups, curGroupPos, lstnr )
.setPositiveButton( R.string.button_move, lstnr2 )
.setNegativeButton( R.string.button_cancel, null )
.create();
Utils.setRemoveOnDismiss( this, dialog, id );
break;
case GET_NAME:
layout =
(LinearLayout)Utils.inflate( this, R.layout.dflt_name );
final EditText etext =
(EditText)layout.findViewById( R.id.name_edit );
etext.setText( CommonPrefs.getDefaultPlayerName( this, 0,
true ) );
dialog = new AlertDialog.Builder( this )
.setTitle( R.string.default_name_title )
.setMessage( R.string.default_name_message )
.setPositiveButton( R.string.button_ok, null )
.setView( layout )
.create();
dialog.setOnDismissListener(new DialogInterface.
OnDismissListener() {
public void onDismiss( DialogInterface dlg ) {
String name = etext.getText().toString();
if ( 0 == name.length() ) {
name = CommonPrefs.
getDefaultPlayerName( GamesList.this,
0, true );
}
CommonPrefs.setDefaultPlayerName( GamesList.this,
name );
}
});
break;
default:
// just drop it; super.onCreateDialog likely failed
break;
}
}
return dialog;
} // onCreateDialog
|
diff --git a/src/com/android/calendar/EditEvent.java b/src/com/android/calendar/EditEvent.java
index 40360936..43d99a37 100644
--- a/src/com/android/calendar/EditEvent.java
+++ b/src/com/android/calendar/EditEvent.java
@@ -1,2335 +1,2335 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar;
import static android.provider.Calendar.EVENT_BEGIN_TIME;
import static android.provider.Calendar.EVENT_END_TIME;
import com.android.calendar.TimezoneAdapter.TimezoneRow;
import com.android.common.Rfc822InputFilter;
import com.android.common.Rfc822Validator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.AsyncQueryHandler;
import android.content.ContentProviderOperation;
import android.content.ContentProviderOperation.Builder;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.pim.EventRecurrence;
import android.provider.Calendar.Attendees;
import android.provider.Calendar.Calendars;
import android.provider.Calendar.Events;
import android.provider.Calendar.Reminders;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.util.Rfc822Token;
import android.text.util.Rfc822Tokenizer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.ResourceCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Formatter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.TimeZone;
public class EditEvent extends Activity implements View.OnClickListener,
DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
private static final String TAG = "EditEvent";
private static final boolean DEBUG = false;
/**
* This is the symbolic name for the key used to pass in the boolean
* for creating all-day events that is part of the extra data of the intent.
* This is used only for creating new events and is set to true if
* the default for the new event should be an all-day event.
*/
public static final String EVENT_ALL_DAY = "allDay";
private static final int MAX_REMINDERS = 5;
private static final int MENU_GROUP_REMINDER = 1;
private static final int MENU_GROUP_SHOW_OPTIONS = 2;
private static final int MENU_GROUP_HIDE_OPTIONS = 3;
private static final int MENU_ADD_REMINDER = 1;
private static final int MENU_SHOW_EXTRA_OPTIONS = 2;
private static final int MENU_HIDE_EXTRA_OPTIONS = 3;
private static final String[] EVENT_PROJECTION = new String[] {
Events._ID, // 0
Events.TITLE, // 1
Events.DESCRIPTION, // 2
Events.EVENT_LOCATION, // 3
Events.ALL_DAY, // 4
Events.HAS_ALARM, // 5
Events.CALENDAR_ID, // 6
Events.DTSTART, // 7
Events.DURATION, // 8
Events.EVENT_TIMEZONE, // 9
Events.RRULE, // 10
Events._SYNC_ID, // 11
Events.TRANSPARENCY, // 12
Events.VISIBILITY, // 13
Events.OWNER_ACCOUNT, // 14
Events.HAS_ATTENDEE_DATA, // 15
};
private static final int EVENT_INDEX_ID = 0;
private static final int EVENT_INDEX_TITLE = 1;
private static final int EVENT_INDEX_DESCRIPTION = 2;
private static final int EVENT_INDEX_EVENT_LOCATION = 3;
private static final int EVENT_INDEX_ALL_DAY = 4;
private static final int EVENT_INDEX_HAS_ALARM = 5;
private static final int EVENT_INDEX_CALENDAR_ID = 6;
private static final int EVENT_INDEX_DTSTART = 7;
private static final int EVENT_INDEX_DURATION = 8;
private static final int EVENT_INDEX_TIMEZONE = 9;
private static final int EVENT_INDEX_RRULE = 10;
private static final int EVENT_INDEX_SYNC_ID = 11;
private static final int EVENT_INDEX_TRANSPARENCY = 12;
private static final int EVENT_INDEX_VISIBILITY = 13;
private static final int EVENT_INDEX_OWNER_ACCOUNT = 14;
private static final int EVENT_INDEX_HAS_ATTENDEE_DATA = 15;
private static final String[] CALENDARS_PROJECTION = new String[] {
Calendars._ID, // 0
Calendars.DISPLAY_NAME, // 1
Calendars.OWNER_ACCOUNT, // 2
Calendars.COLOR, // 3
};
private static final int CALENDARS_INDEX_DISPLAY_NAME = 1;
private static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2;
private static final int CALENDARS_INDEX_COLOR = 3;
private static final String CALENDARS_WHERE = Calendars.ACCESS_LEVEL + ">=" +
Calendars.CONTRIBUTOR_ACCESS + " AND " + Calendars.SYNC_EVENTS + "=1";
private static final String[] REMINDERS_PROJECTION = new String[] {
Reminders._ID, // 0
Reminders.MINUTES, // 1
};
private static final int REMINDERS_INDEX_MINUTES = 1;
private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=%d AND (" +
Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" +
Reminders.METHOD_DEFAULT + ")";
private static final String[] ATTENDEES_PROJECTION = new String[] {
Attendees.ATTENDEE_NAME, // 0
Attendees.ATTENDEE_EMAIL, // 1
};
private static final int ATTENDEES_INDEX_NAME = 0;
private static final int ATTENDEES_INDEX_EMAIL = 1;
private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=? AND "
+ Attendees.ATTENDEE_RELATIONSHIP + "<>" + Attendees.RELATIONSHIP_ORGANIZER;
private static final String ATTENDEES_DELETE_PREFIX = Attendees.EVENT_ID + "=? AND " +
Attendees.ATTENDEE_EMAIL + " IN (";
private static final int DOES_NOT_REPEAT = 0;
private static final int REPEATS_DAILY = 1;
private static final int REPEATS_EVERY_WEEKDAY = 2;
private static final int REPEATS_WEEKLY_ON_DAY = 3;
private static final int REPEATS_MONTHLY_ON_DAY_COUNT = 4;
private static final int REPEATS_MONTHLY_ON_DAY = 5;
private static final int REPEATS_YEARLY = 6;
private static final int REPEATS_CUSTOM = 7;
private static final int MODIFY_UNINITIALIZED = 0;
private static final int MODIFY_SELECTED = 1;
private static final int MODIFY_ALL = 2;
private static final int MODIFY_ALL_FOLLOWING = 3;
private static final int DAY_IN_SECONDS = 24 * 60 * 60;
private int mFirstDayOfWeek; // cached in onCreate
private Uri mUri;
private Cursor mEventCursor;
private Cursor mCalendarsCursor;
private Button mStartDateButton;
private Button mEndDateButton;
private Button mStartTimeButton;
private Button mEndTimeButton;
private Button mSaveButton;
private Button mDeleteButton;
private Button mDiscardButton;
private Button mTimezoneButton;
private CheckBox mAllDayCheckBox;
private Spinner mCalendarsSpinner;
private Spinner mRepeatsSpinner;
private Spinner mAvailabilitySpinner;
private Spinner mVisibilitySpinner;
private TextView mTitleTextView;
private TextView mLocationTextView;
private TextView mDescriptionTextView;
private TextView mTimezoneTextView;
private TextView mTimezoneFooterView;
private TextView mStartTimeHome;
private TextView mStartDateHome;
private TextView mEndTimeHome;
private TextView mEndDateHome;
private View mRemindersSeparator;
private LinearLayout mRemindersContainer;
private LinearLayout mExtraOptions;
private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>();
private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
private Rfc822Validator mEmailValidator;
private MultiAutoCompleteTextView mAttendeesList;
private EmailAddressAdapter mAddressAdapter;
private TimezoneAdapter mTimezoneAdapter;
private String mOriginalAttendees = "";
// Used to control the visibility of the Guests textview. Default to true
private boolean mHasAttendeeData = true;
private EventRecurrence mEventRecurrence = new EventRecurrence();
private String mRrule;
private boolean mCalendarsQueryComplete;
private boolean mSaveAfterQueryComplete;
private ProgressDialog mLoadingCalendarsDialog;
private AlertDialog mNoCalendarsDialog;
private AlertDialog mTimezoneDialog;
private ContentValues mInitialValues;
private String mOwnerAccount;
/**
* If the repeating event is created on the phone and it hasn't been
* synced yet to the web server, then there is a bug where you can't
* delete or change an instance of the repeating event. This case
* can be detected with mSyncId. If mSyncId == null, then the repeating
* event has not been synced to the phone, in which case we won't allow
* the user to change one instance.
*/
private String mSyncId;
private ArrayList<Integer> mRecurrenceIndexes = new ArrayList<Integer> (0);
private ArrayList<Integer> mReminderValues;
private ArrayList<String> mReminderLabels;
private Time mStartTime;
private Time mEndTime;
private String mTimezone;
private int mModification = MODIFY_UNINITIALIZED;
private int mDefaultReminderMinutes;
private DeleteEventHelper mDeleteEventHelper;
private QueryHandler mQueryHandler;
private static StringBuilder mSB = new StringBuilder(50);
private static Formatter mF = new Formatter(mSB, Locale.getDefault());
// This is here in case we need to update tz info later
private Runnable mUpdateTZ = null;
/* This class is used to update the time buttons. */
private class TimeListener implements OnTimeSetListener {
private View mView;
public TimeListener(View view) {
mView = view;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time endTime = mEndTime;
// Cache the start and end millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long endMillis;
if (mView == mStartTimeButton) {
// The start time was changed.
int hourDuration = endTime.hour - startTime.hour;
int minuteDuration = endTime.minute - startTime.minute;
startTime.hour = hourOfDay;
startTime.minute = minute;
startMillis = startTime.normalize(true);
// Also update the end time to keep the duration constant.
endTime.hour = hourOfDay + hourDuration;
endTime.minute = minute + minuteDuration;
} else {
// The end time was changed.
startMillis = startTime.toMillis(true);
endTime.hour = hourOfDay;
endTime.minute = minute;
// Move to the next day if the end time is before the start time.
if (endTime.before(startTime)) {
endTime.monthDay = startTime.monthDay + 1;
}
}
endMillis = endTime.normalize(true);
setDate(mEndDateButton, endMillis);
setTime(mStartTimeButton, startMillis);
setTime(mEndTimeButton, endMillis);
updateHomeTime();
}
}
private class TimeClickListener implements View.OnClickListener {
private Time mTime;
public TimeClickListener(Time time) {
mTime = time;
}
public void onClick(View v) {
new TimePickerDialog(EditEvent.this, new TimeListener(v),
mTime.hour, mTime.minute,
DateFormat.is24HourFormat(EditEvent.this)).show();
}
}
private class DateListener implements OnDateSetListener {
View mView;
public DateListener(View view) {
mView = view;
}
public void onDateSet(DatePicker view, int year, int month, int monthDay) {
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time endTime = mEndTime;
// Cache the start and end millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long endMillis;
if (mView == mStartDateButton) {
// The start date was changed.
int yearDuration = endTime.year - startTime.year;
int monthDuration = endTime.month - startTime.month;
int monthDayDuration = endTime.monthDay - startTime.monthDay;
startTime.year = year;
startTime.month = month;
startTime.monthDay = monthDay;
startMillis = startTime.normalize(true);
// Also update the end date to keep the duration constant.
endTime.year = year + yearDuration;
endTime.month = month + monthDuration;
endTime.monthDay = monthDay + monthDayDuration;
endMillis = endTime.normalize(true);
// If the start date has changed then update the repeats.
populateRepeats();
} else {
// The end date was changed.
startMillis = startTime.toMillis(true);
endTime.year = year;
endTime.month = month;
endTime.monthDay = monthDay;
endMillis = endTime.normalize(true);
// Do not allow an event to have an end time before the start time.
if (endTime.before(startTime)) {
endTime.set(startTime);
endMillis = startMillis;
}
}
setDate(mStartDateButton, startMillis);
setDate(mEndDateButton, endMillis);
setTime(mEndTimeButton, endMillis); // In case end time had to be reset
updateHomeTime();
}
}
private class DateClickListener implements View.OnClickListener {
private Time mTime;
public DateClickListener(Time time) {
mTime = time;
}
public void onClick(View v) {
new DatePickerDialog(EditEvent.this, new DateListener(v), mTime.year,
mTime.month, mTime.monthDay).show();
}
}
static private class CalendarsAdapter extends ResourceCursorAdapter {
public CalendarsAdapter(Context context, Cursor c) {
super(context, R.layout.calendars_item, c);
setDropDownViewResource(R.layout.calendars_dropdown_item);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
View colorBar = view.findViewById(R.id.color);
if (colorBar != null) {
colorBar.setBackgroundDrawable(
Utils.getColorChip(cursor.getInt(CALENDARS_INDEX_COLOR)));
}
TextView name = (TextView) view.findViewById(R.id.calendar_name);
if (name != null) {
String displayName = cursor.getString(CALENDARS_INDEX_DISPLAY_NAME);
name.setText(displayName);
name.setTextColor(0xFF000000);
TextView accountName = (TextView) view.findViewById(R.id.account_name);
if(accountName != null) {
Resources res = context.getResources();
accountName.setText(cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT));
accountName.setVisibility(TextView.VISIBLE);
accountName.setTextColor(res.getColor(R.color.calendar_owner_text_color));
}
}
}
}
// This is called if the user clicks on one of the buttons: "Save",
// "Discard", or "Delete". This is also called if the user clicks
// on the "remove reminder" button.
public void onClick(View v) {
if (v == mSaveButton) {
if (save()) {
finish();
}
return;
}
if (v == mDeleteButton) {
long begin = mStartTime.toMillis(false /* use isDst */);
long end = mEndTime.toMillis(false /* use isDst */);
int which = -1;
switch (mModification) {
case MODIFY_SELECTED:
which = DeleteEventHelper.DELETE_SELECTED;
break;
case MODIFY_ALL_FOLLOWING:
which = DeleteEventHelper.DELETE_ALL_FOLLOWING;
break;
case MODIFY_ALL:
which = DeleteEventHelper.DELETE_ALL;
break;
}
mDeleteEventHelper.delete(begin, end, mEventCursor, which);
return;
}
if (v == mDiscardButton) {
finish();
return;
}
// This must be a click on one of the "remove reminder" buttons
LinearLayout reminderItem = (LinearLayout) v.getParent();
LinearLayout parent = (LinearLayout) reminderItem.getParent();
parent.removeView(reminderItem);
mReminderItems.remove(reminderItem);
updateRemindersVisibility();
}
// This is called if the user cancels a popup dialog. There are two
// dialogs: the "Loading calendars" dialog, and the "No calendars"
// dialog. The "Loading calendars" dialog is shown if there is a delay
// in loading the calendars (needed when creating an event) and the user
// tries to save the event before the calendars have finished loading.
// The "No calendars" dialog is shown if there are no syncable calendars.
public void onCancel(DialogInterface dialog) {
if (dialog == mLoadingCalendarsDialog) {
mSaveAfterQueryComplete = false;
} else if (dialog == mNoCalendarsDialog) {
finish();
}
}
// This is called if the user clicks on a dialog button.
public void onClick(DialogInterface dialog, int which) {
if (dialog == mNoCalendarsDialog) {
finish();
} else if (dialog == mTimezoneDialog) {
if (which >= 0 && which < mTimezoneAdapter.getCount()) {
setTimezone(which);
updateHomeTime();
dialog.dismiss();
}
}
}
private class QueryHandler extends AsyncQueryHandler {
public QueryHandler(ContentResolver cr) {
super(cr);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
// If the query didn't return a cursor for some reason return
if (cursor == null) {
return;
}
// If the Activity is finishing, then close the cursor.
// Otherwise, use the new cursor in the adapter.
if (isFinishing()) {
stopManagingCursor(cursor);
cursor.close();
} else {
mCalendarsCursor = cursor;
startManagingCursor(cursor);
// Stop the spinner
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_OFF);
// If there are no syncable calendars, then we cannot allow
// creating a new event.
if (cursor.getCount() == 0) {
// Cancel the "loading calendars" dialog if it exists
if (mSaveAfterQueryComplete) {
mLoadingCalendarsDialog.cancel();
}
// Create an error message for the user that, when clicked,
// will exit this activity without saving the event.
AlertDialog.Builder builder = new AlertDialog.Builder(EditEvent.this);
builder.setTitle(R.string.no_syncable_calendars)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.no_calendars_found)
.setPositiveButton(android.R.string.ok, EditEvent.this)
.setOnCancelListener(EditEvent.this);
mNoCalendarsDialog = builder.show();
return;
}
int defaultCalendarPosition = findDefaultCalendarPosition(mCalendarsCursor);
// populate the calendars spinner
CalendarsAdapter adapter = new CalendarsAdapter(EditEvent.this, mCalendarsCursor);
mCalendarsSpinner.setAdapter(adapter);
mCalendarsSpinner.setSelection(defaultCalendarPosition);
mCalendarsQueryComplete = true;
if (mSaveAfterQueryComplete) {
mLoadingCalendarsDialog.cancel();
save();
finish();
}
// Find user domain and set it to the validator.
// TODO: we may want to update this validator if the user actually picks
// a different calendar. maybe not. depends on what we want for the
// user experience. this may change when we add support for multiple
// accounts, anyway.
if (mHasAttendeeData && cursor.moveToPosition(defaultCalendarPosition)) {
String ownEmail = cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
if (ownEmail != null) {
String domain = extractDomain(ownEmail);
if (domain != null) {
mEmailValidator = new Rfc822Validator(domain);
mAttendeesList.setValidator(mEmailValidator);
}
}
}
}
}
// Find the calendar position in the cursor that matches calendar in preference
private int findDefaultCalendarPosition(Cursor calendarsCursor) {
if (calendarsCursor.getCount() <= 0) {
return -1;
}
String defaultCalendar = Utils.getSharedPreference(EditEvent.this,
CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, null);
if (defaultCalendar == null) {
return 0;
}
int position = 0;
calendarsCursor.moveToPosition(-1);
while(calendarsCursor.moveToNext()) {
if (defaultCalendar.equals(mCalendarsCursor
.getString(CALENDARS_INDEX_OWNER_ACCOUNT))) {
return position;
}
position++;
}
return 0;
}
}
private static String extractDomain(String email) {
int separator = email.lastIndexOf('@');
if (separator != -1 && ++separator < email.length()) {
return email.substring(separator);
}
return null;
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.edit_event);
boolean newEvent = false;
mFirstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek();
mStartTime = new Time();
mEndTime = new Time();
mTimezone = Utils.getTimeZone(this, mUpdateTZ);
Intent intent = getIntent();
mUri = intent.getData();
if (mUri != null) {
mEventCursor = managedQuery(mUri, EVENT_PROJECTION, null, null, null);
if (mEventCursor == null || mEventCursor.getCount() == 0) {
// The cursor is empty. This can happen if the event was deleted.
finish();
return;
}
}
long begin = intent.getLongExtra(EVENT_BEGIN_TIME, 0);
long end = intent.getLongExtra(EVENT_END_TIME, 0);
String domain = "gmail.com";
boolean allDay = false;
if (mEventCursor != null) {
// The event already exists so fetch the all-day status
mEventCursor.moveToFirst();
mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0;
allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String rrule = mEventCursor.getString(EVENT_INDEX_RRULE);
if (!allDay) {
// only load the event timezone for non-all-day events
// otherwise it defaults to device default
mTimezone = mEventCursor.getString(EVENT_INDEX_TIMEZONE);
}
long calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID);
mOwnerAccount = mEventCursor.getString(EVENT_INDEX_OWNER_ACCOUNT);
if (!TextUtils.isEmpty(mOwnerAccount)) {
String ownerDomain = extractDomain(mOwnerAccount);
if (ownerDomain != null) {
domain = ownerDomain;
}
}
// Remember the initial values
mInitialValues = new ContentValues();
mInitialValues.put(EVENT_BEGIN_TIME, begin);
mInitialValues.put(EVENT_END_TIME, end);
mInitialValues.put(Events.ALL_DAY, allDay ? 1 : 0);
mInitialValues.put(Events.RRULE, rrule);
mInitialValues.put(Events.EVENT_TIMEZONE, mTimezone);
mInitialValues.put(Events.CALENDAR_ID, calendarId);
} else {
newEvent = true;
// We are creating a new event, so set the default from the
// intent (if specified).
allDay = intent.getBooleanExtra(EVENT_ALL_DAY, false);
// Start the spinner
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
// Start a query in the background to read the list of calendars
mQueryHandler = new QueryHandler(getContentResolver());
mQueryHandler.startQuery(0, null, Calendars.CONTENT_URI, CALENDARS_PROJECTION,
CALENDARS_WHERE, null /* selection args */, null /* sort order */);
}
mTimezoneAdapter = new TimezoneAdapter(this, mTimezone);
// If the event is all-day, read the times in UTC timezone
if (begin != 0) {
if (allDay) {
mStartTime.timezone = Time.TIMEZONE_UTC;
mStartTime.set(begin);
mStartTime.timezone = mTimezone;
// Calling normalize to calculate isDst
mStartTime.normalize(true);
} else {
mStartTime.timezone = mTimezone;
mStartTime.set(begin);
}
}
if (end != 0) {
if (allDay) {
mEndTime.timezone = Time.TIMEZONE_UTC;
mEndTime.set(end);
mEndTime.timezone = mTimezone;
// Calling normalize to calculate isDst
mEndTime.normalize(true);
} else {
mEndTime.timezone = mTimezone;
mEndTime.set(end);
}
}
LayoutInflater inflater = getLayoutInflater();
// cache all the widgets
mTitleTextView = (TextView) findViewById(R.id.title);
mLocationTextView = (TextView) findViewById(R.id.location);
mDescriptionTextView = (TextView) findViewById(R.id.description);
mTimezoneTextView = (TextView) findViewById(R.id.timezone_label);
mTimezoneFooterView = (TextView) inflater.inflate(R.layout.timezone_footer, null);
mStartDateButton = (Button) findViewById(R.id.start_date);
mEndDateButton = (Button) findViewById(R.id.end_date);
mStartTimeButton = (Button) findViewById(R.id.start_time);
mEndTimeButton = (Button) findViewById(R.id.end_time);
mStartTimeHome = (TextView) findViewById(R.id.start_time_home);
mStartDateHome = (TextView) findViewById(R.id.start_date_home);
mEndTimeHome = (TextView) findViewById(R.id.end_time_home);
mEndDateHome = (TextView) findViewById(R.id.end_date_home);
mAllDayCheckBox = (CheckBox) findViewById(R.id.is_all_day);
mTimezoneButton = (Button) findViewById(R.id.timezone);
mCalendarsSpinner = (Spinner) findViewById(R.id.calendars);
mRepeatsSpinner = (Spinner) findViewById(R.id.repeats);
mAvailabilitySpinner = (Spinner) findViewById(R.id.availability);
mVisibilitySpinner = (Spinner) findViewById(R.id.visibility);
mRemindersSeparator = findViewById(R.id.reminders_separator);
mRemindersContainer = (LinearLayout) findViewById(R.id.reminder_items_container);
mExtraOptions = (LinearLayout) findViewById(R.id.extra_options_container);
if (mHasAttendeeData) {
mAddressAdapter = new EmailAddressAdapter(this);
mEmailValidator = new Rfc822Validator(domain);
mAttendeesList = initMultiAutoCompleteTextView(R.id.attendees);
} else {
findViewById(R.id.attendees_group).setVisibility(View.GONE);
}
mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if (mEndTime.hour == 0 && mEndTime.minute == 0) {
mEndTime.monthDay--;
long endMillis = mEndTime.normalize(true);
// Do not allow an event to have an end time before the start time.
if (mEndTime.before(mStartTime)) {
mEndTime.set(mStartTime);
endMillis = mEndTime.normalize(true);
}
setDate(mEndDateButton, endMillis);
setTime(mEndTimeButton, endMillis);
}
mStartTimeButton.setVisibility(View.GONE);
mEndTimeButton.setVisibility(View.GONE);
mTimezoneButton.setVisibility(View.GONE);
mTimezoneTextView.setVisibility(View.GONE);
} else {
if (mEndTime.hour == 0 && mEndTime.minute == 0) {
mEndTime.monthDay++;
long endMillis = mEndTime.normalize(true);
setDate(mEndDateButton, endMillis);
setTime(mEndTimeButton, endMillis);
}
mStartTimeButton.setVisibility(View.VISIBLE);
mEndTimeButton.setVisibility(View.VISIBLE);
mTimezoneButton.setVisibility(View.VISIBLE);
mTimezoneTextView.setVisibility(View.VISIBLE);
}
updateHomeTime();
}
});
if (allDay) {
mAllDayCheckBox.setChecked(true);
} else {
mAllDayCheckBox.setChecked(false);
}
mSaveButton = (Button) findViewById(R.id.save);
mSaveButton.setOnClickListener(this);
mDeleteButton = (Button) findViewById(R.id.delete);
mDeleteButton.setOnClickListener(this);
mDiscardButton = (Button) findViewById(R.id.discard);
mDiscardButton.setOnClickListener(this);
// Initialize the reminder values array.
Resources r = getResources();
String[] strings = r.getStringArray(R.array.reminder_minutes_values);
int size = strings.length;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for (int i = 0 ; i < size ; i++) {
list.add(Integer.parseInt(strings[i]));
}
mReminderValues = list;
String[] labels = r.getStringArray(R.array.reminder_minutes_labels);
mReminderLabels = new ArrayList<String>(Arrays.asList(labels));
SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(this);
String durationString =
prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0");
mDefaultReminderMinutes = Integer.parseInt(durationString);
if (newEvent && mDefaultReminderMinutes != 0) {
addReminder(this, this, mReminderItems, mReminderValues,
mReminderLabels, mDefaultReminderMinutes);
}
long eventId = (mEventCursor == null) ? -1 : mEventCursor.getLong(EVENT_INDEX_ID);
ContentResolver cr = getContentResolver();
// Reminders cursor
boolean hasAlarm = (mEventCursor != null)
&& (mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0);
if (hasAlarm) {
Uri uri = Reminders.CONTENT_URI;
String where = String.format(REMINDERS_WHERE, eventId);
Cursor reminderCursor = cr.query(uri, REMINDERS_PROJECTION, where, null, null);
try {
// First pass: collect all the custom reminder minutes (e.g.,
// a reminder of 8 minutes) into a global list.
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
EditEvent.addMinutesToList(this, mReminderValues, mReminderLabels, minutes);
}
// Second pass: create the reminder spinners
reminderCursor.moveToPosition(-1);
while (reminderCursor.moveToNext()) {
int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES);
mOriginalMinutes.add(minutes);
EditEvent.addReminder(this, this, mReminderItems, mReminderValues,
mReminderLabels, minutes);
}
} finally {
reminderCursor.close();
}
}
updateRemindersVisibility();
// Setup the + Add Reminder Button
View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
public void onClick(View v) {
addReminder();
}
};
ImageButton reminderRemoveButton = (ImageButton) findViewById(R.id.reminder_add);
reminderRemoveButton.setOnClickListener(addReminderOnClickListener);
mDeleteEventHelper = new DeleteEventHelper(this, true /* exit when done */);
// Attendees cursor
if (mHasAttendeeData && eventId != -1) {
Uri uri = Attendees.CONTENT_URI;
String[] whereArgs = {Long.toString(eventId)};
Cursor attendeeCursor = cr.query(uri, ATTENDEES_PROJECTION, ATTENDEES_WHERE, whereArgs,
null);
try {
StringBuilder b = new StringBuilder();
while (attendeeCursor.moveToNext()) {
String name = attendeeCursor.getString(ATTENDEES_INDEX_NAME);
String email = attendeeCursor.getString(ATTENDEES_INDEX_EMAIL);
if (email != null) {
if (name != null && name.length() > 0 && !name.equals(email)) {
b.append('"').append(name).append("\" ");
}
b.append('<').append(email).append(">, ");
}
}
if (b.length() > 0) {
mOriginalAttendees = b.toString();
mAttendeesList.setText(mOriginalAttendees);
}
} finally {
attendeeCursor.close();
}
}
if (mEventCursor == null) {
// Allow the intent to specify the fields in the event.
// This will allow other apps to create events easily.
initFromIntent(intent);
}
}
private LinkedHashSet<Rfc822Token> getAddressesFromList(MultiAutoCompleteTextView list) {
list.clearComposingText();
LinkedHashSet<Rfc822Token> addresses = new LinkedHashSet<Rfc822Token>();
Rfc822Tokenizer.tokenize(list.getText(), addresses);
// validate the emails, out of paranoia. they should already be
// validated on input, but drop any invalid emails just to be safe.
Iterator<Rfc822Token> addressIterator = addresses.iterator();
while (addressIterator.hasNext()) {
Rfc822Token address = addressIterator.next();
if (!mEmailValidator.isValid(address.getAddress())) {
Log.w(TAG, "Dropping invalid attendee email address: " + address);
addressIterator.remove();
}
}
return addresses;
}
// From com.google.android.gm.ComposeActivity
private MultiAutoCompleteTextView initMultiAutoCompleteTextView(int res) {
MultiAutoCompleteTextView list = (MultiAutoCompleteTextView) findViewById(res);
list.setAdapter(mAddressAdapter);
list.setTokenizer(new Rfc822Tokenizer());
list.setValidator(mEmailValidator);
// NOTE: assumes no other filters are set
list.setFilters(sRecipientFilters);
return list;
}
/**
* From com.google.android.gm.ComposeActivity
* Implements special address cleanup rules:
* The first space key entry following an "@" symbol that is followed by any combination
* of letters and symbols, including one+ dots and zero commas, should insert an extra
* comma (followed by the space).
*/
private static InputFilter[] sRecipientFilters = new InputFilter[] { new Rfc822InputFilter() };
private void initFromIntent(Intent intent) {
String title = intent.getStringExtra(Events.TITLE);
if (title != null) {
mTitleTextView.setText(title);
}
String location = intent.getStringExtra(Events.EVENT_LOCATION);
if (location != null) {
mLocationTextView.setText(location);
}
String description = intent.getStringExtra(Events.DESCRIPTION);
if (description != null) {
mDescriptionTextView.setText(description);
}
int availability = intent.getIntExtra(Events.TRANSPARENCY, -1);
if (availability != -1) {
mAvailabilitySpinner.setSelection(availability);
}
int visibility = intent.getIntExtra(Events.VISIBILITY, -1);
if (visibility != -1) {
mVisibilitySpinner.setSelection(visibility);
}
String rrule = intent.getStringExtra(Events.RRULE);
if (!TextUtils.isEmpty(rrule)) {
mRrule = rrule;
mEventRecurrence.parse(rrule);
}
}
@Override
protected void onResume() {
super.onResume();
if (mUri != null) {
if (mEventCursor == null || mEventCursor.getCount() == 0) {
// The cursor is empty. This can happen if the event was deleted.
finish();
return;
}
}
if (mEventCursor != null) {
Cursor cursor = mEventCursor;
cursor.moveToFirst();
mRrule = cursor.getString(EVENT_INDEX_RRULE);
String title = cursor.getString(EVENT_INDEX_TITLE);
String description = cursor.getString(EVENT_INDEX_DESCRIPTION);
String location = cursor.getString(EVENT_INDEX_EVENT_LOCATION);
int availability = cursor.getInt(EVENT_INDEX_TRANSPARENCY);
int visibility = cursor.getInt(EVENT_INDEX_VISIBILITY);
if (visibility > 0) {
// For now we the array contains the values 0, 2, and 3. We subtract one to match.
visibility--;
}
if (!TextUtils.isEmpty(mRrule) && mModification == MODIFY_UNINITIALIZED) {
// If this event has not been synced, then don't allow deleting
// or changing a single instance.
mSyncId = cursor.getString(EVENT_INDEX_SYNC_ID);
mEventRecurrence.parse(mRrule);
// If we haven't synced this repeating event yet, then don't
// allow the user to change just one instance.
int itemIndex = 0;
CharSequence[] items;
if (mSyncId == null) {
if(isFirstEventInSeries()) {
// Still display the option so the user knows all events are changing
items = new CharSequence[1];
} else {
items = new CharSequence[2];
}
} else {
if(isFirstEventInSeries()) {
items = new CharSequence[2];
} else {
items = new CharSequence[3];
}
items[itemIndex++] = getText(R.string.modify_event);
}
items[itemIndex++] = getText(R.string.modify_all);
// Do one more check to make sure this remains at the end of the list
if(!isFirstEventInSeries()) {
// TODO Find out why modify all following causes a dup of the first event if
// it's operating on the first event.
items[itemIndex++] = getText(R.string.modify_all_following);
}
// Display the modification dialog.
new AlertDialog.Builder(this)
.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
finish();
}
})
.setTitle(R.string.edit_event_label)
.setItems(items, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
mModification =
(mSyncId == null) ? MODIFY_ALL : MODIFY_SELECTED;
} else if (which == 1) {
mModification =
(mSyncId == null) ? MODIFY_ALL_FOLLOWING : MODIFY_ALL;
} else if (which == 2) {
mModification = MODIFY_ALL_FOLLOWING;
}
// If we are modifying all the events in a
// series then disable and ignore the date.
if (mModification == MODIFY_ALL) {
mStartDateButton.setEnabled(false);
mEndDateButton.setEnabled(false);
} else if (mModification == MODIFY_SELECTED) {
mRepeatsSpinner.setEnabled(false);
}
}
})
.show();
}
mTitleTextView.setText(title);
mLocationTextView.setText(location);
mDescriptionTextView.setText(description);
mAvailabilitySpinner.setSelection(availability);
mVisibilitySpinner.setSelection(visibility);
// This is an existing event so hide the calendar spinner
// since we can't change the calendar.
View calendarGroup = findViewById(R.id.calendar_group);
calendarGroup.setVisibility(View.GONE);
} else {
// New event
if (Time.isEpoch(mStartTime) && Time.isEpoch(mEndTime)) {
mStartTime.setToNow();
// Round the time to the nearest half hour.
mStartTime.second = 0;
int minute = mStartTime.minute;
if (minute == 0) {
// We are already on a half hour increment
} else if (minute > 0 && minute <= 30) {
mStartTime.minute = 30;
} else {
mStartTime.minute = 0;
mStartTime.hour += 1;
}
long startMillis = mStartTime.normalize(true /* ignore isDst */);
mEndTime.set(startMillis + DateUtils.HOUR_IN_MILLIS);
}
// Hide delete button
mDeleteButton.setVisibility(View.GONE);
}
updateRemindersVisibility();
populateWhen();
populateTimezone();
updateHomeTime();
populateRepeats();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item;
item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0,
R.string.add_new_reminder);
item.setIcon(R.drawable.ic_menu_reminder);
item.setAlphabeticShortcut('r');
item = menu.add(MENU_GROUP_SHOW_OPTIONS, MENU_SHOW_EXTRA_OPTIONS, 0,
R.string.edit_event_show_extra_options);
item.setIcon(R.drawable.ic_menu_show_list);
item = menu.add(MENU_GROUP_HIDE_OPTIONS, MENU_HIDE_EXTRA_OPTIONS, 0,
R.string.edit_event_hide_extra_options);
item.setIcon(R.drawable.ic_menu_show_list);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (mReminderItems.size() < MAX_REMINDERS) {
menu.setGroupVisible(MENU_GROUP_REMINDER, true);
menu.setGroupEnabled(MENU_GROUP_REMINDER, true);
} else {
menu.setGroupVisible(MENU_GROUP_REMINDER, false);
menu.setGroupEnabled(MENU_GROUP_REMINDER, false);
}
if (mExtraOptions.getVisibility() == View.VISIBLE) {
menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, false);
menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, true);
} else {
menu.setGroupVisible(MENU_GROUP_SHOW_OPTIONS, true);
menu.setGroupVisible(MENU_GROUP_HIDE_OPTIONS, false);
}
return super.onPrepareOptionsMenu(menu);
}
private void addReminder() {
// TODO: when adding a new reminder, make it different from the
// last one in the list (if any).
if (mDefaultReminderMinutes == 0) {
addReminder(this, this, mReminderItems, mReminderValues,
mReminderLabels, 10 /* minutes */);
} else {
addReminder(this, this, mReminderItems, mReminderValues,
mReminderLabels, mDefaultReminderMinutes);
}
updateRemindersVisibility();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ADD_REMINDER:
addReminder();
return true;
case MENU_SHOW_EXTRA_OPTIONS:
mExtraOptions.setVisibility(View.VISIBLE);
return true;
case MENU_HIDE_EXTRA_OPTIONS:
mExtraOptions.setVisibility(View.GONE);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
// If we are creating a new event, do not create it if the
// title, location and description are all empty, in order to
// prevent accidental "no subject" event creations.
if (mUri != null || !isEmpty()) {
if (!save()) {
// We cannot exit this activity because the calendars
// are still loading.
return;
}
}
finish();
}
private void populateWhen() {
long startMillis = mStartTime.toMillis(false /* use isDst */);
long endMillis = mEndTime.toMillis(false /* use isDst */);
setDate(mStartDateButton, startMillis);
setDate(mEndDateButton, endMillis);
setTime(mStartTimeButton, startMillis);
setTime(mEndTimeButton, endMillis);
mStartDateButton.setOnClickListener(new DateClickListener(mStartTime));
mEndDateButton.setOnClickListener(new DateClickListener(mEndTime));
mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime));
mEndTimeButton.setOnClickListener(new TimeClickListener(mEndTime));
}
private void populateTimezone() {
mTimezoneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTimezoneDialog();
}
});
setTimezone(mTimezoneAdapter.getRowById(mTimezone));
}
/**
* Checks if the start and end times for this event should be
* displayed in the Calendar app's time zone as well and
* formats and displays them.
*/
private void updateHomeTime() {
String tz = Utils.getTimeZone(this, mUpdateTZ);
if (!mAllDayCheckBox.isChecked() && !TextUtils.equals(tz, mTimezone)) {
int flags = DateUtils.FORMAT_SHOW_TIME;
boolean is24Format = DateFormat.is24HourFormat(this);
if (is24Format) {
flags |= DateUtils.FORMAT_24HOUR;
}
long millisStart = mStartTime.toMillis(false);
long millisEnd = mEndTime.toMillis(false);
boolean isDSTStart = mStartTime.isDst != 0;
boolean isDSTEnd = mEndTime.isDst != 0;
// First update the start date and times
String tzDisplay = TimeZone.getTimeZone(tz).getDisplayName(isDSTStart,
TimeZone.SHORT, Locale.getDefault());
StringBuilder time = new StringBuilder();
mSB.setLength(0);
time.append(DateUtils.formatDateRange(this, mF, millisStart, millisStart, flags, tz))
.append(" ").append(tzDisplay);
mStartTimeHome.setText(time.toString());
flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY;
mSB.setLength(0);
mStartDateHome.setText(DateUtils.formatDateRange(this, mF, millisStart, millisStart,
flags, tz).toString());
// Make any adjustments needed for the end times
if (isDSTEnd != isDSTStart) {
tzDisplay = TimeZone.getTimeZone(tz).getDisplayName(isDSTEnd,
TimeZone.SHORT, Locale.getDefault());
}
flags = DateUtils.FORMAT_SHOW_TIME;
if (is24Format) {
flags |= DateUtils.FORMAT_24HOUR;
}
// Then update the end times
time.setLength(0);
mSB.setLength(0);
time.append(DateUtils.formatDateRange(this, mF, millisEnd, millisEnd, flags, tz))
.append(" ").append(tzDisplay);
mEndTimeHome.setText(time.toString());
flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY;
mSB.setLength(0);
mEndDateHome.setText(DateUtils.formatDateRange(this, mF, millisEnd, millisEnd,
flags, tz).toString());
mStartTimeHome.setVisibility(View.VISIBLE);
mStartDateHome.setVisibility(View.VISIBLE);
mEndTimeHome.setVisibility(View.VISIBLE);
mEndDateHome.setVisibility(View.VISIBLE);
} else {
mStartTimeHome.setVisibility(View.GONE);
mStartDateHome.setVisibility(View.GONE);
mEndTimeHome.setVisibility(View.GONE);
mEndDateHome.setVisibility(View.GONE);
}
}
/**
* Removes "Show all timezone" footer and adds all timezones to the dialog.
*/
private void showAllTimezone(ListView listView) {
final ListView lv = listView; // For making this variable available from Runnable.
lv.removeFooterView(mTimezoneFooterView);
mTimezoneAdapter.showAllTimezones();
final int row = mTimezoneAdapter.getRowById(mTimezone);
// we need to post the selection changes to have them have any effect.
lv.post(new Runnable() {
@Override
public void run() {
lv.setItemChecked(row, true);
lv.setSelection(row);
}
});
}
private void showTimezoneDialog() {
mTimezoneAdapter = new TimezoneAdapter(this, mTimezone);
final int row = mTimezoneAdapter.getRowById(mTimezone);
mTimezoneDialog = new AlertDialog.Builder(this)
.setTitle(R.string.timezone_label)
.setSingleChoiceItems(mTimezoneAdapter, row, this)
.create();
final ListView lv = mTimezoneDialog.getListView();
mTimezoneFooterView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAllTimezone(lv);
}
});
lv.addFooterView(mTimezoneFooterView);
mTimezoneDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER &&
lv.getSelectedView() == mTimezoneFooterView) {
showAllTimezone(lv);
return true;
} else {
return false;
}
}
});
mTimezoneDialog.show();
}
private void populateRepeats() {
Time time = mStartTime;
Resources r = getResources();
int resource = android.R.layout.simple_spinner_item;
String[] days = new String[] {
DateUtils.getDayOfWeekString(Calendar.SUNDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.MONDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.TUESDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.WEDNESDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.THURSDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.FRIDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.SATURDAY, DateUtils.LENGTH_MEDIUM),
};
String[] ordinals = r.getStringArray(R.array.ordinal_labels);
// Only display "Custom" in the spinner if the device does not support the
// recurrence functionality of the event. Only display every weekday if
// the event starts on a weekday.
boolean isCustomRecurrence = isCustomRecurrence();
boolean isWeekdayEvent = isWeekdayEvent();
ArrayList<String> repeatArray = new ArrayList<String>(0);
ArrayList<Integer> recurrenceIndexes = new ArrayList<Integer>(0);
repeatArray.add(r.getString(R.string.does_not_repeat));
recurrenceIndexes.add(DOES_NOT_REPEAT);
repeatArray.add(r.getString(R.string.daily));
recurrenceIndexes.add(REPEATS_DAILY);
if (isWeekdayEvent) {
repeatArray.add(r.getString(R.string.every_weekday));
recurrenceIndexes.add(REPEATS_EVERY_WEEKDAY);
}
String format = r.getString(R.string.weekly);
repeatArray.add(String.format(format, time.format("%A")));
recurrenceIndexes.add(REPEATS_WEEKLY_ON_DAY);
// Calculate whether this is the 1st, 2nd, 3rd, 4th, or last appearance of the given day.
int dayNumber = (time.monthDay - 1) / 7;
format = r.getString(R.string.monthly_on_day_count);
repeatArray.add(String.format(format, ordinals[dayNumber], days[time.weekDay]));
recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY_COUNT);
format = r.getString(R.string.monthly_on_day);
repeatArray.add(String.format(format, time.monthDay));
recurrenceIndexes.add(REPEATS_MONTHLY_ON_DAY);
long when = time.toMillis(false);
format = r.getString(R.string.yearly);
int flags = 0;
if (DateFormat.is24HourFormat(this)) {
flags |= DateUtils.FORMAT_24HOUR;
}
repeatArray.add(String.format(format, DateUtils.formatDateTime(this, when, flags)));
recurrenceIndexes.add(REPEATS_YEARLY);
if (isCustomRecurrence) {
repeatArray.add(r.getString(R.string.custom));
recurrenceIndexes.add(REPEATS_CUSTOM);
}
mRecurrenceIndexes = recurrenceIndexes;
int position = recurrenceIndexes.indexOf(DOES_NOT_REPEAT);
if (!TextUtils.isEmpty(mRrule)) {
if (isCustomRecurrence) {
position = recurrenceIndexes.indexOf(REPEATS_CUSTOM);
} else {
switch (mEventRecurrence.freq) {
case EventRecurrence.DAILY:
position = recurrenceIndexes.indexOf(REPEATS_DAILY);
break;
case EventRecurrence.WEEKLY:
if (mEventRecurrence.repeatsOnEveryWeekDay()) {
position = recurrenceIndexes.indexOf(REPEATS_EVERY_WEEKDAY);
} else {
position = recurrenceIndexes.indexOf(REPEATS_WEEKLY_ON_DAY);
}
break;
case EventRecurrence.MONTHLY:
if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY_COUNT);
} else {
position = recurrenceIndexes.indexOf(REPEATS_MONTHLY_ON_DAY);
}
break;
case EventRecurrence.YEARLY:
position = recurrenceIndexes.indexOf(REPEATS_YEARLY);
break;
}
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, resource, repeatArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mRepeatsSpinner.setAdapter(adapter);
mRepeatsSpinner.setSelection(position);
}
// Adds a reminder to the displayed list of reminders.
// Returns true if successfully added reminder, false if no reminders can
// be added.
static boolean addReminder(Activity activity, View.OnClickListener listener,
ArrayList<LinearLayout> items, ArrayList<Integer> values,
ArrayList<String> labels, int minutes) {
if (items.size() >= MAX_REMINDERS) {
return false;
}
LayoutInflater inflater = activity.getLayoutInflater();
LinearLayout parent = (LinearLayout) activity.findViewById(R.id.reminder_items_container);
LinearLayout reminderItem = (LinearLayout) inflater.inflate(R.layout.edit_reminder_item, null);
parent.addView(reminderItem);
Spinner spinner = (Spinner) reminderItem.findViewById(R.id.reminder_value);
Resources res = activity.getResources();
spinner.setPrompt(res.getString(R.string.reminders_label));
int resource = android.R.layout.simple_spinner_item;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, resource, labels);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
ImageButton reminderRemoveButton;
reminderRemoveButton = (ImageButton) reminderItem.findViewById(R.id.reminder_remove);
reminderRemoveButton.setOnClickListener(listener);
int index = findMinutesInReminderList(values, minutes);
spinner.setSelection(index);
items.add(reminderItem);
return true;
}
static void addMinutesToList(Context context, ArrayList<Integer> values,
ArrayList<String> labels, int minutes) {
int index = values.indexOf(minutes);
if (index != -1) {
return;
}
// The requested "minutes" does not exist in the list, so insert it
// into the list.
String label = constructReminderLabel(context, minutes, false);
int len = values.size();
for (int i = 0; i < len; i++) {
if (minutes < values.get(i)) {
values.add(i, minutes);
labels.add(i, label);
return;
}
}
values.add(minutes);
labels.add(len, label);
}
/**
* Finds the index of the given "minutes" in the "values" list.
*
* @param values the list of minutes corresponding to the spinner choices
* @param minutes the minutes to search for in the values list
* @return the index of "minutes" in the "values" list
*/
private static int findMinutesInReminderList(ArrayList<Integer> values, int minutes) {
int index = values.indexOf(minutes);
if (index == -1) {
// This should never happen.
Log.e("Cal", "Cannot find minutes (" + minutes + ") in list");
return 0;
}
return index;
}
// Constructs a label given an arbitrary number of minutes. For example,
// if the given minutes is 63, then this returns the string "63 minutes".
// As another example, if the given minutes is 120, then this returns
// "2 hours".
static String constructReminderLabel(Context context, int minutes, boolean abbrev) {
Resources resources = context.getResources();
int value, resId;
if (minutes % 60 != 0) {
value = minutes;
if (abbrev) {
resId = R.plurals.Nmins;
} else {
resId = R.plurals.Nminutes;
}
} else if (minutes % (24 * 60) != 0) {
value = minutes / 60;
resId = R.plurals.Nhours;
} else {
value = minutes / ( 24 * 60);
resId = R.plurals.Ndays;
}
String format = resources.getQuantityString(resId, value);
return String.format(format, value);
}
private void updateRemindersVisibility() {
if (mReminderItems.size() == 0) {
mRemindersSeparator.setVisibility(View.GONE);
mRemindersContainer.setVisibility(View.GONE);
} else {
mRemindersSeparator.setVisibility(View.VISIBLE);
mRemindersContainer.setVisibility(View.VISIBLE);
}
}
private void setDate(TextView view, long millis) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH |
DateUtils.FORMAT_ABBREV_WEEKDAY;
mSB.setLength(0);
String dateString = DateUtils.formatDateRange(this, mF, millis, millis, flags, mTimezone)
.toString();
view.setText(dateString);
}
private void setTime(TextView view, long millis) {
int flags = DateUtils.FORMAT_SHOW_TIME;
if (DateFormat.is24HourFormat(this)) {
flags |= DateUtils.FORMAT_24HOUR;
}
mSB.setLength(0);
String timeString = DateUtils.formatDateRange(this, mF, millis, millis, flags, mTimezone)
.toString();
view.setText(timeString);
}
private void setTimezone(int i) {
if (i < 0 || i > mTimezoneAdapter.getCount()) {
return; // do nothing
}
TimezoneRow timezone = mTimezoneAdapter.getItem(i);
mTimezoneButton.setText(timezone.toString());
mTimezone = timezone.mId;
mTimezoneAdapter.setCurrentTimezone(mTimezone);
mStartTime.timezone = mTimezone;
mStartTime.normalize(true);
mEndTime.timezone = mTimezone;
mEndTime.normalize(true);
}
// Saves the event. Returns true if it is okay to exit this activity.
private boolean save() {
boolean forceSaveReminders = false;
// If we are creating a new event, then make sure we wait until the
// query to fetch the list of calendars has finished.
if (mEventCursor == null) {
if (!mCalendarsQueryComplete) {
// Wait for the calendars query to finish.
if (mLoadingCalendarsDialog == null) {
// Create the progress dialog
mLoadingCalendarsDialog = ProgressDialog.show(this,
getText(R.string.loading_calendars_title),
getText(R.string.loading_calendars_message),
true, true, this);
mSaveAfterQueryComplete = true;
}
return false;
}
// Avoid creating a new event if the calendars cursor is empty or we clicked through
// too quickly and no calendar was selected (blame the monkey)
if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0 ||
mCalendarsSpinner.getSelectedItemId() == AdapterView.INVALID_ROW_ID) {
Log.w("Cal", "The calendars table does not contain any calendars"
+ " or no calendar was selected."
+ " New event was not created.");
return true;
}
Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
}
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int eventIdIndex = -1;
ContentValues values = getContentValuesFromUi();
Uri uri = mUri;
// save the timezone as a recent one
if (!mAllDayCheckBox.isChecked()) {
mTimezoneAdapter.saveRecentTimezone(mTimezone);
}
// Update the "hasAlarm" field for the event
ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems,
mReminderValues);
int len = reminderMinutes.size();
values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);
// For recurring events, we must make sure that we use duration rather
// than dtend.
if (uri == null) {
// Add hasAttendeeData for a new event
values.put(Events.HAS_ATTENDEE_DATA, 1);
// Create new event with new contents
addRecurrenceRule(values);
if (!TextUtils.isEmpty(mRrule)) {
values.remove(Events.DTEND);
}
eventIdIndex = ops.size();
Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
ops.add(b.build());
forceSaveReminders = true;
} else if (TextUtils.isEmpty(mRrule)) {
// Modify contents of a non-repeating event
addRecurrenceRule(values);
checkTimeDependentFields(values);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
- } else if (mInitialValues.getAsString(Events.RRULE) == null) {
+ } else if (TextUtils.isEmpty(mInitialValues.getAsString(Events.RRULE))) {
// This event was changed from a non-repeating event to a
// repeating event.
addRecurrenceRule(values);
values.remove(Events.DTEND);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
} else if (mModification == MODIFY_SELECTED) {
// Modify contents of the current instance of repeating event
// Create a recurrence exception
long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID));
values.put(Events.ORIGINAL_INSTANCE_TIME, begin);
boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
eventIdIndex = ops.size();
Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
ops.add(b.build());
forceSaveReminders = true;
} else if (mModification == MODIFY_ALL_FOLLOWING) {
// Modify this instance and all future instances of repeating event
addRecurrenceRule(values);
if (TextUtils.isEmpty(mRrule)) {
// We've changed a recurring event to a non-recurring event.
// If the event we are editing is the first in the series,
// then delete the whole series. Otherwise, update the series
// to end at the new start time.
if (isFirstEventInSeries()) {
ops.add(ContentProviderOperation.newDelete(uri).build());
} else {
// Update the current repeating event to end at the new
// start time.
updatePastEvents(ops, uri);
}
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
.build());
} else {
if (isFirstEventInSeries()) {
checkTimeDependentFields(values);
values.remove(Events.DTEND);
Builder b = ContentProviderOperation.newUpdate(uri).withValues(values);
ops.add(b.build());
} else {
// Update the current repeating event to end at the new
// start time.
updatePastEvents(ops, uri);
// Create a new event with the user-modified fields
values.remove(Events.DTEND);
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(
values).build());
}
}
forceSaveReminders = true;
} else if (mModification == MODIFY_ALL) {
// Modify all instances of repeating event
addRecurrenceRule(values);
if (TextUtils.isEmpty(mRrule)) {
// We've changed a recurring event to a non-recurring event.
// Delete the whole series and replace it with a new
// non-recurring event.
ops.add(ContentProviderOperation.newDelete(uri).build());
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
.build());
forceSaveReminders = true;
} else {
checkTimeDependentFields(values);
values.remove(Events.DTEND);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
}
}
// New Event or New Exception to an existing event
boolean newEvent = (eventIdIndex != -1);
if (newEvent) {
saveRemindersWithBackRef(ops, eventIdIndex, reminderMinutes, mOriginalMinutes,
forceSaveReminders);
} else if (uri != null) {
long eventId = ContentUris.parseId(uri);
saveReminders(ops, eventId, reminderMinutes, mOriginalMinutes,
forceSaveReminders);
}
Builder b;
// New event/instance - Set Organizer's response as yes
if (mHasAttendeeData && newEvent) {
values.clear();
int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition();
// Save the default calendar for new events
if (mCalendarsCursor != null) {
if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
String defaultCalendar = mCalendarsCursor
.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
Utils.setSharedPreference(this,
CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, defaultCalendar);
}
}
String ownerEmail = mOwnerAccount;
// Just in case mOwnerAccount is null, try to get owner from mCalendarsCursor
if (ownerEmail == null && mCalendarsCursor != null &&
mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
ownerEmail = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
}
if (ownerEmail != null) {
values.put(Attendees.ATTENDEE_EMAIL, ownerEmail);
values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
int initialStatus = Attendees.ATTENDEE_STATUS_ACCEPTED;
// Don't accept for secondary calendars
if (ownerEmail.endsWith("calendar.google.com")) {
initialStatus = Attendees.ATTENDEE_STATUS_NONE;
}
values.put(Attendees.ATTENDEE_STATUS, initialStatus);
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
ops.add(b.build());
}
}
// TODO: is this the right test? this currently checks if this is
// a new event or an existing event. or is this a paranoia check?
if (mHasAttendeeData && (newEvent || uri != null)) {
Editable attendeesText = mAttendeesList.getText();
// Hit the content provider only if this is a new event or the user has changed it
if (newEvent || !mOriginalAttendees.equals(attendeesText.toString())) {
// figure out which attendees need to be added and which ones
// need to be deleted. use a linked hash set, so we maintain
// order (but also remove duplicates).
LinkedHashSet<Rfc822Token> newAttendees = getAddressesFromList(mAttendeesList);
// the eventId is only used if eventIdIndex is -1.
// TODO: clean up this code.
long eventId = uri != null ? ContentUris.parseId(uri) : -1;
// only compute deltas if this is an existing event.
// new events (being inserted into the Events table) won't
// have any existing attendees.
if (!newEvent) {
HashSet<Rfc822Token> removedAttendees = new HashSet<Rfc822Token>();
HashSet<Rfc822Token> originalAttendees = new HashSet<Rfc822Token>();
Rfc822Tokenizer.tokenize(mOriginalAttendees, originalAttendees);
for (Rfc822Token originalAttendee : originalAttendees) {
if (newAttendees.contains(originalAttendee)) {
// existing attendee. remove from new attendees set.
newAttendees.remove(originalAttendee);
} else {
// no longer in attendees. mark as removed.
removedAttendees.add(originalAttendee);
}
}
// delete removed attendees
b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI);
String[] args = new String[removedAttendees.size() + 1];
args[0] = Long.toString(eventId);
int i = 1;
StringBuilder deleteWhere = new StringBuilder(ATTENDEES_DELETE_PREFIX);
for (Rfc822Token removedAttendee : removedAttendees) {
if (i > 1) {
deleteWhere.append(",");
}
deleteWhere.append("?");
args[i++] = removedAttendee.getAddress();
}
deleteWhere.append(")");
b.withSelection(deleteWhere.toString(), args);
ops.add(b.build());
}
if (newAttendees.size() > 0) {
// Insert the new attendees
for (Rfc822Token attendee : newAttendees) {
values.clear();
values.put(Attendees.ATTENDEE_NAME, attendee.getName());
values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress());
values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE);
if (newEvent) {
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex);
} else {
values.put(Attendees.EVENT_ID, eventId);
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
}
ops.add(b.build());
}
}
}
}
try {
// TODO Move this to background thread
ContentProviderResult[] results =
getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops);
if (DEBUG) {
for (int i = 0; i < results.length; i++) {
Log.v(TAG, "results = " + results[i].toString());
}
}
} catch (RemoteException e) {
Log.w(TAG, "Ignoring unexpected remote exception", e);
} catch (OperationApplicationException e) {
Log.w(TAG, "Ignoring unexpected exception", e);
}
return true;
}
private boolean isFirstEventInSeries() {
int dtStart = mEventCursor.getColumnIndexOrThrow(Events.DTSTART);
long start = mEventCursor.getLong(dtStart);
return start == mStartTime.toMillis(true);
}
private void updatePastEvents(ArrayList<ContentProviderOperation> ops, Uri uri) {
long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
String oldDuration = mEventCursor.getString(EVENT_INDEX_DURATION);
boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
String oldRrule = mEventCursor.getString(EVENT_INDEX_RRULE);
mEventRecurrence.parse(oldRrule);
Time untilTime = new Time();
long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
ContentValues oldValues = new ContentValues();
// The "until" time must be in UTC time in order for Google calendar
// to display it properly. For all-day events, the "until" time string
// must include just the date field, and not the time field. The
// repeating events repeat up to and including the "until" time.
untilTime.timezone = Time.TIMEZONE_UTC;
// Subtract one second from the old begin time to get the new
// "until" time.
untilTime.set(begin - 1000); // subtract one second (1000 millis)
if (allDay) {
untilTime.hour = 0;
untilTime.minute = 0;
untilTime.second = 0;
untilTime.allDay = true;
untilTime.normalize(false);
// For all-day events, the duration must be in days, not seconds.
// Otherwise, Google Calendar will (mistakenly) change this event
// into a non-all-day event.
int len = oldDuration.length();
if (oldDuration.charAt(0) == 'P' && oldDuration.charAt(len - 1) == 'S') {
int seconds = Integer.parseInt(oldDuration.substring(1, len - 1));
int days = (seconds + DAY_IN_SECONDS - 1) / DAY_IN_SECONDS;
oldDuration = "P" + days + "D";
}
}
mEventRecurrence.until = untilTime.format2445();
oldValues.put(Events.DTSTART, oldStartMillis);
oldValues.put(Events.DURATION, oldDuration);
oldValues.put(Events.RRULE, mEventRecurrence.toString());
Builder b = ContentProviderOperation.newUpdate(uri).withValues(oldValues);
ops.add(b.build());
}
private void checkTimeDependentFields(ContentValues values) {
long oldBegin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
long oldEnd = mInitialValues.getAsLong(EVENT_END_TIME);
boolean oldAllDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
String oldRrule = mInitialValues.getAsString(Events.RRULE);
String oldTimezone = mInitialValues.getAsString(Events.EVENT_TIMEZONE);
long newBegin = values.getAsLong(Events.DTSTART);
long newEnd = values.getAsLong(Events.DTEND);
boolean newAllDay = values.getAsInteger(Events.ALL_DAY) != 0;
String newRrule = values.getAsString(Events.RRULE);
String newTimezone = values.getAsString(Events.EVENT_TIMEZONE);
// If none of the time-dependent fields changed, then remove them.
if (oldBegin == newBegin && oldEnd == newEnd && oldAllDay == newAllDay
&& TextUtils.equals(oldRrule, newRrule)
&& TextUtils.equals(oldTimezone, newTimezone)) {
values.remove(Events.DTSTART);
values.remove(Events.DTEND);
values.remove(Events.DURATION);
values.remove(Events.ALL_DAY);
values.remove(Events.RRULE);
values.remove(Events.EVENT_TIMEZONE);
return;
}
if (TextUtils.isEmpty(oldRrule) || TextUtils.isEmpty(newRrule)) {
return;
}
// If we are modifying all events then we need to set DTSTART to the
// start time of the first event in the series, not the current
// date and time. If the start time of the event was changed
// (from, say, 3pm to 4pm), then we want to add the time difference
// to the start time of the first event in the series (the DTSTART
// value). If we are modifying one instance or all following instances,
// then we leave the DTSTART field alone.
if (mModification == MODIFY_ALL) {
long oldStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
if (oldBegin != newBegin) {
// The user changed the start time of this event
long offset = newBegin - oldBegin;
oldStartMillis += offset;
}
values.put(Events.DTSTART, oldStartMillis);
}
}
static ArrayList<Integer> reminderItemsToMinutes(ArrayList<LinearLayout> reminderItems,
ArrayList<Integer> reminderValues) {
int len = reminderItems.size();
ArrayList<Integer> reminderMinutes = new ArrayList<Integer>(len);
for (int index = 0; index < len; index++) {
LinearLayout layout = reminderItems.get(index);
Spinner spinner = (Spinner) layout.findViewById(R.id.reminder_value);
int minutes = reminderValues.get(spinner.getSelectedItemPosition());
reminderMinutes.add(minutes);
}
return reminderMinutes;
}
/**
* Saves the reminders, if they changed. Returns true if the database
* was updated.
*
* @param ops the array of ContentProviderOperations
* @param eventId the id of the event whose reminders are being updated
* @param reminderMinutes the array of reminders set by the user
* @param originalMinutes the original array of reminders
* @param forceSave if true, then save the reminders even if they didn't
* change
* @return true if the database was updated
*/
static boolean saveReminders(ArrayList<ContentProviderOperation> ops, long eventId,
ArrayList<Integer> reminderMinutes, ArrayList<Integer> originalMinutes,
boolean forceSave) {
// If the reminders have not changed, then don't update the database
if (reminderMinutes.equals(originalMinutes) && !forceSave) {
return false;
}
// Delete all the existing reminders for this event
String where = Reminders.EVENT_ID + "=?";
String[] args = new String[] { Long.toString(eventId) };
Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI);
b.withSelection(where, args);
ops.add(b.build());
ContentValues values = new ContentValues();
int len = reminderMinutes.size();
// Insert the new reminders, if any
for (int i = 0; i < len; i++) {
int minutes = reminderMinutes.get(i);
values.clear();
values.put(Reminders.MINUTES, minutes);
values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(Reminders.EVENT_ID, eventId);
b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values);
ops.add(b.build());
}
return true;
}
static boolean saveRemindersWithBackRef(ArrayList<ContentProviderOperation> ops,
int eventIdIndex, ArrayList<Integer> reminderMinutes,
ArrayList<Integer> originalMinutes, boolean forceSave) {
// If the reminders have not changed, then don't update the database
if (reminderMinutes.equals(originalMinutes) && !forceSave) {
return false;
}
// Delete all the existing reminders for this event
Builder b = ContentProviderOperation.newDelete(Reminders.CONTENT_URI);
b.withSelection(Reminders.EVENT_ID + "=?", new String[1]);
b.withSelectionBackReference(0, eventIdIndex);
ops.add(b.build());
ContentValues values = new ContentValues();
int len = reminderMinutes.size();
// Insert the new reminders, if any
for (int i = 0; i < len; i++) {
int minutes = reminderMinutes.get(i);
values.clear();
values.put(Reminders.MINUTES, minutes);
values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
b = ContentProviderOperation.newInsert(Reminders.CONTENT_URI).withValues(values);
b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
ops.add(b.build());
}
return true;
}
private void addRecurrenceRule(ContentValues values) {
updateRecurrenceRule();
if (TextUtils.isEmpty(mRrule)) {
return;
}
values.put(Events.RRULE, mRrule);
long end = mEndTime.toMillis(true /* ignore dst */);
long start = mStartTime.toMillis(true /* ignore dst */);
String duration;
boolean isAllDay = mAllDayCheckBox.isChecked();
if (isAllDay) {
long days = (end - start + DateUtils.DAY_IN_MILLIS - 1) / DateUtils.DAY_IN_MILLIS;
duration = "P" + days + "D";
} else {
long seconds = (end - start) / DateUtils.SECOND_IN_MILLIS;
duration = "P" + seconds + "S";
}
values.put(Events.DURATION, duration);
}
private void clearRecurrence() {
mEventRecurrence.byday = null;
mEventRecurrence.bydayNum = null;
mEventRecurrence.bydayCount = 0;
mEventRecurrence.bymonth = null;
mEventRecurrence.bymonthCount = 0;
mEventRecurrence.bymonthday = null;
mEventRecurrence.bymonthdayCount = 0;
}
private void updateRecurrenceRule() {
int position = mRepeatsSpinner.getSelectedItemPosition();
int selection = mRecurrenceIndexes.get(position);
// Make sure we don't have any leftover data from the previous setting
clearRecurrence();
if (selection == DOES_NOT_REPEAT) {
mRrule = null;
return;
} else if (selection == REPEATS_CUSTOM) {
// Keep custom recurrence as before.
return;
} else if (selection == REPEATS_DAILY) {
mEventRecurrence.freq = EventRecurrence.DAILY;
} else if (selection == REPEATS_EVERY_WEEKDAY) {
mEventRecurrence.freq = EventRecurrence.WEEKLY;
int dayCount = 5;
int[] byday = new int[dayCount];
int[] bydayNum = new int[dayCount];
byday[0] = EventRecurrence.MO;
byday[1] = EventRecurrence.TU;
byday[2] = EventRecurrence.WE;
byday[3] = EventRecurrence.TH;
byday[4] = EventRecurrence.FR;
for (int day = 0; day < dayCount; day++) {
bydayNum[day] = 0;
}
mEventRecurrence.byday = byday;
mEventRecurrence.bydayNum = bydayNum;
mEventRecurrence.bydayCount = dayCount;
} else if (selection == REPEATS_WEEKLY_ON_DAY) {
mEventRecurrence.freq = EventRecurrence.WEEKLY;
int[] days = new int[1];
int dayCount = 1;
int[] dayNum = new int[dayCount];
days[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
// not sure why this needs to be zero, but set it for now.
dayNum[0] = 0;
mEventRecurrence.byday = days;
mEventRecurrence.bydayNum = dayNum;
mEventRecurrence.bydayCount = dayCount;
} else if (selection == REPEATS_MONTHLY_ON_DAY) {
mEventRecurrence.freq = EventRecurrence.MONTHLY;
mEventRecurrence.bydayCount = 0;
mEventRecurrence.bymonthdayCount = 1;
int[] bymonthday = new int[1];
bymonthday[0] = mStartTime.monthDay;
mEventRecurrence.bymonthday = bymonthday;
} else if (selection == REPEATS_MONTHLY_ON_DAY_COUNT) {
mEventRecurrence.freq = EventRecurrence.MONTHLY;
mEventRecurrence.bydayCount = 1;
mEventRecurrence.bymonthdayCount = 0;
int[] byday = new int[1];
int[] bydayNum = new int[1];
// Compute the week number (for example, the "2nd" Monday)
int dayCount = 1 + ((mStartTime.monthDay - 1) / 7);
if (dayCount == 5) {
dayCount = -1;
}
bydayNum[0] = dayCount;
byday[0] = EventRecurrence.timeDay2Day(mStartTime.weekDay);
mEventRecurrence.byday = byday;
mEventRecurrence.bydayNum = bydayNum;
} else if (selection == REPEATS_YEARLY) {
mEventRecurrence.freq = EventRecurrence.YEARLY;
}
// Set the week start day.
mEventRecurrence.wkst = EventRecurrence.calendarDay2Day(mFirstDayOfWeek);
mRrule = mEventRecurrence.toString();
}
private ContentValues getContentValuesFromUi() {
String title = mTitleTextView.getText().toString().trim();
boolean isAllDay = mAllDayCheckBox.isChecked();
String location = mLocationTextView.getText().toString().trim();
String description = mDescriptionTextView.getText().toString().trim();
ContentValues values = new ContentValues();
long startMillis;
long endMillis;
long calendarId;
if (isAllDay) {
// Reset start and end time, increment the monthDay by 1, and set
// the timezone to UTC, as required for all-day events.
mTimezone = Time.TIMEZONE_UTC;
mStartTime.hour = 0;
mStartTime.minute = 0;
mStartTime.second = 0;
mStartTime.timezone = mTimezone;
startMillis = mStartTime.normalize(true);
mEndTime.hour = 0;
mEndTime.minute = 0;
mEndTime.second = 0;
mEndTime.monthDay++;
mEndTime.timezone = mTimezone;
endMillis = mEndTime.normalize(true);
if (mEventCursor == null) {
// This is a new event
calendarId = mCalendarsSpinner.getSelectedItemId();
} else {
calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
}
} else {
if (mEventCursor != null) {
calendarId = mInitialValues.getAsLong(Events.CALENDAR_ID);
} else {
// This is a new event
calendarId = mCalendarsSpinner.getSelectedItemId();
}
// mTimezone is set automatically in onClick
mStartTime.timezone = mTimezone;
mEndTime.timezone = mTimezone;
startMillis = mStartTime.toMillis(true);
endMillis = mEndTime.toMillis(true);
}
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.EVENT_TIMEZONE, mTimezone);
values.put(Events.TITLE, title);
values.put(Events.ALL_DAY, isAllDay ? 1 : 0);
values.put(Events.DTSTART, startMillis);
values.put(Events.DTEND, endMillis);
values.put(Events.DESCRIPTION, description);
values.put(Events.EVENT_LOCATION, location);
values.put(Events.TRANSPARENCY, mAvailabilitySpinner.getSelectedItemPosition());
int visibility = mVisibilitySpinner.getSelectedItemPosition();
if (visibility > 0) {
// For now we the array contains the values 0, 2, and 3. We add one to match.
visibility++;
}
values.put(Events.VISIBILITY, visibility);
return values;
}
private boolean isEmpty() {
String title = mTitleTextView.getText().toString().trim();
if (title.length() > 0) {
return false;
}
String location = mLocationTextView.getText().toString().trim();
if (location.length() > 0) {
return false;
}
String description = mDescriptionTextView.getText().toString().trim();
if (description.length() > 0) {
return false;
}
return true;
}
private boolean isCustomRecurrence() {
if (mEventRecurrence.until != null || mEventRecurrence.interval != 0) {
return true;
}
if (mEventRecurrence.freq == 0) {
return false;
}
switch (mEventRecurrence.freq) {
case EventRecurrence.DAILY:
return false;
case EventRecurrence.WEEKLY:
if (mEventRecurrence.repeatsOnEveryWeekDay() && isWeekdayEvent()) {
return false;
} else if (mEventRecurrence.bydayCount == 1) {
return false;
}
break;
case EventRecurrence.MONTHLY:
if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
return false;
} else if (mEventRecurrence.bydayCount == 0 && mEventRecurrence.bymonthdayCount == 1) {
return false;
}
break;
case EventRecurrence.YEARLY:
return false;
}
return true;
}
private boolean isWeekdayEvent() {
if (mStartTime.weekDay != Time.SUNDAY && mStartTime.weekDay != Time.SATURDAY) {
return true;
}
return false;
}
}
| true | true | private boolean save() {
boolean forceSaveReminders = false;
// If we are creating a new event, then make sure we wait until the
// query to fetch the list of calendars has finished.
if (mEventCursor == null) {
if (!mCalendarsQueryComplete) {
// Wait for the calendars query to finish.
if (mLoadingCalendarsDialog == null) {
// Create the progress dialog
mLoadingCalendarsDialog = ProgressDialog.show(this,
getText(R.string.loading_calendars_title),
getText(R.string.loading_calendars_message),
true, true, this);
mSaveAfterQueryComplete = true;
}
return false;
}
// Avoid creating a new event if the calendars cursor is empty or we clicked through
// too quickly and no calendar was selected (blame the monkey)
if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0 ||
mCalendarsSpinner.getSelectedItemId() == AdapterView.INVALID_ROW_ID) {
Log.w("Cal", "The calendars table does not contain any calendars"
+ " or no calendar was selected."
+ " New event was not created.");
return true;
}
Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
}
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int eventIdIndex = -1;
ContentValues values = getContentValuesFromUi();
Uri uri = mUri;
// save the timezone as a recent one
if (!mAllDayCheckBox.isChecked()) {
mTimezoneAdapter.saveRecentTimezone(mTimezone);
}
// Update the "hasAlarm" field for the event
ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems,
mReminderValues);
int len = reminderMinutes.size();
values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);
// For recurring events, we must make sure that we use duration rather
// than dtend.
if (uri == null) {
// Add hasAttendeeData for a new event
values.put(Events.HAS_ATTENDEE_DATA, 1);
// Create new event with new contents
addRecurrenceRule(values);
if (!TextUtils.isEmpty(mRrule)) {
values.remove(Events.DTEND);
}
eventIdIndex = ops.size();
Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
ops.add(b.build());
forceSaveReminders = true;
} else if (TextUtils.isEmpty(mRrule)) {
// Modify contents of a non-repeating event
addRecurrenceRule(values);
checkTimeDependentFields(values);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
} else if (mInitialValues.getAsString(Events.RRULE) == null) {
// This event was changed from a non-repeating event to a
// repeating event.
addRecurrenceRule(values);
values.remove(Events.DTEND);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
} else if (mModification == MODIFY_SELECTED) {
// Modify contents of the current instance of repeating event
// Create a recurrence exception
long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID));
values.put(Events.ORIGINAL_INSTANCE_TIME, begin);
boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
eventIdIndex = ops.size();
Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
ops.add(b.build());
forceSaveReminders = true;
} else if (mModification == MODIFY_ALL_FOLLOWING) {
// Modify this instance and all future instances of repeating event
addRecurrenceRule(values);
if (TextUtils.isEmpty(mRrule)) {
// We've changed a recurring event to a non-recurring event.
// If the event we are editing is the first in the series,
// then delete the whole series. Otherwise, update the series
// to end at the new start time.
if (isFirstEventInSeries()) {
ops.add(ContentProviderOperation.newDelete(uri).build());
} else {
// Update the current repeating event to end at the new
// start time.
updatePastEvents(ops, uri);
}
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
.build());
} else {
if (isFirstEventInSeries()) {
checkTimeDependentFields(values);
values.remove(Events.DTEND);
Builder b = ContentProviderOperation.newUpdate(uri).withValues(values);
ops.add(b.build());
} else {
// Update the current repeating event to end at the new
// start time.
updatePastEvents(ops, uri);
// Create a new event with the user-modified fields
values.remove(Events.DTEND);
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(
values).build());
}
}
forceSaveReminders = true;
} else if (mModification == MODIFY_ALL) {
// Modify all instances of repeating event
addRecurrenceRule(values);
if (TextUtils.isEmpty(mRrule)) {
// We've changed a recurring event to a non-recurring event.
// Delete the whole series and replace it with a new
// non-recurring event.
ops.add(ContentProviderOperation.newDelete(uri).build());
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
.build());
forceSaveReminders = true;
} else {
checkTimeDependentFields(values);
values.remove(Events.DTEND);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
}
}
// New Event or New Exception to an existing event
boolean newEvent = (eventIdIndex != -1);
if (newEvent) {
saveRemindersWithBackRef(ops, eventIdIndex, reminderMinutes, mOriginalMinutes,
forceSaveReminders);
} else if (uri != null) {
long eventId = ContentUris.parseId(uri);
saveReminders(ops, eventId, reminderMinutes, mOriginalMinutes,
forceSaveReminders);
}
Builder b;
// New event/instance - Set Organizer's response as yes
if (mHasAttendeeData && newEvent) {
values.clear();
int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition();
// Save the default calendar for new events
if (mCalendarsCursor != null) {
if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
String defaultCalendar = mCalendarsCursor
.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
Utils.setSharedPreference(this,
CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, defaultCalendar);
}
}
String ownerEmail = mOwnerAccount;
// Just in case mOwnerAccount is null, try to get owner from mCalendarsCursor
if (ownerEmail == null && mCalendarsCursor != null &&
mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
ownerEmail = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
}
if (ownerEmail != null) {
values.put(Attendees.ATTENDEE_EMAIL, ownerEmail);
values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
int initialStatus = Attendees.ATTENDEE_STATUS_ACCEPTED;
// Don't accept for secondary calendars
if (ownerEmail.endsWith("calendar.google.com")) {
initialStatus = Attendees.ATTENDEE_STATUS_NONE;
}
values.put(Attendees.ATTENDEE_STATUS, initialStatus);
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
ops.add(b.build());
}
}
// TODO: is this the right test? this currently checks if this is
// a new event or an existing event. or is this a paranoia check?
if (mHasAttendeeData && (newEvent || uri != null)) {
Editable attendeesText = mAttendeesList.getText();
// Hit the content provider only if this is a new event or the user has changed it
if (newEvent || !mOriginalAttendees.equals(attendeesText.toString())) {
// figure out which attendees need to be added and which ones
// need to be deleted. use a linked hash set, so we maintain
// order (but also remove duplicates).
LinkedHashSet<Rfc822Token> newAttendees = getAddressesFromList(mAttendeesList);
// the eventId is only used if eventIdIndex is -1.
// TODO: clean up this code.
long eventId = uri != null ? ContentUris.parseId(uri) : -1;
// only compute deltas if this is an existing event.
// new events (being inserted into the Events table) won't
// have any existing attendees.
if (!newEvent) {
HashSet<Rfc822Token> removedAttendees = new HashSet<Rfc822Token>();
HashSet<Rfc822Token> originalAttendees = new HashSet<Rfc822Token>();
Rfc822Tokenizer.tokenize(mOriginalAttendees, originalAttendees);
for (Rfc822Token originalAttendee : originalAttendees) {
if (newAttendees.contains(originalAttendee)) {
// existing attendee. remove from new attendees set.
newAttendees.remove(originalAttendee);
} else {
// no longer in attendees. mark as removed.
removedAttendees.add(originalAttendee);
}
}
// delete removed attendees
b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI);
String[] args = new String[removedAttendees.size() + 1];
args[0] = Long.toString(eventId);
int i = 1;
StringBuilder deleteWhere = new StringBuilder(ATTENDEES_DELETE_PREFIX);
for (Rfc822Token removedAttendee : removedAttendees) {
if (i > 1) {
deleteWhere.append(",");
}
deleteWhere.append("?");
args[i++] = removedAttendee.getAddress();
}
deleteWhere.append(")");
b.withSelection(deleteWhere.toString(), args);
ops.add(b.build());
}
if (newAttendees.size() > 0) {
// Insert the new attendees
for (Rfc822Token attendee : newAttendees) {
values.clear();
values.put(Attendees.ATTENDEE_NAME, attendee.getName());
values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress());
values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE);
if (newEvent) {
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex);
} else {
values.put(Attendees.EVENT_ID, eventId);
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
}
ops.add(b.build());
}
}
}
}
try {
// TODO Move this to background thread
ContentProviderResult[] results =
getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops);
if (DEBUG) {
for (int i = 0; i < results.length; i++) {
Log.v(TAG, "results = " + results[i].toString());
}
}
} catch (RemoteException e) {
Log.w(TAG, "Ignoring unexpected remote exception", e);
} catch (OperationApplicationException e) {
Log.w(TAG, "Ignoring unexpected exception", e);
}
return true;
}
| private boolean save() {
boolean forceSaveReminders = false;
// If we are creating a new event, then make sure we wait until the
// query to fetch the list of calendars has finished.
if (mEventCursor == null) {
if (!mCalendarsQueryComplete) {
// Wait for the calendars query to finish.
if (mLoadingCalendarsDialog == null) {
// Create the progress dialog
mLoadingCalendarsDialog = ProgressDialog.show(this,
getText(R.string.loading_calendars_title),
getText(R.string.loading_calendars_message),
true, true, this);
mSaveAfterQueryComplete = true;
}
return false;
}
// Avoid creating a new event if the calendars cursor is empty or we clicked through
// too quickly and no calendar was selected (blame the monkey)
if (mCalendarsCursor == null || mCalendarsCursor.getCount() == 0 ||
mCalendarsSpinner.getSelectedItemId() == AdapterView.INVALID_ROW_ID) {
Log.w("Cal", "The calendars table does not contain any calendars"
+ " or no calendar was selected."
+ " New event was not created.");
return true;
}
Toast.makeText(this, R.string.creating_event, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.saving_event, Toast.LENGTH_SHORT).show();
}
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int eventIdIndex = -1;
ContentValues values = getContentValuesFromUi();
Uri uri = mUri;
// save the timezone as a recent one
if (!mAllDayCheckBox.isChecked()) {
mTimezoneAdapter.saveRecentTimezone(mTimezone);
}
// Update the "hasAlarm" field for the event
ArrayList<Integer> reminderMinutes = reminderItemsToMinutes(mReminderItems,
mReminderValues);
int len = reminderMinutes.size();
values.put(Events.HAS_ALARM, (len > 0) ? 1 : 0);
// For recurring events, we must make sure that we use duration rather
// than dtend.
if (uri == null) {
// Add hasAttendeeData for a new event
values.put(Events.HAS_ATTENDEE_DATA, 1);
// Create new event with new contents
addRecurrenceRule(values);
if (!TextUtils.isEmpty(mRrule)) {
values.remove(Events.DTEND);
}
eventIdIndex = ops.size();
Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
ops.add(b.build());
forceSaveReminders = true;
} else if (TextUtils.isEmpty(mRrule)) {
// Modify contents of a non-repeating event
addRecurrenceRule(values);
checkTimeDependentFields(values);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
} else if (TextUtils.isEmpty(mInitialValues.getAsString(Events.RRULE))) {
// This event was changed from a non-repeating event to a
// repeating event.
addRecurrenceRule(values);
values.remove(Events.DTEND);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
} else if (mModification == MODIFY_SELECTED) {
// Modify contents of the current instance of repeating event
// Create a recurrence exception
long begin = mInitialValues.getAsLong(EVENT_BEGIN_TIME);
values.put(Events.ORIGINAL_EVENT, mEventCursor.getString(EVENT_INDEX_SYNC_ID));
values.put(Events.ORIGINAL_INSTANCE_TIME, begin);
boolean allDay = mInitialValues.getAsInteger(Events.ALL_DAY) != 0;
values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0);
eventIdIndex = ops.size();
Builder b = ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values);
ops.add(b.build());
forceSaveReminders = true;
} else if (mModification == MODIFY_ALL_FOLLOWING) {
// Modify this instance and all future instances of repeating event
addRecurrenceRule(values);
if (TextUtils.isEmpty(mRrule)) {
// We've changed a recurring event to a non-recurring event.
// If the event we are editing is the first in the series,
// then delete the whole series. Otherwise, update the series
// to end at the new start time.
if (isFirstEventInSeries()) {
ops.add(ContentProviderOperation.newDelete(uri).build());
} else {
// Update the current repeating event to end at the new
// start time.
updatePastEvents(ops, uri);
}
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
.build());
} else {
if (isFirstEventInSeries()) {
checkTimeDependentFields(values);
values.remove(Events.DTEND);
Builder b = ContentProviderOperation.newUpdate(uri).withValues(values);
ops.add(b.build());
} else {
// Update the current repeating event to end at the new
// start time.
updatePastEvents(ops, uri);
// Create a new event with the user-modified fields
values.remove(Events.DTEND);
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(
values).build());
}
}
forceSaveReminders = true;
} else if (mModification == MODIFY_ALL) {
// Modify all instances of repeating event
addRecurrenceRule(values);
if (TextUtils.isEmpty(mRrule)) {
// We've changed a recurring event to a non-recurring event.
// Delete the whole series and replace it with a new
// non-recurring event.
ops.add(ContentProviderOperation.newDelete(uri).build());
eventIdIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(Events.CONTENT_URI).withValues(values)
.build());
forceSaveReminders = true;
} else {
checkTimeDependentFields(values);
values.remove(Events.DTEND);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
}
}
// New Event or New Exception to an existing event
boolean newEvent = (eventIdIndex != -1);
if (newEvent) {
saveRemindersWithBackRef(ops, eventIdIndex, reminderMinutes, mOriginalMinutes,
forceSaveReminders);
} else if (uri != null) {
long eventId = ContentUris.parseId(uri);
saveReminders(ops, eventId, reminderMinutes, mOriginalMinutes,
forceSaveReminders);
}
Builder b;
// New event/instance - Set Organizer's response as yes
if (mHasAttendeeData && newEvent) {
values.clear();
int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition();
// Save the default calendar for new events
if (mCalendarsCursor != null) {
if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
String defaultCalendar = mCalendarsCursor
.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
Utils.setSharedPreference(this,
CalendarPreferenceActivity.KEY_DEFAULT_CALENDAR, defaultCalendar);
}
}
String ownerEmail = mOwnerAccount;
// Just in case mOwnerAccount is null, try to get owner from mCalendarsCursor
if (ownerEmail == null && mCalendarsCursor != null &&
mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
ownerEmail = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT);
}
if (ownerEmail != null) {
values.put(Attendees.ATTENDEE_EMAIL, ownerEmail);
values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
int initialStatus = Attendees.ATTENDEE_STATUS_ACCEPTED;
// Don't accept for secondary calendars
if (ownerEmail.endsWith("calendar.google.com")) {
initialStatus = Attendees.ATTENDEE_STATUS_NONE;
}
values.put(Attendees.ATTENDEE_STATUS, initialStatus);
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
b.withValueBackReference(Reminders.EVENT_ID, eventIdIndex);
ops.add(b.build());
}
}
// TODO: is this the right test? this currently checks if this is
// a new event or an existing event. or is this a paranoia check?
if (mHasAttendeeData && (newEvent || uri != null)) {
Editable attendeesText = mAttendeesList.getText();
// Hit the content provider only if this is a new event or the user has changed it
if (newEvent || !mOriginalAttendees.equals(attendeesText.toString())) {
// figure out which attendees need to be added and which ones
// need to be deleted. use a linked hash set, so we maintain
// order (but also remove duplicates).
LinkedHashSet<Rfc822Token> newAttendees = getAddressesFromList(mAttendeesList);
// the eventId is only used if eventIdIndex is -1.
// TODO: clean up this code.
long eventId = uri != null ? ContentUris.parseId(uri) : -1;
// only compute deltas if this is an existing event.
// new events (being inserted into the Events table) won't
// have any existing attendees.
if (!newEvent) {
HashSet<Rfc822Token> removedAttendees = new HashSet<Rfc822Token>();
HashSet<Rfc822Token> originalAttendees = new HashSet<Rfc822Token>();
Rfc822Tokenizer.tokenize(mOriginalAttendees, originalAttendees);
for (Rfc822Token originalAttendee : originalAttendees) {
if (newAttendees.contains(originalAttendee)) {
// existing attendee. remove from new attendees set.
newAttendees.remove(originalAttendee);
} else {
// no longer in attendees. mark as removed.
removedAttendees.add(originalAttendee);
}
}
// delete removed attendees
b = ContentProviderOperation.newDelete(Attendees.CONTENT_URI);
String[] args = new String[removedAttendees.size() + 1];
args[0] = Long.toString(eventId);
int i = 1;
StringBuilder deleteWhere = new StringBuilder(ATTENDEES_DELETE_PREFIX);
for (Rfc822Token removedAttendee : removedAttendees) {
if (i > 1) {
deleteWhere.append(",");
}
deleteWhere.append("?");
args[i++] = removedAttendee.getAddress();
}
deleteWhere.append(")");
b.withSelection(deleteWhere.toString(), args);
ops.add(b.build());
}
if (newAttendees.size() > 0) {
// Insert the new attendees
for (Rfc822Token attendee : newAttendees) {
values.clear();
values.put(Attendees.ATTENDEE_NAME, attendee.getName());
values.put(Attendees.ATTENDEE_EMAIL, attendee.getAddress());
values.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
values.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE);
if (newEvent) {
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
b.withValueBackReference(Attendees.EVENT_ID, eventIdIndex);
} else {
values.put(Attendees.EVENT_ID, eventId);
b = ContentProviderOperation.newInsert(Attendees.CONTENT_URI)
.withValues(values);
}
ops.add(b.build());
}
}
}
}
try {
// TODO Move this to background thread
ContentProviderResult[] results =
getContentResolver().applyBatch(android.provider.Calendar.AUTHORITY, ops);
if (DEBUG) {
for (int i = 0; i < results.length; i++) {
Log.v(TAG, "results = " + results[i].toString());
}
}
} catch (RemoteException e) {
Log.w(TAG, "Ignoring unexpected remote exception", e);
} catch (OperationApplicationException e) {
Log.w(TAG, "Ignoring unexpected exception", e);
}
return true;
}
|
diff --git a/main/src/main/java/com/bloatit/framework/xcgiserver/LazyLoaders.java b/main/src/main/java/com/bloatit/framework/xcgiserver/LazyLoaders.java
index e02ce3fb2..aed0453b1 100644
--- a/main/src/main/java/com/bloatit/framework/xcgiserver/LazyLoaders.java
+++ b/main/src/main/java/com/bloatit/framework/xcgiserver/LazyLoaders.java
@@ -1,144 +1,144 @@
/*
* Copyright (C) 2011 Linkeos.
*
* This file is part of BloatIt.
*
* BloatIt is free software: you can redistribute it and/or modify it under the
* terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* BloatIt is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BloatIt. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bloatit.framework.xcgiserver;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.bloatit.common.Log;
class LazyLoaders {
public abstract static class LazyComponent<T> {
private T value = null;
private final String name;
private LazyComponent(final String name) {
this.name = name;
}
public final T getValue(final Map<String, String> env) {
if (value != null) {
return value;
}
final String stringValue = env.get(name);
if (stringValue != null) {
value = convert(stringValue);
return value;
}
return getDefault();
}
public abstract T convert(String stringValue);
public abstract T getDefault();
}
public static final class LazyMap extends LazyComponent<Map<String, String>> {
public LazyMap(final String name) {
super(name);
}
@Override
public Map<String, String> convert(final String stringValue) {
final HashMap<String, String> map = new HashMap<String, String>();
final String[] namedValues = stringValue.split(";");
for (final String namedValue : namedValues) {
final String[] aValue = namedValue.split("=");
- if (aValue.length == 2) {
+ if (aValue.length >= 2) {
map.put(aValue[0].trim(), aValue[1].trim());
} else {
Log.framework().warn("Malformed cookie value: " + namedValue);
}
}
return map;
}
@SuppressWarnings("unchecked")
@Override
public Map<String, String> getDefault() {
return Collections.EMPTY_MAP;
}
}
public static final class LazyInt extends LazyComponent<Integer> {
public LazyInt(final String name) {
super(name);
}
@Override
public Integer convert(final String stringValue) {
try {
return Integer.valueOf(stringValue);
} catch (final Exception e) {
Log.framework().error("Malformed integer: " + stringValue);
}
return null;
}
@Override
public Integer getDefault() {
return 0;
}
}
public static final class LazyStringList extends LazyComponent<List<String>> {
private final String separator;
public LazyStringList(final String name, final String separator) {
super(name);
this.separator = separator;
}
@Override
public List<String> convert(final String stringValue) {
return Arrays.asList(stringValue.split(separator));
}
@SuppressWarnings("unchecked")
@Override
public List<String> getDefault() {
return Collections.EMPTY_LIST;
}
}
public static final class LazyString extends LazyComponent<String> {
public LazyString(final String name) {
super(name);
}
@Override
public String convert(final String stringValue) {
return stringValue;
}
@Override
public String getDefault() {
return "";
}
}
}
| true | true | public Map<String, String> convert(final String stringValue) {
final HashMap<String, String> map = new HashMap<String, String>();
final String[] namedValues = stringValue.split(";");
for (final String namedValue : namedValues) {
final String[] aValue = namedValue.split("=");
if (aValue.length == 2) {
map.put(aValue[0].trim(), aValue[1].trim());
} else {
Log.framework().warn("Malformed cookie value: " + namedValue);
}
}
return map;
}
| public Map<String, String> convert(final String stringValue) {
final HashMap<String, String> map = new HashMap<String, String>();
final String[] namedValues = stringValue.split(";");
for (final String namedValue : namedValues) {
final String[] aValue = namedValue.split("=");
if (aValue.length >= 2) {
map.put(aValue[0].trim(), aValue[1].trim());
} else {
Log.framework().warn("Malformed cookie value: " + namedValue);
}
}
return map;
}
|
diff --git a/src/main/battlecode/world/GameWorld.java b/src/main/battlecode/world/GameWorld.java
index 1bcdfe36..b3e49ff6 100644
--- a/src/main/battlecode/world/GameWorld.java
+++ b/src/main/battlecode/world/GameWorld.java
@@ -1,790 +1,791 @@
package battlecode.world;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.List;
import java.util.Set;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.GameActionExceptionType;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.Message;
import battlecode.common.RobotLevel;
import battlecode.common.RobotType;
import battlecode.common.Team;
import battlecode.common.TerrainTile;
import battlecode.engine.ErrorReporter;
import battlecode.engine.GenericWorld;
import battlecode.engine.instrumenter.RobotDeathException;
import battlecode.engine.instrumenter.RobotMonitor;
import battlecode.engine.signal.*;
import battlecode.serial.DominationFactor;
import battlecode.serial.GameStats;
import battlecode.serial.RoundStats;
import battlecode.world.signal.*;
/**
* The primary implementation of the GameWorld interface for
* containing and modifying the game map and the objects on it.
*/
/*
oODO:
- comments
- move methods from RCimpl to here, add signalhandler methods
*/
public class GameWorld extends BaseWorld<InternalObject> implements GenericWorld {
private final GameMap gameMap;
private RoundStats roundStats = null; // stats for each round; new object is created for each round
private final GameStats gameStats = new GameStats(); // end-of-game stats
private double[] teamRoundResources = new double[2];
private double[] lastRoundResources = new double[2];
private final Map<MapLocation3D, InternalObject> gameObjectsByLoc = new HashMap<MapLocation3D, InternalObject>();
private double[] teamResources = new double[2];
private Map<MapLocation, ArrayList<MapLocation>> powerNodeGraph = new HashMap<MapLocation, ArrayList<MapLocation>>();
private List<InternalPowerNode> powerNodes = new ArrayList<InternalPowerNode>();
private Map<Team,InternalPowerNode> baseNodes = new EnumMap<Team,InternalPowerNode>(Team.class);
private Map<Team,List<InternalPowerNode>> connectedNodesByTeam = new EnumMap<Team,List<InternalPowerNode>>(Team.class);
private Map<Team,List<InternalPowerNode>> adjacentNodesByTeam = new EnumMap<Team,List<InternalPowerNode>>(Team.class);
// robots to remove from the game at end of turn
private List<InternalRobot> deadRobots = new ArrayList<InternalRobot>();
private Map<Team,List<InternalRobot>> archons;
@SuppressWarnings("unchecked")
public GameWorld(GameMap gm, String teamA, String teamB, long[][] oldArchonMemory) {
super(gm.getSeed(), teamA, teamB, oldArchonMemory);
gameMap = gm;
archons = new EnumMap<Team,List<InternalRobot>>(Team.class);
archons.put(Team.A,new ArrayList<InternalRobot>());
archons.put(Team.B,new ArrayList<InternalRobot>());
connectedNodesByTeam.put(Team.A,new ArrayList<InternalPowerNode>());
connectedNodesByTeam.put(Team.B,new ArrayList<InternalPowerNode>());
adjacentNodesByTeam.put(Team.A,new ArrayList<InternalPowerNode>());
adjacentNodesByTeam.put(Team.B,new ArrayList<InternalPowerNode>());
}
public int getMapSeed() {
return gameMap.getSeed();
}
public GameMap getGameMap() {
return gameMap;
}
public void processBeginningOfRound() {
currentRound++;
wasBreakpointHit = false;
// process all gameobjects
InternalObject[] gameObjects = new InternalObject[gameObjectsByID.size()];
gameObjects = gameObjectsByID.values().toArray(gameObjects);
for (int i = 0; i < gameObjects.length; i++) {
gameObjects[i].processBeginningOfRound();
}
}
public InternalPowerNode towerToNode(InternalRobot tower) {
return getPowerNode(tower.getLocation());
}
public InternalRobot nodeToTower(InternalPowerNode node) {
return getTower(node.getLocation());
}
public void processEndOfRound() {
// process all gameobjects
InternalObject[] gameObjects = new InternalObject[gameObjectsByID.size()];
gameObjects = gameObjectsByID.values().toArray(gameObjects);
for (int i = 0; i < gameObjects.length; i++) {
gameObjects[i].processEndOfRound();
}
if(timeLimitReached()&&winner==null) {
// copy the node lists, because the damage could kill a node and disconnect the graph
List<InternalPowerNode> teamANodes = new ArrayList<InternalPowerNode>(connectedNodesByTeam.get(Team.A));
List<InternalPowerNode> teamBNodes = new ArrayList<InternalPowerNode>(connectedNodesByTeam.get(Team.B));
InternalRobot tower;
for(InternalPowerNode n : teamANodes) {
tower = nodeToTower(n);
if(tower!=null)
tower.takeDamage(GameConstants.TIME_LIMIT_DAMAGE/teamANodes.size());
}
for(InternalPowerNode n : teamBNodes) {
tower = nodeToTower(n);
if(tower!=null)
tower.takeDamage(GameConstants.TIME_LIMIT_DAMAGE/teamBNodes.size());
}
+ removeDead();
// We have tiebreakers in case both power cores die to end-of-round damage in the same round.
// (If two power cores are killed by robots in the same round, then the team whose core died
// first loses.)
if(nodeToTower(baseNodes.get(Team.A))==null&&nodeToTower(baseNodes.get(Team.B))==null) {
running=false;
int diff=0;
for(InternalPowerNode p : powerNodes) {
if(p.getControllingTeam()==Team.A)
diff++;
else if(p.getControllingTeam()==Team.B)
diff--;
}
if(!(setWinnerIfNonzero(diff,DominationFactor.BARELY_BEAT)||
setWinnerIfNonzero(archons.get(Team.A).size()-archons.get(Team.B).size(),DominationFactor.BARELY_BEAT)))
{
if(teamAName.compareTo(teamBName)<=0)
setWinner(Team.A,DominationFactor.WON_BY_DUBIOUS_REASONS);
else
setWinner(Team.B,DominationFactor.WON_BY_DUBIOUS_REASONS);
}
}
}
long aPoints = Math.round(teamRoundResources[Team.A.ordinal()] * 100), bPoints = Math.round(teamRoundResources[Team.B.ordinal()] * 100);
roundStats = new RoundStats(teamResources[0] * 100, teamResources[1] * 100, teamRoundResources[0] * 100, teamRoundResources[1] * 100);
lastRoundResources = teamRoundResources;
teamRoundResources = new double[2];
}
public boolean setWinnerIfNonzero(int n, DominationFactor d) {
if(n>0)
setWinner(Team.A,d);
else if(n<0)
setWinner(Team.B,d);
return n!=0;
}
public DominationFactor getDominationFactor(Team winner) {
if(archons.get(winner).size()>=GameConstants.NUMBER_OF_ARCHONS)
return DominationFactor.DESTROYED;
else if(!timeLimitReached())
return DominationFactor.OWNED;
else
return DominationFactor.BEAT;
}
public void setWinner(Team t, DominationFactor d) {
winner = t;
gameStats.setDominationFactor(d);
running = false;
for (InternalObject o : gameObjectsByID.values()) {
if (o instanceof InternalRobot)
RobotMonitor.killRobot(o.getID());
}
}
public InternalPowerNode getPowerCore(Team t) {
return baseNodes.get(t);
}
public interface Graph {
public List<MapLocation> neighbors(MapLocation loc);
public MapLocation baseNode(Team t);
public Team team(MapLocation loc);
public void setConnected(MapLocation loc, Team t);
}
private Graph graphImpl = new Graph () {
public List<MapLocation> neighbors(MapLocation loc) {
return powerNodeGraph.get(loc);
}
public MapLocation baseNode(Team t) {
return baseNodes.get(t).getLocation();
}
public Team team(MapLocation loc) {
InternalRobot tower = getTower(loc);
if(tower==null)
return Team.NEUTRAL;
else
return tower.getTeam();
}
public void setConnected(MapLocation loc, Team t) {
InternalPowerNode p = getPowerNode(loc);
p.setConnected(t,true);
if(team(loc)==t)
connectedNodesByTeam.get(t).add(p);
else
adjacentNodesByTeam.get(t).add(p);
}
};
public static class Connections {
private Set<MapLocation> visited = new HashSet<MapLocation>();
private Deque<MapLocation> queue = new ArrayDeque<MapLocation>();
private Team team;
private Graph graph;
public Connections(Graph g, Team t) {
team = t;
graph = g;
add(g.baseNode(t));
}
public void add(MapLocation n) {
if(!visited.contains(n)) {
visited.add(n);
graph.setConnected(n,team);
if(graph.team(n)==team)
queue.push(n);
}
}
public void findAll() {
while(!queue.isEmpty()) {
MapLocation n = queue.pop();
for(MapLocation l : graph.neighbors(n)) {
add(l);
}
}
}
}
public void recomputeConnections() {
for(InternalPowerNode n: powerNodes) {
n.setConnected(Team.A,false);
n.setConnected(Team.B,false);
}
connectedNodesByTeam.get(Team.A).clear();
connectedNodesByTeam.get(Team.B).clear();
adjacentNodesByTeam.get(Team.A).clear();
adjacentNodesByTeam.get(Team.B).clear();
new Connections(graphImpl,Team.A).findAll();
new Connections(graphImpl,Team.B).findAll();
}
public int getConnectedNodeCount(Team t) {
return connectedNodesByTeam.get(t).size();
}
public boolean timeLimitReached() {
return currentRound >= gameMap.getMaxRounds()-1;
}
public double[] getLastRoundResources() {
return lastRoundResources;
}
public InternalObject getObject(MapLocation loc, RobotLevel level) {
return gameObjectsByLoc.get(new MapLocation3D(loc, level));
}
public <T extends InternalObject> T getObjectOfType(MapLocation loc, RobotLevel level, Class<T> cl) {
InternalObject o = getObject(loc, level);
if (cl.isInstance(o))
return cl.cast(o);
else
return null;
}
public InternalRobot getRobot(MapLocation loc, RobotLevel level) {
InternalObject obj = getObject(loc, level);
if (obj instanceof InternalRobot)
return (InternalRobot) obj;
else
return null;
}
public InternalPowerNode getPowerNode(MapLocation loc) {
return (InternalPowerNode)getObject(loc,RobotLevel.POWER_NODE);
}
public InternalRobot getTower(MapLocation loc) {
InternalRobot r = getRobot(loc,RobotType.TOWER.level);
if(r==null||r.type!=RobotType.TOWER)
return null;
else
return r;
}
// should only be called by the InternalObject constructor
public void notifyAddingNewObject(InternalObject o) {
if (gameObjectsByID.containsKey(o.getID()))
return;
gameObjectsByID.put(o.getID(), o);
if (o.getLocation() != null) {
gameObjectsByLoc.put(new MapLocation3D(o.getLocation(), o.getRobotLevel()), o);
}
if (o instanceof InternalPowerNode) {
addPowerNode((InternalPowerNode)o);
}
}
public void addPowerNode(InternalPowerNode p) {
powerNodes.add(p);
powerNodeGraph.put(p.getLocation(),new ArrayList<MapLocation>());
}
public void addArchon(InternalRobot r) {
archons.get(r.getTeam()).add(r);
}
public Collection<InternalObject> allObjects() {
return gameObjectsByID.values();
}
// TODO: move stuff to here
// should only be called by InternalObject.setLocation
public void notifyMovingObject(InternalObject o, MapLocation oldLoc, MapLocation newLoc) {
if (oldLoc != null) {
MapLocation3D oldLoc3D = new MapLocation3D(oldLoc, o.getRobotLevel());
if (gameObjectsByLoc.get(oldLoc3D) != o) {
ErrorReporter.report("Internal Error: invalid oldLoc in notifyMovingObject");
return;
}
gameObjectsByLoc.remove(oldLoc3D);
}
if (newLoc != null) {
gameObjectsByLoc.put(new MapLocation3D(newLoc, o.getRobotLevel()), o);
}
}
public void removeObject(InternalObject o) {
if (o.getLocation() != null) {
MapLocation3D loc3D = new MapLocation3D(o.getLocation(), o.getRobotLevel());
if (gameObjectsByLoc.get(loc3D) == o)
gameObjectsByLoc.remove(loc3D);
else
System.out.println("Couldn't remove " + o + " from the game");
} else
System.out.println("Couldn't remove " + o + " from the game");
if (gameObjectsByID.get(o.getID()) == o)
gameObjectsByID.remove(o.getID());
if (o instanceof InternalRobot) {
InternalRobot r = (InternalRobot) o;
r.freeMemory();
}
}
public boolean exists(InternalObject o) {
return gameObjectsByID.containsKey(o.getID());
}
/**
*@return the TerrainType at a given MapLocation <tt>loc<tt>
*/
public TerrainTile getMapTerrain(MapLocation loc) {
return gameMap.getTerrainTile(loc);
}
// TODO: optimize this too
public int getUnitCount(Team team) {
int result = 0;
for (InternalObject o : gameObjectsByID.values()) {
if (!(o instanceof InternalRobot))
continue;
if (((InternalRobot) o).getTeam() == team)
result++;
}
return result;
}
public MapLocation [] getArchons(Team team) {
return Lists.transform(archons.get(team),Util.objectLocation).toArray(new MapLocation [0]);
}
public double getPoints(Team team) {
return teamRoundResources[team.ordinal()];
}
public boolean canMove(RobotLevel level, MapLocation loc) {
return gameMap.getTerrainTile(loc).isTraversableAtHeight(level) && (gameObjectsByLoc.get(new MapLocation3D(loc, level)) == null);
}
public void splashDamageGround(MapLocation loc, double damage, double falloutFraction) {
//TODO: optimize this
InternalRobot[] robots = getAllRobotsWithinRadiusDonutSq(loc, 2, -1);
for (InternalRobot r : robots) {
if (r.getRobotLevel() == RobotLevel.ON_GROUND) {
if (r.getLocation().equals(loc))
r.changeEnergonLevelFromAttack(-damage);
else
r.changeEnergonLevelFromAttack(-damage * falloutFraction);
}
}
}
public InternalObject[] getAllGameObjects() {
return gameObjectsByID.values().toArray(new InternalObject[gameObjectsByID.size()]);
}
public InternalRobot getRobotByID(int id) {
return (InternalRobot) getObjectByID(id);
}
public Signal[] getAllSignals(boolean includeBytecodesUsedSignal) {
ArrayList<InternalRobot> energonChangedRobots = new ArrayList<InternalRobot>();
ArrayList<InternalRobot> fluxChangedRobots = new ArrayList<InternalRobot>();
ArrayList<InternalRobot> allRobots = null;
if (includeBytecodesUsedSignal)
allRobots = new ArrayList<InternalRobot>();
for (InternalObject obj : gameObjectsByID.values()) {
if (!(obj instanceof InternalRobot))
continue;
InternalRobot r = (InternalRobot) obj;
if (includeBytecodesUsedSignal)
allRobots.add(r);
if (r.clearEnergonChanged()) {
energonChangedRobots.add(r);
}
if (r.clearFluxChanged()) {
fluxChangedRobots.add(r);
}
}
signals.add(new EnergonChangeSignal(energonChangedRobots.toArray(new InternalRobot[]{})));
signals.add(new FluxChangeSignal(fluxChangedRobots.toArray(new InternalRobot[]{})));
if (includeBytecodesUsedSignal)
signals.add(new BytecodesUsedSignal(allRobots.toArray(new InternalRobot[]{})));
return signals.toArray(new Signal[signals.size()]);
}
public RoundStats getRoundStats() {
return roundStats;
}
public GameStats getGameStats() {
return gameStats;
}
public void beginningOfExecution(int robotID) {
InternalRobot r = (InternalRobot) getObjectByID(robotID);
if (r != null)
r.processBeginningOfTurn();
}
public void endOfExecution(int robotID) {
InternalRobot r = (InternalRobot) getObjectByID(robotID);
// if the robot is dead, it won't be in the map any more
if (r != null) {
r.setBytecodesUsed(RobotMonitor.getBytecodesUsed());
r.processEndOfTurn();
}
}
public void resetStatic() {
}
public void createNodeLink(MapLocation id1, MapLocation id2)
{
createNodeLink(id1, id2, true);
}
public void createNodeLink(MapLocation id1, MapLocation id2, boolean bidir)
{
this.powerNodeGraph.get(id1).add(id2);
if(bidir)
this.powerNodeGraph.get(id2).add(id1);
}
public ArrayList<MapLocation> getAdjacentNodes(MapLocation loc) {
return powerNodeGraph.get(loc);
}
public Iterable<InternalPowerNode> getPowerNodesByTeam(final Team t) {
Predicate<InternalPowerNode> pred = new Predicate<InternalPowerNode>() {
public boolean apply(InternalPowerNode p) {
return p.getControllingTeam()==t;
}
};
return Iterables.filter(powerNodes,pred);
}
public List<InternalPowerNode> getCapturableNodes(Team t) {
return adjacentNodesByTeam.get(t);
}
public void notifyDied(InternalRobot r) {
deadRobots.add(r);
}
public void removeDead() {
boolean current = false;
for(InternalRobot r : deadRobots) {
if(r.getID() == RobotMonitor.getCurrentRobotID())
current = true;
visitSignal(new DeathSignal(r));
}
if(current)
throw new RobotDeathException();
}
// ******************************
// SIGNAL HANDLER METHODS
// ******************************
SignalHandler signalHandler = new AutoSignalHandler(this);
public void visitSignal(Signal s) {
signalHandler.visitSignal(s);
}
public void visitAttackSignal(AttackSignal s) {
InternalRobot attacker = (InternalRobot) getObjectByID(s.getRobotID());
if(attacker.type==RobotType.SCORCHER) {
for(InternalObject o : gameObjectsByID.values()) {
if(attacker.type.canAttack(o.getRobotLevel())&&canAttackSquare(attacker,o.getLocation())&&(o instanceof InternalRobot)) {
InternalRobot target = (InternalRobot)o;
target.takeDamage(attacker.type.attackPower,attacker);
}
}
}
else {
MapLocation targetLoc = s.getTargetLoc();
RobotLevel level = s.getTargetHeight();
InternalRobot target = getRobot(targetLoc, level);
if (target != null) {
switch(attacker.type) {
case SCOUT:
double drain = Math.min(attacker.type.attackPower,target.getFlux());
target.adjustFlux(-drain);
attacker.adjustFlux(drain);
break;
case DISRUPTER:
target.takeDamage(attacker.type.attackPower,attacker);
target.delayAttack(GameConstants.DISRUPTER_DELAY);
break;
default:
target.takeDamage(attacker.type.attackPower,attacker);
}
}
}
addSignal(s);
removeDead();
}
public void visitBroadcastSignal(BroadcastSignal s) {
InternalObject sender = gameObjectsByID.get(s.robotID);
Collection<InternalObject> objs = gameObjectsByLoc.values();
Predicate<InternalObject> pred = Util.robotWithinDistance(sender.getLocation(), s.range);
for (InternalObject o : Iterables.filter(objs, pred)) {
InternalRobot r = (InternalRobot) o;
if (r != sender)
r.enqueueIncomingMessage((Message) s.message.clone());
}
s.message = null;
addSignal(s);
}
public void visitDeathSignal(DeathSignal s) {
if (!running) {
// All robots emit death signals after the game
// ends. We still want the client to draw
// the robots.
return;
}
int ID = s.getObjectID();
InternalObject obj = getObjectByID(ID);
if (obj != null) {
removeObject(obj);
addSignal(s);
}
if (obj instanceof InternalRobot) {
InternalRobot r = (InternalRobot) obj;
RobotMonitor.killRobot(ID);
if (r.hasBeenAttacked()) {
gameStats.setUnitKilled(r.getTeam(), currentRound);
}
if(r.type == RobotType.TOWER) {
recomputeConnections();
if(towerToNode(r).isPowerCore())
setWinner(r.getTeam().opponent(),getDominationFactor(r.getTeam().opponent()));
}
}
}
public void visitEnergonChangeSignal(EnergonChangeSignal s) {
int[] robotIDs = s.getRobotIDs();
double[] energon = s.getEnergon();
for (int i = 0; i < robotIDs.length; i++) {
InternalRobot r = (InternalRobot) getObjectByID(robotIDs[i]);
System.out.println("el " + energon[i] + " " + r.getEnergonLevel());
r.changeEnergonLevel(energon[i] - r.getEnergonLevel());
}
}
public void visitIndicatorStringSignal(IndicatorStringSignal s) {
addSignal(s);
}
public void visitMatchObservationSignal(MatchObservationSignal s) {
addSignal(s);
}
public void visitControlBitsSignal(ControlBitsSignal s) {
InternalRobot r = (InternalRobot) getObjectByID(s.getRobotID());
r.setControlBits(s.getControlBits());
addSignal(s);
}
public void visitMovementOverrideSignal(MovementOverrideSignal s) {
InternalRobot r = (InternalRobot) getObjectByID(s.getRobotID());
if (!canMove(r.getRobotLevel(), s.getNewLoc()))
throw new RuntimeException("GameActionException in MovementOverrideSignal",new GameActionException(GameActionExceptionType.CANT_MOVE_THERE, "Cannot move to location: " + s.getNewLoc()));
r.setLocation(s.getNewLoc());
addSignal(s);
}
public void visitMovementSignal(MovementSignal s) {
InternalRobot r = (InternalRobot) getObjectByID(s.getRobotID());
MapLocation loc = s.getNewLoc();//(s.isMovingForward() ? r.getLocation().add(r.getDirection()) : r.getLocation().add(r.getDirection().opposite()));
r.setLocation(loc);
addSignal(s);
}
public void visitSetDirectionSignal(SetDirectionSignal s) {
InternalRobot r = (InternalRobot) getObjectByID(s.getRobotID());
Direction dir = s.getDirection();
r.setDirection(dir);
addSignal(s);
}
public void setPowerCore(InternalPowerNode p, Team t) {
baseNodes.put(t,p);
}
@SuppressWarnings("unchecked")
public void visitSpawnSignal(SpawnSignal s) {
InternalRobot parent;
int parentID = s.getParentID();
MapLocation loc;
if (parentID == 0) {
parent = null;
loc = s.getLoc();
} else {
parent = (InternalRobot) getObjectByID(parentID);
loc = s.getLoc();
}
//note: this also adds the signal
InternalRobot robot = GameWorldFactory.createPlayer(this, s.getType(), loc, s.getTeam(), parent);
if(s.getType()==RobotType.TOWER)
recomputeConnections();
}
// *****************************
// UTILITY METHODS
// *****************************
private static MapLocation origin = new MapLocation(0, 0);
protected static boolean canAttackSquare(InternalRobot ir, MapLocation loc) {
MapLocation myLoc = ir.getLocation();
int d = myLoc.distanceSquaredTo(loc);
return d<=ir.type.attackRadiusMaxSquared && d>= ir.type.attackRadiusMinSquared
&& inAngleRange(myLoc,ir.getDirection(),loc,ir.type.attackCosHalfTheta);
}
protected static boolean inAngleRange(MapLocation sensor, Direction dir, MapLocation target, double cosHalfTheta) {
MapLocation dirVec = origin.add(dir);
double dx = target.x - sensor.x;
double dy = target.y - sensor.y;
int a = dirVec.x;
int b = dirVec.y;
double dotProduct = a * dx + b * dy;
if (dotProduct < 0) {
if (cosHalfTheta > 0)
return false;
} else if (cosHalfTheta < 0)
return true;
double rhs = cosHalfTheta * cosHalfTheta * (dx * dx + dy * dy) * (a * a + b * b);
if (dotProduct < 0)
return (dotProduct * dotProduct <= rhs + 0.00001d);
else
return (dotProduct * dotProduct >= rhs - 0.00001d);
}
// TODO: make a faster implementation of this
protected InternalRobot[] getAllRobotsWithinRadiusDonutSq(MapLocation center, int outerRadiusSquared, int innerRadiusSquared) {
ArrayList<InternalRobot> robots = new ArrayList<InternalRobot>();
for (InternalObject o : gameObjectsByID.values()) {
if (!(o instanceof InternalRobot))
continue;
if (o.getLocation() != null && o.getLocation().distanceSquaredTo(center) <= outerRadiusSquared
&& o.getLocation().distanceSquaredTo(center) > innerRadiusSquared)
robots.add((InternalRobot) o);
}
return robots.toArray(new InternalRobot[robots.size()]);
}
// TODO: make a faster implementation of this
public MapLocation[] getAllMapLocationsWithinRadiusSq(MapLocation center, int radiusSquared) {
ArrayList<MapLocation> locations = new ArrayList<MapLocation>();
int radius = (int) Math.sqrt(radiusSquared);
int minXPos = center.x - radius;
int maxXPos = center.x + radius;
int minYPos = center.y - radius;
int maxYPos = center.y + radius;
for (int x = minXPos; x <= maxXPos; x++) {
for (int y = minYPos; y <= maxYPos; y++) {
MapLocation loc = new MapLocation(x, y);
TerrainTile tile = gameMap.getTerrainTile(loc);
if (!tile.equals(TerrainTile.OFF_MAP) && loc.distanceSquaredTo(center) < radiusSquared)
locations.add(loc);
}
}
return locations.toArray(new MapLocation[locations.size()]);
}
public double resources(Team t) {
return teamResources[t.ordinal()];
}
protected boolean spendResources(Team t, double amount) {
if (teamResources[t.ordinal()] >= amount) {
teamResources[t.ordinal()] -= amount;
return true;
} else
return false;
}
protected void adjustResources(Team t, double amount) {
teamResources[t.ordinal()] += amount;
}
}
| true | true | public void processEndOfRound() {
// process all gameobjects
InternalObject[] gameObjects = new InternalObject[gameObjectsByID.size()];
gameObjects = gameObjectsByID.values().toArray(gameObjects);
for (int i = 0; i < gameObjects.length; i++) {
gameObjects[i].processEndOfRound();
}
if(timeLimitReached()&&winner==null) {
// copy the node lists, because the damage could kill a node and disconnect the graph
List<InternalPowerNode> teamANodes = new ArrayList<InternalPowerNode>(connectedNodesByTeam.get(Team.A));
List<InternalPowerNode> teamBNodes = new ArrayList<InternalPowerNode>(connectedNodesByTeam.get(Team.B));
InternalRobot tower;
for(InternalPowerNode n : teamANodes) {
tower = nodeToTower(n);
if(tower!=null)
tower.takeDamage(GameConstants.TIME_LIMIT_DAMAGE/teamANodes.size());
}
for(InternalPowerNode n : teamBNodes) {
tower = nodeToTower(n);
if(tower!=null)
tower.takeDamage(GameConstants.TIME_LIMIT_DAMAGE/teamBNodes.size());
}
// We have tiebreakers in case both power cores die to end-of-round damage in the same round.
// (If two power cores are killed by robots in the same round, then the team whose core died
// first loses.)
if(nodeToTower(baseNodes.get(Team.A))==null&&nodeToTower(baseNodes.get(Team.B))==null) {
running=false;
int diff=0;
for(InternalPowerNode p : powerNodes) {
if(p.getControllingTeam()==Team.A)
diff++;
else if(p.getControllingTeam()==Team.B)
diff--;
}
if(!(setWinnerIfNonzero(diff,DominationFactor.BARELY_BEAT)||
setWinnerIfNonzero(archons.get(Team.A).size()-archons.get(Team.B).size(),DominationFactor.BARELY_BEAT)))
{
if(teamAName.compareTo(teamBName)<=0)
setWinner(Team.A,DominationFactor.WON_BY_DUBIOUS_REASONS);
else
setWinner(Team.B,DominationFactor.WON_BY_DUBIOUS_REASONS);
}
}
}
long aPoints = Math.round(teamRoundResources[Team.A.ordinal()] * 100), bPoints = Math.round(teamRoundResources[Team.B.ordinal()] * 100);
roundStats = new RoundStats(teamResources[0] * 100, teamResources[1] * 100, teamRoundResources[0] * 100, teamRoundResources[1] * 100);
lastRoundResources = teamRoundResources;
teamRoundResources = new double[2];
}
| public void processEndOfRound() {
// process all gameobjects
InternalObject[] gameObjects = new InternalObject[gameObjectsByID.size()];
gameObjects = gameObjectsByID.values().toArray(gameObjects);
for (int i = 0; i < gameObjects.length; i++) {
gameObjects[i].processEndOfRound();
}
if(timeLimitReached()&&winner==null) {
// copy the node lists, because the damage could kill a node and disconnect the graph
List<InternalPowerNode> teamANodes = new ArrayList<InternalPowerNode>(connectedNodesByTeam.get(Team.A));
List<InternalPowerNode> teamBNodes = new ArrayList<InternalPowerNode>(connectedNodesByTeam.get(Team.B));
InternalRobot tower;
for(InternalPowerNode n : teamANodes) {
tower = nodeToTower(n);
if(tower!=null)
tower.takeDamage(GameConstants.TIME_LIMIT_DAMAGE/teamANodes.size());
}
for(InternalPowerNode n : teamBNodes) {
tower = nodeToTower(n);
if(tower!=null)
tower.takeDamage(GameConstants.TIME_LIMIT_DAMAGE/teamBNodes.size());
}
removeDead();
// We have tiebreakers in case both power cores die to end-of-round damage in the same round.
// (If two power cores are killed by robots in the same round, then the team whose core died
// first loses.)
if(nodeToTower(baseNodes.get(Team.A))==null&&nodeToTower(baseNodes.get(Team.B))==null) {
running=false;
int diff=0;
for(InternalPowerNode p : powerNodes) {
if(p.getControllingTeam()==Team.A)
diff++;
else if(p.getControllingTeam()==Team.B)
diff--;
}
if(!(setWinnerIfNonzero(diff,DominationFactor.BARELY_BEAT)||
setWinnerIfNonzero(archons.get(Team.A).size()-archons.get(Team.B).size(),DominationFactor.BARELY_BEAT)))
{
if(teamAName.compareTo(teamBName)<=0)
setWinner(Team.A,DominationFactor.WON_BY_DUBIOUS_REASONS);
else
setWinner(Team.B,DominationFactor.WON_BY_DUBIOUS_REASONS);
}
}
}
long aPoints = Math.round(teamRoundResources[Team.A.ordinal()] * 100), bPoints = Math.round(teamRoundResources[Team.B.ordinal()] * 100);
roundStats = new RoundStats(teamResources[0] * 100, teamResources[1] * 100, teamRoundResources[0] * 100, teamRoundResources[1] * 100);
lastRoundResources = teamRoundResources;
teamRoundResources = new double[2];
}
|
diff --git a/core/interpreter/src/test/java/org/overture/interpreter/tests/ClassesPpInterpreterTestSuite.java b/core/interpreter/src/test/java/org/overture/interpreter/tests/ClassesPpInterpreterTestSuite.java
index 9520b6d0d1..1582dd3d99 100644
--- a/core/interpreter/src/test/java/org/overture/interpreter/tests/ClassesPpInterpreterTestSuite.java
+++ b/core/interpreter/src/test/java/org/overture/interpreter/tests/ClassesPpInterpreterTestSuite.java
@@ -1,21 +1,21 @@
package org.overture.interpreter.tests;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.overturetool.test.framework.BaseTestSuite;
public class ClassesPpInterpreterTestSuite extends BaseTestSuite
{
public static Test suite() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException
{
org.overturetool.test.framework.Properties.recordTestResults = false;
String name = "Interpreter Class PP TestSuite";
- String root = "src\\test\\resources\\classes";
+ String root = "src\\test\\resources\\test";
TestSuite test = createTestCompleteFile(name, root, InterpreterPpTestCase.class);
return test;
}
}
| true | true | public static Test suite() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException
{
org.overturetool.test.framework.Properties.recordTestResults = false;
String name = "Interpreter Class PP TestSuite";
String root = "src\\test\\resources\\classes";
TestSuite test = createTestCompleteFile(name, root, InterpreterPpTestCase.class);
return test;
}
| public static Test suite() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException
{
org.overturetool.test.framework.Properties.recordTestResults = false;
String name = "Interpreter Class PP TestSuite";
String root = "src\\test\\resources\\test";
TestSuite test = createTestCompleteFile(name, root, InterpreterPpTestCase.class);
return test;
}
|
diff --git a/signserver/src/java/org/signserver/protocol/ws/client/WSClientUtil.java b/signserver/src/java/org/signserver/protocol/ws/client/WSClientUtil.java
index 6a618f10f..e64fafc56 100644
--- a/signserver/src/java/org/signserver/protocol/ws/client/WSClientUtil.java
+++ b/signserver/src/java/org/signserver/protocol/ws/client/WSClientUtil.java
@@ -1,131 +1,131 @@
/*************************************************************************
* *
* SignServer: The OpenSource Automated Signing Server *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.signserver.protocol.ws.client;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.signserver.protocol.ws.Certificate;
import org.signserver.protocol.ws.gen.ProcessRequestWS;
import org.signserver.protocol.ws.gen.ProcessResponseWS;
/**
* Utility class containing help methods for the WS clients
*
* @author Philip Vendil 28 okt 2007
*
* @version $Id: WSClientUtil.java,v 1.3 2007-12-12 14:00:07 herrvendil Exp $
*/
public class WSClientUtil {
/**
* Method used to convert a coded SignRequestWS to a auto generated SignRequestWS
*/
public static List<ProcessRequestWS> convertProcessRequestWS(
List<org.signserver.protocol.ws.ProcessRequestWS> signRequestWS){
List<ProcessRequestWS> retval = new ArrayList<ProcessRequestWS>();
for (Iterator<org.signserver.protocol.ws.ProcessRequestWS> iterator = signRequestWS.iterator(); iterator.hasNext();) {
org.signserver.protocol.ws.ProcessRequestWS next = iterator.next();
ProcessRequestWS temp = new ProcessRequestWS();
temp.setRequestDataBase64(next.getRequestDataBase64());
retval.add(temp);
}
return retval;
}
/**
* Method used to convert a auto generated ProcessResponseWS to a coded ProcessResponseWS
*/
public static List<org.signserver.protocol.ws.ProcessResponseWS> convertProcessResponseWS(
List<ProcessResponseWS> signResponseWS){
List<org.signserver.protocol.ws.ProcessResponseWS> retval = new ArrayList<org.signserver.protocol.ws.ProcessResponseWS>();
for (Iterator<ProcessResponseWS> iterator = signResponseWS.iterator(); iterator.hasNext();) {
ProcessResponseWS next = iterator.next();
org.signserver.protocol.ws.ProcessResponseWS temp = new org.signserver.protocol.ws.ProcessResponseWS();
temp.setResponseDataBase64(next.getResponseDataBase64());
temp.setRequestID(next.getRequestID());
- if(next.getSignerCertificate()!=null){
- temp.setSignerCertificate(convertCertificate(next.getSignerCertificate()));
+ if(next.getWorkerCertificate()!=null){
+ temp.setWorkerCertificate(convertCertificate(next.getWorkerCertificate()));
}
- if(next.getSignerCertificateChain() != null){
+ if(next.getWorkerCertificateChain() != null){
ArrayList<Certificate> certChain = new ArrayList<Certificate>();
- for(org.signserver.protocol.ws.gen.Certificate cert : next.getSignerCertificateChain()){
+ for(org.signserver.protocol.ws.gen.Certificate cert : next.getWorkerCertificateChain()){
certChain.add(convertCertificate(cert));
}
- temp.setSignerCertificateChain(certChain);
+ temp.setWorkerCertificateChain(certChain);
}
retval.add(temp);
}
return retval;
}
/**
* Method to convert a auto generated Certificate to a coded WebService Certificate.
* @param signerCertificate
* @return
*/
private static org.signserver.protocol.ws.Certificate convertCertificate(
org.signserver.protocol.ws.gen.Certificate certificate) {
org.signserver.protocol.ws.Certificate retval = new org.signserver.protocol.ws.Certificate();
retval.setCertificateBase64(certificate.getCertificateBase64());
return retval;
}
/**
* Method to generate a custom SSL Socket Factory from a
* client key store JKS and a trust store JKS.
* @param clientKeyStore Path to the client JKS used for client authentication
* or null if no client authentication should be supported.
* @param clientKeyStorePwd password to unlock key store or null
* if no client authentication should be supported.
* @param trustKeyStore Path to JKS containing all trusted CA certificates
* @param trustKeyStorePwd password to unlock trust key store.
* @return a generated custom SSLSocketFactory
*/
public static SSLSocketFactory genCustomSSLSocketFactory(String clientKeyStore,
String clientKeyStorePwd, String trustKeyStore, String trustKeyStorePwd) throws Exception{
TrustManager[] trustManagers = new TrustManager[] {new CustomJKSTrustStoreManager(trustKeyStore, trustKeyStorePwd)};
SSLContext sc = SSLContext.getInstance("SSL");
if(clientKeyStore != null){
KeyManager[] keyManagers = new KeyManager[] { new CustomJKSKeyManager(clientKeyStore,clientKeyStorePwd)};
sc.init(keyManagers, trustManagers, new java.security.SecureRandom());
}else{
sc.init(null, trustManagers, new java.security.SecureRandom());
}
return sc.getSocketFactory();
}
}
| false | true | public static List<org.signserver.protocol.ws.ProcessResponseWS> convertProcessResponseWS(
List<ProcessResponseWS> signResponseWS){
List<org.signserver.protocol.ws.ProcessResponseWS> retval = new ArrayList<org.signserver.protocol.ws.ProcessResponseWS>();
for (Iterator<ProcessResponseWS> iterator = signResponseWS.iterator(); iterator.hasNext();) {
ProcessResponseWS next = iterator.next();
org.signserver.protocol.ws.ProcessResponseWS temp = new org.signserver.protocol.ws.ProcessResponseWS();
temp.setResponseDataBase64(next.getResponseDataBase64());
temp.setRequestID(next.getRequestID());
if(next.getSignerCertificate()!=null){
temp.setSignerCertificate(convertCertificate(next.getSignerCertificate()));
}
if(next.getSignerCertificateChain() != null){
ArrayList<Certificate> certChain = new ArrayList<Certificate>();
for(org.signserver.protocol.ws.gen.Certificate cert : next.getSignerCertificateChain()){
certChain.add(convertCertificate(cert));
}
temp.setSignerCertificateChain(certChain);
}
retval.add(temp);
}
return retval;
}
| public static List<org.signserver.protocol.ws.ProcessResponseWS> convertProcessResponseWS(
List<ProcessResponseWS> signResponseWS){
List<org.signserver.protocol.ws.ProcessResponseWS> retval = new ArrayList<org.signserver.protocol.ws.ProcessResponseWS>();
for (Iterator<ProcessResponseWS> iterator = signResponseWS.iterator(); iterator.hasNext();) {
ProcessResponseWS next = iterator.next();
org.signserver.protocol.ws.ProcessResponseWS temp = new org.signserver.protocol.ws.ProcessResponseWS();
temp.setResponseDataBase64(next.getResponseDataBase64());
temp.setRequestID(next.getRequestID());
if(next.getWorkerCertificate()!=null){
temp.setWorkerCertificate(convertCertificate(next.getWorkerCertificate()));
}
if(next.getWorkerCertificateChain() != null){
ArrayList<Certificate> certChain = new ArrayList<Certificate>();
for(org.signserver.protocol.ws.gen.Certificate cert : next.getWorkerCertificateChain()){
certChain.add(convertCertificate(cert));
}
temp.setWorkerCertificateChain(certChain);
}
retval.add(temp);
}
return retval;
}
|
diff --git a/src/main/java/com/g414/st9/proto/service/validator/SmallStringValidator.java b/src/main/java/com/g414/st9/proto/service/validator/SmallStringValidator.java
index 4850632..179999f 100644
--- a/src/main/java/com/g414/st9/proto/service/validator/SmallStringValidator.java
+++ b/src/main/java/com/g414/st9/proto/service/validator/SmallStringValidator.java
@@ -1,51 +1,51 @@
package com.g414.st9.proto.service.validator;
/**
* Validates / transforms String values.
*/
public class SmallStringValidator implements
ValidatorTransformer<Object, String> {
public static final int SMALLSTRING_MAX_LENGTH = 255;
private final String attribute;
private final Integer minLength;
private final Integer maxLength;
public SmallStringValidator(String attribute, Integer minLength,
Integer maxLength) {
this.attribute = attribute;
this.minLength = minLength;
this.maxLength = (maxLength == null) ? SMALLSTRING_MAX_LENGTH : Math
.min(SMALLSTRING_MAX_LENGTH, maxLength);
}
public String validateTransform(Object instance) throws ValidationException {
if (instance == null) {
throw new ValidationException("'" + attribute
+ "' must not be null");
}
String instanceString = instance.toString();
int length = instanceString.length();
if (minLength != null && length < minLength) {
throw new ValidationException("'" + attribute
- + "' length be greater than or equal to " + minLength);
+ + "' length must be greater than or equal to " + minLength);
}
if (length > maxLength) {
throw new ValidationException("'" + attribute
- + "' length be less than or equal to " + minLength);
+ + "' length must be less than or equal to " + maxLength);
}
return instanceString;
}
public Object untransform(String instance) throws ValidationException {
if (instance == null) {
throw new ValidationException("'" + attribute
+ "' must not be null");
}
return instance;
}
}
| false | true | public String validateTransform(Object instance) throws ValidationException {
if (instance == null) {
throw new ValidationException("'" + attribute
+ "' must not be null");
}
String instanceString = instance.toString();
int length = instanceString.length();
if (minLength != null && length < minLength) {
throw new ValidationException("'" + attribute
+ "' length be greater than or equal to " + minLength);
}
if (length > maxLength) {
throw new ValidationException("'" + attribute
+ "' length be less than or equal to " + minLength);
}
return instanceString;
}
| public String validateTransform(Object instance) throws ValidationException {
if (instance == null) {
throw new ValidationException("'" + attribute
+ "' must not be null");
}
String instanceString = instance.toString();
int length = instanceString.length();
if (minLength != null && length < minLength) {
throw new ValidationException("'" + attribute
+ "' length must be greater than or equal to " + minLength);
}
if (length > maxLength) {
throw new ValidationException("'" + attribute
+ "' length must be less than or equal to " + maxLength);
}
return instanceString;
}
|
diff --git a/src/org/rsbot/util/io/IniParser.java b/src/org/rsbot/util/io/IniParser.java
index 1d003e95..d62a6398 100644
--- a/src/org/rsbot/util/io/IniParser.java
+++ b/src/org/rsbot/util/io/IniParser.java
@@ -1,109 +1,109 @@
package org.rsbot.util.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
/**
* @author Paris
*/
public class IniParser {
private static final char sectionOpen = '[';
private static final char sectionClose = ']';
private static final char keyBound = '=';
private static final char[] comments = {'#', ';'};
public static final String emptySection = "";
private IniParser() {
}
public static void serialise(final HashMap<String, HashMap<String, String>> data, final BufferedWriter out) throws IOException {
if (data.containsKey(emptySection)) {
writeSection(emptySection, data.get(emptySection), out);
out.newLine();
}
for (final Entry<String, HashMap<String, String>> entry : data.entrySet()) {
final String section = entry.getKey();
if (section.equals(emptySection)) {
continue;
}
writeSection(section, entry.getValue(), out);
out.newLine();
}
}
private static void writeSection(final String section, final HashMap<String, String> map, final BufferedWriter out) throws IOException {
if (!(section == null || section.isEmpty())) {
out.write(sectionOpen);
out.write(section);
out.write(sectionClose);
out.newLine();
}
for (final Entry<String, String> entry : map.entrySet()) {
out.write(entry.getKey());
out.write(keyBound);
out.write(entry.getValue());
out.newLine();
}
}
public static HashMap<String, HashMap<String, String>> deserialise(final File input) throws IOException {
final BufferedReader reader = new BufferedReader(new FileReader(input));
final HashMap<String, HashMap<String, String>> data = deserialise(reader);
reader.close();
return data;
}
public static HashMap<String, HashMap<String, String>> deserialise(final BufferedReader input) throws IOException {
final HashMap<String, HashMap<String, String>> data = new HashMap<String, HashMap<String, String>>();
String line, section = emptySection;
while ((line = input.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
int z;
final int l = line.length();
final char t = line.charAt(0);
if (t == sectionOpen) {
z = line.indexOf(sectionClose, 1);
z = z == -1 ? l : z;
- section = z == 1 ? "" : line.substring(1, z - 1).trim();
+ section = z == 1 ? "" : line.substring(1, z).trim();
} else {
boolean skip = false;
for (final char c : comments) {
if (t == c) {
skip = true;
break;
}
}
if (skip) {
continue;
}
z = line.indexOf(keyBound);
z = z == -1 ? l : z;
String key, value = "";
key = line.substring(0, z).trim();
if (++z < l) {
value = line.substring(z).trim();
}
if (!data.containsKey(section)) {
data.put(section, new HashMap<String, String>());
}
data.get(section).put(key, value);
}
}
return data;
}
public static boolean parseBool(final String mode) {
return mode.equals("1") || mode.equalsIgnoreCase("true") || mode.equalsIgnoreCase("yes");
}
}
| true | true | public static HashMap<String, HashMap<String, String>> deserialise(final BufferedReader input) throws IOException {
final HashMap<String, HashMap<String, String>> data = new HashMap<String, HashMap<String, String>>();
String line, section = emptySection;
while ((line = input.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
int z;
final int l = line.length();
final char t = line.charAt(0);
if (t == sectionOpen) {
z = line.indexOf(sectionClose, 1);
z = z == -1 ? l : z;
section = z == 1 ? "" : line.substring(1, z - 1).trim();
} else {
boolean skip = false;
for (final char c : comments) {
if (t == c) {
skip = true;
break;
}
}
if (skip) {
continue;
}
z = line.indexOf(keyBound);
z = z == -1 ? l : z;
String key, value = "";
key = line.substring(0, z).trim();
if (++z < l) {
value = line.substring(z).trim();
}
if (!data.containsKey(section)) {
data.put(section, new HashMap<String, String>());
}
data.get(section).put(key, value);
}
}
return data;
}
| public static HashMap<String, HashMap<String, String>> deserialise(final BufferedReader input) throws IOException {
final HashMap<String, HashMap<String, String>> data = new HashMap<String, HashMap<String, String>>();
String line, section = emptySection;
while ((line = input.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
int z;
final int l = line.length();
final char t = line.charAt(0);
if (t == sectionOpen) {
z = line.indexOf(sectionClose, 1);
z = z == -1 ? l : z;
section = z == 1 ? "" : line.substring(1, z).trim();
} else {
boolean skip = false;
for (final char c : comments) {
if (t == c) {
skip = true;
break;
}
}
if (skip) {
continue;
}
z = line.indexOf(keyBound);
z = z == -1 ? l : z;
String key, value = "";
key = line.substring(0, z).trim();
if (++z < l) {
value = line.substring(z).trim();
}
if (!data.containsKey(section)) {
data.put(section, new HashMap<String, String>());
}
data.get(section).put(key, value);
}
}
return data;
}
|
diff --git a/src/main/java/org/iplantc/de/client/views/MyDataGrid.java b/src/main/java/org/iplantc/de/client/views/MyDataGrid.java
index 835097d9..fae6371b 100644
--- a/src/main/java/org/iplantc/de/client/views/MyDataGrid.java
+++ b/src/main/java/org/iplantc/de/client/views/MyDataGrid.java
@@ -1,845 +1,845 @@
package org.iplantc.de.client.views;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.iplantc.core.client.widgets.Hyperlink;
import org.iplantc.core.jsonutil.JsonUtil;
import org.iplantc.core.uicommons.client.events.EventBus;
import org.iplantc.core.uicommons.client.util.CommonStoreSorter;
import org.iplantc.core.uicommons.client.views.dialogs.IPlantDialog;
import org.iplantc.core.uicommons.client.views.panels.IPlantDialogPanel;
import org.iplantc.core.uidiskresource.client.models.DiskResource;
import org.iplantc.core.uidiskresource.client.models.File;
import org.iplantc.core.uidiskresource.client.models.Folder;
import org.iplantc.de.client.Constants;
import org.iplantc.de.client.I18N;
import org.iplantc.de.client.dispatchers.IDropLiteWindowDispatcher;
import org.iplantc.de.client.dispatchers.SimpleDownloadWindowDispatcher;
import org.iplantc.de.client.events.disk.mgmt.DiskResourceSelectedEvent;
import org.iplantc.de.client.events.disk.mgmt.DiskResourceSelectedEventHandler;
import org.iplantc.de.client.images.Resources;
import org.iplantc.de.client.models.ClientDataModel;
import org.iplantc.de.client.services.FileDeleteCallback;
import org.iplantc.de.client.services.FolderDeleteCallback;
import org.iplantc.de.client.services.FolderServiceFacade;
import org.iplantc.de.client.utils.DataUtils;
import org.iplantc.de.client.utils.DataViewContextExecutor;
import org.iplantc.de.client.utils.TreeViewContextExecutor;
import org.iplantc.de.client.utils.builders.context.DataContextBuilder;
import org.iplantc.de.client.views.dialogs.MetadataEditorDialog;
import org.iplantc.de.client.views.dialogs.SharingDialog;
import org.iplantc.de.client.views.panels.AddFolderDialogPanel;
import org.iplantc.de.client.views.panels.DataPreviewPanel;
import org.iplantc.de.client.views.panels.DiskresourceMetadataEditorPanel;
import org.iplantc.de.client.views.panels.MetadataEditorPanel;
import org.iplantc.de.client.views.panels.RenameFileDialogPanel;
import org.iplantc.de.client.views.panels.RenameFolderDialogPanel;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.filters.GridFilters;
import com.extjs.gxt.ui.client.widget.grid.filters.StringFilter;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.tips.ToolTip;
import com.extjs.gxt.ui.client.widget.tips.ToolTipConfig;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
/**
* A grid that displays users files and folders. Provides floating menus with support for delete, rename,
* view
*
* @author sriram
*
*/
public class MyDataGrid extends Grid<DiskResource> {
public static final String COLUMN_ID_NAME = DiskResource.NAME;
public static final String COLUMN_ID_DATE_MODIFIED = DiskResource.DATE_MODIFIED;
public static final String COLUMN_ID_DATE_CREATED = DiskResource.DATE_CREATED;
public static final String COLUMN_ID_SIZE = File.SIZE;
public static final String COLUMN_ID_MENU = "menu"; //$NON-NLS-1$
protected ClientDataModel controller;
protected ArrayList<HandlerRegistration> handlers;
protected static CheckBoxSelectionModel<DiskResource> sm;
protected String callertag;
protected String currentFolderId;
private Menu menuActions;
private MenuItem itemAddFolder;
private MenuItem itemRenameResource;
private MenuItem itemViewResource;
private MenuItem itemViewTree;
private MenuItem itemSimpleDownloadResource;
private MenuItem itemBulkDownloadResource;
private MenuItem itemDeleteResource;
private MenuItem itemMetaData;
private MenuItem itemShareResource;
private final DataViewContextExecutor executor;
private final Component maskingParent;
/**
* Create a new MyDataGrid
*
*
* @param store store to be used by the grid
* @param colModel column model describing the columns in the grid
* @param currentFolderId id of the current folder to be displayed
* @param executor data view context executor called when appropriate grid row is clicked
*/
private MyDataGrid(ListStore<DiskResource> store, ColumnModel colModel, String currentFolderId,
DataViewContextExecutor executor, Component maskingParent) {
super(store, colModel);
this.currentFolderId = currentFolderId;
this.executor = executor;
this.maskingParent = maskingParent;
init();
registerHandlers();
}
/**
* Initialize the grid's properties
*/
protected void init() {
setBorders(true);
setHeight(260);
getView().setEmptyText(I18N.DISPLAY.selectFolderToViewContents());
getView().setShowDirtyCells(false);
menuActions = buildActionsMenu();
}
/**
* Handle click event of grid row
*
* @param dr disk resource on which the click was made
* @param tag caller tag
*/
protected void handleRowClick(final DiskResource dr, final String tag) {
if (executor != null && dr instanceof File && this.callertag.equals(tag)) {
DataContextBuilder builder = new DataContextBuilder();
executor.execute(builder.build(dr.getId()));
}
}
/**
* Builds an action menu with items for adding, renaming, viewing, downloading, and deleting disk
* resources.
*
* @return The grid rows' actions menu
*/
private Menu buildActionsMenu() {
Menu actionMenu = new Menu();
buildAddfolderMenuItem();
buildRenameResourceMenuItem();
buildViewResourceMenuItem();
buildViewTreeMenuItem();
buildSimpleDownloadMenuItem();
buildBulDownloadMenuItem();
buildDeleteResourceMenuItem();
buildMetaDataMenuItem();
buildShareResourceMenuItem();
actionMenu.add(itemAddFolder);
actionMenu.add(itemRenameResource);
actionMenu.add(itemViewResource);
actionMenu.add(itemViewTree);
actionMenu.add(itemSimpleDownloadResource);
actionMenu.add(itemBulkDownloadResource);
actionMenu.add(itemDeleteResource);
actionMenu.add(itemMetaData);
actionMenu.add(itemShareResource);
return actionMenu;
}
private void buildShareResourceMenuItem() {
itemShareResource = new MenuItem();
itemShareResource.setText(I18N.DISPLAY.share());
itemShareResource.setIcon(AbstractImagePrototype.create(Resources.ICONS.share()));
itemShareResource.addSelectionListener(new ShareListenerImpl());
}
private void buildMetaDataMenuItem() {
itemMetaData = new MenuItem();
itemMetaData.setText(I18N.DISPLAY.metadata());
itemMetaData.setIcon(AbstractImagePrototype.create(Resources.ICONS.metadata()));
itemMetaData.addSelectionListener(new MetadataListenerImpl());
}
private void buildDeleteResourceMenuItem() {
itemDeleteResource = new MenuItem();
itemDeleteResource.setText(I18N.DISPLAY.delete());
itemDeleteResource.setIcon(AbstractImagePrototype.create(Resources.ICONS.folderDelete()));
itemDeleteResource.addSelectionListener(new DeleteListenerImpl());
}
private void buildBulDownloadMenuItem() {
itemBulkDownloadResource = new MenuItem();
itemBulkDownloadResource.setText(I18N.DISPLAY.bulkDownload());
itemBulkDownloadResource.setIcon(AbstractImagePrototype.create(Resources.ICONS.download()));
itemBulkDownloadResource.addSelectionListener(new BulkDownloadListenerImpl());
}
private void buildSimpleDownloadMenuItem() {
itemSimpleDownloadResource = new MenuItem();
itemSimpleDownloadResource.setText(I18N.DISPLAY.simpleDownload());
itemSimpleDownloadResource.setIcon(AbstractImagePrototype.create(Resources.ICONS.download()));
itemSimpleDownloadResource.addSelectionListener(new SimpleDownloadListenerImpl());
}
private void buildViewTreeMenuItem() {
itemViewTree = new MenuItem();
itemViewTree.setText(I18N.DISPLAY.viewTreeViewer());
itemViewTree.setIcon(AbstractImagePrototype.create(Resources.ICONS.fileView()));
itemViewTree.addSelectionListener(new ViewTreeListenerImpl());
}
private void buildViewResourceMenuItem() {
itemViewResource = new MenuItem();
itemViewResource.setText(I18N.DISPLAY.view());
itemViewResource.setIcon(AbstractImagePrototype.create(Resources.ICONS.fileView()));
itemViewResource.addSelectionListener(new ViewListenerImpl());
}
private void buildRenameResourceMenuItem() {
itemRenameResource = new MenuItem();
itemRenameResource.setText(I18N.DISPLAY.rename());
itemRenameResource.setIcon(AbstractImagePrototype.create(Resources.ICONS.folderRename()));
itemRenameResource.addSelectionListener(new RenameListenerImpl());
}
private void buildAddfolderMenuItem() {
itemAddFolder = new MenuItem();
itemAddFolder.setText(I18N.DISPLAY.newFolder());
itemAddFolder.setIcon(AbstractImagePrototype.create(Resources.ICONS.folderAdd()));
itemAddFolder.addSelectionListener(new NewFolderListenerImpl());
}
/**
* Show the Actions menu at the given absolute x, y position. The items displayed in the menu will
* depend on the resources selected in the grid, according to DataUtils.getSupportedActions.
*
* @param x
* @param y
*
* @see org.iplantc.de.client.utils.DataUtils
*/
public void showMenu(int x, int y) {
List<DiskResource> selected = getSelectionModel().getSelectedItems();
List<DataUtils.Action> actions = DataUtils.getSupportedActions(selected);
if (menuActions != null && actions.size() > 0) {
for (Component item : menuActions.getItems()) {
item.disable();
item.hide();
}
boolean folderActionsEnabled = DataUtils.hasFolders(selected);
if (folderActionsEnabled && selected.size() == 1) {
// Enable the "Add Folder" item as well.
itemAddFolder.enable();
itemAddFolder.show();
}
for (DataUtils.Action action : actions) {
switch (action) {
case RenameFolder:
itemRenameResource.setIcon(AbstractImagePrototype.create(Resources.ICONS
.folderRename()));
itemRenameResource.enable();
itemRenameResource.show();
break;
case RenameFile:
itemRenameResource.setIcon(AbstractImagePrototype.create(Resources.ICONS
.fileRename()));
itemRenameResource.enable();
itemRenameResource.show();
break;
case View:
itemViewResource.enable();
itemViewResource.show();
break;
case ViewTree:
itemViewTree.enable();
itemViewTree.show();
break;
case SimpleDownload:
itemSimpleDownloadResource.enable();
itemSimpleDownloadResource.show();
break;
case BulkDownload:
itemBulkDownloadResource.enable();
itemBulkDownloadResource.show();
break;
case Delete:
ImageResource delIcon = folderActionsEnabled ? Resources.ICONS.folderDelete()
: Resources.ICONS.fileDelete();
itemDeleteResource.setIcon(AbstractImagePrototype.create(delIcon));
itemDeleteResource.enable();
itemDeleteResource.show();
break;
case Metadata:
itemMetaData.enable();
itemMetaData.show();
break;
case Share:
itemShareResource.enable();
- itemRenameResource.show();
+ itemShareResource.show();
break;
}
}
menuActions.showAt(x, y);
}
}
/**
* Builds the CheckBoxSelectionModel used in the ColumnDisplay.ALL ColumnModel.
*/
protected static void buildCheckBoxSelectionModel() {
if (sm != null) {
return;
}
sm = new CheckBoxSelectionModel<DiskResource>() {
@Override
protected void handleMouseClick(GridEvent<DiskResource> event) {
super.handleMouseClick(event);
MyDataGrid grid = (MyDataGrid)event.getGrid();
// Show the actions menu if the menu grid column was clicked.
String colId = grid.getColumnModel().getColumnId(event.getColIndex());
if (colId != null && colId.equals(COLUMN_ID_MENU)) {
// if the row clicked is not selected, then select it
DiskResource resource = listStore.getAt(event.getRowIndex());
if (resource != null && !isSelected(resource)) {
select(resource, true);
}
// show the menu just under the row and column clicked.
Element target = event.getTarget();
grid.showMenu(target.getAbsoluteRight() - 10, target.getAbsoluteBottom());
}
}
@Override
protected void handleMouseDown(GridEvent<DiskResource> event) {
// Only select the row if the checkbox is explicitly selected.
// Assume the checkbox is set as the first column of the row.
if (event.getColIndex() == 0) {
super.handleMouseDown(event);
}
}
};
sm.getColumn().setAlignment(HorizontalAlignment.CENTER);
}
/**
* Create the column model for the tree grid.
*
* @return an instance of ColumnModel representing the columns visible in a grid
*/
protected static ColumnModel buildColumnModel(String tag) {
// build column configs and add them to a list for the ColumnModel.
List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
ColumnConfig name = new ColumnConfig(COLUMN_ID_NAME, I18N.DISPLAY.name(), 235);
name.setRenderer(new NameCellRenderer(tag));
name.setMenuDisabled(true);
ColumnConfig date = new ColumnConfig(COLUMN_ID_DATE_MODIFIED, I18N.DISPLAY.lastModified(), 150);
date.setDateTimeFormat(DateTimeFormat
.getFormat(DateTimeFormat.PredefinedFormat.DATE_TIME_MEDIUM));
date.setMenuDisabled(true);
if (tag.equals(Constants.CLIENT.myDataTag())) {
// add the checkbox as the first column of the row
buildCheckBoxSelectionModel();
columns.add(sm.getColumn());
}
ColumnConfig created = new ColumnConfig(COLUMN_ID_DATE_CREATED, I18N.DISPLAY.createdDate(), 150);
created.setDateTimeFormat(DateTimeFormat
.getFormat(DateTimeFormat.PredefinedFormat.DATE_TIME_MEDIUM));
created.setHidden(true);
created.setMenuDisabled(true);
ColumnConfig size = new ColumnConfig(COLUMN_ID_SIZE, I18N.DISPLAY.size(), 100);
size.setRenderer(new SizeCellRenderer());
size.setHidden(true);
size.setMenuDisabled(true);
ColumnConfig menu = new ColumnConfig(COLUMN_ID_MENU, "", 25); //$NON-NLS-1$
menu.setSortable(false);
menu.setMenuDisabled(true);
columns.addAll(Arrays.asList(name, date, created, size, menu));
return new ColumnModel(columns);
}
@SuppressWarnings("unchecked")
private static MyDataGrid createInstanceImpl(String currentFolderId, String tag,
ClientDataModel controller, Component maskingParent) {
final ListStore<DiskResource> store = new ListStore<DiskResource>();
final ColumnModel colModel = buildColumnModel(tag);
boolean isMyDataWindow = tag.equals(Constants.CLIENT.myDataTag());
MyDataGrid ret;
DataViewContextExecutor executor = null;
if (isMyDataWindow) {
executor = new DataViewContextExecutor();
}
store.setStoreSorter(new CommonStoreSorter());
ret = new MyDataGrid(store, colModel, currentFolderId, executor, maskingParent);
if (isMyDataWindow) {
ret.setSelectionModel(sm);
ret.addPlugin(sm);
ret.addStyleName("menu-row-over"); //$NON-NLS-1$
}
ret.getSelectionModel().setSelectionMode(SelectionMode.SIMPLE);
ret.getView().setForceFit(false);
ret.setAutoExpandMax(2048);
ret.callertag = tag;
ret.controller = controller;
GridFilters filters = new GridFilters();
filters.setLocal(true);
StringFilter nameFilter = new StringFilter("name"); //$NON-NLS-1$
filters.addFilter(nameFilter);
ret.addPlugin(filters);
return ret;
}
/**
* Allocate default instance.
*
* @return newly allocated my data grid.
*/
public static MyDataGrid createInstance(String currentFolderId, String tag,
ClientDataModel controller, Component maskingParent) {
return createInstanceImpl(currentFolderId, tag, controller, maskingParent);
}
/**
* get root folder id
*
* @return id of the root folder t
*/
public String getRootFolderId() {
return controller.getRootFolderId();
}
/**
* Free any unneeded resources.
*/
public void cleanup() {
removeEventHandlers();
removeAllListeners();
}
private void removeEventHandlers() {
EventBus eventbus = EventBus.getInstance();
// unregister
for (HandlerRegistration reg : handlers) {
eventbus.removeHandler(reg);
}
// clear our list
handlers.clear();
}
/**
* register event handlers
*
*/
protected void registerHandlers() {
handlers = new ArrayList<HandlerRegistration>();
EventBus eventbus = EventBus.getInstance();
// disk resource selected
handlers.add(eventbus.addHandler(DiskResourceSelectedEvent.TYPE,
new DiskResourceSelectedEventHandler() {
@Override
public void onSelected(DiskResourceSelectedEvent event) {
handleRowClick(event.getResource(), event.getTag());
}
}));
}
private void showErrorMsg() {
MessageBox.alert(I18N.DISPLAY.permissionErrorTitle(), I18N.DISPLAY.permissionErrorMessage(),
null);
}
private class NewFolderListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
for (DiskResource resource : getSelectionModel().getSelectedItems()) {
if (resource instanceof Folder) {
if (resource != null && resource.getId() != null) {
IPlantDialog dlg = new IPlantDialog(I18N.DISPLAY.newFolder(), 340,
new AddFolderDialogPanel(resource.getId(), maskingParent));
dlg.disableOkButton();
dlg.show();
}
}
}
}
}
private class RenameListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
for (DiskResource resource : getSelectionModel().getSelectedItems()) {
IPlantDialogPanel panel = null;
if (resource instanceof Folder) {
panel = new RenameFolderDialogPanel(resource.getId(), resource.getName(),
maskingParent);
} else if (resource instanceof File) {
panel = new RenameFileDialogPanel(resource.getId(), resource.getName(),
maskingParent);
}
IPlantDialog dlg = new IPlantDialog(I18N.DISPLAY.rename(), 340, panel);
dlg.show();
}
}
}
private class ViewListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
List<DiskResource> resources = getSelectionModel().getSelectedItems();
if (DataUtils.isViewable(resources)) {
List<String> contexts = new ArrayList<String>();
DataContextBuilder builder = new DataContextBuilder();
for (DiskResource resource : resources) {
contexts.add(builder.build(resource.getId()));
}
DataViewContextExecutor executor = new DataViewContextExecutor();
executor.execute(contexts);
} else {
showErrorMsg();
}
}
}
private class ShareListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
List<DiskResource> resources = getSelectionModel().getSelectedItems();
if (DataUtils.isSharable(resources)) {
showSharingDialog(resources);
} else {
showErrorMsg();
}
}
}
private void showSharingDialog(List<DiskResource> resources) {
SharingDialog sd = new SharingDialog(resources);
sd.show();
}
private class ViewTreeListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
List<DiskResource> resources = getSelectionModel().getSelectedItems();
if (DataUtils.isViewable(resources)) {
DataContextBuilder builder = new DataContextBuilder();
TreeViewContextExecutor executor = new TreeViewContextExecutor();
for (DiskResource resource : resources) {
executor.execute(builder.build(resource.getId()));
}
} else {
showErrorMsg();
}
}
}
private class MetadataListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
DiskResource dr = getSelectionModel().getSelectedItems().get(0);
final MetadataEditorPanel mep = new DiskresourceMetadataEditorPanel(dr);
MetadataEditorDialog d = new MetadataEditorDialog(
I18N.DISPLAY.metadata() + ":" + dr.getId(), mep); //$NON-NLS-1$
d.setSize(500, 300);
d.setResizable(false);
d.show();
}
}
private class SimpleDownloadListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
List<DiskResource> resources = getSelectionModel().getSelectedItems();
if (DataUtils.isDownloadable(resources)) {
if (resources.size() == 1) {
downloadNow(resources.get(0).getId());
} else {
launchDownloadWindow(resources);
}
} else {
showErrorMsg();
}
}
private void downloadNow(String path) {
FolderServiceFacade service = new FolderServiceFacade();
service.simpleDownload(path);
}
private void launchDownloadWindow(List<DiskResource> resources) {
List<String> paths = new ArrayList<String>();
for (DiskResource resource : resources) {
if (resource instanceof File) {
paths.add(resource.getId());
}
}
SimpleDownloadWindowDispatcher dispatcher = new SimpleDownloadWindowDispatcher();
dispatcher.launchDownloadWindow(paths);
}
}
private class BulkDownloadListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
List<DiskResource> resources = getSelectionModel().getSelectedItems();
if (DataUtils.isDownloadable(resources)) {
IDropLiteWindowDispatcher dispatcher = new IDropLiteWindowDispatcher();
dispatcher.launchDownloadWindow(resources);
} else {
showErrorMsg();
}
}
}
private class DeleteListenerImpl extends SelectionListener<MenuEvent> {
@Override
public void componentSelected(MenuEvent ce) {
final Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {
@Override
public void handleEvent(MessageBoxEvent ce) {
Button btn = ce.getButtonClicked();
// did the user click yes?
if (btn.getItemId().equals(Dialog.YES)) {
confirmDelete();
}
}
};
// if folders are selected, display a "folder delete" confirmation
if (DataUtils.hasFolders(getSelectionModel().getSelectedItems())) {
MessageBox.confirm(I18N.DISPLAY.warning(), I18N.DISPLAY.folderDeleteWarning(), callback);
} else {
confirmDelete();
}
}
private void confirmDelete() {
final Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {
@Override
public void handleEvent(MessageBoxEvent ce) {
Button btn = ce.getButtonClicked();
if (btn.getItemId().equals(Dialog.YES)) {
doDelete();
}
}
};
MessageBox.confirm(I18N.DISPLAY.deleteFilesTitle(), I18N.DISPLAY.deleteFilesMsg(), callback);
}
private void doDelete() {
// first we need to fill our id lists
List<String> idFolders = new ArrayList<String>();
List<String> idFiles = new ArrayList<String>();
List<DiskResource> resources = getSelectionModel().getSelectedItems();
if (DataUtils.isDeletable(resources)) {
for (DiskResource resource : getSelectionModel().getSelectedItems()) {
if (resource instanceof Folder) {
idFolders.add(resource.getId());
} else if (resource instanceof File) {
idFiles.add(resource.getId());
}
}
// call the appropriate delete services
FolderServiceFacade facade = new FolderServiceFacade(maskingParent);
if (idFiles.size() > 0) {
facade.deleteFiles(JsonUtil.buildJsonArrayString(idFiles), new FileDeleteCallback(
idFiles));
}
if (idFolders.size() > 0) {
facade.deleteFolders(JsonUtil.buildJsonArrayString(idFolders),
new FolderDeleteCallback(idFolders));
}
} else {
showErrorMsg();
}
}
}
}
/**
* A custom renderer that renders folder / file names as hyperlink
*
* @author sriram
*
*/
class NameCellRenderer implements GridCellRenderer<DiskResource> {
private final String callertag;
NameCellRenderer(String caller) {
callertag = caller;
}
@Override
public Object render(final DiskResource model, String property, ColumnData config, int rowIndex,
int colIndex, ListStore<DiskResource> store, final Grid<DiskResource> grid) {
Hyperlink link = null;
if (model instanceof Folder) {
link = new Hyperlink("<img src='./gxt/images/default/tree/folder.gif'/> " //$NON-NLS-1$
+ model.getName(), "mydata_name"); //$NON-NLS-1$
} else {
link = new Hyperlink("<img src='./images/file.gif'/> " + model.getName(), "mydata_name"); //$NON-NLS-1$ //$NON-NLS-2$
addPreviewToolTip(link, model);
}
link.addListener(Events.OnClick, new Listener<BaseEvent>() {
@Override
public void handleEvent(BaseEvent be) {
DiskResourceSelectedEvent e = new DiskResourceSelectedEvent(model, callertag);
EventBus.getInstance().fireEvent(e);
}
});
link.setWidth(model.getName().length());
return link;
}
private void addPreviewToolTip(Component target, final DiskResource resource) {
ToolTipConfig ttConfig = new ToolTipConfig();
ttConfig.setShowDelay(1000);
ttConfig.setDismissDelay(0); // never hide tool tip while mouse is still over it
ttConfig.setAnchorToTarget(true);
ttConfig.setTitle(I18N.DISPLAY.preview() + ": " + resource.getName()); //$NON-NLS-1$
final LayoutContainer pnl = new LayoutContainer();
final DataPreviewPanel previewPanel = new DataPreviewPanel();
pnl.add(previewPanel);
ToolTip tip = new ToolTip(target, ttConfig) {
// overridden to populate the preview
@Override
protected void updateContent() {
getHeader().setText(title);
if (resource != null) {
previewPanel.update(resource);
}
}
};
tip.setWidth(312);
tip.add(pnl);
}
}
class SizeCellRenderer implements GridCellRenderer<DiskResource> {
@Override
public Object render(DiskResource model, String property, ColumnData config, int rowIndex,
int colIndex, ListStore<DiskResource> store, Grid<DiskResource> grid) {
if (model instanceof Folder) {
return null;
} else {
File f = (File)model;
return DataUtils.getSizeForDisplay(f.getSize());
}
}
}
| true | true | public void showMenu(int x, int y) {
List<DiskResource> selected = getSelectionModel().getSelectedItems();
List<DataUtils.Action> actions = DataUtils.getSupportedActions(selected);
if (menuActions != null && actions.size() > 0) {
for (Component item : menuActions.getItems()) {
item.disable();
item.hide();
}
boolean folderActionsEnabled = DataUtils.hasFolders(selected);
if (folderActionsEnabled && selected.size() == 1) {
// Enable the "Add Folder" item as well.
itemAddFolder.enable();
itemAddFolder.show();
}
for (DataUtils.Action action : actions) {
switch (action) {
case RenameFolder:
itemRenameResource.setIcon(AbstractImagePrototype.create(Resources.ICONS
.folderRename()));
itemRenameResource.enable();
itemRenameResource.show();
break;
case RenameFile:
itemRenameResource.setIcon(AbstractImagePrototype.create(Resources.ICONS
.fileRename()));
itemRenameResource.enable();
itemRenameResource.show();
break;
case View:
itemViewResource.enable();
itemViewResource.show();
break;
case ViewTree:
itemViewTree.enable();
itemViewTree.show();
break;
case SimpleDownload:
itemSimpleDownloadResource.enable();
itemSimpleDownloadResource.show();
break;
case BulkDownload:
itemBulkDownloadResource.enable();
itemBulkDownloadResource.show();
break;
case Delete:
ImageResource delIcon = folderActionsEnabled ? Resources.ICONS.folderDelete()
: Resources.ICONS.fileDelete();
itemDeleteResource.setIcon(AbstractImagePrototype.create(delIcon));
itemDeleteResource.enable();
itemDeleteResource.show();
break;
case Metadata:
itemMetaData.enable();
itemMetaData.show();
break;
case Share:
itemShareResource.enable();
itemRenameResource.show();
break;
}
}
menuActions.showAt(x, y);
}
}
| public void showMenu(int x, int y) {
List<DiskResource> selected = getSelectionModel().getSelectedItems();
List<DataUtils.Action> actions = DataUtils.getSupportedActions(selected);
if (menuActions != null && actions.size() > 0) {
for (Component item : menuActions.getItems()) {
item.disable();
item.hide();
}
boolean folderActionsEnabled = DataUtils.hasFolders(selected);
if (folderActionsEnabled && selected.size() == 1) {
// Enable the "Add Folder" item as well.
itemAddFolder.enable();
itemAddFolder.show();
}
for (DataUtils.Action action : actions) {
switch (action) {
case RenameFolder:
itemRenameResource.setIcon(AbstractImagePrototype.create(Resources.ICONS
.folderRename()));
itemRenameResource.enable();
itemRenameResource.show();
break;
case RenameFile:
itemRenameResource.setIcon(AbstractImagePrototype.create(Resources.ICONS
.fileRename()));
itemRenameResource.enable();
itemRenameResource.show();
break;
case View:
itemViewResource.enable();
itemViewResource.show();
break;
case ViewTree:
itemViewTree.enable();
itemViewTree.show();
break;
case SimpleDownload:
itemSimpleDownloadResource.enable();
itemSimpleDownloadResource.show();
break;
case BulkDownload:
itemBulkDownloadResource.enable();
itemBulkDownloadResource.show();
break;
case Delete:
ImageResource delIcon = folderActionsEnabled ? Resources.ICONS.folderDelete()
: Resources.ICONS.fileDelete();
itemDeleteResource.setIcon(AbstractImagePrototype.create(delIcon));
itemDeleteResource.enable();
itemDeleteResource.show();
break;
case Metadata:
itemMetaData.enable();
itemMetaData.show();
break;
case Share:
itemShareResource.enable();
itemShareResource.show();
break;
}
}
menuActions.showAt(x, y);
}
}
|
diff --git a/src/main/java/org/mule/modules/morphia/QueryBuilder.java b/src/main/java/org/mule/modules/morphia/QueryBuilder.java
index 8e4a756..48cc115 100644
--- a/src/main/java/org/mule/modules/morphia/QueryBuilder.java
+++ b/src/main/java/org/mule/modules/morphia/QueryBuilder.java
@@ -1,138 +1,136 @@
/**
* Mule Morphia Connector
*
* Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.modules.morphia;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.query.Query;
import org.bson.types.ObjectId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class QueryBuilder {
private Query<?> query;
private Map<String, Object> filters;
private Integer offset;
private Integer limit;
private String order;
private List<String> fields;
private Boolean disableCursorTimeout;
private Boolean disableSnapshotMode;
private Boolean disableValidation;
private QueryBuilder(Datastore datastore, String className) throws ClassNotFoundException {
query = datastore.createQuery(Class.forName(className));
}
public static QueryBuilder newBuilder(Datastore datastore, String className) throws ClassNotFoundException {
return new QueryBuilder(datastore, className);
}
public QueryBuilder setFilters(Map<String, Object> filters) {
this.filters = filters;
return this;
}
public QueryBuilder addFilter(String key, Object value) {
if(filters == null) {
filters = new HashMap<String, Object>();
}
filters.put(key, value);
return this;
}
public QueryBuilder setOffset(Integer offset) {
this.offset = offset;
return this;
}
public QueryBuilder setLimit(Integer limit) {
this.limit = limit;
return this;
}
public QueryBuilder setOrder(String order) {
this.order = order;
return this;
}
public QueryBuilder setFields(List<String> fields) {
this.fields = fields;
return this;
}
public QueryBuilder addField(String field) {
if(fields == null) {
fields = new ArrayList<String>();
}
fields.add(field);
return this;
}
public QueryBuilder setDisableCursorTimeout(Boolean disableCursorTimeout) {
this.disableCursorTimeout = disableCursorTimeout;
return this;
}
public QueryBuilder setDisableSnapshotMode(Boolean disableSnapshotMode) {
this.disableSnapshotMode = disableSnapshotMode;
return this;
}
public QueryBuilder setDisableValidation(Boolean disableValidation) {
this.disableValidation = disableValidation;
return this;
}
public Query<?> getQuery() throws ClassNotFoundException {
if( disableCursorTimeout != null && disableValidation.booleanValue() ) {
query.disableCursorTimeout();
}
if( disableSnapshotMode != null && disableSnapshotMode.booleanValue() ) {
query.disableSnapshotMode();
}
if( disableValidation != null && disableValidation.booleanValue() ) {
query.disableValidation();
}
if (filters != null) {
addFilters(query, filters);
}
if (offset != null) {
query.offset(offset);
}
if (limit != null) {
query.limit(limit);
}
if (order != null) {
query.order(order);
}
if (fields != null) {
- for (String field : fields) {
- query.retrievedFields(true, field);
- }
+ query.retrievedFields(true, fields.toArray(new String[]{}));
}
return query;
}
private void addFilters(Query<?> query, Map<String, Object> filters) throws ClassNotFoundException {
for (String condition : filters.keySet()) {
query.filter(condition, filters.get(condition));
}
}
}
| true | true | public Query<?> getQuery() throws ClassNotFoundException {
if( disableCursorTimeout != null && disableValidation.booleanValue() ) {
query.disableCursorTimeout();
}
if( disableSnapshotMode != null && disableSnapshotMode.booleanValue() ) {
query.disableSnapshotMode();
}
if( disableValidation != null && disableValidation.booleanValue() ) {
query.disableValidation();
}
if (filters != null) {
addFilters(query, filters);
}
if (offset != null) {
query.offset(offset);
}
if (limit != null) {
query.limit(limit);
}
if (order != null) {
query.order(order);
}
if (fields != null) {
for (String field : fields) {
query.retrievedFields(true, field);
}
}
return query;
}
| public Query<?> getQuery() throws ClassNotFoundException {
if( disableCursorTimeout != null && disableValidation.booleanValue() ) {
query.disableCursorTimeout();
}
if( disableSnapshotMode != null && disableSnapshotMode.booleanValue() ) {
query.disableSnapshotMode();
}
if( disableValidation != null && disableValidation.booleanValue() ) {
query.disableValidation();
}
if (filters != null) {
addFilters(query, filters);
}
if (offset != null) {
query.offset(offset);
}
if (limit != null) {
query.limit(limit);
}
if (order != null) {
query.order(order);
}
if (fields != null) {
query.retrievedFields(true, fields.toArray(new String[]{}));
}
return query;
}
|
diff --git a/org.eclipse.xtext.xdoc/xtend-gen/org/eclipse/xtext/xdoc/generator/EclipseHelpUriUtil.java b/org.eclipse.xtext.xdoc/xtend-gen/org/eclipse/xtext/xdoc/generator/EclipseHelpUriUtil.java
index d225e9f..a0b7c1b 100644
--- a/org.eclipse.xtext.xdoc/xtend-gen/org/eclipse/xtext/xdoc/generator/EclipseHelpUriUtil.java
+++ b/org.eclipse.xtext.xdoc/xtend-gen/org/eclipse/xtext/xdoc/generator/EclipseHelpUriUtil.java
@@ -1,300 +1,324 @@
package org.eclipse.xtext.xdoc.generator;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Extension;
import org.eclipse.xtext.xbase.lib.InputOutput;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.ObjectExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import org.eclipse.xtext.xdoc.generator.util.EclipseNamingExtensions;
import org.eclipse.xtext.xdoc.xdoc.AbstractSection;
import org.eclipse.xtext.xdoc.xdoc.Chapter;
import org.eclipse.xtext.xdoc.xdoc.ChapterRef;
import org.eclipse.xtext.xdoc.xdoc.Document;
import org.eclipse.xtext.xdoc.xdoc.Identifiable;
import org.eclipse.xtext.xdoc.xdoc.ImageRef;
import org.eclipse.xtext.xdoc.xdoc.Part;
import org.eclipse.xtext.xdoc.xdoc.PartRef;
import org.eclipse.xtext.xdoc.xdoc.Ref;
import org.eclipse.xtext.xdoc.xdoc.Section;
import org.eclipse.xtext.xdoc.xdoc.Section2;
import org.eclipse.xtext.xdoc.xdoc.Section2Ref;
import org.eclipse.xtext.xdoc.xdoc.SectionRef;
@SuppressWarnings("all")
public class EclipseHelpUriUtil {
@Inject
@Extension
private EclipseNamingExtensions eclipseNamingExtensions;
private Map<AbstractSection,AbstractSection> section2fileSection;
private Document doc;
public void initialize(final Document doc) {
HashMap<AbstractSection,AbstractSection> _newHashMap = CollectionLiterals.<AbstractSection, AbstractSection>newHashMap();
this.section2fileSection = _newHashMap;
this.doc = doc;
this.populateFileMap(doc);
}
public URI getAbsoluteTargetURI(final ImageRef img) {
URI _xblockexpression = null;
{
final AbstractSection container = EcoreUtil2.<AbstractSection>getContainerOfType(img, AbstractSection.class);
final AbstractSection fileSection = this.section2fileSection.get(container);
URI _relativeTargetURI = this.getRelativeTargetURI(img);
URI _targetURI = this.getTargetURI(fileSection);
URI _resolve = _relativeTargetURI.resolve(_targetURI);
_xblockexpression = (_resolve);
}
return _xblockexpression;
}
public URI getRelativeTargetURI(final ImageRef img) {
URI _xblockexpression = null;
{
String _path = img.getPath();
URI _createURI = URI.createURI(_path);
Resource _eResource = img.eResource();
URI _uRI = _eResource.getURI();
final URI imageAbsoluteURI = _createURI.resolve(_uRI);
Resource _eResource_1 = this.doc.eResource();
URI _uRI_1 = _eResource_1.getURI();
URI _deresolve = imageAbsoluteURI.deresolve(_uRI_1);
_xblockexpression = (_deresolve);
}
return _xblockexpression;
}
public URI getTargetURI(final Ref it) {
URI _xblockexpression = null;
{
Identifiable _ref = it.getRef();
final AbstractSection container = EcoreUtil2.<AbstractSection>getContainerOfType(_ref, AbstractSection.class);
final AbstractSection fileSection = this.section2fileSection.get(container);
URI _xifexpression = null;
boolean _equals = ObjectExtensions.operator_equals(fileSection, null);
if (_equals) {
URI _xblockexpression_1 = null;
{
Identifiable _ref_1 = it.getRef();
String _name = _ref_1.getName();
String _plus = ("error: Cannot resolve reference to " + _name);
String _plus_1 = (_plus + " from ");
Identifiable _ref_2 = it.getRef();
Resource _eResource = _ref_2.eResource();
URI _uRI = _eResource.getURI();
String _plus_2 = (_plus_1 + _uRI);
InputOutput.<String>println(_plus_2);
_xblockexpression_1 = (((URI) null));
}
_xifexpression = _xblockexpression_1;
} else {
URI _targetURI = this.getTargetURI(fileSection);
Identifiable _ref_1 = it.getRef();
String _localId = this.eclipseNamingExtensions.getLocalId(_ref_1);
URI _appendFragment = _targetURI.appendFragment(_localId);
URI _targetURI_1 = this.getTargetURI(this.doc);
URI _deresolve = _appendFragment.deresolve(_targetURI_1);
_xifexpression = _deresolve;
}
_xblockexpression = (_xifexpression);
}
return _xblockexpression;
}
public URI getTargetURI(final AbstractSection it) {
URI _switchResult = null;
boolean _matched = false;
if (!_matched) {
if (it instanceof PartRef) {
final PartRef _partRef = (PartRef)it;
_matched=true;
Part _part = _partRef.getPart();
URI _targetURI = this.getTargetURI(_part);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof ChapterRef) {
final ChapterRef _chapterRef = (ChapterRef)it;
_matched=true;
Chapter _chapter = _chapterRef.getChapter();
URI _targetURI = this.getTargetURI(_chapter);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof SectionRef) {
final SectionRef _sectionRef = (SectionRef)it;
_matched=true;
Section _section = _sectionRef.getSection();
URI _targetURI = this.getTargetURI(_section);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof Section2Ref) {
final Section2Ref _section2Ref = (Section2Ref)it;
_matched=true;
Section2 _section2 = _section2Ref.getSection2();
URI _targetURI = this.getTargetURI(_section2);
_switchResult = _targetURI;
}
}
if (!_matched) {
+ if (it instanceof Part) {
+ final Part _part = (Part)it;
+ _matched=true;
+ URI _targetURI = this.targetURI(((Identifiable) _part));
+ _switchResult = _targetURI;
+ }
+ }
+ if (!_matched) {
+ if (it instanceof Chapter) {
+ final Chapter _chapter = (Chapter)it;
+ _matched=true;
+ URI _targetURI = this.targetURI(((Identifiable) _chapter));
+ _switchResult = _targetURI;
+ }
+ }
+ if (!_matched) {
+ if (it instanceof Document) {
+ final Document _document = (Document)it;
+ _matched=true;
+ URI _targetURI = this.targetURI(((Identifiable) _document));
+ _switchResult = _targetURI;
+ }
+ }
+ if (!_matched) {
URI _xblockexpression = null;
{
final AbstractSection container = EcoreUtil2.<AbstractSection>getContainerOfType(it, AbstractSection.class);
final AbstractSection fileSection = this.section2fileSection.get(container);
URI _targetURI = this.getTargetURI(fileSection);
String _localId = this.eclipseNamingExtensions.getLocalId(it);
URI _appendFragment = _targetURI.appendFragment(_localId);
URI _targetURI_1 = this.getTargetURI(this.doc);
URI _deresolve = _appendFragment.deresolve(_targetURI_1);
_xblockexpression = (_deresolve);
}
_switchResult = _xblockexpression;
}
return _switchResult;
}
protected void _populateFileMap(final Document it) {
this.section2fileSection.put(it, it);
EList<Chapter> _chapters = it.getChapters();
final Procedure1<Chapter> _function = new Procedure1<Chapter>() {
public void apply(final Chapter it) {
EclipseHelpUriUtil.this.populateFileMap(it);
}
};
IterableExtensions.<Chapter>forEach(_chapters, _function);
EList<Part> _parts = it.getParts();
final Procedure1<Part> _function_1 = new Procedure1<Part>() {
public void apply(final Part it) {
EclipseHelpUriUtil.this.populateFileMap(it);
}
};
IterableExtensions.<Part>forEach(_parts, _function_1);
}
protected void _populateFileMap(final Chapter it) {
this.section2fileSection.put(it, it);
EList<Section> _subSections = it.getSubSections();
final Procedure1<Section> _function = new Procedure1<Section>() {
public void apply(final Section section) {
EclipseHelpUriUtil.this.populateFileMap(section, it);
}
};
IterableExtensions.<Section>forEach(_subSections, _function);
}
protected void _populateFileMap(final ChapterRef it) {
Chapter _chapter = it.getChapter();
this.populateFileMap(_chapter);
}
protected void _populateFileMap(final Part it) {
this.section2fileSection.put(it, it);
EList<Chapter> _chapters = it.getChapters();
final Procedure1<Chapter> _function = new Procedure1<Chapter>() {
public void apply(final Chapter chapter) {
EclipseHelpUriUtil.this.populateFileMap(chapter);
}
};
IterableExtensions.<Chapter>forEach(_chapters, _function);
}
protected void _populateFileMap(final PartRef it) {
Part _part = it.getPart();
this.populateFileMap(_part);
}
protected void _populateFileMap(final AbstractSection it, final AbstractSection fileSection) {
this.section2fileSection.put(it, fileSection);
EList<EObject> _eContents = it.eContents();
Iterable<AbstractSection> _filter = Iterables.<AbstractSection>filter(_eContents, AbstractSection.class);
final Procedure1<AbstractSection> _function = new Procedure1<AbstractSection>() {
public void apply(final AbstractSection section) {
EclipseHelpUriUtil.this.populateFileMap(section, fileSection);
}
};
IterableExtensions.<AbstractSection>forEach(_filter, _function);
}
protected void _populateFileMap(final Section2Ref it, final AbstractSection fileSection) {
Section2 _section2 = it.getSection2();
this.populateFileMap(_section2, fileSection);
}
protected void _populateFileMap(final SectionRef it, final AbstractSection fileSection) {
Section _section = it.getSection();
this.populateFileMap(_section, fileSection);
}
private URI targetURI(final Identifiable it) {
URI _xblockexpression = null;
{
Resource _eResource = it.eResource();
final URI resourceURI = _eResource.getURI();
String _fullURL = this.eclipseNamingExtensions.getFullURL(it);
final URI fullURL = URI.createURI(_fullURL);
int _segmentCount = resourceURI.segmentCount();
int _minus = (_segmentCount - 2);
URI _trimSegments = resourceURI.trimSegments(_minus);
URI _appendSegment = _trimSegments.appendSegment("contents");
String[] _segments = fullURL.segments();
URI _appendSegments = _appendSegment.appendSegments(_segments);
_xblockexpression = (_appendSegments);
}
return _xblockexpression;
}
public void populateFileMap(final AbstractSection it) {
if (it instanceof ChapterRef) {
_populateFileMap((ChapterRef)it);
return;
} else if (it instanceof PartRef) {
_populateFileMap((PartRef)it);
return;
} else if (it instanceof Chapter) {
_populateFileMap((Chapter)it);
return;
} else if (it instanceof Document) {
_populateFileMap((Document)it);
return;
} else if (it instanceof Part) {
_populateFileMap((Part)it);
return;
} else {
throw new IllegalArgumentException("Unhandled parameter types: " +
Arrays.<Object>asList(it).toString());
}
}
public void populateFileMap(final AbstractSection it, final AbstractSection fileSection) {
if (it instanceof Section2Ref) {
_populateFileMap((Section2Ref)it, fileSection);
return;
} else if (it instanceof SectionRef) {
_populateFileMap((SectionRef)it, fileSection);
return;
} else if (it != null) {
_populateFileMap(it, fileSection);
return;
} else {
throw new IllegalArgumentException("Unhandled parameter types: " +
Arrays.<Object>asList(it, fileSection).toString());
}
}
}
| true | true | public URI getTargetURI(final AbstractSection it) {
URI _switchResult = null;
boolean _matched = false;
if (!_matched) {
if (it instanceof PartRef) {
final PartRef _partRef = (PartRef)it;
_matched=true;
Part _part = _partRef.getPart();
URI _targetURI = this.getTargetURI(_part);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof ChapterRef) {
final ChapterRef _chapterRef = (ChapterRef)it;
_matched=true;
Chapter _chapter = _chapterRef.getChapter();
URI _targetURI = this.getTargetURI(_chapter);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof SectionRef) {
final SectionRef _sectionRef = (SectionRef)it;
_matched=true;
Section _section = _sectionRef.getSection();
URI _targetURI = this.getTargetURI(_section);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof Section2Ref) {
final Section2Ref _section2Ref = (Section2Ref)it;
_matched=true;
Section2 _section2 = _section2Ref.getSection2();
URI _targetURI = this.getTargetURI(_section2);
_switchResult = _targetURI;
}
}
if (!_matched) {
URI _xblockexpression = null;
{
final AbstractSection container = EcoreUtil2.<AbstractSection>getContainerOfType(it, AbstractSection.class);
final AbstractSection fileSection = this.section2fileSection.get(container);
URI _targetURI = this.getTargetURI(fileSection);
String _localId = this.eclipseNamingExtensions.getLocalId(it);
URI _appendFragment = _targetURI.appendFragment(_localId);
URI _targetURI_1 = this.getTargetURI(this.doc);
URI _deresolve = _appendFragment.deresolve(_targetURI_1);
_xblockexpression = (_deresolve);
}
_switchResult = _xblockexpression;
}
return _switchResult;
}
| public URI getTargetURI(final AbstractSection it) {
URI _switchResult = null;
boolean _matched = false;
if (!_matched) {
if (it instanceof PartRef) {
final PartRef _partRef = (PartRef)it;
_matched=true;
Part _part = _partRef.getPart();
URI _targetURI = this.getTargetURI(_part);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof ChapterRef) {
final ChapterRef _chapterRef = (ChapterRef)it;
_matched=true;
Chapter _chapter = _chapterRef.getChapter();
URI _targetURI = this.getTargetURI(_chapter);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof SectionRef) {
final SectionRef _sectionRef = (SectionRef)it;
_matched=true;
Section _section = _sectionRef.getSection();
URI _targetURI = this.getTargetURI(_section);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof Section2Ref) {
final Section2Ref _section2Ref = (Section2Ref)it;
_matched=true;
Section2 _section2 = _section2Ref.getSection2();
URI _targetURI = this.getTargetURI(_section2);
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof Part) {
final Part _part = (Part)it;
_matched=true;
URI _targetURI = this.targetURI(((Identifiable) _part));
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof Chapter) {
final Chapter _chapter = (Chapter)it;
_matched=true;
URI _targetURI = this.targetURI(((Identifiable) _chapter));
_switchResult = _targetURI;
}
}
if (!_matched) {
if (it instanceof Document) {
final Document _document = (Document)it;
_matched=true;
URI _targetURI = this.targetURI(((Identifiable) _document));
_switchResult = _targetURI;
}
}
if (!_matched) {
URI _xblockexpression = null;
{
final AbstractSection container = EcoreUtil2.<AbstractSection>getContainerOfType(it, AbstractSection.class);
final AbstractSection fileSection = this.section2fileSection.get(container);
URI _targetURI = this.getTargetURI(fileSection);
String _localId = this.eclipseNamingExtensions.getLocalId(it);
URI _appendFragment = _targetURI.appendFragment(_localId);
URI _targetURI_1 = this.getTargetURI(this.doc);
URI _deresolve = _appendFragment.deresolve(_targetURI_1);
_xblockexpression = (_deresolve);
}
_switchResult = _xblockexpression;
}
return _switchResult;
}
|
diff --git a/proxytoys/website/src/java/minimesh/LinkChecker.java b/proxytoys/website/src/java/minimesh/LinkChecker.java
index 7519a57..06e025d 100644
--- a/proxytoys/website/src/java/minimesh/LinkChecker.java
+++ b/proxytoys/website/src/java/minimesh/LinkChecker.java
@@ -1,85 +1,85 @@
package minimesh;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
/**
* Verifies all the links in a SiteMap.
*
* @author Joe Walnes
*/
public class LinkChecker {
private final Collection knownPageFileNames;
private final SiteMap siteMap;
private final Reporter reporter;
/**
* Callback for errors.
*/
public static interface Reporter {
void badLink(Page page, String link);
}
public LinkChecker(SiteMap siteMap, Reporter reporter) {
this.siteMap = siteMap;
this.reporter = reporter;
knownPageFileNames = new HashSet();
List allPages = siteMap.getAllPages();
for (Iterator iterator = allPages.iterator(); iterator.hasNext();) {
Page page = (Page)iterator.next();
knownPageFileNames.add(page.getFilename());
}
}
/**
* Verifies all the links in the site. Returns true if all links are valid.
*
* @return
*/
public boolean verify() {
boolean success = true;
List allPages = siteMap.getAllPages();
for (Iterator iterator = allPages.iterator(); iterator.hasNext();) {
Page page = (Page)iterator.next();
Collection links = page.getLinks();
for (Iterator iterator1 = links.iterator(); iterator1.hasNext();) {
String link = (String)iterator1.next();
if (!verifyLink(link)) {
success = false;
reporter.badLink(page, link);
}
}
}
return success;
}
protected boolean verifyLink(String link) {
if (link.startsWith("mailto:")) {
// todo: valid email addresses should be configurable
return true;
} else if (link.startsWith("http://")) {
// todo: HTTP get this address to check it's valid (cache result)
return true;
} else if (link.startsWith("nntp://")) {
// todo: News get this address to check it's valid (cache result)
return true;
- } else if (link.startsWith("javadoc/")) {
+ } else if (link.startsWith("apidocs/")) {
// todo: Check the class is valid
return true;
} else {
if (link.lastIndexOf('#') > 0) {
// todo: Check anchors
link = link.substring(0, link.lastIndexOf('#'));
}
if (knownPageFileNames.contains(link)) {
return true;
}
}
return false;
}
}
| true | true | protected boolean verifyLink(String link) {
if (link.startsWith("mailto:")) {
// todo: valid email addresses should be configurable
return true;
} else if (link.startsWith("http://")) {
// todo: HTTP get this address to check it's valid (cache result)
return true;
} else if (link.startsWith("nntp://")) {
// todo: News get this address to check it's valid (cache result)
return true;
} else if (link.startsWith("javadoc/")) {
// todo: Check the class is valid
return true;
} else {
if (link.lastIndexOf('#') > 0) {
// todo: Check anchors
link = link.substring(0, link.lastIndexOf('#'));
}
if (knownPageFileNames.contains(link)) {
return true;
}
}
return false;
}
| protected boolean verifyLink(String link) {
if (link.startsWith("mailto:")) {
// todo: valid email addresses should be configurable
return true;
} else if (link.startsWith("http://")) {
// todo: HTTP get this address to check it's valid (cache result)
return true;
} else if (link.startsWith("nntp://")) {
// todo: News get this address to check it's valid (cache result)
return true;
} else if (link.startsWith("apidocs/")) {
// todo: Check the class is valid
return true;
} else {
if (link.lastIndexOf('#') > 0) {
// todo: Check anchors
link = link.substring(0, link.lastIndexOf('#'));
}
if (knownPageFileNames.contains(link)) {
return true;
}
}
return false;
}
|
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/metamodel/MetamodelTest.java b/test/src/com/redhat/ceylon/compiler/java/test/metamodel/MetamodelTest.java
index ff408c193..f6b8ffe61 100755
--- a/test/src/com/redhat/ceylon/compiler/java/test/metamodel/MetamodelTest.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/metamodel/MetamodelTest.java
@@ -1,126 +1,126 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.metamodel;
import org.junit.Test;
import com.redhat.ceylon.compiler.java.test.CompilerError;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
public class MetamodelTest extends CompilerTest {
@Override
protected ModuleWithArtifact getDestModuleWithArtifact(){
return new ModuleWithArtifact("com.redhat.ceylon.compiler.java.test.metamodel", "123");
}
@Test
public void testRuntime() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.runtime", "runtime.ceylon", "types.ceylon", "visitor.ceylon");
}
@Test
public void testInteropRuntime() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.interopRuntime", "interopRuntime.ceylon", "JavaType.java");
}
@Test
public void testAnnotations() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.annotationTests", "annotationTypes.ceylon", "annotationTests.ceylon");
}
@Test
public void testTypeLiterals() {
compareWithJavaSource("Literals");
}
@Test
public void testTypeLiteralRuntime() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.literalsRuntime", "Literals.ceylon", "literalsRuntime.ceylon");
}
@Test
public void testBugCL238() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug238", "bug238.ceylon");
}
@Test
public void testBugCL245() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug245", "bug245.ceylon");
}
@Test
public void testBugCL257() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug257", "bug257.ceylon");
}
@Test
public void testBugCL258() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug258", "bug258.ceylon");
}
@Test
public void testBugCL263() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug263", "bug263.ceylon");
}
@Test
public void testBug1196() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug1196test", "bug1196.ceylon");
}
@Test
public void testBug1197() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug1197", "bug1197.ceylon");
}
@Test
public void testBug1198() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug1198", "bug1198.ceylon");
}
@Test
public void testBug1199() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug1199", "bug1199.ceylon");
}
@Test
public void testBug1201() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug1201", "bug1201.ceylon");
}
@Test
public void testBug1209() {
assertErrors("bug1209",
- new CompilerError(3, "metamodel references to local values not supported")
+ new CompilerError(3, "metamodel reference to local value")
);
}
@Test
public void testBug1205() {
compareWithJavaSource("bug1205");
}
@Test
public void testBug1210() {
compileAndRun("com.redhat.ceylon.compiler.java.test.metamodel.bug1210", "bug1210.ceylon");
}
}
| true | true | public void testBug1209() {
assertErrors("bug1209",
new CompilerError(3, "metamodel references to local values not supported")
);
}
| public void testBug1209() {
assertErrors("bug1209",
new CompilerError(3, "metamodel reference to local value")
);
}
|
diff --git a/src/com/android/gallery3d/ui/DialogDetailsView.java b/src/com/android/gallery3d/ui/DialogDetailsView.java
index 07ebc3c..adc9de1 100644
--- a/src/com/android/gallery3d/ui/DialogDetailsView.java
+++ b/src/com/android/gallery3d/ui/DialogDetailsView.java
@@ -1,250 +1,250 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.ui;
import static com.android.gallery3d.ui.DetailsWindowConfig.FONT_SIZE;
import static com.android.gallery3d.ui.DetailsWindowConfig.LEFT_RIGHT_EXTRA_PADDING;
import static com.android.gallery3d.ui.DetailsWindowConfig.LINE_SPACING;
import static com.android.gallery3d.ui.DetailsWindowConfig.PREFERRED_WIDTH;
import static com.android.gallery3d.ui.DetailsWindowConfig.TOP_BOTTOM_EXTRA_PADDING;
import com.android.gallery3d.R;
import com.android.gallery3d.app.GalleryActivity;
import com.android.gallery3d.common.Utils;
import com.android.gallery3d.data.MediaDetails;
import com.android.gallery3d.ui.DetailsAddressResolver.AddressResolvingListener;
import com.android.gallery3d.ui.DetailsHelper.CloseListener;
import com.android.gallery3d.ui.DetailsHelper.DetailsViewContainer;
import com.android.gallery3d.ui.DetailsHelper.DetailsSource;
import com.android.gallery3d.util.Future;
import com.android.gallery3d.util.FutureListener;
import com.android.gallery3d.util.GalleryUtils;
import com.android.gallery3d.util.ReverseGeocoder;
import com.android.gallery3d.util.ThreadPool.Job;
import com.android.gallery3d.util.ThreadPool.JobContext;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.graphics.Rect;
import android.location.Address;
import android.os.Handler;
import android.os.Message;
import android.text.format.Formatter;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Map.Entry;
public class DialogDetailsView implements DetailsViewContainer {
@SuppressWarnings("unused")
private static final String TAG = "DialogDetailsView";
private GalleryActivity mContext;
private DetailsAdapter mAdapter;
private MediaDetails mDetails;
private DetailsSource mSource;
private int mIndex;
private Dialog mDialog;
private int mLocationIndex;
private CloseListener mListener;
public DialogDetailsView(GalleryActivity activity, DetailsSource source) {
mContext = activity;
mSource = source;
}
public void show() {
reloadDetails(mSource.getIndex());
mDialog.show();
}
public void hide() {
mDialog.hide();
}
public void reloadDetails(int indexHint) {
int index = mSource.findIndex(indexHint);
if (index == -1) return;
MediaDetails details = mSource.getDetails();
if (details != null) {
if (mIndex == index && mDetails == details) return;
mIndex = index;
mDetails = details;
setDetails(details);
}
}
public boolean isVisible() {
return mDialog.isShowing();
}
private void setDetails(MediaDetails details) {
mAdapter = new DetailsAdapter(details);
String title = String.format(
mContext.getAndroidContext().getString(R.string.details_title),
mIndex + 1, mSource.size());
mDialog = new AlertDialog.Builder((Activity) mContext)
.setAdapter(mAdapter, null)
.setTitle(title)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mDialog.dismiss();
}
})
.create();
mDialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
if (mListener != null) {
mListener.onClose();
}
}
});
}
private class DetailsAdapter extends BaseAdapter implements AddressResolvingListener {
private ArrayList<String> mItems;
public DetailsAdapter(MediaDetails details) {
Context context = mContext.getAndroidContext();
mItems = new ArrayList<String>(details.size());
mLocationIndex = -1;
setDetails(context, details);
}
private void setDetails(Context context, MediaDetails details) {
for (Entry<Integer, Object> detail : details) {
String value;
switch (detail.getKey()) {
case MediaDetails.INDEX_LOCATION: {
double[] latlng = (double[]) detail.getValue();
mLocationIndex = mItems.size();
- value = DetailsHelper.resolveAddress(mContext, latlng, mAdapter);
+ value = DetailsHelper.resolveAddress(mContext, latlng, this);
break;
}
case MediaDetails.INDEX_SIZE: {
value = Formatter.formatFileSize(
context, (Long) detail.getValue());
break;
}
case MediaDetails.INDEX_WHITE_BALANCE: {
value = "1".equals(detail.getValue())
? context.getString(R.string.manual)
: context.getString(R.string.auto);
break;
}
case MediaDetails.INDEX_FLASH: {
MediaDetails.FlashState flash =
(MediaDetails.FlashState) detail.getValue();
// TODO: camera doesn't fill in the complete values, show more information
// when it is fixed.
if (flash.isFlashFired()) {
value = context.getString(R.string.flash_on);
} else {
value = context.getString(R.string.flash_off);
}
break;
}
case MediaDetails.INDEX_EXPOSURE_TIME: {
value = (String) detail.getValue();
double time = Double.valueOf(value);
if (time < 1.0f) {
value = String.format("1/%d", (int) (0.5f + 1 / time));
} else {
int integer = (int) time;
time -= integer;
value = String.valueOf(integer) + "''";
if (time > 0.0001) {
value += String.format(" 1/%d", (int) (0.5f + 1 / time));
}
}
break;
}
default: {
Object valueObj = detail.getValue();
// This shouldn't happen, log its key to help us diagnose the problem.
Utils.assertTrue(valueObj != null, "%s's value is Null",
DetailsHelper.getDetailsName(context, detail.getKey()));
value = valueObj.toString();
}
}
int key = detail.getKey();
if (details.hasUnit(key)) {
value = String.format("%s : %s %s", DetailsHelper.getDetailsName(
context, key), value, context.getString(details.getUnit(key)));
} else {
value = String.format("%s : %s", DetailsHelper.getDetailsName(
context, key), value);
}
mItems.add(value);
}
}
public boolean areAllItemsEnabled() {
return false;
}
public boolean isEnabled(int position) {
return false;
}
public int getCount() {
return mItems.size();
}
public Object getItem(int position) {
return mDetails.getDetail(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = (TextView) LayoutInflater.from(mContext.getAndroidContext()).inflate(
R.layout.details, parent, false);
} else {
tv = (TextView) convertView;
}
tv.setText(mItems.get(position));
return tv;
}
public void onAddressAvailable(String address) {
mItems.set(mLocationIndex, address);
}
}
public void setCloseListener(CloseListener listener) {
mListener = listener;
}
}
| true | true | private void setDetails(Context context, MediaDetails details) {
for (Entry<Integer, Object> detail : details) {
String value;
switch (detail.getKey()) {
case MediaDetails.INDEX_LOCATION: {
double[] latlng = (double[]) detail.getValue();
mLocationIndex = mItems.size();
value = DetailsHelper.resolveAddress(mContext, latlng, mAdapter);
break;
}
case MediaDetails.INDEX_SIZE: {
value = Formatter.formatFileSize(
context, (Long) detail.getValue());
break;
}
case MediaDetails.INDEX_WHITE_BALANCE: {
value = "1".equals(detail.getValue())
? context.getString(R.string.manual)
: context.getString(R.string.auto);
break;
}
case MediaDetails.INDEX_FLASH: {
MediaDetails.FlashState flash =
(MediaDetails.FlashState) detail.getValue();
// TODO: camera doesn't fill in the complete values, show more information
// when it is fixed.
if (flash.isFlashFired()) {
value = context.getString(R.string.flash_on);
} else {
value = context.getString(R.string.flash_off);
}
break;
}
case MediaDetails.INDEX_EXPOSURE_TIME: {
value = (String) detail.getValue();
double time = Double.valueOf(value);
if (time < 1.0f) {
value = String.format("1/%d", (int) (0.5f + 1 / time));
} else {
int integer = (int) time;
time -= integer;
value = String.valueOf(integer) + "''";
if (time > 0.0001) {
value += String.format(" 1/%d", (int) (0.5f + 1 / time));
}
}
break;
}
default: {
Object valueObj = detail.getValue();
// This shouldn't happen, log its key to help us diagnose the problem.
Utils.assertTrue(valueObj != null, "%s's value is Null",
DetailsHelper.getDetailsName(context, detail.getKey()));
value = valueObj.toString();
}
}
int key = detail.getKey();
if (details.hasUnit(key)) {
value = String.format("%s : %s %s", DetailsHelper.getDetailsName(
context, key), value, context.getString(details.getUnit(key)));
} else {
value = String.format("%s : %s", DetailsHelper.getDetailsName(
context, key), value);
}
mItems.add(value);
}
}
| private void setDetails(Context context, MediaDetails details) {
for (Entry<Integer, Object> detail : details) {
String value;
switch (detail.getKey()) {
case MediaDetails.INDEX_LOCATION: {
double[] latlng = (double[]) detail.getValue();
mLocationIndex = mItems.size();
value = DetailsHelper.resolveAddress(mContext, latlng, this);
break;
}
case MediaDetails.INDEX_SIZE: {
value = Formatter.formatFileSize(
context, (Long) detail.getValue());
break;
}
case MediaDetails.INDEX_WHITE_BALANCE: {
value = "1".equals(detail.getValue())
? context.getString(R.string.manual)
: context.getString(R.string.auto);
break;
}
case MediaDetails.INDEX_FLASH: {
MediaDetails.FlashState flash =
(MediaDetails.FlashState) detail.getValue();
// TODO: camera doesn't fill in the complete values, show more information
// when it is fixed.
if (flash.isFlashFired()) {
value = context.getString(R.string.flash_on);
} else {
value = context.getString(R.string.flash_off);
}
break;
}
case MediaDetails.INDEX_EXPOSURE_TIME: {
value = (String) detail.getValue();
double time = Double.valueOf(value);
if (time < 1.0f) {
value = String.format("1/%d", (int) (0.5f + 1 / time));
} else {
int integer = (int) time;
time -= integer;
value = String.valueOf(integer) + "''";
if (time > 0.0001) {
value += String.format(" 1/%d", (int) (0.5f + 1 / time));
}
}
break;
}
default: {
Object valueObj = detail.getValue();
// This shouldn't happen, log its key to help us diagnose the problem.
Utils.assertTrue(valueObj != null, "%s's value is Null",
DetailsHelper.getDetailsName(context, detail.getKey()));
value = valueObj.toString();
}
}
int key = detail.getKey();
if (details.hasUnit(key)) {
value = String.format("%s : %s %s", DetailsHelper.getDetailsName(
context, key), value, context.getString(details.getUnit(key)));
} else {
value = String.format("%s : %s", DetailsHelper.getDetailsName(
context, key), value);
}
mItems.add(value);
}
}
|
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/MetaDataPopulator.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/MetaDataPopulator.java
index e21769e01..728704ffe 100644
--- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/MetaDataPopulator.java
+++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/MetaDataPopulator.java
@@ -1,401 +1,399 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* 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 API and implementation
*******************************************************************************/
package org.eclipse.birt.report.data.adapter.impl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IResultMetaData;
import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil;
import org.eclipse.birt.report.model.api.ColumnHintHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.JointDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.ScriptDataSetHandle;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
import org.eclipse.birt.report.model.api.elements.structures.ResultSetColumn;
/**
* Retrieve metaData from resultset property.
*
*/
public class MetaDataPopulator
{
private static final char RENAME_SEPARATOR = '_';//$NON-NLS-1$
private static final String UNNAME_PREFIX = "UNNAMED"; //$NON-NLS-1$
/**
* populate all output columns in viewer display. The output columns is
* retrieved from oda dataset handles's RESULT_SET_PROP and
* COMPUTED_COLUMNS_PROP.
*
* @throws BirtException
*/
public static IResultMetaData retrieveResultMetaData(
DataSetHandle dataSetHandle ) throws BirtException
{
List resultSetList = null;
if ( dataSetHandle instanceof OdaDataSetHandle )
{
PropertyHandle handle = dataSetHandle.getPropertyHandle( OdaDataSetHandle.RESULT_SET_PROP );
- if ( handle.isLocal( ) )
- resultSetList = handle.getListValue( );
+ resultSetList = handle.getListValue( );
}
else if ( dataSetHandle instanceof ScriptDataSetHandle )
{
PropertyHandle handle = dataSetHandle.getPropertyHandle( DataSetHandle.RESULT_SET_HINTS_PROP );
- if ( handle.isLocal( ) )
- resultSetList = handle.getListValue( );
+ resultSetList = handle.getListValue( );
}
else
{
return null;
}
List computedList = (List) dataSetHandle.getProperty( OdaDataSetHandle.COMPUTED_COLUMNS_PROP );
List columnMeta = new ArrayList( );
ResultSetColumnDefinition columnDef;
int count = 0;
// populate result set columns
if ( resultSetList != null && !resultSetList.isEmpty( ) )
{
ResultSetColumn resultSetColumn;
HashSet orgColumnNameSet = new HashSet( );
HashSet uniqueColumnNameSet = new HashSet( );
for ( int n = 0; n < resultSetList.size( ); n++ )
{
orgColumnNameSet.add( ( (ResultSetColumn) resultSetList.get( n ) ).getColumnName( ) );
}
for ( int i = 0; i < resultSetList.size( ); i++ )
{
resultSetColumn = (ResultSetColumn) resultSetList.get( i );
String columnName = resultSetColumn.getColumnName( );
String uniqueColumnName = getUniqueName( orgColumnNameSet,
uniqueColumnNameSet,
columnName,
i );
uniqueColumnNameSet.add( uniqueColumnName );
if ( !uniqueColumnName.equals( columnName ) )
{
updateModelColumn( dataSetHandle, uniqueColumnName, i + 1 );
}
columnDef = new ResultSetColumnDefinition( uniqueColumnName );
columnDef.setDataTypeName( resultSetColumn.getDataType( ) );
columnDef.setDataType( DataAdapterUtil.adaptModelDataType( resultSetColumn.getDataType( ) ) );
if ( resultSetColumn.getPosition( ) != null )
columnDef.setColumnPosition( resultSetColumn.getPosition( )
.intValue( ) );
if ( resultSetColumn.getNativeDataType( ) != null )
columnDef.setNativeDataType( resultSetColumn.getNativeDataType( )
.intValue( ) );
if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null )
{
ColumnHintHandle columnHint = findColumnHint( dataSetHandle,
uniqueColumnName );
columnDef.setAlias( columnHint.getAlias( ) );
columnDef.setLableName( columnHint.getDisplayName( ) );
}
columnDef.setComputedColumn( false );
columnMeta.add( columnDef );
}
count += resultSetList.size( );
// populate computed columns
if ( computedList != null )
{
for ( int n = 0; n < computedList.size( ); n++ )
{
orgColumnNameSet.add( ( (ComputedColumn) computedList.get( n ) ).getName( ) );
}
ComputedColumn computedColumn;
for ( int i = 0; i < computedList.size( ); i++ )
{
computedColumn = (ComputedColumn) computedList.get( i );
String columnName = computedColumn.getName( );
String uniqueColumnName = getUniqueName( orgColumnNameSet,
uniqueColumnNameSet,
columnName,
i + count );
uniqueColumnNameSet.add( uniqueColumnName );
if ( !uniqueColumnName.equals( columnName ) )
{
updateComputedColumn( dataSetHandle, uniqueColumnName, columnName );
}
columnDef = new ResultSetColumnDefinition( uniqueColumnName );
columnDef.setDataTypeName( computedColumn.getDataType( ) );
columnDef.setDataType( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelDataType( computedColumn.getDataType( ) ) );
if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null )
{
ColumnHintHandle columnHint = findColumnHint( dataSetHandle,
uniqueColumnName );
columnDef.setAlias( columnHint.getAlias( ) );
columnDef.setLableName( columnHint.getDisplayName( ) );
}
columnDef.setComputedColumn( true );
columnMeta.add( columnDef );
}
}
return new ResultMetaData2( columnMeta );
}
return null;
}
/**
* find column hint according to the columnName
*
* @param columnName
* @return
*/
private static ColumnHintHandle findColumnHint( DataSetHandle dataSetHandle, String columnName )
{
Iterator columnHintIter = dataSetHandle.columnHintsIterator( );
if ( columnHintIter != null )
{
while ( columnHintIter.hasNext( ) )
{
ColumnHintHandle modelColumnHint = (ColumnHintHandle) columnHintIter.next( );
if ( modelColumnHint.getColumnName( ).equals( columnName ) )
return modelColumnHint;
}
}
return null;
}
/**
* Whether need to use resultHint, which stands for resultSetHint,
* columnHint or both
*
* @param dataSetHandle
* @return
* @throws BirtException
*/
public static boolean needsUseResultHint( DataSetHandle dataSetHandle,
IResultMetaData metaData ) throws BirtException
{
boolean hasResultSetHint = false;
boolean hasColumnHint = false;
PropertyHandle handle = dataSetHandle.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP );
if ( handle != null )
hasColumnHint = handle.iterator( ).hasNext( );
hasResultSetHint = populateResultsetHint( dataSetHandle, metaData );
if ( !hasResultSetHint )
{
hasResultSetHint = checkHandleType( dataSetHandle );
}
return hasResultSetHint || hasColumnHint;
}
/**
*
* @param dataSetHandle
* @param metaData
* @param columnCount
* @param hasResultSetHint
* @return
* @throws BirtException
*/
private static boolean populateResultsetHint( DataSetHandle dataSetHandle,
IResultMetaData metaData ) throws BirtException
{
boolean hasResultSetHint = false;
int columnCount = 0;
HashSet orgColumnNameSet = new HashSet( );
HashSet uniqueColumnNameSet = new HashSet( );
if ( metaData != null )
{
columnCount = metaData.getColumnCount( );
for ( int n = 0; n < columnCount; n++ )
{
orgColumnNameSet.add( metaData.getColumnName( n + 1 ) );
}
}
for ( int i = 0; i < columnCount; i++ )
{
String columnName = metaData.getColumnName( i + 1 );
String uniqueColumnName = getUniqueName( orgColumnNameSet,
uniqueColumnNameSet,
columnName,
i );
uniqueColumnNameSet.add( uniqueColumnName );
if ( !uniqueColumnName.equals( columnName ) )
{
updateModelColumn( dataSetHandle, uniqueColumnName, i + 1 );
if ( hasResultSetHint != true )
hasResultSetHint = true;
}
}
return hasResultSetHint;
}
/**
*
* @param orgColumnNameSet
* @param newColumnNameSet
* @param columnName
* @param index
* @return
*/
public static String getUniqueName( HashSet orgColumnNameSet,
HashSet newColumnNameSet, String columnName, int index )
{
String newColumnName;
if ( columnName == null
|| columnName.trim( ).length( ) == 0
|| newColumnNameSet.contains( columnName ) )
{
// name conflict or no name,give this column a unique name
if ( columnName == null || columnName.trim( ).length( ) == 0 )
newColumnName = UNNAME_PREFIX
+ RENAME_SEPARATOR + String.valueOf( index + 1 );
else
newColumnName = columnName
+ RENAME_SEPARATOR + String.valueOf( index + 1 );
int i = 1;
while ( orgColumnNameSet.contains( newColumnName )
|| newColumnNameSet.contains( newColumnName ) )
{
newColumnName += String.valueOf( RENAME_SEPARATOR ) + i;
i++;
}
}
else
{
newColumnName = columnName;
}
return newColumnName;
}
/**
* whether need to use result hint
*
* @param dataSetHandle
* @return
*/
private static boolean checkHandleType( DataSetHandle dataSetHandle )
{
if ( dataSetHandle instanceof ScriptDataSetHandle )
return true;
else if ( dataSetHandle instanceof JointDataSetHandle )
{
Iterator iter = ( (JointDataSetHandle) dataSetHandle ).dataSetsIterator();
while (iter.hasNext( ))
{
DataSetHandle dsHandle = (DataSetHandle)iter.next( );
if ( dsHandle != null
&& dsHandle instanceof ScriptDataSetHandle )
{
return true;
}
else if ( dsHandle instanceof JointDataSetHandle )
{
if ( checkHandleType( dsHandle ) )
return true;
}
}
}
return false;
}
/**
*
* @param ds
* @param uniqueColumnName
* @param index
* @throws BirtException
*/
private static void updateModelColumn( DataSetHandle ds, String uniqueColumnName,
int index ) throws BirtException
{
PropertyHandle resultSetColumns = ds.getPropertyHandle( DataSetHandle.RESULT_SET_PROP );
if ( resultSetColumns == null )
return;
// update result set columns
Iterator iterator = resultSetColumns.iterator( );
while ( iterator.hasNext( ) )
{
ResultSetColumnHandle rsColumnHandle = (ResultSetColumnHandle) iterator.next( );
assert rsColumnHandle.getPosition( ) != null;
if ( rsColumnHandle.getPosition( ).intValue( ) == index )
{
if ( rsColumnHandle.getColumnName( ) != null
&& !rsColumnHandle.getColumnName( )
.equals( uniqueColumnName ) )
{
rsColumnHandle.setColumnName( uniqueColumnName );
}
break;
}
}
}
/**
*
* @param ds
* @param uniqueColumnName
* @param index
* @throws BirtException
*/
private static void updateComputedColumn( DataSetHandle ds,
String uniqueColumnName, String originalName ) throws BirtException
{
PropertyHandle computedColumn = ds.getPropertyHandle( DataSetHandle.COMPUTED_COLUMNS_PROP );
if ( computedColumn == null )
return;
// update result set columns
Iterator iterator = computedColumn.iterator( );
while ( iterator.hasNext( ) )
{
ComputedColumnHandle compColumnHandle = (ComputedColumnHandle) iterator.next( );
if ( compColumnHandle.getName( ) != null
&& compColumnHandle.getName( ).equals( originalName ) )
{
compColumnHandle.setName( uniqueColumnName );
}
}
}
}
| false | true | public static IResultMetaData retrieveResultMetaData(
DataSetHandle dataSetHandle ) throws BirtException
{
List resultSetList = null;
if ( dataSetHandle instanceof OdaDataSetHandle )
{
PropertyHandle handle = dataSetHandle.getPropertyHandle( OdaDataSetHandle.RESULT_SET_PROP );
if ( handle.isLocal( ) )
resultSetList = handle.getListValue( );
}
else if ( dataSetHandle instanceof ScriptDataSetHandle )
{
PropertyHandle handle = dataSetHandle.getPropertyHandle( DataSetHandle.RESULT_SET_HINTS_PROP );
if ( handle.isLocal( ) )
resultSetList = handle.getListValue( );
}
else
{
return null;
}
List computedList = (List) dataSetHandle.getProperty( OdaDataSetHandle.COMPUTED_COLUMNS_PROP );
List columnMeta = new ArrayList( );
ResultSetColumnDefinition columnDef;
int count = 0;
// populate result set columns
if ( resultSetList != null && !resultSetList.isEmpty( ) )
{
ResultSetColumn resultSetColumn;
HashSet orgColumnNameSet = new HashSet( );
HashSet uniqueColumnNameSet = new HashSet( );
for ( int n = 0; n < resultSetList.size( ); n++ )
{
orgColumnNameSet.add( ( (ResultSetColumn) resultSetList.get( n ) ).getColumnName( ) );
}
for ( int i = 0; i < resultSetList.size( ); i++ )
{
resultSetColumn = (ResultSetColumn) resultSetList.get( i );
String columnName = resultSetColumn.getColumnName( );
String uniqueColumnName = getUniqueName( orgColumnNameSet,
uniqueColumnNameSet,
columnName,
i );
uniqueColumnNameSet.add( uniqueColumnName );
if ( !uniqueColumnName.equals( columnName ) )
{
updateModelColumn( dataSetHandle, uniqueColumnName, i + 1 );
}
columnDef = new ResultSetColumnDefinition( uniqueColumnName );
columnDef.setDataTypeName( resultSetColumn.getDataType( ) );
columnDef.setDataType( DataAdapterUtil.adaptModelDataType( resultSetColumn.getDataType( ) ) );
if ( resultSetColumn.getPosition( ) != null )
columnDef.setColumnPosition( resultSetColumn.getPosition( )
.intValue( ) );
if ( resultSetColumn.getNativeDataType( ) != null )
columnDef.setNativeDataType( resultSetColumn.getNativeDataType( )
.intValue( ) );
if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null )
{
ColumnHintHandle columnHint = findColumnHint( dataSetHandle,
uniqueColumnName );
columnDef.setAlias( columnHint.getAlias( ) );
columnDef.setLableName( columnHint.getDisplayName( ) );
}
columnDef.setComputedColumn( false );
columnMeta.add( columnDef );
}
count += resultSetList.size( );
// populate computed columns
if ( computedList != null )
{
for ( int n = 0; n < computedList.size( ); n++ )
{
orgColumnNameSet.add( ( (ComputedColumn) computedList.get( n ) ).getName( ) );
}
ComputedColumn computedColumn;
for ( int i = 0; i < computedList.size( ); i++ )
{
computedColumn = (ComputedColumn) computedList.get( i );
String columnName = computedColumn.getName( );
String uniqueColumnName = getUniqueName( orgColumnNameSet,
uniqueColumnNameSet,
columnName,
i + count );
uniqueColumnNameSet.add( uniqueColumnName );
if ( !uniqueColumnName.equals( columnName ) )
{
updateComputedColumn( dataSetHandle, uniqueColumnName, columnName );
}
columnDef = new ResultSetColumnDefinition( uniqueColumnName );
columnDef.setDataTypeName( computedColumn.getDataType( ) );
columnDef.setDataType( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelDataType( computedColumn.getDataType( ) ) );
if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null )
{
ColumnHintHandle columnHint = findColumnHint( dataSetHandle,
uniqueColumnName );
columnDef.setAlias( columnHint.getAlias( ) );
columnDef.setLableName( columnHint.getDisplayName( ) );
}
columnDef.setComputedColumn( true );
columnMeta.add( columnDef );
}
}
return new ResultMetaData2( columnMeta );
}
return null;
}
| public static IResultMetaData retrieveResultMetaData(
DataSetHandle dataSetHandle ) throws BirtException
{
List resultSetList = null;
if ( dataSetHandle instanceof OdaDataSetHandle )
{
PropertyHandle handle = dataSetHandle.getPropertyHandle( OdaDataSetHandle.RESULT_SET_PROP );
resultSetList = handle.getListValue( );
}
else if ( dataSetHandle instanceof ScriptDataSetHandle )
{
PropertyHandle handle = dataSetHandle.getPropertyHandle( DataSetHandle.RESULT_SET_HINTS_PROP );
resultSetList = handle.getListValue( );
}
else
{
return null;
}
List computedList = (List) dataSetHandle.getProperty( OdaDataSetHandle.COMPUTED_COLUMNS_PROP );
List columnMeta = new ArrayList( );
ResultSetColumnDefinition columnDef;
int count = 0;
// populate result set columns
if ( resultSetList != null && !resultSetList.isEmpty( ) )
{
ResultSetColumn resultSetColumn;
HashSet orgColumnNameSet = new HashSet( );
HashSet uniqueColumnNameSet = new HashSet( );
for ( int n = 0; n < resultSetList.size( ); n++ )
{
orgColumnNameSet.add( ( (ResultSetColumn) resultSetList.get( n ) ).getColumnName( ) );
}
for ( int i = 0; i < resultSetList.size( ); i++ )
{
resultSetColumn = (ResultSetColumn) resultSetList.get( i );
String columnName = resultSetColumn.getColumnName( );
String uniqueColumnName = getUniqueName( orgColumnNameSet,
uniqueColumnNameSet,
columnName,
i );
uniqueColumnNameSet.add( uniqueColumnName );
if ( !uniqueColumnName.equals( columnName ) )
{
updateModelColumn( dataSetHandle, uniqueColumnName, i + 1 );
}
columnDef = new ResultSetColumnDefinition( uniqueColumnName );
columnDef.setDataTypeName( resultSetColumn.getDataType( ) );
columnDef.setDataType( DataAdapterUtil.adaptModelDataType( resultSetColumn.getDataType( ) ) );
if ( resultSetColumn.getPosition( ) != null )
columnDef.setColumnPosition( resultSetColumn.getPosition( )
.intValue( ) );
if ( resultSetColumn.getNativeDataType( ) != null )
columnDef.setNativeDataType( resultSetColumn.getNativeDataType( )
.intValue( ) );
if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null )
{
ColumnHintHandle columnHint = findColumnHint( dataSetHandle,
uniqueColumnName );
columnDef.setAlias( columnHint.getAlias( ) );
columnDef.setLableName( columnHint.getDisplayName( ) );
}
columnDef.setComputedColumn( false );
columnMeta.add( columnDef );
}
count += resultSetList.size( );
// populate computed columns
if ( computedList != null )
{
for ( int n = 0; n < computedList.size( ); n++ )
{
orgColumnNameSet.add( ( (ComputedColumn) computedList.get( n ) ).getName( ) );
}
ComputedColumn computedColumn;
for ( int i = 0; i < computedList.size( ); i++ )
{
computedColumn = (ComputedColumn) computedList.get( i );
String columnName = computedColumn.getName( );
String uniqueColumnName = getUniqueName( orgColumnNameSet,
uniqueColumnNameSet,
columnName,
i + count );
uniqueColumnNameSet.add( uniqueColumnName );
if ( !uniqueColumnName.equals( columnName ) )
{
updateComputedColumn( dataSetHandle, uniqueColumnName, columnName );
}
columnDef = new ResultSetColumnDefinition( uniqueColumnName );
columnDef.setDataTypeName( computedColumn.getDataType( ) );
columnDef.setDataType( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelDataType( computedColumn.getDataType( ) ) );
if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null )
{
ColumnHintHandle columnHint = findColumnHint( dataSetHandle,
uniqueColumnName );
columnDef.setAlias( columnHint.getAlias( ) );
columnDef.setLableName( columnHint.getDisplayName( ) );
}
columnDef.setComputedColumn( true );
columnMeta.add( columnDef );
}
}
return new ResultMetaData2( columnMeta );
}
return null;
}
|
diff --git a/twitter4j-core/src/main/java/twitter4j/internal/http/commons40/CommonsHttpClientImpl.java b/twitter4j-core/src/main/java/twitter4j/internal/http/commons40/CommonsHttpClientImpl.java
index 31fb0037..ff84cb92 100644
--- a/twitter4j-core/src/main/java/twitter4j/internal/http/commons40/CommonsHttpClientImpl.java
+++ b/twitter4j-core/src/main/java/twitter4j/internal/http/commons40/CommonsHttpClientImpl.java
@@ -1,123 +1,126 @@
/*
Copyright (c) 2007-2010, Yusuke Yamamoto
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 Yusuke Yamamoto 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 Yusuke Yamamoto ``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 Yusuke Yamamoto 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 twitter4j.internal.http.commons40;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import twitter4j.TwitterException;
import twitter4j.internal.http.HttpClientConfiguration;
import twitter4j.internal.http.HttpParameter;
import twitter4j.internal.http.HttpRequest;
import twitter4j.internal.http.RequestMethod;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Twitter4J 2.1.2
*/
public class CommonsHttpClientImpl implements twitter4j.internal.http.HttpClient {
private HttpClientConfiguration conf;
public CommonsHttpClientImpl(HttpClientConfiguration conf) {
this.conf = conf;
}
public twitter4j.internal.http.HttpResponse request(twitter4j.internal.http.HttpRequest req) throws TwitterException {
try {
HttpClient client = new DefaultHttpClient();
HttpRequestBase commonsRequest = null;
if (req.getMethod() == RequestMethod.GET) {
commonsRequest = new HttpGet(composeURL(req));
} else if (req.getMethod() == RequestMethod.POST) {
HttpPost post = new HttpPost(req.getURL());
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(asNameValuePairList(req), "UTF-8");
- post.setEntity(entity);
+ List<NameValuePair> nameValuePair = asNameValuePairList(req);
+ if (null != nameValuePair) {
+ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePair, "UTF-8");
+ post.setEntity(entity);
+ }
commonsRequest = post;
} else if (req.getMethod() == RequestMethod.DELETE) {
commonsRequest = new HttpDelete(composeURL(req));
} else if (req.getMethod() == RequestMethod.HEAD) {
commonsRequest = new HttpHead(composeURL(req));
} else if (req.getMethod() == RequestMethod.PUT) {
commonsRequest = new HttpPut(composeURL(req));
} else {
throw new AssertionError();
}
Map<String, String> headers = req.getRequestHeaders();
for (String headerName : headers.keySet()) {
commonsRequest.addHeader(headerName, headers.get(headerName));
}
String authorizationHeader;
if (null != req.getAuthorization()
&& null != (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req))) {
commonsRequest.addHeader("Authorization", authorizationHeader);
}
CommonsHttpResponseImpl res = new CommonsHttpResponseImpl(client.execute(commonsRequest));
if(200 != res.getStatusCode()){
throw new TwitterException(res.asString() ,res);
}
return res;
} catch (IOException e) {
throw new TwitterException(e);
}
}
private String composeURL(HttpRequest req){
List<NameValuePair> params = asNameValuePairList(req);
if (null != params) {
return req.getURL() + "?" + URLEncodedUtils.format(params, "UTF-8");
} else {
return req.getURL();
}
}
private List<NameValuePair> asNameValuePairList(HttpRequest req){
if (null != req.getParameters() && req.getParameters().length > 0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (HttpParameter parameter : req.getParameters()) {
params.add(new BasicNameValuePair(parameter.getName(), parameter.getValue()));
}
return params;
}else{
return null;
}
}
}
| true | true | public twitter4j.internal.http.HttpResponse request(twitter4j.internal.http.HttpRequest req) throws TwitterException {
try {
HttpClient client = new DefaultHttpClient();
HttpRequestBase commonsRequest = null;
if (req.getMethod() == RequestMethod.GET) {
commonsRequest = new HttpGet(composeURL(req));
} else if (req.getMethod() == RequestMethod.POST) {
HttpPost post = new HttpPost(req.getURL());
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(asNameValuePairList(req), "UTF-8");
post.setEntity(entity);
commonsRequest = post;
} else if (req.getMethod() == RequestMethod.DELETE) {
commonsRequest = new HttpDelete(composeURL(req));
} else if (req.getMethod() == RequestMethod.HEAD) {
commonsRequest = new HttpHead(composeURL(req));
} else if (req.getMethod() == RequestMethod.PUT) {
commonsRequest = new HttpPut(composeURL(req));
} else {
throw new AssertionError();
}
Map<String, String> headers = req.getRequestHeaders();
for (String headerName : headers.keySet()) {
commonsRequest.addHeader(headerName, headers.get(headerName));
}
String authorizationHeader;
if (null != req.getAuthorization()
&& null != (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req))) {
commonsRequest.addHeader("Authorization", authorizationHeader);
}
CommonsHttpResponseImpl res = new CommonsHttpResponseImpl(client.execute(commonsRequest));
if(200 != res.getStatusCode()){
throw new TwitterException(res.asString() ,res);
}
return res;
} catch (IOException e) {
throw new TwitterException(e);
}
}
| public twitter4j.internal.http.HttpResponse request(twitter4j.internal.http.HttpRequest req) throws TwitterException {
try {
HttpClient client = new DefaultHttpClient();
HttpRequestBase commonsRequest = null;
if (req.getMethod() == RequestMethod.GET) {
commonsRequest = new HttpGet(composeURL(req));
} else if (req.getMethod() == RequestMethod.POST) {
HttpPost post = new HttpPost(req.getURL());
List<NameValuePair> nameValuePair = asNameValuePairList(req);
if (null != nameValuePair) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePair, "UTF-8");
post.setEntity(entity);
}
commonsRequest = post;
} else if (req.getMethod() == RequestMethod.DELETE) {
commonsRequest = new HttpDelete(composeURL(req));
} else if (req.getMethod() == RequestMethod.HEAD) {
commonsRequest = new HttpHead(composeURL(req));
} else if (req.getMethod() == RequestMethod.PUT) {
commonsRequest = new HttpPut(composeURL(req));
} else {
throw new AssertionError();
}
Map<String, String> headers = req.getRequestHeaders();
for (String headerName : headers.keySet()) {
commonsRequest.addHeader(headerName, headers.get(headerName));
}
String authorizationHeader;
if (null != req.getAuthorization()
&& null != (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req))) {
commonsRequest.addHeader("Authorization", authorizationHeader);
}
CommonsHttpResponseImpl res = new CommonsHttpResponseImpl(client.execute(commonsRequest));
if(200 != res.getStatusCode()){
throw new TwitterException(res.asString() ,res);
}
return res;
} catch (IOException e) {
throw new TwitterException(e);
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityLiquidRouter.java b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityLiquidRouter.java
index cb927039..383ee423 100644
--- a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityLiquidRouter.java
+++ b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityLiquidRouter.java
@@ -1,245 +1,246 @@
package powercrystals.minefactoryreloaded.tile.machine;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.ITankContainer;
import net.minecraftforge.liquids.LiquidContainerRegistry;
import net.minecraftforge.liquids.LiquidStack;
import net.minecraftforge.liquids.LiquidTank;
import powercrystals.core.position.BlockPosition;
import powercrystals.minefactoryreloaded.gui.client.GuiFactoryInventory;
import powercrystals.minefactoryreloaded.gui.client.GuiLiquidRouter;
import powercrystals.minefactoryreloaded.gui.container.ContainerLiquidRouter;
import powercrystals.minefactoryreloaded.tile.base.TileEntityFactoryInventory;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class TileEntityLiquidRouter extends TileEntityFactoryInventory implements ITankContainer
{
private LiquidTank[] _bufferTanks = new LiquidTank[6];
private static final ForgeDirection[] _outputDirections = new ForgeDirection[]
{ ForgeDirection.DOWN, ForgeDirection.UP, ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.EAST, ForgeDirection.WEST };
public TileEntityLiquidRouter()
{
for(int i = 0; i < 6; i++)
{
_bufferTanks[i] = new LiquidTank(LiquidContainerRegistry.BUCKET_VOLUME);
_bufferTanks[i].setTankPressure(-1);
}
}
@Override
public void updateEntity()
{
super.updateEntity();
for(int i = 0; i < 6; i++)
{
if(_bufferTanks[i].getLiquid() != null && _bufferTanks[i].getLiquid().amount > 0)
{
_bufferTanks[i].getLiquid().amount -= pumpLiquid(_bufferTanks[i].getLiquid(), true);
}
}
}
private int pumpLiquid(LiquidStack resource, boolean doFill)
{
if(resource == null || resource.itemID <= 0 || resource.amount <= 0) return 0;
int amountRemaining = resource.amount;
int[] routes = getRoutesForLiquid(resource);
int[] defaultRoutes = getDefaultRoutes();
if(hasRoutes(routes))
{
amountRemaining = weightedRouteLiquid(resource, routes, amountRemaining, doFill);
}
else if(hasRoutes(defaultRoutes))
{
amountRemaining = weightedRouteLiquid(resource, defaultRoutes, amountRemaining, doFill);
}
return resource.amount - amountRemaining;
}
private int weightedRouteLiquid(LiquidStack resource, int[] routes, int amountRemaining, boolean doFill)
{
if(amountRemaining < totalWeight(routes))
{
int outdir = weightedRandomSide(routes);
TileEntity te = BlockPosition.getAdjacentTileEntity(this, _outputDirections[outdir]);
if(te != null && te instanceof ITankContainer)
{
amountRemaining -= ((ITankContainer)te).fill(_outputDirections[outdir].getOpposite(), new LiquidStack(resource.itemID, amountRemaining, resource.itemMeta), doFill);
}
}
else
{
+ int startingAmount = amountRemaining;
for(int i = 0; i < routes.length; i++)
{
TileEntity te = BlockPosition.getAdjacentTileEntity(this, _outputDirections[i]);
if(te != null && te instanceof ITankContainer && routes[i] > 0)
{
- amountRemaining -= ((ITankContainer)te).fill(_outputDirections[i].getOpposite(), new LiquidStack(resource.itemID, amountRemaining * routes[i] / totalWeight(routes), resource.itemMeta), doFill);
+ amountRemaining -= ((ITankContainer)te).fill(_outputDirections[i].getOpposite(), new LiquidStack(resource.itemID, startingAmount * routes[i] / totalWeight(routes), resource.itemMeta), doFill);
if(amountRemaining <= 0)
{
break;
}
}
}
}
return amountRemaining;
}
private int weightedRandomSide(int[] routeWeights)
{
int random = worldObj.rand.nextInt(totalWeight(routeWeights));
for(int i = 0; i < routeWeights.length; i++)
{
random -= routeWeights[i];
if(random < 0)
{
return i;
}
}
return -1;
}
private int totalWeight(int[] routeWeights)
{
int total = 0;
for(int weight : routeWeights)
{
total += weight;
}
return total;
}
private boolean hasRoutes(int[] routeWeights)
{
for(int weight : routeWeights)
{
if(weight > 0) return true;
}
return false;
}
private int[] getRoutesForLiquid(LiquidStack resource)
{
int[] routeWeights = new int[6];
for(int i = 0; i < 6; i++)
{
if(LiquidContainerRegistry.containsLiquid(_inventory[i], resource))
{
routeWeights[i] = _inventory[i].stackSize;
}
else
{
routeWeights[i] = 0;
}
}
return routeWeights;
}
private int[] getDefaultRoutes()
{
int[] routeWeights = new int[6];
for(int i = 0; i < 6; i++)
{
if(LiquidContainerRegistry.isEmptyContainer(_inventory[i]))
{
routeWeights[i] = _inventory[i].stackSize;
}
else
{
routeWeights[i] = 0;
}
}
return routeWeights;
}
@Override
public int fill(ForgeDirection from, LiquidStack resource, boolean doFill)
{
return pumpLiquid(resource, doFill);
}
@Override
public int fill(int tankIndex, LiquidStack resource, boolean doFill)
{
return pumpLiquid(resource, doFill);
}
@Override
public LiquidStack drain(ForgeDirection from, int maxDrain, boolean doDrain)
{
return null;
}
@Override
public LiquidStack drain(int tankIndex, int maxDrain, boolean doDrain)
{
return null;
}
@Override
public ILiquidTank[] getTanks(ForgeDirection direction)
{
return new ILiquidTank[] { _bufferTanks[direction.ordinal()] };
}
@Override
public ILiquidTank getTank(ForgeDirection direction, LiquidStack type)
{
if(LiquidContainerRegistry.containsLiquid(_inventory[direction.ordinal()], type))
{
return _bufferTanks[direction.ordinal()];
}
return null;
}
@Override
public int getSizeInventory()
{
return 6;
}
@Override
public boolean shouldDropSlotWhenBroken(int slot)
{
return false;
}
@Override
public String getInvName()
{
return "Liquid Router";
}
@Override
public String getGuiBackground()
{
return "liquidrouter.png";
}
@Override
@SideOnly(Side.CLIENT)
public GuiFactoryInventory getGui(InventoryPlayer inventoryPlayer)
{
return new GuiLiquidRouter(getContainer(inventoryPlayer), this);
}
@Override
public ContainerLiquidRouter getContainer(InventoryPlayer inventoryPlayer)
{
return new ContainerLiquidRouter(this, inventoryPlayer);
}
}
| false | true | private int weightedRouteLiquid(LiquidStack resource, int[] routes, int amountRemaining, boolean doFill)
{
if(amountRemaining < totalWeight(routes))
{
int outdir = weightedRandomSide(routes);
TileEntity te = BlockPosition.getAdjacentTileEntity(this, _outputDirections[outdir]);
if(te != null && te instanceof ITankContainer)
{
amountRemaining -= ((ITankContainer)te).fill(_outputDirections[outdir].getOpposite(), new LiquidStack(resource.itemID, amountRemaining, resource.itemMeta), doFill);
}
}
else
{
for(int i = 0; i < routes.length; i++)
{
TileEntity te = BlockPosition.getAdjacentTileEntity(this, _outputDirections[i]);
if(te != null && te instanceof ITankContainer && routes[i] > 0)
{
amountRemaining -= ((ITankContainer)te).fill(_outputDirections[i].getOpposite(), new LiquidStack(resource.itemID, amountRemaining * routes[i] / totalWeight(routes), resource.itemMeta), doFill);
if(amountRemaining <= 0)
{
break;
}
}
}
}
return amountRemaining;
}
| private int weightedRouteLiquid(LiquidStack resource, int[] routes, int amountRemaining, boolean doFill)
{
if(amountRemaining < totalWeight(routes))
{
int outdir = weightedRandomSide(routes);
TileEntity te = BlockPosition.getAdjacentTileEntity(this, _outputDirections[outdir]);
if(te != null && te instanceof ITankContainer)
{
amountRemaining -= ((ITankContainer)te).fill(_outputDirections[outdir].getOpposite(), new LiquidStack(resource.itemID, amountRemaining, resource.itemMeta), doFill);
}
}
else
{
int startingAmount = amountRemaining;
for(int i = 0; i < routes.length; i++)
{
TileEntity te = BlockPosition.getAdjacentTileEntity(this, _outputDirections[i]);
if(te != null && te instanceof ITankContainer && routes[i] > 0)
{
amountRemaining -= ((ITankContainer)te).fill(_outputDirections[i].getOpposite(), new LiquidStack(resource.itemID, startingAmount * routes[i] / totalWeight(routes), resource.itemMeta), doFill);
if(amountRemaining <= 0)
{
break;
}
}
}
}
return amountRemaining;
}
|
diff --git a/src/main/java/org/elasticsearch/index/fielddata/FieldDataStats.java b/src/main/java/org/elasticsearch/index/fielddata/FieldDataStats.java
index f9255ab2dd5..33f898f02b0 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/FieldDataStats.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/FieldDataStats.java
@@ -1,99 +1,99 @@
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.index.fielddata;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import java.io.IOException;
/**
*/
public class FieldDataStats implements Streamable, ToXContent {
long memorySize;
long evictions;
public FieldDataStats() {
}
public FieldDataStats(long memorySize, long evictions) {
this.memorySize = memorySize;
this.evictions = evictions;
}
public void add(FieldDataStats stats) {
this.memorySize += stats.memorySize;
this.evictions += stats.evictions;
}
public long getMemorySizeInBytes() {
return this.memorySize;
}
public ByteSizeValue getMemorySize() {
return new ByteSizeValue(memorySize);
}
public long getEvictions() {
return this.evictions;
}
public static FieldDataStats readFieldDataStats(StreamInput in) throws IOException {
FieldDataStats stats = new FieldDataStats();
stats.readFrom(in);
return stats;
}
@Override
public void readFrom(StreamInput in) throws IOException {
memorySize = in.readVLong();
evictions = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(memorySize);
out.writeVLong(evictions);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.FIELD_DATA);
- builder.field(Fields.MEMORY_SIZE, memorySize);
- builder.field(Fields.MEMORY_SIZE_IN_BYTES, getMemorySize().toString());
+ builder.field(Fields.MEMORY_SIZE, getMemorySize().toString());
+ builder.field(Fields.MEMORY_SIZE_IN_BYTES, memorySize);
builder.field(Fields.EVICTIONS, getEvictions());
builder.endObject();
return builder;
}
static final class Fields {
static final XContentBuilderString FIELD_DATA = new XContentBuilderString("field_data");
static final XContentBuilderString MEMORY_SIZE = new XContentBuilderString("memory_size");
static final XContentBuilderString MEMORY_SIZE_IN_BYTES = new XContentBuilderString("memory_size_in_bytes");
static final XContentBuilderString EVICTIONS = new XContentBuilderString("evictions");
}
}
| true | true | public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.FIELD_DATA);
builder.field(Fields.MEMORY_SIZE, memorySize);
builder.field(Fields.MEMORY_SIZE_IN_BYTES, getMemorySize().toString());
builder.field(Fields.EVICTIONS, getEvictions());
builder.endObject();
return builder;
}
| public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.FIELD_DATA);
builder.field(Fields.MEMORY_SIZE, getMemorySize().toString());
builder.field(Fields.MEMORY_SIZE_IN_BYTES, memorySize);
builder.field(Fields.EVICTIONS, getEvictions());
builder.endObject();
return builder;
}
|
diff --git a/src/com/dmdirc/addons/ui_swing/textpane/TextPaneCanvas.java b/src/com/dmdirc/addons/ui_swing/textpane/TextPaneCanvas.java
index c57da84e..4d751342 100644
--- a/src/com/dmdirc/addons/ui_swing/textpane/TextPaneCanvas.java
+++ b/src/com/dmdirc/addons/ui_swing/textpane/TextPaneCanvas.java
@@ -1,944 +1,944 @@
/*
* Copyright (c) 2006-2010 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.addons.ui_swing.textpane;
import com.dmdirc.addons.ui_swing.BackgroundOption;
import com.dmdirc.addons.ui_swing.UIUtilities;
import com.dmdirc.addons.ui_swing.components.frames.TextFrame;
import com.dmdirc.config.ConfigManager;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.ui.messages.IRCTextAttribute;
import com.dmdirc.util.URLBuilder;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextHitInfo;
import java.awt.font.TextLayout;
import java.io.IOException;
import java.net.URL;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
/** Canvas object to draw text. */
class TextPaneCanvas extends JPanel implements MouseInputListener,
ComponentListener, AdjustmentListener, ConfigChangeListener {
/**
* A version number for this class. It should be changed whenever the
* class structure is changed (or anything else that would prevent
* serialized objects being unserialized with the new class).
*/
private static final long serialVersionUID = 8;
/** Hand cursor. */
private static final Cursor HAND_CURSOR = new Cursor(Cursor.HAND_CURSOR);
/** Single Side padding for textpane. */
private static final int SINGLE_SIDE_PADDING = 3;
/** Both Side padding for textpane. */
private static final int DOUBLE_SIDE_PADDING = SINGLE_SIDE_PADDING * 2;
/** IRCDocument. */
private final IRCDocument document;
/** parent textpane. */
private final TextPane textPane;
/** Position -> TextLayout. */
private final Map<Rectangle, TextLayout> positions;
/** TextLayout -> Line numbers. */
private final Map<TextLayout, LineInfo> textLayouts;
/** Start line. */
private int startLine;
/** Selection. */
private LinePosition selection;
/** First visible line. */
private int firstVisibleLine;
/** Last visible line. */
private int lastVisibleLine;
/** Background image. */
private Image backgroundImage;
/** Config Manager. */
private ConfigManager manager;
/** Config domain. */
private String domain;
/** Background image option. */
private BackgroundOption backgroundOption;
/**
* Creates a new text pane canvas.
*
* @param parent parent text pane for the canvas
* @param document IRCDocument to be displayed
*/
public TextPaneCanvas(final TextPane parent, final IRCDocument document) {
super();
this.document = document;
textPane = parent;
this.manager = parent.getWindow().getConfigManager();
this.domain = ((TextFrame) parent.getWindow()).getController().
getDomain();
startLine = 0;
setDoubleBuffered(true);
setOpaque(true);
textLayouts = new HashMap<TextLayout, LineInfo>();
positions = new HashMap<Rectangle, TextLayout>();
selection = new LinePosition(-1, -1, -1, -1);
addMouseListener(this);
addMouseMotionListener(this);
addComponentListener(this);
manager.addChangeListener(domain, "textpanebackground", this);
manager.addChangeListener(domain, "textpanebackgroundoption", this);
updateCachedSettings();
}
/**
* Paints the text onto the canvas.
*
* @param graphics graphics object to draw onto
*/
@Override
public void paintComponent(final Graphics graphics) {
final Graphics2D g = (Graphics2D) graphics;
final Map desktopHints = (Map) Toolkit.getDefaultToolkit().
getDesktopProperty("awt.font.desktophints");
if (desktopHints != null) {
g.addRenderingHints(desktopHints);
}
g.setColor(textPane.getBackground());
g.fill(g.getClipBounds());
UIUtilities.paintBackground(g, getBounds(), backgroundImage,
backgroundOption);
paintOntoGraphics(g);
}
/**
* Re calculates positions of lines and repaints if required.
*/
protected void recalc() {
if (isVisible()) {
repaint();
}
}
private void updateCachedSettings() {
final String backgroundPath = manager.getOption(domain,
"textpanebackground");
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
try {
final URL url = URLBuilder.buildURL(backgroundPath);
if (url != null) {
backgroundImage = ImageIO.read(url);
}
} catch (IOException ex) {
backgroundImage = null;
}
}
});
try {
backgroundOption = BackgroundOption.valueOf(manager.getOption(domain,
"textpanebackgroundoption"));
} catch (IllegalArgumentException ex) {
backgroundOption = BackgroundOption.CENTER;
}
}
private void paintOntoGraphics(final Graphics2D g) {
final float formatWidth = getWidth() - DOUBLE_SIDE_PADDING;
final float formatHeight = getHeight();
float drawPosY = formatHeight;
int paragraphStart;
int paragraphEnd;
LineBreakMeasurer lineMeasurer;
textLayouts.clear();
positions.clear();
//check theres something to draw and theres some space to draw in
if (document.getNumLines() == 0 || formatWidth < 1) {
setCursor(Cursor.getDefaultCursor());
return;
}
// Check the start line is in range
if (startLine >= document.getNumLines()) {
startLine = document.getNumLines() - 1;
}
if (startLine <= 0) {
startLine = 0;
}
//sets the last visible line
lastVisibleLine = startLine;
firstVisibleLine = startLine;
// Iterate through the lines
for (int line = startLine; line >= 0; line--) {
float drawPosX;
final AttributedCharacterIterator iterator = document.getStyledLine(
line);
int lineHeight = document.getLineHeight(line);
lineHeight += lineHeight * 0.2;
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
lineMeasurer = new LineBreakMeasurer(iterator,
g.getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
final int wrappedLine = getNumWrappedLines(lineMeasurer,
paragraphStart, paragraphEnd,
formatWidth);
if (wrappedLine > 1) {
drawPosY -= lineHeight * wrappedLine;
}
if (line == startLine) {
drawPosY += DOUBLE_SIDE_PADDING;
}
int numberOfWraps = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
// Calculate the Y offset
if (wrappedLine == 1) {
drawPosY -= lineHeight;
} else if (numberOfWraps != 0) {
drawPosY += lineHeight;
}
// Calculate the initial X position
if (layout.isLeftToRight()) {
drawPosX = SINGLE_SIDE_PADDING;
} else {
drawPosX = formatWidth - layout.getAdvance();
}
// Check if the target is in range
if (drawPosY >= 0 || drawPosY <= formatHeight) {
g.setColor(textPane.getForeground());
layout.draw(g, drawPosX, drawPosY + layout.getDescent());
doHighlight(line, chars, layout, g, drawPosY, drawPosX);
firstVisibleLine = line;
textLayouts.put(layout, new LineInfo(line, numberOfWraps));
positions.put(new Rectangle(0, (int) (drawPosY - layout.
- getAscent()), (int) (formatWidth +
- DOUBLE_SIDE_PADDING), lineHeight), layout);
+ getDescent() - layout.getDescent()), (int) (formatWidth +
+ DOUBLE_SIDE_PADDING), document.getLineHeight(line)), layout);
}
numberOfWraps++;
chars += layout.getCharacterCount();
}
if (numberOfWraps > 1) {
drawPosY -= lineHeight * (wrappedLine - 1);
}
if (drawPosY <= 0) {
break;
}
}
checkForLink();
}
/**
* Returns the number of timesa line will wrap.
*
* @param lineMeasurer LineBreakMeasurer to work out wrapping for
* @param paragraphStart Start index of the paragraph
* @param paragraphEnd End index of the paragraph
* @param formatWidth Width to wrap at
*
* @return Number of times the line wraps
*/
private int getNumWrappedLines(final LineBreakMeasurer lineMeasurer,
final int paragraphStart,
final int paragraphEnd,
final float formatWidth) {
int wrappedLine = 0;
while (lineMeasurer.getPosition() < paragraphEnd) {
lineMeasurer.nextLayout(formatWidth);
wrappedLine++;
}
lineMeasurer.setPosition(paragraphStart);
return wrappedLine;
}
/**
* Redraws the text that has been highlighted.
*
* @param line Line number
* @param chars Number of characters so far in the line
* @param layout Current line textlayout
* @param g Graphics surface to draw highlight on
* @param drawPosY current y location of the line
* @param drawPosX current x location of the line
*/
private void doHighlight(final int line, final int chars,
final TextLayout layout, final Graphics2D g,
final float drawPosY, final float drawPosX) {
int selectionStartLine;
int selectionStartChar;
int selectionEndLine;
int selectionEndChar;
if (selection.getStartLine() > selection.getEndLine()) {
// Swap both
selectionStartLine = selection.getEndLine();
selectionStartChar = selection.getEndPos();
selectionEndLine = selection.getStartLine();
selectionEndChar = selection.getStartPos();
} else if (selection.getStartLine() == selection.getEndLine() &&
selection.getStartPos() > selection.getEndPos()) {
// Just swap the chars
selectionStartLine = selection.getStartLine();
selectionStartChar = selection.getEndPos();
selectionEndLine = selection.getEndLine();
selectionEndChar = selection.getStartPos();
} else {
// Swap nothing
selectionStartLine = selection.getStartLine();
selectionStartChar = selection.getStartPos();
selectionEndLine = selection.getEndLine();
selectionEndChar = selection.getEndPos();
}
//Does this line need highlighting?
if (selectionStartLine <= line && selectionEndLine >= line) {
int firstChar;
int lastChar;
// Determine the first char we care about
if (selectionStartLine < line || selectionStartChar < chars) {
firstChar = chars;
} else {
firstChar = selectionStartChar;
}
// ... And the last
if (selectionEndLine > line || selectionEndChar > chars + layout.getCharacterCount()) {
lastChar = chars + layout.getCharacterCount();
} else {
lastChar = selectionEndChar;
}
// If the selection includes the chars we're showing
if (lastChar > chars && firstChar < chars +
layout.getCharacterCount()) {
String text = document.getLine(line).getText();
if (firstChar >= 0 && text.length() > lastChar) {
text = text.substring(firstChar, lastChar);
}
if (text.isEmpty()) {
return;
}
final AttributedCharacterIterator iterator = document.
getStyledLine(line);
int lineHeight = document.getLineHeight(line);
lineHeight += lineHeight * 0.2;
final AttributedString as = new AttributedString(iterator,
firstChar,
lastChar);
as.addAttribute(TextAttribute.FOREGROUND,
textPane.getBackground());
as.addAttribute(TextAttribute.BACKGROUND,
textPane.getForeground());
final TextLayout newLayout = new TextLayout(as.getIterator(),
g.getFontRenderContext());
final Shape shape = layout.getLogicalHighlightShape(firstChar -
chars,
lastChar -
chars);
final int trans = (int) (newLayout.getDescent() + drawPosY);
if (firstChar != 0) {
g.translate(shape.getBounds().getX(), 0);
}
newLayout.draw(g, drawPosX, trans);
if (firstChar != 0) {
g.translate(-1 * shape.getBounds().getX(), 0);
}
}
}
}
/**
* {@{@inheritDoc}
*
* @param e Adjustment event
*/
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
if (startLine != e.getValue()) {
startLine = e.getValue();
recalc();
}
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseClicked(final MouseEvent e) {
String clickedText = "";
final int start;
final int end;
final LineInfo lineInfo = getClickPosition(getMousePosition());
if (lineInfo.getLine() != -1) {
clickedText = document.getLine(lineInfo.getLine()).getText();
if (lineInfo.getIndex() == -1) {
start = -1;
end = -1;
} else {
final int[] extent =
getSurroundingWordIndexes(clickedText,
lineInfo.getIndex());
start = extent[0];
end = extent[1];
}
if (e.getClickCount() == 2) {
selection.setStartLine(lineInfo.getLine());
selection.setEndLine(lineInfo.getLine());
selection.setStartPos(start);
selection.setEndPos(end);
textPane.copy();
textPane.clearSelection();
} else if (e.getClickCount() == 3) {
selection.setStartLine(lineInfo.getLine());
selection.setEndLine(lineInfo.getLine());
selection.setStartPos(0);
selection.setEndPos(clickedText.length());
textPane.copy();
textPane.clearSelection();
}
}
e.setSource(textPane);
textPane.dispatchEvent(e);
}
/**
* Returns the type of text this click represents.
*
* @param lineInfo Line info of click.
*
* @return Click type for specified position
*/
public ClickType getClickType(final LineInfo lineInfo) {
if (lineInfo.getLine() != -1) {
final AttributedCharacterIterator iterator = document.getStyledLine(
lineInfo.getLine());
final int index = lineInfo.getIndex();
if (index >= iterator.getBeginIndex() && index <= iterator.
getEndIndex()) {
iterator.setIndex(lineInfo.getIndex());
Object linkattr =
iterator.getAttributes().get(IRCTextAttribute.HYPERLINK);
if (linkattr instanceof String) {
return ClickType.HYPERLINK;
}
linkattr =
iterator.getAttributes().get(IRCTextAttribute.CHANNEL);
if (linkattr instanceof String) {
return ClickType.CHANNEL;
}
linkattr = iterator.getAttributes().get(
IRCTextAttribute.NICKNAME);
if (linkattr instanceof String) {
return ClickType.NICKNAME;
}
} else {
return ClickType.NORMAL;
}
}
return ClickType.NORMAL;
}
/**
* Returns the atrriute value for the specified location.
*
* @param lineInfo Specified location
*
* @return Specified value
*/
public Object getAttributeValueAtPoint(LineInfo lineInfo) {
if (lineInfo.getLine() != -1) {
final AttributedCharacterIterator iterator = document.getStyledLine(
lineInfo.getLine());
iterator.setIndex(lineInfo.getIndex());
Object linkattr =
iterator.getAttributes().get(IRCTextAttribute.HYPERLINK);
if (linkattr instanceof String) {
return linkattr;
}
linkattr = iterator.getAttributes().get(IRCTextAttribute.CHANNEL);
if (linkattr instanceof String) {
return linkattr;
}
linkattr = iterator.getAttributes().get(IRCTextAttribute.NICKNAME);
if (linkattr instanceof String) {
return linkattr;
}
}
return null;
}
/**
* Returns the indexes for the word surrounding the index in the specified
* string.
*
* @param text Text to get word from
* @param index Index to get surrounding word
*
* @return Indexes of the word surrounding the index (start, end)
*/
protected int[] getSurroundingWordIndexes(final String text,
final int index) {
final int start = getSurroundingWordStart(text, index);
final int end = getSurroundingWordEnd(text, index);
if (start < 0 || end > text.length() || start > end) {
return new int[]{0, 0};
}
return new int[]{start, end};
}
/**
* Returns the start index for the word surrounding the index in the
* specified string.
*
* @param text Text to get word from
* @param index Index to get surrounding word
*
* @return Start index of the word surrounding the index
*/
private int getSurroundingWordStart(final String text, final int index) {
int start = index;
// Traverse backwards
while (start > 0 && start < text.length() && text.charAt(start) != ' ') {
start--;
}
if (start + 1 < text.length() && text.charAt(start) == ' ') {
start++;
}
return start;
}
/**
* Returns the end index for the word surrounding the index in the
* specified string.
*
* @param text Text to get word from
* @param index Index to get surrounding word
*
* @return End index of the word surrounding the index
*/
private int getSurroundingWordEnd(final String text, final int index) {
int end = index;
// And forwards
while (end < text.length() && end > 0 && text.charAt(end) != ' ') {
end++;
}
return end;
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mousePressed(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
highlightEvent(MouseEventType.CLICK, e);
}
e.setSource(textPane);
textPane.dispatchEvent(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseReleased(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
highlightEvent(MouseEventType.RELEASE, e);
}
e.setSource(textPane);
textPane.dispatchEvent(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseDragged(final MouseEvent e) {
if (e.getModifiersEx() == MouseEvent.BUTTON1_DOWN_MASK) {
highlightEvent(MouseEventType.DRAG, e);
}
e.setSource(textPane);
textPane.dispatchEvent(e);
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseEntered(final MouseEvent e) {
//Ignore
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseExited(final MouseEvent e) {
//Ignore
}
/**
* {@inheritDoc}
*
* @param e Mouse event
*/
@Override
public void mouseMoved(final MouseEvent e) {
checkForLink();
}
/** Checks for a link under the cursor and sets appropriately. */
private void checkForLink() {
final LineInfo lineInfo = getClickPosition(getMousePosition());
if (lineInfo.getLine() != -1 && document.getLine(lineInfo.getLine()) !=
null) {
final AttributedCharacterIterator iterator = document.getStyledLine(
lineInfo.getLine());
if (lineInfo.getIndex() < iterator.getBeginIndex() ||
lineInfo.getIndex() > iterator.getEndIndex()) {
return;
}
iterator.setIndex(lineInfo.getIndex());
Object linkattr =
iterator.getAttributes().get(IRCTextAttribute.HYPERLINK);
if (linkattr instanceof String) {
setCursor(HAND_CURSOR);
return;
}
linkattr = iterator.getAttributes().get(IRCTextAttribute.CHANNEL);
if (linkattr instanceof String) {
setCursor(HAND_CURSOR);
return;
}
linkattr = iterator.getAttributes().get(IRCTextAttribute.NICKNAME);
if (linkattr instanceof String) {
setCursor(HAND_CURSOR);
return;
}
}
if (getCursor() == HAND_CURSOR) {
setCursor(Cursor.getDefaultCursor());
}
}
/**
* Sets the selection for the given event.
*
* @param type mouse event type
* @param e responsible mouse event
*/
protected void highlightEvent(final MouseEventType type,
final MouseEvent e) {
if (isVisible()) {
Point point = e.getLocationOnScreen();
SwingUtilities.convertPointFromScreen(point, this);
if (!contains(point)) {
final Rectangle bounds = getBounds();
final Point mousePos = e.getPoint();
if (mousePos.getX() < bounds.getX()) {
point.setLocation(bounds.getX() + SINGLE_SIDE_PADDING,
point.getY());
} else if (mousePos.getX() > (bounds.getX() + bounds.
getWidth())) {
point.setLocation(bounds.getX() + bounds.getWidth() -
SINGLE_SIDE_PADDING,
point.getY());
}
if (mousePos.getY() < bounds.getY()) {
point.setLocation(point.getX(), bounds.getY() +
DOUBLE_SIDE_PADDING);
} else if (mousePos.getY() >
(bounds.getY() + bounds.getHeight())) {
point.setLocation(bounds.getX() + bounds.getWidth() -
SINGLE_SIDE_PADDING, bounds.getY() +
bounds.getHeight() - DOUBLE_SIDE_PADDING);
}
}
final LineInfo info = getClickPosition(point);
if (info.getLine() == -1 && info.getPart() == -1 && contains(point)) {
info.setLine(0);
info.setPart(0);
info.setIndex(0);
}
if (info.getLine() != -1 && info.getPart() != -1) {
if (type == MouseEventType.CLICK) {
selection.setStartLine(info.getLine());
selection.setStartPos(info.getIndex());
}
selection.setEndLine(info.getLine());
selection.setEndPos(info.getIndex());
recalc();
}
}
}
/**
*
* Returns the line information from a mouse click inside the textpane.
*
* @param point mouse position
*
* @return line number, line part, position in whole line
*/
public LineInfo getClickPosition(final Point point) {
int lineNumber = -1;
int linePart = -1;
int pos = 0;
if (point != null) {
for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) {
if (entry.getKey().contains(point)) {
lineNumber = textLayouts.get(entry.getValue()).getLine();
linePart = textLayouts.get(entry.getValue()).getPart();
}
}
pos = getHitPosition(lineNumber, linePart, (int) point.getX(),
(int) point.getY());
}
return new LineInfo(lineNumber, linePart, pos);
}
/**
* Returns the character index for a specified line and part for a specific hit position.
*
* @param lineNumber Line number
* @param linePart Line part
* @param x X position
* @param y Y position
*
* @return Hit position
*/
private int getHitPosition(final int lineNumber, final int linePart,
final int x, final int y) {
int pos = 0;
for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) {
if (textLayouts.get(entry.getValue()).getLine() == lineNumber) {
if (textLayouts.get(entry.getValue()).getPart() < linePart) {
pos += entry.getValue().getCharacterCount();
} else if (textLayouts.get(entry.getValue()).getPart() ==
linePart) {
final TextHitInfo hit = entry.getValue().hitTestChar(x -
DOUBLE_SIDE_PADDING, y);
pos += hit.getInsertionIndex();
}
}
}
return pos;
}
/**
* Returns the selected range info.
*
* @return Selected range info
*/
protected LinePosition getSelectedRange() {
if (selection.getStartLine() > selection.getEndLine()) {
// Swap both
return new LinePosition(selection.getEndLine(),
selection.getEndPos(), selection.getStartLine(),
selection.getStartPos());
} else if (selection.getStartLine() == selection.getEndLine() &&
selection.getStartPos() > selection.getEndPos()) {
// Just swap the chars
return new LinePosition(selection.getStartLine(), selection.
getEndPos(), selection.getEndLine(),
selection.getStartPos());
} else {
// Swap nothing
return new LinePosition(selection.getStartLine(), selection.
getStartPos(), selection.getEndLine(),
selection.getEndPos());
}
}
/** Clears the selection. */
protected void clearSelection() {
selection.setEndLine(selection.getStartLine());
selection.setEndPos(selection.getStartPos());
recalc();
}
/**
* Selects the specified region of text.
*
* @param position Line position
*/
public void setSelectedRange(final LinePosition position) {
selection = new LinePosition(position);
recalc();
}
/**
* Returns the first visible line.
*
* @return the line number of the first visible line
*/
public int getFirstVisibleLine() {
return firstVisibleLine;
}
/**
* Returns the last visible line.
*
* @return the line number of the last visible line
*/
public int getLastVisibleLine() {
return lastVisibleLine;
}
/**
* Returns the number of visible lines.
*
* @return Number of visible lines
*/
public int getNumVisibleLines() {
return lastVisibleLine - firstVisibleLine;
}
/**
* {@inheritDoc}
*
* @param e Component event
*/
@Override
public void componentResized(final ComponentEvent e) {
recalc();
}
/**
* {@inheritDoc}
*
* @param e Component event
*/
@Override
public void componentMoved(final ComponentEvent e) {
//Ignore
}
/**
* {@inheritDoc}
*
* @param e Component event
*/
@Override
public void componentShown(final ComponentEvent e) {
//Ignore
}
/**
* {@inheritDoc}
*
* @param e Component event
*/
@Override
public void componentHidden(final ComponentEvent e) {
//Ignore
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
updateCachedSettings();
}
}
| true | true | private void paintOntoGraphics(final Graphics2D g) {
final float formatWidth = getWidth() - DOUBLE_SIDE_PADDING;
final float formatHeight = getHeight();
float drawPosY = formatHeight;
int paragraphStart;
int paragraphEnd;
LineBreakMeasurer lineMeasurer;
textLayouts.clear();
positions.clear();
//check theres something to draw and theres some space to draw in
if (document.getNumLines() == 0 || formatWidth < 1) {
setCursor(Cursor.getDefaultCursor());
return;
}
// Check the start line is in range
if (startLine >= document.getNumLines()) {
startLine = document.getNumLines() - 1;
}
if (startLine <= 0) {
startLine = 0;
}
//sets the last visible line
lastVisibleLine = startLine;
firstVisibleLine = startLine;
// Iterate through the lines
for (int line = startLine; line >= 0; line--) {
float drawPosX;
final AttributedCharacterIterator iterator = document.getStyledLine(
line);
int lineHeight = document.getLineHeight(line);
lineHeight += lineHeight * 0.2;
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
lineMeasurer = new LineBreakMeasurer(iterator,
g.getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
final int wrappedLine = getNumWrappedLines(lineMeasurer,
paragraphStart, paragraphEnd,
formatWidth);
if (wrappedLine > 1) {
drawPosY -= lineHeight * wrappedLine;
}
if (line == startLine) {
drawPosY += DOUBLE_SIDE_PADDING;
}
int numberOfWraps = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
// Calculate the Y offset
if (wrappedLine == 1) {
drawPosY -= lineHeight;
} else if (numberOfWraps != 0) {
drawPosY += lineHeight;
}
// Calculate the initial X position
if (layout.isLeftToRight()) {
drawPosX = SINGLE_SIDE_PADDING;
} else {
drawPosX = formatWidth - layout.getAdvance();
}
// Check if the target is in range
if (drawPosY >= 0 || drawPosY <= formatHeight) {
g.setColor(textPane.getForeground());
layout.draw(g, drawPosX, drawPosY + layout.getDescent());
doHighlight(line, chars, layout, g, drawPosY, drawPosX);
firstVisibleLine = line;
textLayouts.put(layout, new LineInfo(line, numberOfWraps));
positions.put(new Rectangle(0, (int) (drawPosY - layout.
getAscent()), (int) (formatWidth +
DOUBLE_SIDE_PADDING), lineHeight), layout);
}
numberOfWraps++;
chars += layout.getCharacterCount();
}
if (numberOfWraps > 1) {
drawPosY -= lineHeight * (wrappedLine - 1);
}
if (drawPosY <= 0) {
break;
}
}
checkForLink();
}
| private void paintOntoGraphics(final Graphics2D g) {
final float formatWidth = getWidth() - DOUBLE_SIDE_PADDING;
final float formatHeight = getHeight();
float drawPosY = formatHeight;
int paragraphStart;
int paragraphEnd;
LineBreakMeasurer lineMeasurer;
textLayouts.clear();
positions.clear();
//check theres something to draw and theres some space to draw in
if (document.getNumLines() == 0 || formatWidth < 1) {
setCursor(Cursor.getDefaultCursor());
return;
}
// Check the start line is in range
if (startLine >= document.getNumLines()) {
startLine = document.getNumLines() - 1;
}
if (startLine <= 0) {
startLine = 0;
}
//sets the last visible line
lastVisibleLine = startLine;
firstVisibleLine = startLine;
// Iterate through the lines
for (int line = startLine; line >= 0; line--) {
float drawPosX;
final AttributedCharacterIterator iterator = document.getStyledLine(
line);
int lineHeight = document.getLineHeight(line);
lineHeight += lineHeight * 0.2;
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
lineMeasurer = new LineBreakMeasurer(iterator,
g.getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
final int wrappedLine = getNumWrappedLines(lineMeasurer,
paragraphStart, paragraphEnd,
formatWidth);
if (wrappedLine > 1) {
drawPosY -= lineHeight * wrappedLine;
}
if (line == startLine) {
drawPosY += DOUBLE_SIDE_PADDING;
}
int numberOfWraps = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
// Calculate the Y offset
if (wrappedLine == 1) {
drawPosY -= lineHeight;
} else if (numberOfWraps != 0) {
drawPosY += lineHeight;
}
// Calculate the initial X position
if (layout.isLeftToRight()) {
drawPosX = SINGLE_SIDE_PADDING;
} else {
drawPosX = formatWidth - layout.getAdvance();
}
// Check if the target is in range
if (drawPosY >= 0 || drawPosY <= formatHeight) {
g.setColor(textPane.getForeground());
layout.draw(g, drawPosX, drawPosY + layout.getDescent());
doHighlight(line, chars, layout, g, drawPosY, drawPosX);
firstVisibleLine = line;
textLayouts.put(layout, new LineInfo(line, numberOfWraps));
positions.put(new Rectangle(0, (int) (drawPosY - layout.
getDescent() - layout.getDescent()), (int) (formatWidth +
DOUBLE_SIDE_PADDING), document.getLineHeight(line)), layout);
}
numberOfWraps++;
chars += layout.getCharacterCount();
}
if (numberOfWraps > 1) {
drawPosY -= lineHeight * (wrappedLine - 1);
}
if (drawPosY <= 0) {
break;
}
}
checkForLink();
}
|
diff --git a/src/com/irccloud/android/fragment/MessageViewFragment.java b/src/com/irccloud/android/fragment/MessageViewFragment.java
index c85aa7f5..6255766b 100644
--- a/src/com/irccloud/android/fragment/MessageViewFragment.java
+++ b/src/com/irccloud/android/fragment/MessageViewFragment.java
@@ -1,2155 +1,2155 @@
/*
* Copyright (c) 2013 IRCCloud, Ltd.
*
* 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.irccloud.android.fragment;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import android.support.v4.app.ListFragment;
import android.text.TextUtils;
import android.view.animation.AlphaAnimation;
import android.widget.*;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.google.gson.JsonObject;
import com.irccloud.android.AsyncTaskEx;
import com.irccloud.android.data.BuffersDataSource;
import com.irccloud.android.fragment.BuffersListFragment.OnBufferSelectedListener;
import com.irccloud.android.CollapsedEventsList;
import com.irccloud.android.ColorFormatter;
import com.irccloud.android.data.EventsDataSource;
import com.irccloud.android.IRCCloudJSONObject;
import com.irccloud.android.Ignore;
import com.irccloud.android.NetworkConnection;
import com.irccloud.android.R;
import com.irccloud.android.data.ServersDataSource;
public class MessageViewFragment extends ListFragment {
private NetworkConnection conn;
private TextView statusView;
private View headerViewContainer;
private View headerView;
private TextView backlogFailed;
private Button loadBacklogButton;
private TextView unreadTopLabel;
private TextView unreadBottomLabel;
private View unreadTopView;
private View unreadBottomView;
private TextView highlightsTopLabel;
private TextView highlightsBottomLabel;
private BuffersDataSource.Buffer buffer;
private ServersDataSource.Server server;
private long earliest_eid;
private long backlog_eid = 0;
private boolean requestingBacklog = false;
private float avgInsertTime = 0;
private int newMsgs = 0;
private long newMsgTime = 0;
private int newHighlights = 0;
private MessageViewListener mListener;
private TextView errorMsg = null;
private TextView connectingMsg = null;
private ProgressBar progressBar = null;
private Timer countdownTimer = null;
private String error = null;
private View connecting = null;
private View awayView = null;
private TextView awayTxt = null;
private int timestamp_width = -1;
private View globalMsgView = null;
private TextView globalMsg = null;
private ProgressBar spinner = null;
public static final int ROW_MESSAGE = 0;
public static final int ROW_TIMESTAMP = 1;
public static final int ROW_BACKLOGMARKER = 2;
public static final int ROW_SOCKETCLOSED = 3;
public static final int ROW_LASTSEENEID = 4;
private static final String TYPE_TIMESTAMP = "__timestamp__";
private static final String TYPE_BACKLOGMARKER = "__backlog__";
private static final String TYPE_LASTSEENEID = "__lastseeneid__";
private MessageAdapter adapter;
private long currentCollapsedEid = -1;
private CollapsedEventsList collapsedEvents = new CollapsedEventsList();
private int lastCollapsedDay = -1;
private HashSet<Long> expandedSectionEids = new HashSet<Long>();
private RefreshTask refreshTask = null;
private HeartbeatTask heartbeatTask = null;
private Ignore ignore = new Ignore();
private Timer tapTimer = null;
private boolean longPressOverride = false;
private LinkMovementMethodNoLongPress linkMovementMethodNoLongPress = new LinkMovementMethodNoLongPress();
public boolean ready = false;
private boolean dirty = true;
private final Object adapterLock = new Object();
public View suggestionsContainer = null;
public GridView suggestions = null;
private class LinkMovementMethodNoLongPress extends LinkMovementMethod {
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
if(longPressOverride) {
longPressOverride = false;
return false;
} else {
return super.onTouchEvent(widget, buffer, event);
}
}
}
private class MessageAdapter extends BaseAdapter {
ArrayList<EventsDataSource.Event> data;
private ListFragment ctx;
private long max_eid = 0;
private long min_eid = 0;
private int lastDay = -1;
private int lastSeenEidMarkerPosition = -1;
private int currentGroupPosition = -1;
private TreeSet<Integer> unseenHighlightPositions;
private class ViewHolder {
int type;
TextView timestamp;
TextView message;
ImageView expandable;
ImageView failed;
}
public MessageAdapter(ListFragment context) {
ctx = context;
data = new ArrayList<EventsDataSource.Event>();
unseenHighlightPositions = new TreeSet<Integer>(Collections.reverseOrder());
}
public void clear() {
max_eid = 0;
min_eid = 0;
lastDay = -1;
lastSeenEidMarkerPosition = -1;
currentGroupPosition = -1;
data.clear();
unseenHighlightPositions.clear();
}
public void clearPending() {
for(int i = 0; i < data.size(); i++) {
if(data.get(i).reqid != -1 && data.get(i).color == R.color.timestamp) {
data.remove(i);
i--;
}
}
}
public void removeItem(long eid) {
for(int i = 0; i < data.size(); i++) {
if(data.get(i).eid == eid) {
data.remove(i);
i--;
}
}
}
public int getBacklogMarkerPosition() {
try {
for(int i = 0; data != null && i < data.size(); i++) {
EventsDataSource.Event e = data.get(i);
if(e != null && e.row_type == ROW_BACKLOGMARKER) {
return i;
}
}
} catch (Exception e) {
}
return -1;
}
public int insertLastSeenEIDMarker() {
EventsDataSource.Event e = EventsDataSource.getInstance().new Event();
e.type = TYPE_LASTSEENEID;
e.row_type = ROW_LASTSEENEID;
e.bg_color = R.drawable.socketclosed_bg;
for(int i = 0; i < data.size(); i++) {
if(data.get(i).row_type == ROW_LASTSEENEID) {
data.remove(i);
}
}
if(min_eid > 0 && buffer.last_seen_eid > 0 && min_eid >= buffer.last_seen_eid) {
lastSeenEidMarkerPosition = 0;
} else {
for(int i = data.size() - 1; i >= 0; i--) {
if(data.get(i).eid <= buffer.last_seen_eid) {
lastSeenEidMarkerPosition = i;
break;
}
}
if(lastSeenEidMarkerPosition != data.size() - 1) {
if(lastSeenEidMarkerPosition > 0 && data.get(lastSeenEidMarkerPosition - 1).row_type == ROW_TIMESTAMP)
lastSeenEidMarkerPosition--;
if(lastSeenEidMarkerPosition > 0)
data.add(lastSeenEidMarkerPosition + 1, e);
} else {
lastSeenEidMarkerPosition = -1;
}
}
return lastSeenEidMarkerPosition;
}
public void clearLastSeenEIDMarker() {
for(int i = 0; i < data.size(); i++) {
if(data.get(i).row_type == ROW_LASTSEENEID) {
data.remove(i);
}
}
lastSeenEidMarkerPosition = -1;
}
public int getLastSeenEIDPosition() {
return lastSeenEidMarkerPosition;
}
public int getUnreadHighlightsAbovePosition(int pos) {
int count = 0;
Iterator<Integer> i = unseenHighlightPositions.iterator();
while(i.hasNext()) {
Integer p = i.next();
if(p < pos)
break;
count++;
}
return unseenHighlightPositions.size() - count;
}
public synchronized void addItem(long eid, EventsDataSource.Event e) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(eid / 1000);
int insert_pos = -1;
SimpleDateFormat formatter = null;
if(e.timestamp == null || e.timestamp.length() == 0) {
formatter = new SimpleDateFormat("h:mm a");
if(conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
try {
JSONObject prefs = conn.getUserInfo().prefs;
if(prefs.has("time-24hr") && prefs.getBoolean("time-24hr")) {
if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds"))
formatter = new SimpleDateFormat("H:mm:ss");
else
formatter = new SimpleDateFormat("H:mm");
} else if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds")) {
formatter = new SimpleDateFormat("h:mm:ss a");
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
e.timestamp = formatter.format(calendar.getTime());
}
e.group_eid = currentCollapsedEid;
if(e.group_msg != null && e.html == null)
e.html = e.group_msg;
/*if(e.html != null) {
e.html = ColorFormatter.irc_to_html(e.html);
e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server);
}*/
if(e.day < 1) {
e.day = calendar.get(Calendar.DAY_OF_YEAR);
}
if(currentGroupPosition > 0 && eid == currentCollapsedEid && e.eid != eid) { //Shortcut for replacing the current group
calendar.setTimeInMillis(e.eid / 1000);
lastDay = e.day;
data.remove(currentGroupPosition);
data.add(currentGroupPosition, e);
insert_pos = currentGroupPosition;
} else if(eid > max_eid || data.size() == 0 || eid > data.get(data.size()-1).eid) { //Message at the bottom
if(data.size() > 0) {
lastDay = data.get(data.size()-1).day;
} else {
lastDay = 0;
}
max_eid = eid;
data.add(e);
insert_pos = data.size() - 1;
} else if(min_eid > eid) { //Message goes on top
if(data.size() > 1) {
lastDay = data.get(1).day;
if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline
data.add(0, e);
insert_pos = 0;
} else { //Insert below the dateline
data.add(1, e);
insert_pos = 1;
}
} else {
data.add(0, e);
insert_pos = 0;
}
} else {
int i = 0;
for(EventsDataSource.Event e1 : data) {
if(e1.row_type != ROW_TIMESTAMP && e1.eid > eid && e.eid == eid && e1.group_eid != eid) { //Insert the message
if(i > 0 && data.get(i-1).row_type != ROW_TIMESTAMP) {
lastDay = data.get(i-1).day;
data.add(i, e);
insert_pos = i;
break;
} else { //There was a date line above our insertion point
lastDay = e1.day;
if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline
if(i > 1) {
lastDay = data.get(i-2).day;
} else {
//We're above the first dateline, so we'll need to put a new one on top!
lastDay = 0;
}
data.add(i-1, e);
insert_pos = i-1;
} else { //Insert below the dateline
data.add(i, e);
insert_pos = i;
}
break;
}
} else if(e1.row_type != ROW_TIMESTAMP && (e1.eid == eid || e1.group_eid == eid)) { //Replace the message
lastDay = calendar.get(Calendar.DAY_OF_YEAR);
data.remove(i);
data.add(i, e);
insert_pos = i;
break;
}
i++;
}
}
if(insert_pos == -1) {
Log.e("IRCCloud", "Couldn't insert EID: " + eid + " MSG: " + e.html);
return;
}
if(eid > buffer.last_seen_eid && e.highlight)
unseenHighlightPositions.add(insert_pos);
if(eid < min_eid || min_eid == 0)
min_eid = eid;
if(eid == currentCollapsedEid && e.eid == eid) {
currentGroupPosition = insert_pos;
} else if(currentCollapsedEid == -1) {
currentGroupPosition = -1;
}
if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) {
if(formatter == null)
formatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
else
formatter.applyPattern("EEEE, MMMM dd, yyyy");
EventsDataSource.Event d = EventsDataSource.getInstance().new Event();
d.type = TYPE_TIMESTAMP;
d.row_type = ROW_TIMESTAMP;
d.eid = eid;
d.timestamp = formatter.format(calendar.getTime());
d.bg_color = R.drawable.row_timestamp_bg;
d.day = lastDay = calendar.get(Calendar.DAY_OF_YEAR);
data.add(insert_pos, d);
if(currentGroupPosition > -1)
currentGroupPosition++;
}
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return data.get(position).eid;
}
public void format() {
for(int i = 0; i < data.size(); i++) {
EventsDataSource.Event e = data.get(i);
synchronized(e) {
if(e.html != null) {
try {
e.html = ColorFormatter.irc_to_html(e.html);
e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server);
if(e.msg != null && e.msg.length() > 0)
e.contentDescription = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(e.msg), e.linkify, server).toString();
} catch (Exception ex) {
}
}
}
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
EventsDataSource.Event e = data.get(position);
synchronized (e) {
View row = convertView;
ViewHolder holder;
if(row != null && ((ViewHolder)row.getTag()).type != e.row_type)
row = null;
if (row == null) {
LayoutInflater inflater = ctx.getLayoutInflater(null);
if(e.row_type == ROW_BACKLOGMARKER)
row = inflater.inflate(R.layout.row_backlogmarker, null);
else if(e.row_type == ROW_TIMESTAMP)
row = inflater.inflate(R.layout.row_timestamp, null);
else if(e.row_type == ROW_SOCKETCLOSED)
row = inflater.inflate(R.layout.row_socketclosed, null);
else if(e.row_type == ROW_LASTSEENEID)
row = inflater.inflate(R.layout.row_lastseeneid, null);
else
row = inflater.inflate(R.layout.row_message, null);
holder = new ViewHolder();
holder.timestamp = (TextView) row.findViewById(R.id.timestamp);
holder.message = (TextView) row.findViewById(R.id.message);
holder.expandable = (ImageView) row.findViewById(R.id.expandable);
holder.failed = (ImageView) row.findViewById(R.id.failed);
holder.type = e.row_type;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
row.setOnClickListener(new OnItemClickListener(position));
if(e.html != null && e.formatted == null) {
e.html = ColorFormatter.irc_to_html(e.html);
e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server);
if(e.msg != null && e.msg.length() > 0)
e.contentDescription = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(e.msg), e.linkify, server).toString();
}
if(e.row_type == ROW_MESSAGE) {
if(e.bg_color == R.color.message_bg)
row.setBackgroundDrawable(null);
else
row.setBackgroundResource(e.bg_color);
if(e.contentDescription != null && e.from != null && e.from.length() > 0 && e.msg != null && e.msg.length() > 0) {
row.setContentDescription("Message from " + e.from + " at " + e.timestamp + ": " + e.contentDescription);
}
}
if(holder.timestamp != null) {
if(e.highlight)
holder.timestamp.setTextColor(getResources().getColor(R.color.highlight_timestamp));
else if(e.row_type != ROW_TIMESTAMP)
holder.timestamp.setTextColor(getResources().getColor(R.color.timestamp));
holder.timestamp.setText(e.timestamp);
holder.timestamp.setMinWidth(timestamp_width);
}
if(e.row_type == ROW_SOCKETCLOSED) {
if(e.msg.length() > 0) {
holder.timestamp.setVisibility(View.VISIBLE);
holder.message.setVisibility(View.VISIBLE);
} else {
holder.timestamp.setVisibility(View.GONE);
holder.message.setVisibility(View.GONE);
}
}
if(holder.message != null && e.html != null) {
holder.message.setMovementMethod(linkMovementMethodNoLongPress);
holder.message.setOnClickListener(new OnItemClickListener(position));
if(e.msg != null && e.msg.startsWith("<pre>"))
holder.message.setTypeface(Typeface.MONOSPACE);
else
holder.message.setTypeface(Typeface.DEFAULT);
try {
holder.message.setTextColor(getResources().getColorStateList(e.color));
} catch (Exception e1) {
}
if(e.color == R.color.timestamp || e.pending)
holder.message.setLinkTextColor(getResources().getColor(R.color.lightLinkColor));
else
holder.message.setLinkTextColor(getResources().getColor(R.color.linkColor));
holder.message.setText(e.formatted);
if(e.from != null && e.from.length() > 0 && e.msg != null && e.msg.length() > 0) {
holder.message.setContentDescription(e.from + ": " + e.contentDescription);
}
}
if(holder.expandable != null) {
if(e.group_eid > 0 && (e.group_eid != e.eid || expandedSectionEids.contains(e.group_eid))) {
if(expandedSectionEids.contains(e.group_eid)) {
if(e.group_eid == e.eid + 1) {
holder.expandable.setImageResource(R.drawable.bullet_toggle_minus);
row.setBackgroundResource(R.color.status_bg);
} else {
holder.expandable.setImageResource(R.drawable.tiny_plus);
row.setBackgroundResource(R.color.expanded_row_bg);
}
} else {
holder.expandable.setImageResource(R.drawable.bullet_toggle_plus);
}
holder.expandable.setVisibility(View.VISIBLE);
} else {
holder.expandable.setVisibility(View.GONE);
}
}
if(holder.failed != null)
holder.failed.setVisibility(e.failed?View.VISIBLE:View.GONE);
return row;
}
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.messageview, container, false);
connecting = v.findViewById(R.id.connecting);
errorMsg = (TextView)v.findViewById(R.id.errorMsg);
connectingMsg = (TextView)v.findViewById(R.id.connectingMsg);
progressBar = (ProgressBar)v.findViewById(R.id.connectingProgress);
statusView = (TextView)v.findViewById(R.id.statusView);
statusView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(server != null && server.status != null && server.status.equalsIgnoreCase("disconnected")) {
conn.reconnect(buffer.cid);
}
}
});
awayView = v.findViewById(R.id.away);
awayView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
conn.back(buffer.cid);
}
});
awayTxt = (TextView)v.findViewById(R.id.awayTxt);
unreadBottomView = v.findViewById(R.id.unreadBottom);
unreadBottomView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getListView().setSelection(adapter.getCount() - 1);
}
});
unreadBottomLabel = (TextView)v.findViewById(R.id.unread);
highlightsBottomLabel = (TextView)v.findViewById(R.id.highlightsBottom);
unreadTopView = v.findViewById(R.id.unreadTop);
unreadTopView.setVisibility(View.GONE);
unreadTopView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(adapter.getLastSeenEIDPosition() > 0) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
unreadTopView.setVisibility(View.GONE);
}
getListView().setSelection(adapter.getLastSeenEIDPosition());
}
});
unreadTopLabel = (TextView)v.findViewById(R.id.unreadTopText);
highlightsTopLabel = (TextView)v.findViewById(R.id.highlightsTop);
Button b = (Button)v.findViewById(R.id.markAsRead);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
unreadTopView.setVisibility(View.GONE);
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
});
globalMsgView = v.findViewById(R.id.globalMessageView);
globalMsg = (TextView)v.findViewById(R.id.globalMessageTxt);
b = (Button)v.findViewById(R.id.dismissGlobalMessage);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(conn != null)
conn.globalMsg = null;
update_global_msg();
}
});
((ListView)v.findViewById(android.R.id.list)).setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
if(pos > 1 && pos <= adapter.data.size()) {
longPressOverride = mListener.onMessageLongClicked(adapter.data.get(pos - 1));
return longPressOverride;
} else {
return false;
}
}
});
spinner = (ProgressBar)v.findViewById(R.id.spinner);
suggestionsContainer = v.findViewById(R.id.suggestionsContainer);
suggestions = (GridView)v.findViewById(R.id.suggestions);
headerViewContainer = getLayoutInflater(null).inflate(R.layout.messageview_header, null);
headerView = headerViewContainer.findViewById(R.id.progress);
backlogFailed = (TextView)headerViewContainer.findViewById(R.id.backlogFailed);
loadBacklogButton = (Button)headerViewContainer.findViewById(R.id.loadBacklogButton);
loadBacklogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
headerView.setVisibility(View.VISIBLE);
conn.request_backlog(buffer.cid, buffer.bid, earliest_eid);
}
});
return v;
}
public void showSpinner(boolean show) {
if(show) {
AlphaAnimation anim = new AlphaAnimation(0, 1);
anim.setDuration(150);
anim.setFillAfter(true);
spinner.setAnimation(anim);
spinner.setVisibility(View.VISIBLE);
} else {
AlphaAnimation anim = new AlphaAnimation(1, 0);
anim.setDuration(150);
anim.setFillAfter(true);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
spinner.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
spinner.setAnimation(anim);
}
}
private OnScrollListener mOnScrollListener = new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(!ready)
return;
if(connecting.getVisibility() == View.VISIBLE)
return;
if(headerView != null && buffer != null && buffer.min_eid > 0 && conn.ready) {
if(firstVisibleItem == 0 && !requestingBacklog && headerView.getVisibility() == View.VISIBLE && conn.getState() == NetworkConnection.STATE_CONNECTED) {
requestingBacklog = true;
conn.request_backlog(buffer.cid, buffer.bid, earliest_eid);
}
}
if(unreadBottomView != null && adapter != null && adapter.data.size() > 0) {
if(firstVisibleItem + visibleItemCount == totalItemCount) {
unreadBottomView.setVisibility(View.GONE);
if(unreadTopView.getVisibility() == View.GONE) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
newMsgs = 0;
newMsgTime = 0;
newHighlights = 0;
}
}
if(firstVisibleItem + visibleItemCount < totalItemCount) {
View v = view.getChildAt(0);
buffer.scrolledUp = true;
buffer.scrollPosition = firstVisibleItem;
buffer.scrollPositionOffset = (v == null)?0:v.getTop();
} else {
buffer.scrolledUp = false;
buffer.scrollPosition = -1;
}
if(adapter != null && adapter.data.size() > 0 && unreadTopView != null && unreadTopView.getVisibility() == View.VISIBLE) {
mUpdateTopUnreadRunnable.run();
int markerPos = -1;
if(adapter != null)
markerPos = adapter.getLastSeenEIDPosition();
if(markerPos > 1 && getListView().getFirstVisiblePosition() <= markerPos) {
unreadTopView.setVisibility(View.GONE);
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conn = NetworkConnection.getInstance();
if(savedInstanceState != null && savedInstanceState.containsKey("bid")) {
buffer = BuffersDataSource.getInstance().getBuffer(savedInstanceState.getInt("bid"));
if(buffer != null)
server = ServersDataSource.getInstance().getServer(buffer.cid);
backlog_eid = savedInstanceState.getLong("backlog_eid");
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (MessageViewListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement MessageViewListener");
}
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
if(buffer != null)
state.putInt("bid", buffer.bid);
state.putLong("backlog_eid", backlog_eid);
}
@Override
public void setArguments(Bundle args) {
ready = false;
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = null;
if(tapTimer != null)
tapTimer.cancel();
tapTimer = null;
if(buffer == null || (args.containsKey("bid") && args.getInt("bid", 0) != buffer.bid)) {
dirty = true;
}
buffer = BuffersDataSource.getInstance().getBuffer(args.getInt("bid", -1));
server = ServersDataSource.getInstance().getServer(buffer.cid);
requestingBacklog = false;
avgInsertTime = 0;
newMsgs = 0;
newMsgTime = 0;
newHighlights = 0;
earliest_eid = 0;
backlog_eid = 0;
currentCollapsedEid = -1;
lastCollapsedDay = -1;
if(server != null) {
ignore.setIgnores(server.ignores);
if(server.away != null && server.away.length() > 0) {
awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + server.away + ")"))).toString());
awayView.setVisibility(View.VISIBLE);
} else {
awayView.setVisibility(View.GONE);
}
update_status(server.status, server.fail_info);
}
if(unreadTopView != null)
unreadTopView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
if(getListView().getHeaderViewsCount() == 0) {
getListView().addHeaderView(headerViewContainer);
}
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)headerView.getLayoutParams();
lp.topMargin = 0;
headerView.setLayoutParams(lp);
lp = (ViewGroup.MarginLayoutParams)backlogFailed.getLayoutParams();
lp.topMargin = 0;
backlogFailed.setLayoutParams(lp);
if(EventsDataSource.getInstance().getEventsForBuffer(buffer.bid) != null) {
requestingBacklog = true;
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
if(adapter != null) {
refreshTask.execute((Void)null);
} else {
refreshTask.onPreExecute();
refreshTask.onPostExecute(refreshTask.doInBackground());
}
} else {
if(buffer == null || buffer.min_eid == 0 || earliest_eid == buffer.min_eid || conn.getState() != NetworkConnection.STATE_CONNECTED || !conn.ready) {
headerView.setVisibility(View.GONE);
} else {
headerView.setVisibility(View.VISIBLE);
}
if(adapter != null) {
adapter.clear();
adapter.notifyDataSetInvalidated();
}
mListener.onMessageViewReady();
ready = true;
}
}
private synchronized void insertEvent(final MessageAdapter adapter, EventsDataSource.Event event, boolean backlog, boolean nextIsGrouped) {
synchronized(adapterLock) {
try {
boolean colors = false;
if(!event.self && conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("nick-colors") && conn.getUserInfo().prefs.getBoolean("nick-colors"))
colors = true;
long start = System.currentTimeMillis();
if(event.eid <= buffer.min_eid) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
if(earliest_eid == 0 || event.eid < earliest_eid)
earliest_eid = event.eid;
String type = event.type;
long eid = event.eid;
if(type.startsWith("you_"))
type = type.substring(4);
if(type.equals("joined_channel") || type.equals("parted_channel") || type.equals("nickchange") || type.equals("quit") || type.equals("user_channel_mode")) {
boolean shouldExpand = false;
boolean showChan = !buffer.type.equals("channel");
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = null;
if(buffer.type.equals("channel")) {
if(conn.getUserInfo().prefs.has("channel-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("buffer-hideJoinPart");
}
if(hiddenMap != null && hiddenMap.has(String.valueOf(buffer.bid)) && hiddenMap.getBoolean(String.valueOf(buffer.bid))) {
adapter.removeItem(event.eid);
if(!backlog)
adapter.notifyDataSetChanged();
return;
}
JSONObject expandMap = null;
if(buffer.type.equals("channel")) {
if(conn.getUserInfo().prefs.has("channel-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("channel-expandJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("buffer-expandJoinPart");
}
if(expandMap != null && expandMap.has(String.valueOf(buffer.bid)) && expandMap.getBoolean(String.valueOf(buffer.bid))) {
shouldExpand = true;
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(eid / 1000);
if(shouldExpand)
expandedSectionEids.clear();
if(currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay || shouldExpand) {
collapsedEvents.clear();
currentCollapsedEid = eid;
lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR);
}
if(!showChan)
event.chan = buffer.name;
if(!collapsedEvents.addEvent(event))
collapsedEvents.clear();
if((currentCollapsedEid == event.eid || shouldExpand) && type.equals("user_channel_mode")) {
event.color = R.color.row_message_label;
event.bg_color = R.color.status_bg;
} else {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
String msg;
if(expandedSectionEids.contains(currentCollapsedEid)) {
CollapsedEventsList c = new CollapsedEventsList();
c.PREFIX = collapsedEvents.PREFIX;
c.addEvent(event);
msg = c.getCollapsedMessage(showChan);
if(!nextIsGrouped) {
String group_msg = collapsedEvents.getCollapsedMessage(showChan);
if(group_msg == null && type.equals("nickchange")) {
group_msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(group_msg == null && type.equals("user_channel_mode")) {
if(event.from != null && event.from.length() > 0)
- msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.from + "</b>";
+ msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by <b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>";
else
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>";
currentCollapsedEid = eid;
}
EventsDataSource.Event heading = EventsDataSource.getInstance().new Event();
heading.type = "__expanded_group_heading__";
heading.cid = event.cid;
heading.bid = event.bid;
heading.eid = currentCollapsedEid - 1;
heading.group_msg = group_msg;
heading.color = R.color.timestamp;
heading.bg_color = R.color.message_bg;
heading.linkify = false;
adapter.addItem(currentCollapsedEid - 1, heading);
}
event.timestamp = null;
} else {
msg = (nextIsGrouped && currentCollapsedEid != event.eid)?"":collapsedEvents.getCollapsedMessage(showChan);
}
if(msg == null && type.equals("nickchange")) {
msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(msg == null && type.equals("user_channel_mode")) {
if(event.from != null && event.from.length() > 0)
- msg = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>";
+ msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by <b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>";
else
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>";
currentCollapsedEid = eid;
}
if(!expandedSectionEids.contains(currentCollapsedEid)) {
if(eid != currentCollapsedEid) {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
eid = currentCollapsedEid;
}
event.group_msg = msg;
event.html = null;
event.formatted = null;
event.linkify = false;
} else {
currentCollapsedEid = -1;
collapsedEvents.clear();
if(event.html == null) {
if(event.from != null)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, colors) + "</b> " + event.msg;
else if(event.type.equals("buffer_msg") && event.server != null)
event.html = "<b>" + event.server + "</b> " + event.msg;
else
event.html = event.msg;
}
}
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
if(from != null && event.hostmask != null && !type.equals("user_channel_mode") && !type.contains("kicked")) {
String usermask = from + "!" + event.hostmask;
if(ignore.match(usermask)) {
if(unreadTopView != null && unreadTopView.getVisibility() == View.GONE && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
return;
}
}
if(type.equals("channel_mode")) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
} else if(type.equals("buffer_me_msg")) {
event.html = "— <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode, colors) + "</b> " + event.msg + "</i>";
} else if(type.equals("notice")) {
if(event.from != null && event.from.length() > 0)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> ";
else
event.html = "";
if(buffer.type.equals("console") && event.to_chan && event.chan != null && event.chan.length() > 0) {
event.html += event.chan + "﹕ " + event.msg;
} else {
event.html += event.msg;
}
} else if(type.equals("kicked_channel")) {
event.html = "← ";
if(event.type.startsWith("you_"))
event.html += "You";
else
event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null, false) + "</b>";
if(event.type.startsWith("you_"))
event.html += " were";
else
event.html += " was";
if(event.hostmask != null && event.hostmask.length() > 0)
event.html += " kicked by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b> (" + event.hostmask + ")";
else
event.html += " kicked by the server <b>" + event.nick + "</b>";
if(event.msg != null && event.msg.length() > 0)
event.html += ": " + event.msg;
} else if(type.equals("callerid")) {
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> ("+ event.hostmask + ") " + event.msg + " Tap to accept.";
} else if(type.equals("channel_mode_list_change")) {
if(event.from.length() == 0) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
}
}
adapter.addItem(eid, event);
if(!backlog)
adapter.notifyDataSetChanged();
long time = (System.currentTimeMillis() - start);
if(avgInsertTime == 0)
avgInsertTime = time;
avgInsertTime += time;
avgInsertTime /= 2.0;
//Log.i("IRCCloud", "Average insert time: " + avgInsertTime);
if(!backlog && buffer.scrolledUp && !event.self && event.isImportant(type)) {
if(newMsgTime == 0)
newMsgTime = System.currentTimeMillis();
newMsgs++;
if(event.highlight)
newHighlights++;
update_unread();
}
if(!backlog && !buffer.scrolledUp) {
getListView().setSelection(adapter.getCount() - 1);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
getListView().setSelection(adapter.getCount() - 1);
} catch (Exception e) {
//List view isn't ready yet
}
}
}, 200);
}
if(!backlog && event.highlight && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit();
editor.putBoolean("mentionTip", true);
editor.commit();
}
if(!backlog) {
int markerPos = adapter.getLastSeenEIDPosition();
if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) {
unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class OnItemClickListener implements OnClickListener {
private int pos;
OnItemClickListener(int position){
pos = position;
}
@Override
public void onClick(View arg0) {
longPressOverride = false;
if(pos < 0 || pos >= adapter.data.size())
return;
if(adapter != null) {
if(tapTimer != null) {
tapTimer.cancel();
tapTimer = null;
mListener.onMessageDoubleClicked(adapter.data.get(pos));
} else {
Timer t = new Timer();
t.schedule(new TimerTask() {
int position = pos;
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
if(adapter != null && adapter.data != null && position < adapter.data.size()) {
EventsDataSource.Event e = adapter.data.get(position);
if(e != null) {
if(e.type.equals("channel_invite")) {
conn.join(buffer.cid, e.old_nick, null);
} else if(e.type.equals("callerid")) {
conn.say(buffer.cid, null, "/accept " + e.from);
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(buffer.cid, e.from);
if(b != null) {
mListener.onBufferSelected(b.bid);
} else {
conn.say(b.cid, null, "/query " + e.from);
}
} else {
long group = e.group_eid;
if(expandedSectionEids.contains(group))
expandedSectionEids.remove(group);
else if(e.eid != group)
expandedSectionEids.add(group);
if(e.eid != e.group_eid) {
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
refreshTask.execute((Void)null);
}
}
}
}
}
});
tapTimer = null;
}
}, 300);
tapTimer = t;
}
}
}
}
@SuppressWarnings("unchecked")
public void onResume() {
super.onResume();
conn.addHandler(mHandler);
if(conn.getState() != NetworkConnection.STATE_CONNECTED || !NetworkConnection.getInstance().ready) {
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
anim.setDuration(200);
anim.setFillAfter(true);
connecting.startAnimation(anim);
connecting.setVisibility(View.VISIBLE);
}
getListView().requestFocus();
getListView().setOnScrollListener(mOnScrollListener);
updateReconnecting();
update_global_msg();
}
private class HeartbeatTask extends AsyncTaskEx<Void, Void, Void> {
@Override
protected void onPreExecute() {
//Log.d("IRCCloud", "Heartbeat task created. Ready: " + ready + " BID: " + bid);
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
}
if(isCancelled())
return null;
if(connecting.getVisibility() == View.VISIBLE)
return null;
try {
TreeMap<Long, EventsDataSource.Event> events = EventsDataSource.getInstance().getEventsForBuffer(buffer.bid);
if(events != null && events.size() > 0) {
Long eid = events.get(events.lastKey()).eid;
if(eid > buffer.last_seen_eid && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) {
if(getActivity() != null && getActivity().getIntent() != null)
getActivity().getIntent().putExtra("last_seen_eid", eid);
NetworkConnection.getInstance().heartbeat(buffer.cid, buffer.bid, eid);
BuffersDataSource.getInstance().updateLastSeenEid(buffer.bid, eid);
}
}
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(!isCancelled())
heartbeatTask = null;
}
}
private class FormatTask extends AsyncTaskEx<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
adapter.format();
return null;
}
@Override
protected void onPostExecute(Void result) {
}
}
private class RefreshTask extends AsyncTaskEx<Void, Void, Void> {
private MessageAdapter adapter;
TreeMap<Long,EventsDataSource.Event> events;
int oldPosition = -1;
int topOffset = -1;
@Override
protected void onPreExecute() {
//Debug.startMethodTracing("refresh");
try {
oldPosition = getListView().getFirstVisiblePosition();
View v = getListView().getChildAt(0);
topOffset = (v == null) ? 0 : v.getTop();
} catch (IllegalStateException e) {
//The list view isn't on screen anymore
cancel(true);
refreshTask = null;
}
}
@SuppressWarnings("unchecked")
@Override
protected Void doInBackground(Void... params) {
long time = System.currentTimeMillis();
if(buffer != null)
events = EventsDataSource.getInstance().getEventsForBuffer(buffer.bid);
Log.i("IRCCloud", "Loaded data in " + (System.currentTimeMillis() - time) + "ms");
if(!isCancelled() && events != null && events.size() > 0) {
events = (TreeMap<Long, EventsDataSource.Event>)events.clone();
if(isCancelled())
return null;
if(events != null && events.size() > 0) {
try {
if(MessageViewFragment.this.adapter != null && MessageViewFragment.this.adapter.data.size() > 0 && earliest_eid > events.firstKey()) {
if(oldPosition > 0 && oldPosition == MessageViewFragment.this.adapter.data.size())
oldPosition--;
EventsDataSource.Event e = MessageViewFragment.this.adapter.data.get(oldPosition);
if(e != null)
backlog_eid = e.group_eid - 1;
else
backlog_eid = -1;
if(backlog_eid < 0) {
backlog_eid = MessageViewFragment.this.adapter.getItemId(oldPosition) - 1;
}
EventsDataSource.Event backlogMarker = EventsDataSource.getInstance().new Event();
backlogMarker.eid = backlog_eid;
backlogMarker.type = TYPE_BACKLOGMARKER;
backlogMarker.row_type = ROW_BACKLOGMARKER;
backlogMarker.html = "__backlog__";
backlogMarker.bg_color = R.color.message_bg;
events.put(backlog_eid, backlogMarker);
}
adapter = new MessageAdapter(MessageViewFragment.this);
refresh(adapter, events);
} catch (IndexOutOfBoundsException e) {
return null;
} catch (IllegalStateException e) {
//The list view doesn't exist yet
Log.e("IRCCloud", "Tried to refresh the message list, but it didn't exist.");
}
} else if(buffer != null && buffer.min_eid > 0 && conn.ready && conn.getState() == NetworkConnection.STATE_CONNECTED) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.VISIBLE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(!isCancelled() && adapter != null) {
try {
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) headerView.getLayoutParams();
if(adapter.getLastSeenEIDPosition() == 0)
lp.topMargin = (int)getResources().getDimension(R.dimen.top_bar_height);
else
lp.topMargin = 0;
headerView.setLayoutParams(lp);
lp = (ViewGroup.MarginLayoutParams)backlogFailed.getLayoutParams();
if(adapter.getLastSeenEIDPosition() == 0)
lp.topMargin = (int)getResources().getDimension(R.dimen.top_bar_height);
else
lp.topMargin = 0;
backlogFailed.setLayoutParams(lp);
setListAdapter(adapter);
MessageViewFragment.this.adapter = adapter;
if(events != null && events.size() > 0) {
int markerPos = adapter.getBacklogMarkerPosition();
if(markerPos != -1 && requestingBacklog)
getListView().setSelectionFromTop(oldPosition + markerPos + 1, headerViewContainer.getHeight());
else if(!buffer.scrolledUp)
getListView().setSelection(adapter.getCount() - 1);
else {
getListView().setSelectionFromTop(buffer.scrollPosition, buffer.scrollPositionOffset);
newMsgs = 0;
newHighlights = 0;
for(int i = adapter.data.size() - 1; i >= 0; i--) {
EventsDataSource.Event e = adapter.data.get(i);
if(e.eid <= buffer.last_seen_eid)
break;
if(e.isImportant(buffer.type)) {
if(e.highlight)
newHighlights++;
else
newMsgs++;
}
}
update_unread();
}
}
new FormatTask().execute((Void)null);
} catch (IllegalStateException e) {
//The list view isn't on screen anymore
}
refreshTask = null;
requestingBacklog = false;
//Debug.stopMethodTracing();
}
}
}
private synchronized void refresh(MessageAdapter adapter, TreeMap<Long,EventsDataSource.Event> events) {
synchronized (adapterLock) {
if(conn.getReconnectTimestamp() == 0)
conn.cancel_idle_timer(); //This may take a while...
if(dirty) {
Log.i("IRCCloud", "BID changed, clearing caches");
EventsDataSource.getInstance().clearCacheForBuffer(buffer.bid);
dirty = false;
}
collapsedEvents.clear();
currentCollapsedEid = -1;
lastCollapsedDay = -1;
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
try {
JSONObject prefs = conn.getUserInfo().prefs;
timestamp_width = (int)getResources().getDimension(R.dimen.timestamp_base);
if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds"))
timestamp_width += (int)getResources().getDimension(R.dimen.timestamp_seconds);
if(!prefs.has("time-24hr") || !prefs.getBoolean("time-24hr"))
timestamp_width += (int)getResources().getDimension(R.dimen.timestamp_ampm);
} catch (Exception e) {
}
} else {
timestamp_width = getResources().getDimensionPixelSize(R.dimen.timestamp_base) + getResources().getDimensionPixelSize(R.dimen.timestamp_ampm);
}
if(events == null || (events.size() == 0 && buffer.min_eid > 0)) {
if(buffer != null && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) {
requestingBacklog = true;
mHandler.post(new Runnable() {
@Override
public void run() {
conn.request_backlog(buffer.cid, buffer.bid, 0);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
} else if(events.size() > 0) {
if(server != null) {
ignore.setIgnores(server.ignores);
collapsedEvents.PREFIX = server.PREFIX;
} else {
ignore.setIgnores(null);
collapsedEvents.PREFIX = null;
}
earliest_eid = events.firstKey();
if(events.firstKey() > buffer.min_eid && buffer.min_eid > 0 && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.VISIBLE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
if(events.size() > 0) {
avgInsertTime = 0;
//Debug.startMethodTracing("refresh");
long start = System.currentTimeMillis();
Iterator<EventsDataSource.Event> i = events.values().iterator();
EventsDataSource.Event next = i.next();
Calendar calendar = Calendar.getInstance();
while(next != null) {
EventsDataSource.Event e = next;
next = i.hasNext()?i.next():null;
String type = (next == null)?"":next.type;
if(next != null && currentCollapsedEid != -1 && !expandedSectionEids.contains(currentCollapsedEid) && (type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode"))) {
calendar.setTimeInMillis(next.eid / 1000);
insertEvent(adapter, e, true, calendar.get(Calendar.DAY_OF_YEAR) == lastCollapsedDay);
} else {
insertEvent(adapter, e, true, false);
}
}
adapter.insertLastSeenEIDMarker();
Log.i("IRCCloud", "Backlog rendering took: " + (System.currentTimeMillis() - start) + "ms");
//Debug.stopMethodTracing();
avgInsertTime = 0;
//adapter.notifyDataSetChanged();
}
}
mHandler.removeCallbacks(mUpdateTopUnreadRunnable);
mHandler.postDelayed(mUpdateTopUnreadRunnable, 100);
if(conn.getReconnectTimestamp() == 0 && conn.getState() == NetworkConnection.STATE_CONNECTED)
conn.schedule_idle_timer();
}
}
private Runnable mUpdateTopUnreadRunnable = new Runnable() {
@Override
public void run() {
if(adapter != null) {
try {
int markerPos = adapter.getLastSeenEIDPosition();
if(markerPos >= 0 && getListView().getFirstVisiblePosition() > (markerPos + 1)) {
if(shouldTrackUnread()) {
int highlights = adapter.getUnreadHighlightsAbovePosition(getListView().getFirstVisiblePosition());
int count = (getListView().getFirstVisiblePosition() - markerPos - 1) - highlights;
String txt = "";
if(highlights > 0) {
if(highlights == 1)
txt = "mention";
else if(highlights > 0)
txt = "mentions";
highlightsTopLabel.setText(String.valueOf(highlights));
highlightsTopLabel.setVisibility(View.VISIBLE);
if(count > 0)
txt += " and ";
} else {
highlightsTopLabel.setVisibility(View.GONE);
}
if(markerPos == 0) {
long seconds = (long)Math.ceil((earliest_eid - buffer.last_seen_eid) / 1000000.0);
if(seconds < 0) {
if(count < 0) {
unreadTopView.setVisibility(View.GONE);
return;
} else {
if(count == 1)
txt += count + " unread message";
else if(count > 0)
txt += count + " unread messages";
}
} else {
int minutes = (int)Math.ceil(seconds / 60.0);
int hours = (int)Math.ceil(seconds / 60.0 / 60.0);
int days = (int)Math.ceil(seconds / 60.0 / 60.0 / 24.0);
if(hours >= 24) {
if(days == 1)
txt += days + " day of unread messages";
else
txt += days + " days of unread messages";
} else if(hours > 0) {
if(hours == 1)
txt += hours + " hour of unread messages";
else
txt += hours + " hours of unread messages";
} else if(minutes > 0) {
if(minutes == 1)
txt += minutes + " minute of unread messages";
else
txt += minutes + " minutes of unread messages";
} else {
if(seconds == 1)
txt += seconds + " second of unread messages";
else
txt += seconds + " seconds of unread messages";
}
}
} else {
if(count == 1)
txt += count + " unread message";
else if(count > 0)
txt += count + " unread messages";
}
unreadTopLabel.setText(txt);
unreadTopView.setVisibility(View.VISIBLE);
} else {
unreadTopView.setVisibility(View.GONE);
}
} else {
if(markerPos > 0) {
unreadTopView.setVisibility(View.GONE);
if(adapter.data.size() > 0) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
}
}
if(server != null)
update_status(server.status, server.fail_info);
if(mListener != null && !ready)
mListener.onMessageViewReady();
ready = true;
} catch (IllegalStateException e) {
//The list view wasn't on screen yet
}
}
}
};
private boolean shouldTrackUnread() {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) {
try {
JSONObject disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread");
if(disabledMap.has(String.valueOf(buffer.bid)) && disabledMap.getBoolean(String.valueOf(buffer.bid))) {
return false;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
private class UnreadRefreshRunnable implements Runnable {
@Override
public void run() {
update_unread();
}
}
UnreadRefreshRunnable unreadRefreshRunnable = null;
private void update_unread() {
if(unreadRefreshRunnable != null) {
mHandler.removeCallbacks(unreadRefreshRunnable);
unreadRefreshRunnable = null;
}
if(newMsgs > 0) {
/*int minutes = (int)((System.currentTimeMillis() - newMsgTime)/60000);
if(minutes < 1)
unreadBottomLabel.setText("Less than a minute of chatter (");
else if(minutes == 1)
unreadBottomLabel.setText("1 minute of chatter (");
else
unreadBottomLabel.setText(minutes + " minutes of chatter (");
if(newMsgs == 1)
unreadBottomLabel.setText(unreadBottomLabel.getText() + "1 message)");
else
unreadBottomLabel.setText(unreadBottomLabel.getText() + (newMsgs + " messages)"));*/
String txt = "";
int msgCnt = newMsgs - newHighlights;
if(newHighlights > 0) {
if(newHighlights == 1)
txt = "mention";
else
txt = "mentions";
if(msgCnt > 0)
txt += " and ";
highlightsBottomLabel.setText(String.valueOf(newHighlights));
highlightsBottomLabel.setVisibility(View.VISIBLE);
} else {
highlightsBottomLabel.setVisibility(View.GONE);
}
if(msgCnt == 1)
txt += msgCnt + " unread message";
else if(msgCnt > 0)
txt += msgCnt + " unread messages";
unreadBottomLabel.setText(txt);
unreadBottomView.setVisibility(View.VISIBLE);
unreadRefreshRunnable = new UnreadRefreshRunnable();
mHandler.postDelayed(unreadRefreshRunnable, 10000);
}
}
private class StatusRefreshRunnable implements Runnable {
String status;
JsonObject fail_info;
public StatusRefreshRunnable(String status, JsonObject fail_info) {
this.status = status;
this.fail_info = fail_info;
}
@Override
public void run() {
update_status(status, fail_info);
}
}
StatusRefreshRunnable statusRefreshRunnable = null;
public static String ordinal(int i) {
String[] sufixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
switch (i % 100) {
case 11:
case 12:
case 13:
return i + "th";
default:
return i + sufixes[i % 10];
}
}
private String reason_txt(String reason) {
String r = reason;
if(reason.equalsIgnoreCase("pool_lost")) {
r = "Connection pool failed";
} else if(reason.equalsIgnoreCase("no_pool")) {
r = "No available connection pools";
} else if(reason.equalsIgnoreCase("enetdown")) {
r = "Network down";
} else if(reason.equalsIgnoreCase("etimedout") || reason.equalsIgnoreCase("timeout")) {
r = "Timed out";
} else if(reason.equalsIgnoreCase("ehostunreach")) {
r = "Host unreachable";
} else if(reason.equalsIgnoreCase("econnrefused")) {
r = "Connection refused";
} else if(reason.equalsIgnoreCase("nxdomain") || reason.equalsIgnoreCase("einval")) {
r = "Invalid hostname";
} else if(reason.equalsIgnoreCase("server_ping_timeout")) {
r = "PING timeout";
} else if(reason.equalsIgnoreCase("ssl_certificate_error")) {
r = "SSL certificate error";
} else if(reason.equalsIgnoreCase("ssl_error")) {
r = "SSL error";
} else if(reason.equalsIgnoreCase("crash")) {
r = "Connection crashed";
} else if(reason.equalsIgnoreCase("networks")) {
r = "You've exceeded the connection limit for free accounts.";
} else if(reason.equalsIgnoreCase("passworded_servers")) {
r = "You can't connect to passworded servers with free accounts.";
}
return r;
}
private void update_status(String status, JsonObject fail_info) {
if(statusRefreshRunnable != null) {
mHandler.removeCallbacks(statusRefreshRunnable);
statusRefreshRunnable = null;
}
if(status.equals("connected_ready")) {
if(server != null && server.lag >= 2*1000*1000) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Slow ping response from " + server.hostname + " (" + (server.lag / 1000 / 1000) + "s)");
} else {
statusView.setVisibility(View.GONE);
statusView.setText("");
}
} else if(status.equals("quitting")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Disconnecting");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("disconnected")) {
statusView.setVisibility(View.VISIBLE);
if(fail_info.has("reason") && fail_info.get("reason").getAsString().length() > 0) {
String text = "Disconnected: ";
if(fail_info.has("type") && fail_info.get("type").getAsString().equals("connecting_restricted")) {
text = reason_txt(fail_info.get("reason").getAsString());
if(text.equals(fail_info.get("reason").getAsString()))
text = "You can’t connect to this server with a free account.";
} else {
if(fail_info.has("type") && fail_info.get("type").getAsString().equals("killed"))
text = "Disconnected - Killed: ";
else if(fail_info.has("type") && fail_info.get("type").getAsString().equals("connecting_failed"))
text = "Disconnected: Failed to connect - ";
text += reason_txt(fail_info.get("reason").getAsString());
}
statusView.setText(text);
statusView.setTextColor(getResources().getColor(R.color.status_fail_text));
statusView.setBackgroundResource(R.drawable.status_fail_bg);
} else {
statusView.setText("Disconnected. Tap to reconnect.");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
}
} else if(status.equals("queued")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connection queued");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("connecting")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connecting");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("connected")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connected");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("connected_joining")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connected: Joining Channels");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("pool_unavailable")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connection temporarily unavailable");
statusView.setTextColor(getResources().getColor(R.color.status_fail_text));
statusView.setBackgroundResource(R.drawable.status_fail_bg);
} else if(status.equals("waiting_to_retry")) {
try {
statusView.setVisibility(View.VISIBLE);
long seconds = (fail_info.get("timestamp").getAsLong() + fail_info.get("retry_timeout").getAsLong() - conn.clockOffset) - System.currentTimeMillis()/1000;
if(seconds > 0) {
String text = "Disconnected";
if(fail_info.has("reason") && fail_info.get("reason").getAsString().length() > 0) {
String reason = fail_info.get("reason").getAsString();
reason = reason_txt(reason);
text += ": " + reason + ". ";
} else
text += "; ";
text += "Reconnecting in ";
int minutes = (int)(seconds / 60.0);
int hours = (int)(seconds / 60.0 / 60.0);
int days = (int)(seconds / 60.0 / 60.0 / 24.0);
if(days > 0) {
if(days == 1)
text += days + " day.";
else
text += days + " days.";
} else if(hours > 0) {
if(hours == 1)
text += hours + " hour.";
else
text += hours + " hours.";
} else if(minutes > 0) {
if(minutes == 1)
text += minutes + " minute.";
else
text += minutes + " minutes.";
} else {
if(seconds == 1)
text += seconds + " second.";
else
text += seconds + " seconds.";
}
int attempts = fail_info.get("attempts").getAsInt();
if(attempts > 1)
text += " (" + ordinal(attempts) + " attempt)";
statusView.setText(text);
statusView.setTextColor(getResources().getColor(R.color.status_fail_text));
statusView.setBackgroundResource(R.drawable.status_fail_bg);
statusRefreshRunnable = new StatusRefreshRunnable(status, fail_info);
} else {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Ready to connect, waiting our turn…");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
}
mHandler.postDelayed(statusRefreshRunnable, 500);
} catch (Exception e) {
e.printStackTrace();
}
} else if(status.equals("ip_retry")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Trying another IP address");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
}
}
private void update_global_msg() {
if(globalMsgView != null) {
if(conn != null && conn.globalMsg != null) {
globalMsg.setText(conn.globalMsg);
globalMsgView.setVisibility(View.VISIBLE);
} else {
globalMsgView.setVisibility(View.GONE);
}
}
}
@Override
public void onPause() {
super.onPause();
if(statusRefreshRunnable != null) {
mHandler.removeCallbacks(statusRefreshRunnable);
statusRefreshRunnable = null;
}
if(conn != null)
conn.removeHandler(mHandler);
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, -1);
anim.setDuration(10);
anim.setFillAfter(true);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation arg0) {
connecting.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
connecting.startAnimation(anim);
error = null;
try {
getListView().setOnScrollListener(null);
} catch (Exception e) {
}
}
private void updateReconnecting() {
if(conn.getState() == NetworkConnection.STATE_CONNECTED) {
connectingMsg.setText("Loading");
} else if(conn.getState() == NetworkConnection.STATE_CONNECTING || conn.getReconnectTimestamp() > 0) {
progressBar.setProgress(0);
progressBar.setIndeterminate(true);
if(connecting.getVisibility() == View.GONE) {
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
anim.setDuration(200);
anim.setFillAfter(true);
connecting.startAnimation(anim);
connecting.setVisibility(View.VISIBLE);
}
if(conn.getState() == NetworkConnection.STATE_DISCONNECTED && conn.getReconnectTimestamp() > 0) {
String plural = "";
int seconds = (int)((conn.getReconnectTimestamp() - System.currentTimeMillis()) / 1000);
if(seconds != 1)
plural = "s";
if(seconds < 1) {
connectingMsg.setText("Connecting");
errorMsg.setVisibility(View.GONE);
} else if(seconds > 10 && error != null) {
connectingMsg.setText("Reconnecting in " + seconds + " second" + plural);
errorMsg.setText(error);
errorMsg.setVisibility(View.VISIBLE);
} else {
connectingMsg.setText("Reconnecting in " + seconds + " second" + plural);
errorMsg.setVisibility(View.GONE);
error = null;
}
try {
if(countdownTimer != null)
countdownTimer.cancel();
countdownTimer = new Timer();
countdownTimer.schedule( new TimerTask(){
public void run() {
if(conn.getState() == NetworkConnection.STATE_DISCONNECTED) {
mHandler.post(new Runnable() {
@Override
public void run() {
updateReconnecting();
}
});
}
countdownTimer = null;
}
}, 1000);
} catch (Exception e) {
}
} else {
connectingMsg.setText("Connecting");
error = null;
errorMsg.setVisibility(View.GONE);
}
} else {
connectingMsg.setText("Offline");
progressBar.setIndeterminate(false);
progressBar.setProgress(0);
}
}
private final Handler mHandler = new Handler() {
IRCCloudJSONObject e;
public void handleMessage(Message msg) {
switch (msg.what) {
case NetworkConnection.EVENT_DEBUG:
errorMsg.setVisibility(View.VISIBLE);
errorMsg.setText(msg.obj.toString());
break;
case NetworkConnection.EVENT_PROGRESS:
float progress = (Float)msg.obj;
if(progressBar.getProgress() < progress) {
progressBar.setIndeterminate(false);
progressBar.setProgress((int)progress);
}
break;
case NetworkConnection.EVENT_BACKLOG_START:
progressBar.setProgress(0);
break;
case NetworkConnection.EVENT_BACKLOG_FAILED:
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.VISIBLE);
loadBacklogButton.setVisibility(View.VISIBLE);
break;
case NetworkConnection.EVENT_BACKLOG_END:
if(connecting.getVisibility() == View.VISIBLE) {
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);
anim.setDuration(200);
anim.setFillAfter(true);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation arg0) {
connecting.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
connecting.startAnimation(anim);
error = null;
}
case NetworkConnection.EVENT_CONNECTIVITY:
updateReconnecting();
case NetworkConnection.EVENT_USERINFO:
dirty = true;
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
refreshTask.execute((Void)null);
break;
case NetworkConnection.EVENT_FAILURE_MSG:
IRCCloudJSONObject o = (IRCCloudJSONObject)msg.obj;
try {
error = o.getString("message");
if(error.equals("temp_unavailable"))
error = "Your account is temporarily unavailable";
updateReconnecting();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NetworkConnection.EVENT_CONNECTIONLAG:
try {
IRCCloudJSONObject object = (IRCCloudJSONObject)msg.obj;
if(server != null && buffer != null && object.cid() == buffer.cid) {
update_status(server.status, server.fail_info);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NetworkConnection.EVENT_STATUSCHANGED:
try {
IRCCloudJSONObject object = (IRCCloudJSONObject)msg.obj;
if(buffer != null && object.cid() == buffer.cid) {
update_status(object.getString("new_status"), object.getJsonObject("fail_info"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NetworkConnection.EVENT_SETIGNORES:
e = (IRCCloudJSONObject)msg.obj;
if(buffer != null && e.cid() == buffer.cid) {
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
refreshTask.execute((Void)null);
}
break;
case NetworkConnection.EVENT_HEARTBEATECHO:
if(buffer != null && adapter != null && adapter.data.size() > 0) {
if(buffer.last_seen_eid == adapter.data.get(adapter.data.size() - 1).eid || !shouldTrackUnread()) {
unreadTopView.setVisibility(View.GONE);
}
}
break;
case NetworkConnection.EVENT_CHANNELTOPIC:
case NetworkConnection.EVENT_JOIN:
case NetworkConnection.EVENT_PART:
case NetworkConnection.EVENT_NICKCHANGE:
case NetworkConnection.EVENT_QUIT:
case NetworkConnection.EVENT_KICK:
case NetworkConnection.EVENT_CHANNELMODE:
case NetworkConnection.EVENT_SELFDETAILS:
case NetworkConnection.EVENT_USERMODE:
case NetworkConnection.EVENT_USERCHANNELMODE:
e = (IRCCloudJSONObject)msg.obj;
if(buffer != null && e.bid() == buffer.bid) {
EventsDataSource.Event event = EventsDataSource.getInstance().getEvent(e.eid(), e.bid());
insertEvent(adapter, event, false, false);
}
break;
case NetworkConnection.EVENT_BUFFERMSG:
EventsDataSource.Event event = (EventsDataSource.Event)msg.obj;
if(buffer != null && event.bid == buffer.bid) {
if(event.from != null && event.from.equalsIgnoreCase(buffer.name) && event.reqid == -1) {
adapter.clearPending();
} else if(event.reqid != -1) {
for(int i = 0; i < adapter.data.size(); i++) {
EventsDataSource.Event e = adapter.data.get(i);
if(e.reqid == event.reqid && e.pending) {
if(i > 1) {
EventsDataSource.Event p = adapter.data.get(i-1);
if(p.row_type == ROW_TIMESTAMP) {
adapter.data.remove(p);
i--;
}
}
adapter.data.remove(e);
i--;
}
}
}
insertEvent(adapter, event, false, false);
}
break;
case NetworkConnection.EVENT_AWAY:
case NetworkConnection.EVENT_SELFBACK:
if(server != null) {
if(server.away != null && server.away.length() > 0) {
awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + server.away + ")"))).toString());
awayView.setVisibility(View.VISIBLE);
} else {
awayView.setVisibility(View.GONE);
}
}
break;
case NetworkConnection.EVENT_GLOBALMSG:
update_global_msg();
break;
default:
break;
}
}
};
public interface MessageViewListener extends OnBufferSelectedListener {
public void onMessageViewReady();
public boolean onMessageLongClicked(EventsDataSource.Event event);
public void onMessageDoubleClicked(EventsDataSource.Event event);
}
}
| false | true | private synchronized void insertEvent(final MessageAdapter adapter, EventsDataSource.Event event, boolean backlog, boolean nextIsGrouped) {
synchronized(adapterLock) {
try {
boolean colors = false;
if(!event.self && conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("nick-colors") && conn.getUserInfo().prefs.getBoolean("nick-colors"))
colors = true;
long start = System.currentTimeMillis();
if(event.eid <= buffer.min_eid) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
if(earliest_eid == 0 || event.eid < earliest_eid)
earliest_eid = event.eid;
String type = event.type;
long eid = event.eid;
if(type.startsWith("you_"))
type = type.substring(4);
if(type.equals("joined_channel") || type.equals("parted_channel") || type.equals("nickchange") || type.equals("quit") || type.equals("user_channel_mode")) {
boolean shouldExpand = false;
boolean showChan = !buffer.type.equals("channel");
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = null;
if(buffer.type.equals("channel")) {
if(conn.getUserInfo().prefs.has("channel-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("buffer-hideJoinPart");
}
if(hiddenMap != null && hiddenMap.has(String.valueOf(buffer.bid)) && hiddenMap.getBoolean(String.valueOf(buffer.bid))) {
adapter.removeItem(event.eid);
if(!backlog)
adapter.notifyDataSetChanged();
return;
}
JSONObject expandMap = null;
if(buffer.type.equals("channel")) {
if(conn.getUserInfo().prefs.has("channel-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("channel-expandJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("buffer-expandJoinPart");
}
if(expandMap != null && expandMap.has(String.valueOf(buffer.bid)) && expandMap.getBoolean(String.valueOf(buffer.bid))) {
shouldExpand = true;
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(eid / 1000);
if(shouldExpand)
expandedSectionEids.clear();
if(currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay || shouldExpand) {
collapsedEvents.clear();
currentCollapsedEid = eid;
lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR);
}
if(!showChan)
event.chan = buffer.name;
if(!collapsedEvents.addEvent(event))
collapsedEvents.clear();
if((currentCollapsedEid == event.eid || shouldExpand) && type.equals("user_channel_mode")) {
event.color = R.color.row_message_label;
event.bg_color = R.color.status_bg;
} else {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
String msg;
if(expandedSectionEids.contains(currentCollapsedEid)) {
CollapsedEventsList c = new CollapsedEventsList();
c.PREFIX = collapsedEvents.PREFIX;
c.addEvent(event);
msg = c.getCollapsedMessage(showChan);
if(!nextIsGrouped) {
String group_msg = collapsedEvents.getCollapsedMessage(showChan);
if(group_msg == null && type.equals("nickchange")) {
group_msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(group_msg == null && type.equals("user_channel_mode")) {
if(event.from != null && event.from.length() > 0)
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.from + "</b>";
else
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>";
currentCollapsedEid = eid;
}
EventsDataSource.Event heading = EventsDataSource.getInstance().new Event();
heading.type = "__expanded_group_heading__";
heading.cid = event.cid;
heading.bid = event.bid;
heading.eid = currentCollapsedEid - 1;
heading.group_msg = group_msg;
heading.color = R.color.timestamp;
heading.bg_color = R.color.message_bg;
heading.linkify = false;
adapter.addItem(currentCollapsedEid - 1, heading);
}
event.timestamp = null;
} else {
msg = (nextIsGrouped && currentCollapsedEid != event.eid)?"":collapsedEvents.getCollapsedMessage(showChan);
}
if(msg == null && type.equals("nickchange")) {
msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(msg == null && type.equals("user_channel_mode")) {
if(event.from != null && event.from.length() > 0)
msg = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>";
else
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>";
currentCollapsedEid = eid;
}
if(!expandedSectionEids.contains(currentCollapsedEid)) {
if(eid != currentCollapsedEid) {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
eid = currentCollapsedEid;
}
event.group_msg = msg;
event.html = null;
event.formatted = null;
event.linkify = false;
} else {
currentCollapsedEid = -1;
collapsedEvents.clear();
if(event.html == null) {
if(event.from != null)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, colors) + "</b> " + event.msg;
else if(event.type.equals("buffer_msg") && event.server != null)
event.html = "<b>" + event.server + "</b> " + event.msg;
else
event.html = event.msg;
}
}
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
if(from != null && event.hostmask != null && !type.equals("user_channel_mode") && !type.contains("kicked")) {
String usermask = from + "!" + event.hostmask;
if(ignore.match(usermask)) {
if(unreadTopView != null && unreadTopView.getVisibility() == View.GONE && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
return;
}
}
if(type.equals("channel_mode")) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
} else if(type.equals("buffer_me_msg")) {
event.html = "— <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode, colors) + "</b> " + event.msg + "</i>";
} else if(type.equals("notice")) {
if(event.from != null && event.from.length() > 0)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> ";
else
event.html = "";
if(buffer.type.equals("console") && event.to_chan && event.chan != null && event.chan.length() > 0) {
event.html += event.chan + "﹕ " + event.msg;
} else {
event.html += event.msg;
}
} else if(type.equals("kicked_channel")) {
event.html = "← ";
if(event.type.startsWith("you_"))
event.html += "You";
else
event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null, false) + "</b>";
if(event.type.startsWith("you_"))
event.html += " were";
else
event.html += " was";
if(event.hostmask != null && event.hostmask.length() > 0)
event.html += " kicked by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b> (" + event.hostmask + ")";
else
event.html += " kicked by the server <b>" + event.nick + "</b>";
if(event.msg != null && event.msg.length() > 0)
event.html += ": " + event.msg;
} else if(type.equals("callerid")) {
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> ("+ event.hostmask + ") " + event.msg + " Tap to accept.";
} else if(type.equals("channel_mode_list_change")) {
if(event.from.length() == 0) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
}
}
adapter.addItem(eid, event);
if(!backlog)
adapter.notifyDataSetChanged();
long time = (System.currentTimeMillis() - start);
if(avgInsertTime == 0)
avgInsertTime = time;
avgInsertTime += time;
avgInsertTime /= 2.0;
//Log.i("IRCCloud", "Average insert time: " + avgInsertTime);
if(!backlog && buffer.scrolledUp && !event.self && event.isImportant(type)) {
if(newMsgTime == 0)
newMsgTime = System.currentTimeMillis();
newMsgs++;
if(event.highlight)
newHighlights++;
update_unread();
}
if(!backlog && !buffer.scrolledUp) {
getListView().setSelection(adapter.getCount() - 1);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
getListView().setSelection(adapter.getCount() - 1);
} catch (Exception e) {
//List view isn't ready yet
}
}
}, 200);
}
if(!backlog && event.highlight && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit();
editor.putBoolean("mentionTip", true);
editor.commit();
}
if(!backlog) {
int markerPos = adapter.getLastSeenEIDPosition();
if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) {
unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| private synchronized void insertEvent(final MessageAdapter adapter, EventsDataSource.Event event, boolean backlog, boolean nextIsGrouped) {
synchronized(adapterLock) {
try {
boolean colors = false;
if(!event.self && conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("nick-colors") && conn.getUserInfo().prefs.getBoolean("nick-colors"))
colors = true;
long start = System.currentTimeMillis();
if(event.eid <= buffer.min_eid) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
if(earliest_eid == 0 || event.eid < earliest_eid)
earliest_eid = event.eid;
String type = event.type;
long eid = event.eid;
if(type.startsWith("you_"))
type = type.substring(4);
if(type.equals("joined_channel") || type.equals("parted_channel") || type.equals("nickchange") || type.equals("quit") || type.equals("user_channel_mode")) {
boolean shouldExpand = false;
boolean showChan = !buffer.type.equals("channel");
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = null;
if(buffer.type.equals("channel")) {
if(conn.getUserInfo().prefs.has("channel-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("buffer-hideJoinPart");
}
if(hiddenMap != null && hiddenMap.has(String.valueOf(buffer.bid)) && hiddenMap.getBoolean(String.valueOf(buffer.bid))) {
adapter.removeItem(event.eid);
if(!backlog)
adapter.notifyDataSetChanged();
return;
}
JSONObject expandMap = null;
if(buffer.type.equals("channel")) {
if(conn.getUserInfo().prefs.has("channel-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("channel-expandJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("buffer-expandJoinPart");
}
if(expandMap != null && expandMap.has(String.valueOf(buffer.bid)) && expandMap.getBoolean(String.valueOf(buffer.bid))) {
shouldExpand = true;
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(eid / 1000);
if(shouldExpand)
expandedSectionEids.clear();
if(currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay || shouldExpand) {
collapsedEvents.clear();
currentCollapsedEid = eid;
lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR);
}
if(!showChan)
event.chan = buffer.name;
if(!collapsedEvents.addEvent(event))
collapsedEvents.clear();
if((currentCollapsedEid == event.eid || shouldExpand) && type.equals("user_channel_mode")) {
event.color = R.color.row_message_label;
event.bg_color = R.color.status_bg;
} else {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
String msg;
if(expandedSectionEids.contains(currentCollapsedEid)) {
CollapsedEventsList c = new CollapsedEventsList();
c.PREFIX = collapsedEvents.PREFIX;
c.addEvent(event);
msg = c.getCollapsedMessage(showChan);
if(!nextIsGrouped) {
String group_msg = collapsedEvents.getCollapsedMessage(showChan);
if(group_msg == null && type.equals("nickchange")) {
group_msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(group_msg == null && type.equals("user_channel_mode")) {
if(event.from != null && event.from.length() > 0)
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by <b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>";
else
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>";
currentCollapsedEid = eid;
}
EventsDataSource.Event heading = EventsDataSource.getInstance().new Event();
heading.type = "__expanded_group_heading__";
heading.cid = event.cid;
heading.bid = event.bid;
heading.eid = currentCollapsedEid - 1;
heading.group_msg = group_msg;
heading.color = R.color.timestamp;
heading.bg_color = R.color.message_bg;
heading.linkify = false;
adapter.addItem(currentCollapsedEid - 1, heading);
}
event.timestamp = null;
} else {
msg = (nextIsGrouped && currentCollapsedEid != event.eid)?"":collapsedEvents.getCollapsedMessage(showChan);
}
if(msg == null && type.equals("nickchange")) {
msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(msg == null && type.equals("user_channel_mode")) {
if(event.from != null && event.from.length() > 0)
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by <b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>";
else
msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>";
currentCollapsedEid = eid;
}
if(!expandedSectionEids.contains(currentCollapsedEid)) {
if(eid != currentCollapsedEid) {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
eid = currentCollapsedEid;
}
event.group_msg = msg;
event.html = null;
event.formatted = null;
event.linkify = false;
} else {
currentCollapsedEid = -1;
collapsedEvents.clear();
if(event.html == null) {
if(event.from != null)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, colors) + "</b> " + event.msg;
else if(event.type.equals("buffer_msg") && event.server != null)
event.html = "<b>" + event.server + "</b> " + event.msg;
else
event.html = event.msg;
}
}
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
if(from != null && event.hostmask != null && !type.equals("user_channel_mode") && !type.contains("kicked")) {
String usermask = from + "!" + event.hostmask;
if(ignore.match(usermask)) {
if(unreadTopView != null && unreadTopView.getVisibility() == View.GONE && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
return;
}
}
if(type.equals("channel_mode")) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
} else if(type.equals("buffer_me_msg")) {
event.html = "— <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode, colors) + "</b> " + event.msg + "</i>";
} else if(type.equals("notice")) {
if(event.from != null && event.from.length() > 0)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> ";
else
event.html = "";
if(buffer.type.equals("console") && event.to_chan && event.chan != null && event.chan.length() > 0) {
event.html += event.chan + "﹕ " + event.msg;
} else {
event.html += event.msg;
}
} else if(type.equals("kicked_channel")) {
event.html = "← ";
if(event.type.startsWith("you_"))
event.html += "You";
else
event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null, false) + "</b>";
if(event.type.startsWith("you_"))
event.html += " were";
else
event.html += " was";
if(event.hostmask != null && event.hostmask.length() > 0)
event.html += " kicked by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b> (" + event.hostmask + ")";
else
event.html += " kicked by the server <b>" + event.nick + "</b>";
if(event.msg != null && event.msg.length() > 0)
event.html += ": " + event.msg;
} else if(type.equals("callerid")) {
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> ("+ event.hostmask + ") " + event.msg + " Tap to accept.";
} else if(type.equals("channel_mode_list_change")) {
if(event.from.length() == 0) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
}
}
adapter.addItem(eid, event);
if(!backlog)
adapter.notifyDataSetChanged();
long time = (System.currentTimeMillis() - start);
if(avgInsertTime == 0)
avgInsertTime = time;
avgInsertTime += time;
avgInsertTime /= 2.0;
//Log.i("IRCCloud", "Average insert time: " + avgInsertTime);
if(!backlog && buffer.scrolledUp && !event.self && event.isImportant(type)) {
if(newMsgTime == 0)
newMsgTime = System.currentTimeMillis();
newMsgs++;
if(event.highlight)
newHighlights++;
update_unread();
}
if(!backlog && !buffer.scrolledUp) {
getListView().setSelection(adapter.getCount() - 1);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
getListView().setSelection(adapter.getCount() - 1);
} catch (Exception e) {
//List view isn't ready yet
}
}
}, 200);
}
if(!backlog && event.highlight && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit();
editor.putBoolean("mentionTip", true);
editor.commit();
}
if(!backlog) {
int markerPos = adapter.getLastSeenEIDPosition();
if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) {
unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
diff --git a/src/com/justjournal/ctl/AddLink.java b/src/com/justjournal/ctl/AddLink.java
index a2c5fcc4..9641e8c4 100644
--- a/src/com/justjournal/ctl/AddLink.java
+++ b/src/com/justjournal/ctl/AddLink.java
@@ -1,109 +1,109 @@
/*
Copyright (c) 2005-2006, Lucas Holt
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 Just Journal 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 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.justjournal.ctl;
import com.justjournal.db.UserLinkDao;
import com.justjournal.db.UserLinkTo;
import org.apache.log4j.Category;
/**
* User: laffer1
* Date: Dec 28, 2005
* Time: 2:02:10 PM
*/
public class AddLink extends Protected {
private static Category log = Category.getInstance(AddLink.class.getName());
protected String title;
protected String uri;
public String getMyLogin() {
return this.currentLoginName();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
protected String insidePerform() throws Exception {
if (log.isDebugEnabled())
log.debug("insidePerform(): Attempting to add link.");
if (this.currentLoginId() < 1)
addError("login", "The login timed out or is invalid.");
if (title == null || title.length() < 1)
addError("title", "The link title is required.");
if (uri == null || uri.length() < 11)
addError("uri", "The URI is the website address and must be similar to http://www.justjournal.com/");
if (!this.hasErrors()) {
try {
UserLinkDao dao = new UserLinkDao();
UserLinkTo ul = new UserLinkTo();
ul.setTitle(title);
ul.setUri(uri);
ul.setUserId(this.currentLoginId());
- if (!dao.add(ul)) ;
- addError("Add Link", "Error adding link.");
+ if (!dao.add(ul))
+ addError("Add Link", "Error adding link.");
}
catch (Exception e) {
addError("Add Link", "Could not add the link.");
if (log.isDebugEnabled())
log.debug("insidePerform(): " + e.getMessage());
}
}
if (this.hasErrors())
return ERROR;
else
return SUCCESS;
}
}
| true | true | protected String insidePerform() throws Exception {
if (log.isDebugEnabled())
log.debug("insidePerform(): Attempting to add link.");
if (this.currentLoginId() < 1)
addError("login", "The login timed out or is invalid.");
if (title == null || title.length() < 1)
addError("title", "The link title is required.");
if (uri == null || uri.length() < 11)
addError("uri", "The URI is the website address and must be similar to http://www.justjournal.com/");
if (!this.hasErrors()) {
try {
UserLinkDao dao = new UserLinkDao();
UserLinkTo ul = new UserLinkTo();
ul.setTitle(title);
ul.setUri(uri);
ul.setUserId(this.currentLoginId());
if (!dao.add(ul)) ;
addError("Add Link", "Error adding link.");
}
catch (Exception e) {
addError("Add Link", "Could not add the link.");
if (log.isDebugEnabled())
log.debug("insidePerform(): " + e.getMessage());
}
}
if (this.hasErrors())
return ERROR;
else
return SUCCESS;
}
| protected String insidePerform() throws Exception {
if (log.isDebugEnabled())
log.debug("insidePerform(): Attempting to add link.");
if (this.currentLoginId() < 1)
addError("login", "The login timed out or is invalid.");
if (title == null || title.length() < 1)
addError("title", "The link title is required.");
if (uri == null || uri.length() < 11)
addError("uri", "The URI is the website address and must be similar to http://www.justjournal.com/");
if (!this.hasErrors()) {
try {
UserLinkDao dao = new UserLinkDao();
UserLinkTo ul = new UserLinkTo();
ul.setTitle(title);
ul.setUri(uri);
ul.setUserId(this.currentLoginId());
if (!dao.add(ul))
addError("Add Link", "Error adding link.");
}
catch (Exception e) {
addError("Add Link", "Could not add the link.");
if (log.isDebugEnabled())
log.debug("insidePerform(): " + e.getMessage());
}
}
if (this.hasErrors())
return ERROR;
else
return SUCCESS;
}
|
diff --git a/simulator/src/java/main/ca/nengo/model/impl/SocketUDPNode.java b/simulator/src/java/main/ca/nengo/model/impl/SocketUDPNode.java
index d42ed627..b7880a8b 100644
--- a/simulator/src/java/main/ca/nengo/model/impl/SocketUDPNode.java
+++ b/simulator/src/java/main/ca/nengo/model/impl/SocketUDPNode.java
@@ -1,626 +1,627 @@
/*
The contents of this file are subject to the Mozilla Public License Version 1.1
(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.mozilla.org/MPL/
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.
The Original Code is "PassthroughNode.java". Description:
"A Node that passes values through unaltered.
This can be useful if an input to a Network is actually routed to multiple destinations,
but you want to handle this connectivity within the Network rather than expose multiple
terminations"
The Initial Developer of the Original Code is Bryan Tripp & Centre for Theoretical Neuroscience, University of Waterloo. Copyright (C) 2006-2008. All Rights Reserved.
Alternatively, the contents of this file may be used under the terms of the GNU
Public License license (the GPL License), in which case the provisions of GPL
License are applicable instead of those above. If you wish to allow use of your
version of this file only under the terms of the GPL License and not to allow
others to use your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice and other
provisions required by the GPL License. If you do not delete the provisions above,
a recipient may use your version of this file under either the MPL or the GPL License.
*/
/*
* Created on 24-May-07
*/
package ca.nengo.model.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.io.IOException;
import java.net.InetAddress;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.apache.log4j.Logger;
import ca.nengo.model.InstantaneousOutput;
import ca.nengo.model.Node;
import ca.nengo.model.Origin;
import ca.nengo.model.RealOutput;
import ca.nengo.model.Resettable;
import ca.nengo.model.SimulationException;
import ca.nengo.model.SimulationMode;
import ca.nengo.model.SpikeOutput;
import ca.nengo.model.StructuralException;
import ca.nengo.model.Termination;
import ca.nengo.model.Units;
import ca.nengo.model.impl.PassthroughNode.PassthroughTermination;
import ca.nengo.util.MU;
import ca.nengo.util.ScriptGenException;
import ca.nengo.util.VisiblyMutable;
import ca.nengo.util.VisiblyMutableUtils;
import ca.nengo.util.VisiblyMutable.Listener;
/**
* <p>A Node that sends and receives data through sockets via a UDP connection.</p>
*
* <p>This can be useful if an input to a Network is actually routed to multiple destinations,
* but you want to handle this connectivity within the Network rather than expose multiple
* terminations.</p>
*
* @author Bryan Tripp
*/
public class SocketUDPNode implements Node, Resettable {
//implementation note: this class doesn't nicely extend AbstractNode
private static Logger ourLogger = Logger.getLogger(SocketUDPNode.class);
/**
* Default name for a termination
*/
public static final String TERMINATION = "termination";
/**
* Default name for an origin
*/
public static final String ORIGIN = "origin";
private static final long serialVersionUID = 1L;
private String myName;
private int myDimension;
private Map<String, PassthroughTermination> myTerminations;
private BasicOrigin myOrigin;
private String myDocumentation;
private transient List<VisiblyMutable.Listener> myListeners;
private int myLocalPort;
private int myGivenLocalPort;
private InetAddress myDestAddress;
private int myDestPort;
private DatagramSocket mySocket;
private int mySocketTimeout;
private boolean myIgnoreTimestamp;
private PriorityQueue<float[]> mySocketBuffer;
private NengoUDPPacketComparator myComparator;
private boolean myIsReceiver;
private boolean myIsSender;
private ByteOrder myByteOrder = ByteOrder.BIG_ENDIAN;
private float myUpdateInterval = 0;
private float myNextUpdate = 0;
/**
* Constructor for a SocketUDPNode that sends and receives data.
*
* @param name Node name
* @param dimension Dimension of data passing through
* @param localPort Port number on the local machine to bind to. Set to 0 to bind to first available port.
* @param destAddress Destination address to connect to
* @param destPort Destination port to connect to
* @param socketTimeout Timeout on socket in milliseconds (socket blocks until timeout expires)
* @throws UnknownHostException
* @throws SocketException
*/
public SocketUDPNode(String name, int dimension, int localPort, String destAddress, int destPort,
int socketTimeout, boolean ignoreTimestamp) throws UnknownHostException {
myName = name;
myDimension = dimension;
myTerminations = new HashMap<String, PassthroughTermination>(10);
myLocalPort = localPort;
myGivenLocalPort = localPort; // Stored
myDestAddress = InetAddress.getByName(destAddress);
myDestPort = destPort;
mySocketTimeout = socketTimeout;
myIgnoreTimestamp = ignoreTimestamp;
myComparator = new NengoUDPPacketComparator();
mySocketBuffer = new PriorityQueue<float[]>(10, myComparator);
mySocket = null;
myNextUpdate = 0;
myIsSender = false;
myIsReceiver = false;
myOrigin = null;
if (myDestPort > 0)
myIsSender = true;
if (myLocalPort > 0) {
myIsReceiver = true;
myOrigin = new BasicOrigin(this, ORIGIN, dimension, Units.UNK);
}
reset(false);
}
/**
* Constructor for a SocketUDPNode that acts just like a passthrough node (not receiving or sending
* anything over sockets)
*
* @param name Node name
* @param dimension Dimension of data passing through
*/
// public SocketUDPNode(String name, int dimension)
// throws UnknownHostException, SocketException {
// this(name, dimension, -1, "", -1, 0, false);
// }
/**
* Constructor for a SocketUDPNode that only receives data.
*
* @param name Node name
* @param dimension Dimension of data passing through
* @param localPort Port number on the local machine to bind to. Set to 0 to bind to first available port.
* @param socketTimeout Timeout on socket in milliseconds (socket blocks until timeout expires)
*/
public SocketUDPNode(String name, int dimension, int localPort, int socketTimeout)
throws UnknownHostException {
this(name, dimension, localPort, "", -1, Math.max(socketTimeout, 1), false);
}
/**
* Constructor for a SocketUDPNode that only receives data, with an option to ignore the timestamp on
* incoming packets.
*
* @param name Node name
* @param dimension Dimension of data passing through
* @param localPort Port number on the local machine to bind to. Set to 0 to bind to first available port.
* @param ignoreTimestamp Set to true to ignore timestamps on incoming packets.
* @param socketTimeout Timeout on socket in milliseconds (socket blocks until timeout expires)
*/
public SocketUDPNode(String name, int dimension, int localPort, int socketTimeout,
boolean ignoreTimestamp) throws UnknownHostException {
this(name, dimension, localPort, "", -1, Math.max(socketTimeout, 1), ignoreTimestamp);
}
/**
* Constructor for a SocketUDPNode that only sends data.
*
* @param name Node name
* @param dimension Dimension of data passing through
* @param destAddress Destination address to connect to
* @param destPort Destination port to connect to
*/
public SocketUDPNode(String name, int dimension, String destAddress, int destPort)
throws UnknownHostException {
this(name, dimension, -1, destAddress, destPort, -1, false);
}
public void initialize() throws SimulationException{
if (mySocket != null)
// Socket has already been initialized, don't try to reinitialize it.
return;
try{
if (myLocalPort > 0)
// Create a socket if localPort > 0 (i.e. we want to receive data from somewhere)
// or if destPort > 0 (i.e. we want to send data to somewhere - we still need a socket to send stuff)
mySocket = new DatagramSocket(myLocalPort);
else {
// If localPort is not defined (defaults to -1), then create socket on first available port
// and set localPort to the port the socket has connected to.
mySocket = new DatagramSocket();
myLocalPort = mySocket.getLocalPort();
}
if (mySocketTimeout > 0)
mySocket.setSoTimeout(mySocketTimeout);
}
catch( Exception e ) {
throw new SimulationException(e);
}
}
/**
* @see ca.nengo.model.Node#getName()
*/
public String getName() {
return myName;
}
/**
* @param name The new name
*/
public void setName(String name) throws StructuralException {
VisiblyMutableUtils.nameChanged(this, getName(), name, myListeners);
myName = name;
}
public int getDimension(){
return myDimension;
}
public void setDimension(int dimension) {
myDimension = dimension;
}
public int getLocalPort(){
return myLocalPort;
}
public InetAddress getDestInetAddress(){
return myDestAddress;
}
public int getDestPort(){
return myDestPort;
}
public int getSocketTimeout(){
return mySocketTimeout;
}
public boolean getIgnoreTimestamp(){
return myIgnoreTimestamp;
}
public boolean isSender(){
return myIsSender;
}
public boolean isReceiver(){
return myIsReceiver;
}
public void setByteOrder(ByteOrder byteOrder){
myByteOrder = byteOrder;
}
public void setByteOrder(String byteOrder){
if (byteOrder.toLowerCase() == "little")
myByteOrder = ByteOrder.LITTLE_ENDIAN;
else if (byteOrder.toLowerCase() == "big")
myByteOrder = ByteOrder.BIG_ENDIAN;
}
public void setUpdateInterval(float interval){
myUpdateInterval = interval;
}
/**
* @see ca.nengo.model.Node#getOrigin(java.lang.String)
*/
public Origin getOrigin(String name) throws StructuralException {
if (ORIGIN.equals(name) && myOrigin != null) {
return myOrigin;
} else {
throw new StructuralException("Unknown origin: " + name);
}
}
/**
* @see ca.nengo.model.Node#getOrigins()
*/
public Origin[] getOrigins() {
if (myOrigin != null)
return new Origin[]{myOrigin};
else
return new Origin[0];
}
public Termination addTermination(String name, float[][] transform)
throws StructuralException {
for (Termination t : getTerminations()) {
if (t.getName().equals(name))
throw new StructuralException("This node already contains a termination named " + name);
}
PassthroughTermination result = new PassthroughTermination(this, name, transform);
myTerminations.put(name, result);
return result;
}
/**
* @see ca.nengo.model.Node#getTermination(java.lang.String)
*/
public Termination getTermination(String name) throws StructuralException {
if (myTerminations.containsKey(name)) {
return myTerminations.get(name);
} else {
throw new StructuralException("Unknown termination: " + name);
}
}
/**
* @see ca.nengo.model.Node#getTerminations()
*/
public Termination[] getTerminations() {
return myTerminations.values().toArray(new PassthroughTermination[0]);
}
/**
* @see ca.nengo.model.Node#run(float, float)
*/
public void run(float startTime, float endTime) throws SimulationException {
// TODO: Thread this thing, so that it doesn't block if the blocking receive calls
// are called before the send calls. (waiting for a receive before a send causes
// a deadlock situation.
if (isSender() && startTime >= myNextUpdate) {
if (mySocket == null)
// If for some reason the socket hasn't been initialized, then initialize it.
initialize();
if (myTerminations.isEmpty())
throw new SimulationException("SocketUDPNode is sender, but has no terminations to get data from.");
else {
// TODO: Test with spiking outputs?
float[] values = new float[myDimension];
Iterator<PassthroughTermination> it = myTerminations.values().iterator();
while (it.hasNext()) {
PassthroughTermination termination = it.next();
InstantaneousOutput io = termination.getValues();
if (io instanceof RealOutput) {
values = MU.sum(values, ((RealOutput) io).getValues());
} else if (io instanceof SpikeOutput) {
boolean[] spikes = ((SpikeOutput) io).getValues();
for (int i = 0; i < spikes.length; i++) {
if (spikes[i]) {
values[i] += 1f/(endTime - startTime);
}
}
} else if (io == null) {
throw new SimulationException("Null input to Termination " + termination.getName());
} else {
throw new SimulationException("Output type unknown: " + io.getClass().getName());
}
}
// Send values over the socket.
// Datagram format:
// - bytes 1-4: Timestamp (float)
// - bytes 4-(myDim+1)*4: values[i] (float)
ByteBuffer buffer = ByteBuffer.allocate((myDimension + 1) * 4);
buffer.order(myByteOrder);
buffer.putFloat((float)((startTime + endTime + myUpdateInterval) / 2.0));
for(int i = 0; i < myDimension; i++)
buffer.putFloat(values[i]);
byte[] bufArray = buffer.array();
DatagramPacket packet = new DatagramPacket(bufArray, bufArray.length, myDestAddress, myDestPort);
try {
mySocket.send(packet);
}
catch (IOException e) {
// TODO: Handle this better
throw new SimulationException(e);
}
}
}
if (isReceiver()) {
float[] values = new float[myDimension];
float[] tempValues = new float[myDimension+1];
// Check items in priority queue to see if there is anything that is good to go (i.e. timestamp is within
// startTime and endTime.
boolean foundItem = false;
boolean foundFutureItem = false;
int i = 0;
while (!mySocketBuffer.isEmpty()) {
tempValues = (float[]) mySocketBuffer.peek();
foundItem = (tempValues[0] >= startTime && tempValues[0] <= endTime) || myIgnoreTimestamp;
foundFutureItem = tempValues[0] > endTime;
if (foundItem)
mySocketBuffer.remove();
else
break;
}
if (foundItem) {
// If an item was found in the queue (i.e. message with future timestamp was received before), use this
// data instead of waiting on socket for new data.
for (i = 0; i < myDimension; i++)
values[i] = tempValues[i+1];
}
else if (foundFutureItem || startTime < myNextUpdate) {
// Buffer contained item in the future, so skip waiting for a new packet to arrive, and hurry
// the heck up.
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
}
else {
// If no items were found in queue, wait on socket for new data.
try {
byte[] bufArray = new byte[(myDimension + 1) * 4];
DatagramPacket packet = new DatagramPacket(bufArray, bufArray.length);
while (true) {
mySocket.receive(packet);
ByteBuffer buffer = ByteBuffer.wrap(bufArray);
buffer.order(myByteOrder);
for (i = 0; i < myDimension + 1; i++) {
tempValues[i] = buffer.getFloat();
}
// Check for timestamp for validity (i.e. within the start and end of this run call).
if ((tempValues[0] >= startTime && tempValues[0] <= endTime) || myIgnoreTimestamp || tempValues[0] < 0) {
// Valid timestamp encountered; or have been instructed to ignore timestamps.
// No further actions required, just break out of while loop.
- values = Arrays.copyOfRange(tempValues, 1, myDimension+1);
+ //values = Arrays.copyOfRange(tempValues, 1, myDimension+1);
+ System.arraycopy(tempValues, 1, values, 0, myDimension);
break;
}
else if (tempValues[0] > endTime) {
// Future timestamp encountered, place into priority queue, use previous origin value as
// current value, and then out of while loop.
// Note: we break out of the while loop because receiving future timestamps means this
// system is (potentially) running slow.
mySocketBuffer.add(tempValues.clone());
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
break;
}
// Past timestamp encountered. Just ignore it, and wait for another packet.
}
}
catch (SocketTimeoutException e){
// If a timeout occurs, don't really do anything, just keep the origin at the previous value.
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
}
catch (Exception e){
// TODO: Handle this better
throw new SimulationException(e);
}
}
myOrigin.setValues(new RealOutputImpl(values, Units.UNK, endTime));
}
if (startTime >= myNextUpdate)
myNextUpdate += myUpdateInterval;
}
/**
* @see ca.nengo.model.Resettable#reset(boolean)
*/
public void reset(boolean randomize) {
float time = 0;
myNextUpdate = 0;
if (myOrigin != null) {
try {
if (myOrigin.getValues() != null) {
myOrigin.getValues().getTime();
}
} catch (SimulationException e) {
ourLogger.warn("Exception getting time from existing output during reset", e);
}
myOrigin.setValues(new RealOutputImpl(new float[myOrigin.getDimensions()], Units.UNK, time));
myOrigin.reset(randomize);
}
mySocketBuffer.clear();
}
/**
* @see ca.nengo.model.SimulationMode.ModeConfigurable#getMode()
*/
public SimulationMode getMode() {
return SimulationMode.DEFAULT;
}
/**
* Does nothing (only DEFAULT mode is supported).
*
* @see ca.nengo.model.SimulationMode.ModeConfigurable#setMode(ca.nengo.model.SimulationMode)
*/
public void setMode(SimulationMode mode) {
}
/**
* @see ca.nengo.model.Node#getDocumentation()
*/
public String getDocumentation() {
return myDocumentation;
}
/**
* @see ca.nengo.model.Node#setDocumentation(java.lang.String)
*/
public void setDocumentation(String text) {
myDocumentation = text;
}
/**
* @see ca.nengo.util.VisiblyMutable#addChangeListener(ca.nengo.util.VisiblyMutable.Listener)
*/
public void addChangeListener(Listener listener) {
if (myListeners == null) {
myListeners = new ArrayList<Listener>(2);
}
myListeners.add(listener);
}
/**
* @see ca.nengo.util.VisiblyMutable#removeChangeListener(ca.nengo.util.VisiblyMutable.Listener)
*/
public void removeChangeListener(Listener listener) {
myListeners.remove(listener);
}
@Override
public Node clone() throws CloneNotSupportedException {
if (mySocket != null) {
// Cannot clone a SocketUDPNode (because you cannot bind to a socket already bound to)
throw new CloneNotSupportedException("SocketUDPNode can only be cloned if it is not already bound to a socket.");
}
else {
try {
SocketUDPNode result = (SocketUDPNode) super.clone();
if (myOrigin != null)
result.myOrigin = myOrigin.clone(result);
result.myTerminations = new HashMap<String, PassthroughTermination>(10);
for (PassthroughTermination oldTerm : myTerminations.values()) {
PassthroughTermination newTerm = oldTerm.clone(result);
result.myTerminations.put(newTerm.getName(), newTerm);
}
result.myListeners = new ArrayList<Listener>(2);
// Note: Cloning a SocketUDPNode is weird, because it copies all of the pre-existing socket values
// like destination address, port, etc.
result.myComparator = new NengoUDPPacketComparator();
result.myDestAddress = InetAddress.getByName(myDestAddress.getHostAddress());
result.myDestPort = myDestPort;
result.myDimension = myDimension;
result.myDocumentation = myDocumentation;
result.myGivenLocalPort = myGivenLocalPort;
result.myIgnoreTimestamp = myIgnoreTimestamp;
result.myLocalPort = myLocalPort;
result.mySocketBuffer = new PriorityQueue<float[]>(10, myComparator);
result.mySocketTimeout = mySocketTimeout;
return result;
}
catch (UnknownHostException e){
throw new CloneNotSupportedException("SocketUDPNode clone error: " + e.getMessage());
}
}
}
public Node[] getChildren() {
return new Node[0];
}
public String toScript(HashMap<String, Object> scriptData) throws ScriptGenException {
return "";
}
public void close(){
// Close the socket when object is finalized.
if (mySocket != null){
mySocket.close();
mySocket = null;
}
// Restore myLocalPort value to the value originally provided by the user.
// myLocalPort value is overwritten during initialize() function call, and this is so that
// when the socket node is re-initialized after closure, it uses the same settings.
myLocalPort = myGivenLocalPort;
reset(false);
}
private class NengoUDPPacketComparator implements Comparator<float[]> {
public int compare(float[] o1, float[] o2) {
return o1[0] < o2[0] ? -1 : o1[0] == o2[0] ? 0 : 1;
}
}
}
| true | true | public void run(float startTime, float endTime) throws SimulationException {
// TODO: Thread this thing, so that it doesn't block if the blocking receive calls
// are called before the send calls. (waiting for a receive before a send causes
// a deadlock situation.
if (isSender() && startTime >= myNextUpdate) {
if (mySocket == null)
// If for some reason the socket hasn't been initialized, then initialize it.
initialize();
if (myTerminations.isEmpty())
throw new SimulationException("SocketUDPNode is sender, but has no terminations to get data from.");
else {
// TODO: Test with spiking outputs?
float[] values = new float[myDimension];
Iterator<PassthroughTermination> it = myTerminations.values().iterator();
while (it.hasNext()) {
PassthroughTermination termination = it.next();
InstantaneousOutput io = termination.getValues();
if (io instanceof RealOutput) {
values = MU.sum(values, ((RealOutput) io).getValues());
} else if (io instanceof SpikeOutput) {
boolean[] spikes = ((SpikeOutput) io).getValues();
for (int i = 0; i < spikes.length; i++) {
if (spikes[i]) {
values[i] += 1f/(endTime - startTime);
}
}
} else if (io == null) {
throw new SimulationException("Null input to Termination " + termination.getName());
} else {
throw new SimulationException("Output type unknown: " + io.getClass().getName());
}
}
// Send values over the socket.
// Datagram format:
// - bytes 1-4: Timestamp (float)
// - bytes 4-(myDim+1)*4: values[i] (float)
ByteBuffer buffer = ByteBuffer.allocate((myDimension + 1) * 4);
buffer.order(myByteOrder);
buffer.putFloat((float)((startTime + endTime + myUpdateInterval) / 2.0));
for(int i = 0; i < myDimension; i++)
buffer.putFloat(values[i]);
byte[] bufArray = buffer.array();
DatagramPacket packet = new DatagramPacket(bufArray, bufArray.length, myDestAddress, myDestPort);
try {
mySocket.send(packet);
}
catch (IOException e) {
// TODO: Handle this better
throw new SimulationException(e);
}
}
}
if (isReceiver()) {
float[] values = new float[myDimension];
float[] tempValues = new float[myDimension+1];
// Check items in priority queue to see if there is anything that is good to go (i.e. timestamp is within
// startTime and endTime.
boolean foundItem = false;
boolean foundFutureItem = false;
int i = 0;
while (!mySocketBuffer.isEmpty()) {
tempValues = (float[]) mySocketBuffer.peek();
foundItem = (tempValues[0] >= startTime && tempValues[0] <= endTime) || myIgnoreTimestamp;
foundFutureItem = tempValues[0] > endTime;
if (foundItem)
mySocketBuffer.remove();
else
break;
}
if (foundItem) {
// If an item was found in the queue (i.e. message with future timestamp was received before), use this
// data instead of waiting on socket for new data.
for (i = 0; i < myDimension; i++)
values[i] = tempValues[i+1];
}
else if (foundFutureItem || startTime < myNextUpdate) {
// Buffer contained item in the future, so skip waiting for a new packet to arrive, and hurry
// the heck up.
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
}
else {
// If no items were found in queue, wait on socket for new data.
try {
byte[] bufArray = new byte[(myDimension + 1) * 4];
DatagramPacket packet = new DatagramPacket(bufArray, bufArray.length);
while (true) {
mySocket.receive(packet);
ByteBuffer buffer = ByteBuffer.wrap(bufArray);
buffer.order(myByteOrder);
for (i = 0; i < myDimension + 1; i++) {
tempValues[i] = buffer.getFloat();
}
// Check for timestamp for validity (i.e. within the start and end of this run call).
if ((tempValues[0] >= startTime && tempValues[0] <= endTime) || myIgnoreTimestamp || tempValues[0] < 0) {
// Valid timestamp encountered; or have been instructed to ignore timestamps.
// No further actions required, just break out of while loop.
values = Arrays.copyOfRange(tempValues, 1, myDimension+1);
break;
}
else if (tempValues[0] > endTime) {
// Future timestamp encountered, place into priority queue, use previous origin value as
// current value, and then out of while loop.
// Note: we break out of the while loop because receiving future timestamps means this
// system is (potentially) running slow.
mySocketBuffer.add(tempValues.clone());
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
break;
}
// Past timestamp encountered. Just ignore it, and wait for another packet.
}
}
catch (SocketTimeoutException e){
// If a timeout occurs, don't really do anything, just keep the origin at the previous value.
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
}
catch (Exception e){
// TODO: Handle this better
throw new SimulationException(e);
}
}
myOrigin.setValues(new RealOutputImpl(values, Units.UNK, endTime));
}
if (startTime >= myNextUpdate)
myNextUpdate += myUpdateInterval;
}
| public void run(float startTime, float endTime) throws SimulationException {
// TODO: Thread this thing, so that it doesn't block if the blocking receive calls
// are called before the send calls. (waiting for a receive before a send causes
// a deadlock situation.
if (isSender() && startTime >= myNextUpdate) {
if (mySocket == null)
// If for some reason the socket hasn't been initialized, then initialize it.
initialize();
if (myTerminations.isEmpty())
throw new SimulationException("SocketUDPNode is sender, but has no terminations to get data from.");
else {
// TODO: Test with spiking outputs?
float[] values = new float[myDimension];
Iterator<PassthroughTermination> it = myTerminations.values().iterator();
while (it.hasNext()) {
PassthroughTermination termination = it.next();
InstantaneousOutput io = termination.getValues();
if (io instanceof RealOutput) {
values = MU.sum(values, ((RealOutput) io).getValues());
} else if (io instanceof SpikeOutput) {
boolean[] spikes = ((SpikeOutput) io).getValues();
for (int i = 0; i < spikes.length; i++) {
if (spikes[i]) {
values[i] += 1f/(endTime - startTime);
}
}
} else if (io == null) {
throw new SimulationException("Null input to Termination " + termination.getName());
} else {
throw new SimulationException("Output type unknown: " + io.getClass().getName());
}
}
// Send values over the socket.
// Datagram format:
// - bytes 1-4: Timestamp (float)
// - bytes 4-(myDim+1)*4: values[i] (float)
ByteBuffer buffer = ByteBuffer.allocate((myDimension + 1) * 4);
buffer.order(myByteOrder);
buffer.putFloat((float)((startTime + endTime + myUpdateInterval) / 2.0));
for(int i = 0; i < myDimension; i++)
buffer.putFloat(values[i]);
byte[] bufArray = buffer.array();
DatagramPacket packet = new DatagramPacket(bufArray, bufArray.length, myDestAddress, myDestPort);
try {
mySocket.send(packet);
}
catch (IOException e) {
// TODO: Handle this better
throw new SimulationException(e);
}
}
}
if (isReceiver()) {
float[] values = new float[myDimension];
float[] tempValues = new float[myDimension+1];
// Check items in priority queue to see if there is anything that is good to go (i.e. timestamp is within
// startTime and endTime.
boolean foundItem = false;
boolean foundFutureItem = false;
int i = 0;
while (!mySocketBuffer.isEmpty()) {
tempValues = (float[]) mySocketBuffer.peek();
foundItem = (tempValues[0] >= startTime && tempValues[0] <= endTime) || myIgnoreTimestamp;
foundFutureItem = tempValues[0] > endTime;
if (foundItem)
mySocketBuffer.remove();
else
break;
}
if (foundItem) {
// If an item was found in the queue (i.e. message with future timestamp was received before), use this
// data instead of waiting on socket for new data.
for (i = 0; i < myDimension; i++)
values[i] = tempValues[i+1];
}
else if (foundFutureItem || startTime < myNextUpdate) {
// Buffer contained item in the future, so skip waiting for a new packet to arrive, and hurry
// the heck up.
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
}
else {
// If no items were found in queue, wait on socket for new data.
try {
byte[] bufArray = new byte[(myDimension + 1) * 4];
DatagramPacket packet = new DatagramPacket(bufArray, bufArray.length);
while (true) {
mySocket.receive(packet);
ByteBuffer buffer = ByteBuffer.wrap(bufArray);
buffer.order(myByteOrder);
for (i = 0; i < myDimension + 1; i++) {
tempValues[i] = buffer.getFloat();
}
// Check for timestamp for validity (i.e. within the start and end of this run call).
if ((tempValues[0] >= startTime && tempValues[0] <= endTime) || myIgnoreTimestamp || tempValues[0] < 0) {
// Valid timestamp encountered; or have been instructed to ignore timestamps.
// No further actions required, just break out of while loop.
//values = Arrays.copyOfRange(tempValues, 1, myDimension+1);
System.arraycopy(tempValues, 1, values, 0, myDimension);
break;
}
else if (tempValues[0] > endTime) {
// Future timestamp encountered, place into priority queue, use previous origin value as
// current value, and then out of while loop.
// Note: we break out of the while loop because receiving future timestamps means this
// system is (potentially) running slow.
mySocketBuffer.add(tempValues.clone());
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
break;
}
// Past timestamp encountered. Just ignore it, and wait for another packet.
}
}
catch (SocketTimeoutException e){
// If a timeout occurs, don't really do anything, just keep the origin at the previous value.
values = ((RealOutputImpl) myOrigin.getValues()).getValues().clone();
}
catch (Exception e){
// TODO: Handle this better
throw new SimulationException(e);
}
}
myOrigin.setValues(new RealOutputImpl(values, Units.UNK, endTime));
}
if (startTime >= myNextUpdate)
myNextUpdate += myUpdateInterval;
}
|
diff --git a/disambiguation-work/disambiguation-work-impl/src/main/java/pl/edu/icm/coansys/disambiguation/work/voter/AuthorsVoter.java b/disambiguation-work/disambiguation-work-impl/src/main/java/pl/edu/icm/coansys/disambiguation/work/voter/AuthorsVoter.java
index 08f52c65..ca70e9af 100644
--- a/disambiguation-work/disambiguation-work-impl/src/main/java/pl/edu/icm/coansys/disambiguation/work/voter/AuthorsVoter.java
+++ b/disambiguation-work/disambiguation-work-impl/src/main/java/pl/edu/icm/coansys/disambiguation/work/voter/AuthorsVoter.java
@@ -1,144 +1,144 @@
/*
* This file is part of CoAnSys project.
* Copyright (c) 2012-2013 ICM-UW
*
* CoAnSys is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* CoAnSys is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CoAnSys. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.coansys.disambiguation.work.voter;
import java.util.List;
import pl.edu.icm.coansys.commons.java.Pair;
import pl.edu.icm.coansys.commons.java.StringTools;
import pl.edu.icm.coansys.commons.reparser.Node;
import pl.edu.icm.coansys.commons.reparser.RegexpParser;
import pl.edu.icm.coansys.commons.stringsimilarity.JaroWinklerSimilarity;
import pl.edu.icm.coansys.commons.stringsimilarity.SimilarityCalculator;
import pl.edu.icm.coansys.models.DocumentProtos;
/**
*
* @author Artur Czeczko <[email protected]>
*/
public class AuthorsVoter extends AbstractSimilarityVoter {
@Override
public Vote vote(DocumentProtos.DocumentWrapper doc1, DocumentProtos.DocumentWrapper doc2) {
Pair<String[], Boolean> doc1surnames = extractSurnames(doc1);
Pair<String[], Boolean> doc2surnames = extractSurnames(doc2);
if (doc1surnames.getX().length == 0 || doc2surnames.getX().length == 0) {
return new Vote(Vote.VoteStatus.ABSTAIN);
}
float firstAuthorComponent = 0.0f;
float allAuthorsMatchFactor = 0.75f;
if (doc1surnames.getY() && doc2surnames.getY()) {
String doc1firstAuthor = doc1surnames.getX()[0];
String doc2firstAuthor = doc2surnames.getX()[0];
SimilarityCalculator similarity = getSimilarityCalculator();
if (similarity.calculateSimilarity(doc1firstAuthor, doc2firstAuthor) > 0.5f) {
firstAuthorComponent = 0.667f;
allAuthorsMatchFactor = 0.33f;
} else {
allAuthorsMatchFactor = 0.667f;
}
}
float probability = firstAuthorComponent +
allAuthorsMatchFactor * allAuthorsMatching(doc1surnames.getX(), doc2surnames.getX());
if (probability > 1.0f) {
probability = 1.0f;
}
if (probability < 0.0f) {
probability = 0.0f;
}
return new Vote(Vote.VoteStatus.PROBABILITY, probability);
}
private Pair<String[], Boolean> extractSurnames(DocumentProtos.DocumentWrapper doc) {
RegexpParser authorParser = new RegexpParser("authorParser.properties", "author");
List<DocumentProtos.Author> authorList = doc.getDocumentMetadata().getBasicMetadata().getAuthorList();
String[] resultByPositionNb = new String[authorList.size()];
String[] resultByOrder = new String[authorList.size()];
boolean positionsCorrect = true;
int orderNb = 0;
for (DocumentProtos.Author author : doc.getDocumentMetadata().getBasicMetadata().getAuthorList()) {
String surname;
if (author.hasSurname()) {
surname = author.getSurname();
} else {
String fullname = author.getName();
try {
Node authorNode = authorParser.parse(fullname);
Node surnameNode = authorNode.getFirstField("surname");
surname = surnameNode.getValue();
} catch (NullPointerException ex) {
surname = fullname;
}
}
surname = StringTools.normalize(surname);
if (positionsCorrect) {
if (!author.hasPositionNumber()) {
positionsCorrect = false;
} else {
int authorPosition = author.getPositionNumber() - 1;
- if (authorPosition >= resultByPositionNb.length || resultByPositionNb[authorPosition] != null) {
+ if (authorPosition < 0 || authorPosition >= resultByPositionNb.length || resultByPositionNb[authorPosition] != null) {
positionsCorrect = false;
} else {
resultByPositionNb[authorPosition] = surname;
}
}
}
resultByOrder[orderNb] = surname;
orderNb++;
}
return new Pair<String[], Boolean>(positionsCorrect ? resultByPositionNb : resultByOrder, positionsCorrect);
}
private SimilarityCalculator getSimilarityCalculator() {
return new JaroWinklerSimilarity();
}
/**
*
*
* @param doc1authors
* @param doc2authors
* @return
*/
private float allAuthorsMatching(String[] doc1authors, String[] doc2authors) {
int intersectionSize = 0;
SimilarityCalculator similarity = getSimilarityCalculator();
for (String d1author : doc1authors) {
for (String d2author : doc2authors) {
if (similarity.calculateSimilarity(d1author, d2author) > 0.5) {
intersectionSize++;
break;
}
}
}
return 2.0f * intersectionSize / (doc1authors.length + doc2authors.length);
}
}
| true | true | private Pair<String[], Boolean> extractSurnames(DocumentProtos.DocumentWrapper doc) {
RegexpParser authorParser = new RegexpParser("authorParser.properties", "author");
List<DocumentProtos.Author> authorList = doc.getDocumentMetadata().getBasicMetadata().getAuthorList();
String[] resultByPositionNb = new String[authorList.size()];
String[] resultByOrder = new String[authorList.size()];
boolean positionsCorrect = true;
int orderNb = 0;
for (DocumentProtos.Author author : doc.getDocumentMetadata().getBasicMetadata().getAuthorList()) {
String surname;
if (author.hasSurname()) {
surname = author.getSurname();
} else {
String fullname = author.getName();
try {
Node authorNode = authorParser.parse(fullname);
Node surnameNode = authorNode.getFirstField("surname");
surname = surnameNode.getValue();
} catch (NullPointerException ex) {
surname = fullname;
}
}
surname = StringTools.normalize(surname);
if (positionsCorrect) {
if (!author.hasPositionNumber()) {
positionsCorrect = false;
} else {
int authorPosition = author.getPositionNumber() - 1;
if (authorPosition >= resultByPositionNb.length || resultByPositionNb[authorPosition] != null) {
positionsCorrect = false;
} else {
resultByPositionNb[authorPosition] = surname;
}
}
}
resultByOrder[orderNb] = surname;
orderNb++;
}
return new Pair<String[], Boolean>(positionsCorrect ? resultByPositionNb : resultByOrder, positionsCorrect);
}
| private Pair<String[], Boolean> extractSurnames(DocumentProtos.DocumentWrapper doc) {
RegexpParser authorParser = new RegexpParser("authorParser.properties", "author");
List<DocumentProtos.Author> authorList = doc.getDocumentMetadata().getBasicMetadata().getAuthorList();
String[] resultByPositionNb = new String[authorList.size()];
String[] resultByOrder = new String[authorList.size()];
boolean positionsCorrect = true;
int orderNb = 0;
for (DocumentProtos.Author author : doc.getDocumentMetadata().getBasicMetadata().getAuthorList()) {
String surname;
if (author.hasSurname()) {
surname = author.getSurname();
} else {
String fullname = author.getName();
try {
Node authorNode = authorParser.parse(fullname);
Node surnameNode = authorNode.getFirstField("surname");
surname = surnameNode.getValue();
} catch (NullPointerException ex) {
surname = fullname;
}
}
surname = StringTools.normalize(surname);
if (positionsCorrect) {
if (!author.hasPositionNumber()) {
positionsCorrect = false;
} else {
int authorPosition = author.getPositionNumber() - 1;
if (authorPosition < 0 || authorPosition >= resultByPositionNb.length || resultByPositionNb[authorPosition] != null) {
positionsCorrect = false;
} else {
resultByPositionNb[authorPosition] = surname;
}
}
}
resultByOrder[orderNb] = surname;
orderNb++;
}
return new Pair<String[], Boolean>(positionsCorrect ? resultByPositionNb : resultByOrder, positionsCorrect);
}
|
diff --git a/android/src/com/google/zxing/client/android/PlanarYUV420LuminanceSource.java b/android/src/com/google/zxing/client/android/PlanarYUV420LuminanceSource.java
index 1ee3e830..c25f9385 100644
--- a/android/src/com/google/zxing/client/android/PlanarYUV420LuminanceSource.java
+++ b/android/src/com/google/zxing/client/android/PlanarYUV420LuminanceSource.java
@@ -1,76 +1,77 @@
/*
* Copyright 2009 ZXing 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 com.google.zxing.client.android;
import android.graphics.Bitmap;
import com.google.zxing.LuminanceSource;
public final class PlanarYUV420LuminanceSource extends AbstractPlanarYUVLuminanceSource {
public PlanarYUV420LuminanceSource(byte[] yuvData, int dataWidth, int dataHeight,
int left, int top, int width, int height) {
super(yuvData, dataWidth, dataHeight, left, top, width, height);
}
@Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new PlanarYUV420LuminanceSource(
getYUVData(), getDataWidth(), getDataHeight(), left, top, width, height);
}
@Override
public Bitmap renderFullColorBitmap(boolean halfSize) {
// TODO implement halfSize
int width = getWidth();
int height = getHeight();
int dataWidth = getDataWidth();
+ int dataHeight = getDataHeight();
byte[] yuv = getYUVData();
- int expectedYBytes = width * height;
+ int expectedYBytes = dataWidth * dataHeight;
int expectedUBytes = expectedYBytes >> 2;
int expectedVBytes = expectedYBytes >> 2;
int expectedBytes = expectedYBytes + expectedUBytes + expectedVBytes;
if (yuv.length != expectedBytes) {
throw new IllegalStateException("Expected " + expectedBytes + " bytes");
}
int[] pixels = new int[width * height];
int inputYOffset = getTop() * getDataWidth() + getLeft();
int uOffset = expectedYBytes;
int vOffset = expectedYBytes + expectedUBytes;
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
for (int x = 0; x < width; x++) {
int yOffset = inputYOffset + x;
int yDataRow = yOffset / dataWidth;
int yDataOffset = yOffset % dataWidth;
int uvOffset = ((yDataRow >> 1) * dataWidth + yDataOffset) >> 1;
int y1 = yuv[yOffset] & 0xFF;
int u = yuv[uOffset + uvOffset] & 0xFF;
int v = yuv[vOffset + uvOffset] & 0XFF;
pixels[outputOffset + x] =
OPAQUE_ALPHA | InterleavedYUV422LuminanceSource.yuvToRGB(y1, u, v);
}
inputYOffset += dataWidth;
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
}
| false | true | public Bitmap renderFullColorBitmap(boolean halfSize) {
// TODO implement halfSize
int width = getWidth();
int height = getHeight();
int dataWidth = getDataWidth();
byte[] yuv = getYUVData();
int expectedYBytes = width * height;
int expectedUBytes = expectedYBytes >> 2;
int expectedVBytes = expectedYBytes >> 2;
int expectedBytes = expectedYBytes + expectedUBytes + expectedVBytes;
if (yuv.length != expectedBytes) {
throw new IllegalStateException("Expected " + expectedBytes + " bytes");
}
int[] pixels = new int[width * height];
int inputYOffset = getTop() * getDataWidth() + getLeft();
int uOffset = expectedYBytes;
int vOffset = expectedYBytes + expectedUBytes;
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
for (int x = 0; x < width; x++) {
int yOffset = inputYOffset + x;
int yDataRow = yOffset / dataWidth;
int yDataOffset = yOffset % dataWidth;
int uvOffset = ((yDataRow >> 1) * dataWidth + yDataOffset) >> 1;
int y1 = yuv[yOffset] & 0xFF;
int u = yuv[uOffset + uvOffset] & 0xFF;
int v = yuv[vOffset + uvOffset] & 0XFF;
pixels[outputOffset + x] =
OPAQUE_ALPHA | InterleavedYUV422LuminanceSource.yuvToRGB(y1, u, v);
}
inputYOffset += dataWidth;
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
| public Bitmap renderFullColorBitmap(boolean halfSize) {
// TODO implement halfSize
int width = getWidth();
int height = getHeight();
int dataWidth = getDataWidth();
int dataHeight = getDataHeight();
byte[] yuv = getYUVData();
int expectedYBytes = dataWidth * dataHeight;
int expectedUBytes = expectedYBytes >> 2;
int expectedVBytes = expectedYBytes >> 2;
int expectedBytes = expectedYBytes + expectedUBytes + expectedVBytes;
if (yuv.length != expectedBytes) {
throw new IllegalStateException("Expected " + expectedBytes + " bytes");
}
int[] pixels = new int[width * height];
int inputYOffset = getTop() * getDataWidth() + getLeft();
int uOffset = expectedYBytes;
int vOffset = expectedYBytes + expectedUBytes;
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
for (int x = 0; x < width; x++) {
int yOffset = inputYOffset + x;
int yDataRow = yOffset / dataWidth;
int yDataOffset = yOffset % dataWidth;
int uvOffset = ((yDataRow >> 1) * dataWidth + yDataOffset) >> 1;
int y1 = yuv[yOffset] & 0xFF;
int u = yuv[uOffset + uvOffset] & 0xFF;
int v = yuv[vOffset + uvOffset] & 0XFF;
pixels[outputOffset + x] =
OPAQUE_ALPHA | InterleavedYUV422LuminanceSource.yuvToRGB(y1, u, v);
}
inputYOffset += dataWidth;
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
|
diff --git a/framework/src/play-test/src/main/java/play/test/Helpers.java b/framework/src/play-test/src/main/java/play/test/Helpers.java
index 813a214ef..173e55e4f 100644
--- a/framework/src/play-test/src/main/java/play/test/Helpers.java
+++ b/framework/src/play-test/src/main/java/play/test/Helpers.java
@@ -1,494 +1,498 @@
package play.test;
import play.*;
import play.mvc.*;
import play.api.test.Helpers$;
import play.libs.*;
import play.libs.F.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.htmlunit.*;
import java.util.*;
/**
* Helper functions to run tests.
*/
public class Helpers implements play.mvc.Http.Status, play.mvc.Http.HeaderNames {
public static String GET = "GET";
public static String POST = "POST";
public static String PUT = "PUT";
public static String DELETE = "DELETE";
public static String HEAD = "HEAD";
// --
public static Class<? extends WebDriver> HTMLUNIT = HtmlUnitDriver.class;
public static Class<? extends WebDriver> FIREFOX = FirefoxDriver.class;
// --
@SuppressWarnings(value = "unchecked")
private static Result invokeHandler(play.api.mvc.Handler handler, FakeRequest fakeRequest) {
if(handler instanceof play.core.j.JavaAction) {
play.api.mvc.Action action = (play.api.mvc.Action)handler;
return wrapScalaResult(action.apply(fakeRequest.getWrappedRequest()));
} else {
throw new RuntimeException("This is not a JavaAction and can't be invoked this way.");
}
}
private static SimpleResult wrapScalaResult(scala.concurrent.Future<play.api.mvc.SimpleResult> result) {
if (result == null) {
return null;
} else {
final play.api.mvc.SimpleResult simpleResult = new Promise<play.api.mvc.SimpleResult>(result).get();
return new SimpleResult() {
public play.api.mvc.SimpleResult getWrappedSimpleResult() {
return simpleResult;
}
};
}
}
private static SimpleResult unwrapJavaResult(Result result) {
if (result instanceof SimpleResult) {
return (SimpleResult) result;
} else {
return wrapScalaResult(result.getWrappedResult());
}
}
// --
/**
* Call an action method while decorating it with the right @With interceptors.
*/
public static Result callAction(HandlerRef actionReference) {
return callAction(actionReference, fakeRequest());
}
/**
* Call an action method while decorating it with the right @With interceptors.
*/
public static Result callAction(HandlerRef actionReference, FakeRequest fakeRequest) {
play.api.mvc.HandlerRef handlerRef = (play.api.mvc.HandlerRef)actionReference;
return invokeHandler(handlerRef.handler(), fakeRequest);
}
/**
* Build a new GET / fake request.
*/
public static FakeRequest fakeRequest() {
return new FakeRequest();
}
/**
* Build a new fake request.
*/
public static FakeRequest fakeRequest(String method, String uri) {
return new FakeRequest(method, uri);
}
/**
* Build a new fake application.
*/
public static FakeApplication fakeApplication() {
return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), new HashMap<String,Object>(), new ArrayList<String>(), null);
}
/**
* Build a new fake application.
*/
public static FakeApplication fakeApplication(GlobalSettings global) {
return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), new HashMap<String,Object>(), new ArrayList<String>(), global);
}
/**
* A fake Global
*/
public static GlobalSettings fakeGlobal() {
return new GlobalSettings();
}
/**
* Constructs a in-memory (h2) database configuration to add to a FakeApplication.
*/
public static Map<String,String> inMemoryDatabase() {
return inMemoryDatabase("default");
}
/**
* Constructs a in-memory (h2) database configuration to add to a FakeApplication.
*/
public static Map<String,String> inMemoryDatabase(String name) {
return inMemoryDatabase(name, Collections.<String, String>emptyMap());
}
/**
* Constructs a in-memory (h2) database configuration to add to a FakeApplication.
*/
public static Map<String,String> inMemoryDatabase(String name, Map<String, String> options) {
return Scala.asJava(play.api.test.Helpers.inMemoryDatabase(name, Scala.asScala(options)));
}
/**
* Build a new fake application.
*/
public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration) {
return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, new ArrayList<String>(), null);
}
/**
* Build a new fake application.
*/
public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, GlobalSettings global) {
return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, new ArrayList<String>(), global);
}
/**
* Build a new fake application.
*/
public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugin) {
return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, additionalPlugin, null);
}
/**
* Build a new fake application.
*/
public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugin, GlobalSettings global) {
return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, additionalPlugin, global);
}
/**
* Build a new fake application.
*/
public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugins, List<String> withoutPlugins) {
return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, additionalPlugins, withoutPlugins, null);
}
/**
* Build a new fake application.
*/
public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugins, List<String> withoutPlugins, GlobalSettings global) {
return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, additionalPlugins, withoutPlugins, global);
}
/**
* Extracts the Status code of this Result value.
*/
public static int status(Result result) {
return unwrapJavaResult(result).getWrappedSimpleResult().header().status();
}
/**
* Extracts the Location header of this Result value if this Result is a Redirect.
*/
public static String redirectLocation(Result result) {
return header(LOCATION, result);
}
/**
* Extracts the Flash values of this Result value.
*/
public static play.mvc.Http.Flash flash(Result result) {
return play.core.j.JavaResultExtractor.getFlash(unwrapJavaResult(result));
}
/**
* Extracts the Session of this Result value.
*/
public static play.mvc.Http.Session session(Result result) {
return play.core.j.JavaResultExtractor.getSession(unwrapJavaResult(result));
}
/**
* * Extracts a Cookie value from this Result value
*/
public static play.mvc.Http.Cookie cookie(String name, Result result) {
return play.core.j.JavaResultExtractor.getCookies(unwrapJavaResult(result)).get(name);
}
/**
* Extracts an Header value of this Result value.
*/
public static String header(String header, Result result) {
return play.core.j.JavaResultExtractor.getHeaders(unwrapJavaResult(result)).get(header);
}
/**
* Extracts all Headers of this Result value.
*/
public static Map<String,String> headers(Result result) {
return play.core.j.JavaResultExtractor.getHeaders(unwrapJavaResult(result));
}
/**
* Extracts the Content-Type of this Content value.
*/
public static String contentType(Content content) {
return content.contentType();
}
/**
* Extracts the Content-Type of this Result value.
*/
public static String contentType(Result result) {
String h = header(CONTENT_TYPE, result);
if(h == null) return null;
if(h.contains(";")) {
return h.substring(0, h.indexOf(";")).trim();
} else {
return h.trim();
}
}
/**
* Extracts the Charset of this Result value.
*/
public static String charset(Result result) {
String h = header(CONTENT_TYPE, result);
if(h == null) return null;
if(h.contains("; charset=")) {
return h.substring(h.indexOf("; charset=") + 10, h.length()).trim();
} else {
return null;
}
}
/**
* Extracts the content as bytes.
*/
public static byte[] contentAsBytes(Result result) {
return play.core.j.JavaResultExtractor.getBody(unwrapJavaResult(result));
}
/**
* Extracts the content as bytes.
*/
public static byte[] contentAsBytes(Content content) {
return content.body().getBytes();
}
/**
* Extracts the content as String.
*/
public static String contentAsString(Content content) {
return content.body();
}
/**
* Extracts the content as String.
*/
public static String contentAsString(Result result) {
try {
String charset = charset(result);
if(charset == null) {
charset = "utf-8";
}
return new String(contentAsBytes(result), charset);
} catch(RuntimeException e) {
throw e;
} catch(Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Use the Router to determine the Action to call for this request and executes it.
* @deprecated
* @see #route instead
*/
@SuppressWarnings(value = "unchecked")
public static Result routeAndCall(FakeRequest fakeRequest) {
try {
return routeAndCall((Class<? extends play.core.Router.Routes>)FakeRequest.class.getClassLoader().loadClass("Routes"), fakeRequest);
} catch(RuntimeException e) {
throw e;
} catch(Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Use the Router to determine the Action to call for this request and executes it.
* @deprecated
* @see #route instead
*/
public static Result routeAndCall(Class<? extends play.core.Router.Routes> router, FakeRequest fakeRequest) {
try {
play.core.Router.Routes routes = (play.core.Router.Routes)router.getClassLoader().loadClass(router.getName() + "$").getDeclaredField("MODULE$").get(null);
if(routes.routes().isDefinedAt(fakeRequest.getWrappedRequest())) {
return invokeHandler(routes.routes().apply(fakeRequest.getWrappedRequest()), fakeRequest);
} else {
return null;
}
} catch(RuntimeException e) {
throw e;
} catch(Throwable t) {
throw new RuntimeException(t);
}
}
public static Result route(FakeRequest fakeRequest) {
return route(play.Play.application(), fakeRequest);
}
public static Result route(Application app, FakeRequest fakeRequest) {
final scala.Option<scala.concurrent.Future<play.api.mvc.SimpleResult>> opt = play.api.test.Helpers.jRoute(app.getWrappedApplication(), fakeRequest.fake);
return wrapScalaResult(Scala.orNull(opt));
}
public static Result route(Application app, FakeRequest fakeRequest, byte[] body) {
return wrapScalaResult(Scala.orNull(play.api.test.Helpers.jRoute(app.getWrappedApplication(), fakeRequest.getWrappedRequest(), body)));
}
public static Result route(FakeRequest fakeRequest, byte[] body) {
return route(play.Play.application(), fakeRequest, body);
}
/**
* Starts a new application.
*/
public static void start(FakeApplication fakeApplication) {
play.api.Play.start(fakeApplication.getWrappedApplication());
}
/**
* Stops an application.
*/
public static void stop(FakeApplication fakeApplication) {
play.api.Play.stop();
play.api.libs.ws.WS$.MODULE$.resetClient();
}
/**
* Executes a block of code in a running application.
*/
public static synchronized void running(FakeApplication fakeApplication, final Runnable block) {
try {
start(fakeApplication);
block.run();
} finally {
stop(fakeApplication);
}
}
/**
* Creates a new Test server.
*/
public static TestServer testServer(int port) {
return new TestServer(port, fakeApplication());
}
/**
* Creates a new Test server.
*/
public static TestServer testServer(int port, FakeApplication app) {
return new TestServer(port, app);
}
/**
* Starts a Test server.
*/
public static void start(TestServer server) {
server.start();
}
/**
* Stops a Test server.
*/
public static void stop(TestServer server) {
server.stop();
}
/**
* Executes a block of code in a running server.
*/
public static synchronized void running(TestServer server, final Runnable block) {
try {
start(server);
block.run();
} finally {
stop(server);
}
}
/**
* Executes a block of code in a running server, with a test browser.
*/
public static synchronized void running(TestServer server, Class<? extends WebDriver> webDriver, final Callback<TestBrowser> block) {
TestBrowser browser = null;
TestServer startedServer = null;
try {
start(server);
startedServer = server;
browser = testBrowser(webDriver);
block.invoke(browser);
+ } catch(Error e) {
+ throw e;
+ } catch(RuntimeException re) {
+ throw re;
} catch(Throwable t) {
throw new RuntimeException(t);
} finally {
if(browser != null) {
browser.quit();
}
if(startedServer != null) {
stop(startedServer);
}
}
}
/**
* Creates a Test Browser.
*/
public static TestBrowser testBrowser() {
return testBrowser(HTMLUNIT);
}
/**
* Creates a Test Browser.
*/
public static TestBrowser testBrowser(int port) {
return testBrowser(HTMLUNIT, port);
}
/**
* Creates a Test Browser.
*/
public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver) {
return testBrowser(webDriver, Helpers$.MODULE$.testServerPort());
}
/**
* Creates a Test Browser.
*/
public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver, int port) {
try {
return new TestBrowser(webDriver, "http://localhost:" + port);
} catch(RuntimeException e) {
throw e;
} catch(Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Creates a Test Browser.
*/
public static TestBrowser testBrowser(WebDriver of, int port) {
return new TestBrowser(of, "http://localhost:" + port);
}
/**
* Creates a Test Browser.
*/
public static TestBrowser testBrowser(WebDriver of) {
return testBrowser(of, Helpers$.MODULE$.testServerPort());
}
}
| true | true | public static synchronized void running(TestServer server, Class<? extends WebDriver> webDriver, final Callback<TestBrowser> block) {
TestBrowser browser = null;
TestServer startedServer = null;
try {
start(server);
startedServer = server;
browser = testBrowser(webDriver);
block.invoke(browser);
} catch(Throwable t) {
throw new RuntimeException(t);
} finally {
if(browser != null) {
browser.quit();
}
if(startedServer != null) {
stop(startedServer);
}
}
}
| public static synchronized void running(TestServer server, Class<? extends WebDriver> webDriver, final Callback<TestBrowser> block) {
TestBrowser browser = null;
TestServer startedServer = null;
try {
start(server);
startedServer = server;
browser = testBrowser(webDriver);
block.invoke(browser);
} catch(Error e) {
throw e;
} catch(RuntimeException re) {
throw re;
} catch(Throwable t) {
throw new RuntimeException(t);
} finally {
if(browser != null) {
browser.quit();
}
if(startedServer != null) {
stop(startedServer);
}
}
}
|
diff --git a/runner/src/main/java/org/jclouds/cli/runner/Main.java b/runner/src/main/java/org/jclouds/cli/runner/Main.java
index e1c9743..f8a1497 100644
--- a/runner/src/main/java/org/jclouds/cli/runner/Main.java
+++ b/runner/src/main/java/org/jclouds/cli/runner/Main.java
@@ -1,328 +1,328 @@
/*
* Copyright (C) 2012, the original 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.jclouds.cli.runner;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import jline.Terminal;
import org.apache.felix.gogo.commands.Action;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.CommandException;
import org.apache.felix.gogo.commands.basic.AbstractCommand;
import org.apache.felix.gogo.runtime.CommandNotFoundException;
import org.apache.felix.gogo.runtime.CommandProcessorImpl;
import org.apache.felix.gogo.runtime.threadio.ThreadIOImpl;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.command.Function;
import org.apache.karaf.shell.console.NameScoping;
import org.apache.karaf.shell.console.jline.Console;
import org.apache.karaf.shell.console.jline.TerminalFactory;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
/**
* This is forked from Apache Karaf and aligned to the needs of jclouds cli.
*/
public class Main {
private static final String KARAF_HOME = "karaf.home";
private static final Class[] parameters = new Class[] {URL.class};
private String application = System.getProperty("karaf.name", "root");
private String user = "karaf";
public static void main(String args[]) throws Exception {
Main main = new Main();
main.run(args);
}
/**
* Use this method when the shell is being executed as a top level shell.
*
* @param args
* @throws Exception
*/
public void run(String args[]) throws Exception {
ThreadIOImpl threadio = new ThreadIOImpl();
threadio.start();
ClassLoader cl = Main.class.getClassLoader();
//This is a workaround for windows machines struggling with long class paths.
loadJarsFromPath(System.getProperty(KARAF_HOME) + File.separator + "system");
loadJarsFromPath(System.getProperty(KARAF_HOME) + File.separator + "deploy");
CommandProcessorImpl commandProcessor = new CommandProcessorImpl(threadio);
discoverCommands(commandProcessor, cl);
InputStream in = unwrap(System.in);
PrintStream out = wrap(unwrap(System.out));
PrintStream err = wrap(unwrap(System.err));
try {
run(commandProcessor, args, in, out, err);
} catch (Throwable t) {
System.exit(1);
}
System.exit(0);
}
/**
* Loads Jars found under the specified path.
* @throws IOException
*/
public void loadJarsFromPath(String path) throws IOException {
Queue<File> dirs = new LinkedList<File>();
dirs.add(new File(path));
while (!dirs.isEmpty()) {
for (File f : dirs.poll().listFiles()) {
if (f.isDirectory()) {
dirs.add(f);
} else if (f.isFile() && f.getAbsolutePath().endsWith(".jar") && !f.getAbsolutePath().contains("pax-logging")) {
//We make sure to exclude pax logging jars when running outside of OSGi, since we use external logging jars in that case.
addURL(f.toURI().toURL());
}
}
}
}
public static void addURL(URL u) throws IOException
{
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[] {u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}
}
private void run(final CommandProcessorImpl commandProcessor, String[] args, final InputStream in, final PrintStream out, final PrintStream err) throws Throwable {
if (args.length > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++) {
if (i > 0) {
sb.append(" ");
}
sb.append(args[i]);
}
// Shell is directly executing a sub/command, we don't setup a terminal and console
// in this case, this avoids us reading from stdin un-necessarily.
CommandSession session = commandProcessor.createSession(in, out, err);
session.put("USER", user);
session.put("APPLICATION", application);
session.put(NameScoping.MULTI_SCOPE_MODE_KEY, Boolean.toString(isMultiScopeMode()));
try {
session.execute(sb);
} catch (Throwable t) {
if (t instanceof CommandNotFoundException) {
String str = Ansi.ansi()
.fg(Ansi.Color.RED)
.a("Command not found: ")
.a(Ansi.Attribute.INTENSITY_BOLD)
.a(((CommandNotFoundException) t).getCommand())
.a(Ansi.Attribute.INTENSITY_BOLD_OFF)
.fg(Ansi.Color.DEFAULT).toString();
- session.getConsole().println(str);
+ err.println(str);
} else if (t instanceof CommandException) {
- session.getConsole().println(((CommandException) t).getNiceHelp());
+ err.println(((CommandException) t).getNiceHelp());
} else {
- session.getConsole().print(Ansi.ansi().fg(Ansi.Color.RED).toString());
- t.printStackTrace(session.getConsole());
- session.getConsole().print(Ansi.ansi().fg(Ansi.Color.DEFAULT).toString());
+ err.print(Ansi.ansi().fg(Ansi.Color.RED).toString());
+ t.printStackTrace(err);
+ err.print(Ansi.ansi().fg(Ansi.Color.DEFAULT).toString());
}
throw t;
}
} else {
// We are going into full blown interactive shell mode.
final TerminalFactory terminalFactory = new TerminalFactory();
final Terminal terminal = terminalFactory.getTerminal();
Console console = createConsole(commandProcessor, in, out, err, terminal);
CommandSession session = console.getSession();
session.put("USER", user);
session.put("APPLICATION", application);
session.put(NameScoping.MULTI_SCOPE_MODE_KEY, Boolean.toString(isMultiScopeMode()));
session.put("#LINES", new Function() {
public Object execute(CommandSession session, List<Object> arguments) throws Exception {
return Integer.toString(terminal.getHeight());
}
});
session.put("#COLUMNS", new Function() {
public Object execute(CommandSession session, List<Object> arguments) throws Exception {
return Integer.toString(terminal.getWidth());
}
});
session.put(".jline.terminal", terminal);
console.run();
terminalFactory.destroy();
}
}
/**
* Allow sub classes of main to change the Console implementation used.
*
* @param commandProcessor
* @param in
* @param out
* @param err
* @param terminal
* @return
* @throws Exception
*/
protected Console createConsole(CommandProcessorImpl commandProcessor, InputStream in, PrintStream out, PrintStream err, Terminal terminal) throws Exception {
return new Console(commandProcessor, in, out, err, terminal, null);
}
/**
* Sub classes can override so that their registered commands do not conflict with the default shell
* implementation.
*
* @return
*/
public String getDiscoveryResource() {
return "META-INF/services/org/apache/karaf/shell/commands";
}
private void discoverCommands(CommandProcessorImpl commandProcessor, ClassLoader cl) throws IOException, ClassNotFoundException {
Enumeration<URL> urls = cl.getResources(getDiscoveryResource());
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
try {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
line = line.trim();
if (line.isEmpty() || line.charAt(0) == '#') {
continue;
}
final Class<Action> actionClass = (Class<Action>) cl.loadClass(line);
Command cmd = actionClass.getAnnotation(Command.class);
Function function = new AbstractCommand() {
@Override
public Action createNewAction() {
try {
return ((Class<? extends Action>) actionClass).newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
};
addCommand(cmd, function, commandProcessor);
}
} finally {
reader.close();
}
}
}
protected void addCommand(Command cmd, Function function, CommandProcessorImpl commandProcessor) {
try {
commandProcessor.addCommand(cmd.scope(), function, cmd.name());
} catch (Exception e) {
}
}
public String getApplication() {
return application;
}
public void setApplication(String application) {
this.application = application;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
/**
* Returns whether or not we are in multi-scope mode.
* <p/>
* The default mode is multi-scoped where we prefix commands by their scope. If we are in single
* scoped mode then we don't use scope prefixes when registering or tab completing commands.
*/
public boolean isMultiScopeMode() {
return true;
}
private static PrintStream wrap(PrintStream stream) {
OutputStream o = AnsiConsole.wrapOutputStream(stream);
if (o instanceof PrintStream) {
return ((PrintStream) o);
} else {
return new PrintStream(o);
}
}
private static <T> T unwrap(T stream) {
try {
Method mth = stream.getClass().getMethod("getRoot");
return (T) mth.invoke(stream);
} catch (Throwable t) {
return stream;
}
}
private static List<URL> getFiles(File base) throws MalformedURLException {
List<URL> urls = new ArrayList<URL>();
getFiles(base, urls);
return urls;
}
private static void getFiles(File base, List<URL> urls) throws MalformedURLException {
for (File f : base.listFiles()) {
if (f.isDirectory()) {
getFiles(f, urls);
} else if (f.getName().endsWith(".jar")) {
urls.add(f.toURI().toURL());
}
}
}
}
| false | true | private void run(final CommandProcessorImpl commandProcessor, String[] args, final InputStream in, final PrintStream out, final PrintStream err) throws Throwable {
if (args.length > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++) {
if (i > 0) {
sb.append(" ");
}
sb.append(args[i]);
}
// Shell is directly executing a sub/command, we don't setup a terminal and console
// in this case, this avoids us reading from stdin un-necessarily.
CommandSession session = commandProcessor.createSession(in, out, err);
session.put("USER", user);
session.put("APPLICATION", application);
session.put(NameScoping.MULTI_SCOPE_MODE_KEY, Boolean.toString(isMultiScopeMode()));
try {
session.execute(sb);
} catch (Throwable t) {
if (t instanceof CommandNotFoundException) {
String str = Ansi.ansi()
.fg(Ansi.Color.RED)
.a("Command not found: ")
.a(Ansi.Attribute.INTENSITY_BOLD)
.a(((CommandNotFoundException) t).getCommand())
.a(Ansi.Attribute.INTENSITY_BOLD_OFF)
.fg(Ansi.Color.DEFAULT).toString();
session.getConsole().println(str);
} else if (t instanceof CommandException) {
session.getConsole().println(((CommandException) t).getNiceHelp());
} else {
session.getConsole().print(Ansi.ansi().fg(Ansi.Color.RED).toString());
t.printStackTrace(session.getConsole());
session.getConsole().print(Ansi.ansi().fg(Ansi.Color.DEFAULT).toString());
}
throw t;
}
} else {
// We are going into full blown interactive shell mode.
final TerminalFactory terminalFactory = new TerminalFactory();
final Terminal terminal = terminalFactory.getTerminal();
Console console = createConsole(commandProcessor, in, out, err, terminal);
CommandSession session = console.getSession();
session.put("USER", user);
session.put("APPLICATION", application);
session.put(NameScoping.MULTI_SCOPE_MODE_KEY, Boolean.toString(isMultiScopeMode()));
session.put("#LINES", new Function() {
public Object execute(CommandSession session, List<Object> arguments) throws Exception {
return Integer.toString(terminal.getHeight());
}
});
session.put("#COLUMNS", new Function() {
public Object execute(CommandSession session, List<Object> arguments) throws Exception {
return Integer.toString(terminal.getWidth());
}
});
session.put(".jline.terminal", terminal);
console.run();
terminalFactory.destroy();
}
}
| private void run(final CommandProcessorImpl commandProcessor, String[] args, final InputStream in, final PrintStream out, final PrintStream err) throws Throwable {
if (args.length > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++) {
if (i > 0) {
sb.append(" ");
}
sb.append(args[i]);
}
// Shell is directly executing a sub/command, we don't setup a terminal and console
// in this case, this avoids us reading from stdin un-necessarily.
CommandSession session = commandProcessor.createSession(in, out, err);
session.put("USER", user);
session.put("APPLICATION", application);
session.put(NameScoping.MULTI_SCOPE_MODE_KEY, Boolean.toString(isMultiScopeMode()));
try {
session.execute(sb);
} catch (Throwable t) {
if (t instanceof CommandNotFoundException) {
String str = Ansi.ansi()
.fg(Ansi.Color.RED)
.a("Command not found: ")
.a(Ansi.Attribute.INTENSITY_BOLD)
.a(((CommandNotFoundException) t).getCommand())
.a(Ansi.Attribute.INTENSITY_BOLD_OFF)
.fg(Ansi.Color.DEFAULT).toString();
err.println(str);
} else if (t instanceof CommandException) {
err.println(((CommandException) t).getNiceHelp());
} else {
err.print(Ansi.ansi().fg(Ansi.Color.RED).toString());
t.printStackTrace(err);
err.print(Ansi.ansi().fg(Ansi.Color.DEFAULT).toString());
}
throw t;
}
} else {
// We are going into full blown interactive shell mode.
final TerminalFactory terminalFactory = new TerminalFactory();
final Terminal terminal = terminalFactory.getTerminal();
Console console = createConsole(commandProcessor, in, out, err, terminal);
CommandSession session = console.getSession();
session.put("USER", user);
session.put("APPLICATION", application);
session.put(NameScoping.MULTI_SCOPE_MODE_KEY, Boolean.toString(isMultiScopeMode()));
session.put("#LINES", new Function() {
public Object execute(CommandSession session, List<Object> arguments) throws Exception {
return Integer.toString(terminal.getHeight());
}
});
session.put("#COLUMNS", new Function() {
public Object execute(CommandSession session, List<Object> arguments) throws Exception {
return Integer.toString(terminal.getWidth());
}
});
session.put(".jline.terminal", terminal);
console.run();
terminalFactory.destroy();
}
}
|
diff --git a/org.amanzi.awe.afp/src/org/amanzi/awe/afp/executors/AfpProcessExecutor.java b/org.amanzi.awe.afp/src/org/amanzi/awe/afp/executors/AfpProcessExecutor.java
index 0e8fb49c9..b3b34ca32 100644
--- a/org.amanzi.awe.afp/src/org/amanzi/awe/afp/executors/AfpProcessExecutor.java
+++ b/org.amanzi.awe.afp/src/org/amanzi/awe/afp/executors/AfpProcessExecutor.java
@@ -1,260 +1,261 @@
/* AWE - Amanzi Wireless Explorer
* http://awe.amanzi.org
* (C) 2008-2009, AmanziTel AB
*
* This library is provided under the terms of the Eclipse Public License
* as described at http://www.eclipse.org/legal/epl-v10.html. Any use,
* reproduction or distribution of the library constitutes recipient's
* acceptance of this agreement.
*
* This library is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.amanzi.awe.afp.executors;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import org.amanzi.awe.afp.Activator;
import org.amanzi.awe.afp.AfpEngine;
import org.amanzi.awe.afp.loaders.AfpExporter;
import org.amanzi.awe.console.AweConsolePlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
/**
* Afp Process Executor
* Executes the Afp Process, and shows the output, errors and progress on Awe Console
* User can terminate the process at any time from progress bar.
*
* @author Rahul
*
*/
public class AfpProcessExecutor extends Job {
/** Process to execute the command*/
private Process process;
private AfpProcessProgress progress;
/** Flag whether process is completed*/
private boolean jobFinished = false;
long progressTime =0;
private Node afpRoot;
protected GraphDatabaseService neo;
protected Transaction transaction;
private HashMap<String, String> parameters;
public AfpProcessExecutor(String name, Node afpRoot, final GraphDatabaseService service, HashMap<String, String> parameters) {
super(name);
this.afpRoot = afpRoot;
this.neo = service;
this.parameters = parameters;
}
public void setProgress(AfpProcessProgress progress) {
this.progress = progress;
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public IStatus run(IProgressMonitor monitor){
monitor.beginTask("Execute Afp", 100);
AfpExporter afpE = new AfpExporter(afpRoot);
createFiles(monitor, afpE);
Runtime run = Runtime.getRuntime();
try {
AfpEngine engine = AfpEngine.getAfpEngine();
String path = engine.getAfpEngineExecutablePath();
- String command = path + " \"" + afpE.controlFileName + "\"";
- AweConsolePlugin.info("Executing Cmd: " + command);
- process = run.exec(command);
+ //String command = path + " \"" + afpE.controlFileName + "\"";
+ //AweConsolePlugin.info("Executing Cmd: " + command);
+ //process = run.exec(command);
+ process = run.exec(new String[]{path,afpE.controlFileName});
monitor.worked(20);
/**
* Thread to read the stderr and display it on Awe Console
*/
Thread errorThread = new Thread("AFP stderr"){
@Override
public void run(){
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String output = null;
try{
while ((output = error.readLine()) != null){
//TODO have to make it red
AweConsolePlugin.error(output);
}
error.close();
AweConsolePlugin.info("AFP stderr closed");
}catch(IOException ioe){
AweConsolePlugin.debug(ioe.getLocalizedMessage());
}
jobFinished = true;
}
};
/**
* Thread to read the stdout and display it on Awe Console
*/
Thread outputThread = new Thread("AFP stdout"){
@Override
public void run(){
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
String output = null;
try{
while ((output = input.readLine()) != null){
// check the progress variable
AweConsolePlugin.info(output);
checkForProgress(output);
}
input.close();
writer.close();
AweConsolePlugin.info("AFP stdout closed");
}catch(IOException ioe){
AweConsolePlugin.debug(ioe.getLocalizedMessage());
}
}
};
errorThread.start();
outputThread.start();
/**
* poll the monitor to check if the process is over
* or if the user have terminated it.
*/
while (true) {
if (!errorThread.isAlive()) {
AweConsolePlugin.info("AFP Threads terminated, closing process...");
process.destroy();
break;
}
if (monitor.isCanceled()){
AweConsolePlugin.info("User cancelled worker, stopping AFP...");
process.destroy();
break;
}
if(jobFinished){
AweConsolePlugin.info("AFP Finished, closing process...");
process.destroy();
break;
}
//Thread.sleep(100);
try {
errorThread.join(1000);
outputThread.join(100);
} catch (Exception e) {
AweConsolePlugin.info("Interrupted waiting for threads: " + e);
}
}
}catch (Exception e){
e.printStackTrace();
AweConsolePlugin.exception(e);
return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getLocalizedMessage(), e);
}
return Status.OK_STATUS;
}
/**
* Writes data in files to be used as input by the C++ engine
* @param monitor
*/
private void createFiles(IProgressMonitor monitor, AfpExporter afpE){
/** Create the control file */
afpE.createControlFile(parameters);
/** Create the carrier file */
afpE.createCarrierFile();
/** Create the neighbours file */
afpE.createNeighboursFile();
/** Create the interference file */
afpE.createInterferenceFile();
/** Create the cliques file */
afpE.createCliquesFile();
/** Create the forbidden file */
afpE.createForbiddenFile();
/** Create the exception file */
afpE.createExceptionFile();
afpE.createParamFile();
}
public void onProgressUpdate(int result, long time, long remaingtotal,
long sectorSeperations, long siteSeperation, long freqConstraints,
long interference, long neighbor, long tringulation, long shadowing) {
if(progressTime ==0) {
progressTime = time;
} else {
if(time == progressTime)
time +=10;
}
if(this.progress != null) {
this.progress.onProgressUpdate(result, time, remaingtotal,
sectorSeperations, siteSeperation, freqConstraints,
interference, neighbor, tringulation, shadowing);
}
}
void checkForProgress(String output) {
if(output.startsWith("PROGRESS CoIT1Done/CoIT1")) {
// progress line
String[] tokens = output.split(",");
if (tokens.length >= 3) {
try {
long time = Long.parseLong(tokens[1]);
long completed = Long.parseLong(tokens[2]);
long total = Long.parseLong(tokens[3]);
AweConsolePlugin
.info(" total " + total);
if (completed > total) {
completed = total;
}
AweConsolePlugin.info(" completed "
+ completed);
onProgressUpdate(0, time *1000, total - completed,
0, 0, 0, 0, 0, 0, 0);
} catch (Exception e) {
}
}
}
}
}
| true | true | public IStatus run(IProgressMonitor monitor){
monitor.beginTask("Execute Afp", 100);
AfpExporter afpE = new AfpExporter(afpRoot);
createFiles(monitor, afpE);
Runtime run = Runtime.getRuntime();
try {
AfpEngine engine = AfpEngine.getAfpEngine();
String path = engine.getAfpEngineExecutablePath();
String command = path + " \"" + afpE.controlFileName + "\"";
AweConsolePlugin.info("Executing Cmd: " + command);
process = run.exec(command);
monitor.worked(20);
/**
* Thread to read the stderr and display it on Awe Console
*/
Thread errorThread = new Thread("AFP stderr"){
@Override
public void run(){
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String output = null;
try{
while ((output = error.readLine()) != null){
//TODO have to make it red
AweConsolePlugin.error(output);
}
error.close();
AweConsolePlugin.info("AFP stderr closed");
}catch(IOException ioe){
AweConsolePlugin.debug(ioe.getLocalizedMessage());
}
jobFinished = true;
}
};
/**
* Thread to read the stdout and display it on Awe Console
*/
Thread outputThread = new Thread("AFP stdout"){
@Override
public void run(){
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
String output = null;
try{
while ((output = input.readLine()) != null){
// check the progress variable
AweConsolePlugin.info(output);
checkForProgress(output);
}
input.close();
writer.close();
AweConsolePlugin.info("AFP stdout closed");
}catch(IOException ioe){
AweConsolePlugin.debug(ioe.getLocalizedMessage());
}
}
};
errorThread.start();
outputThread.start();
/**
* poll the monitor to check if the process is over
* or if the user have terminated it.
*/
while (true) {
if (!errorThread.isAlive()) {
AweConsolePlugin.info("AFP Threads terminated, closing process...");
process.destroy();
break;
}
if (monitor.isCanceled()){
AweConsolePlugin.info("User cancelled worker, stopping AFP...");
process.destroy();
break;
}
if(jobFinished){
AweConsolePlugin.info("AFP Finished, closing process...");
process.destroy();
break;
}
//Thread.sleep(100);
try {
errorThread.join(1000);
outputThread.join(100);
} catch (Exception e) {
AweConsolePlugin.info("Interrupted waiting for threads: " + e);
}
}
}catch (Exception e){
e.printStackTrace();
AweConsolePlugin.exception(e);
return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getLocalizedMessage(), e);
}
return Status.OK_STATUS;
}
| public IStatus run(IProgressMonitor monitor){
monitor.beginTask("Execute Afp", 100);
AfpExporter afpE = new AfpExporter(afpRoot);
createFiles(monitor, afpE);
Runtime run = Runtime.getRuntime();
try {
AfpEngine engine = AfpEngine.getAfpEngine();
String path = engine.getAfpEngineExecutablePath();
//String command = path + " \"" + afpE.controlFileName + "\"";
//AweConsolePlugin.info("Executing Cmd: " + command);
//process = run.exec(command);
process = run.exec(new String[]{path,afpE.controlFileName});
monitor.worked(20);
/**
* Thread to read the stderr and display it on Awe Console
*/
Thread errorThread = new Thread("AFP stderr"){
@Override
public void run(){
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String output = null;
try{
while ((output = error.readLine()) != null){
//TODO have to make it red
AweConsolePlugin.error(output);
}
error.close();
AweConsolePlugin.info("AFP stderr closed");
}catch(IOException ioe){
AweConsolePlugin.debug(ioe.getLocalizedMessage());
}
jobFinished = true;
}
};
/**
* Thread to read the stdout and display it on Awe Console
*/
Thread outputThread = new Thread("AFP stdout"){
@Override
public void run(){
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
String output = null;
try{
while ((output = input.readLine()) != null){
// check the progress variable
AweConsolePlugin.info(output);
checkForProgress(output);
}
input.close();
writer.close();
AweConsolePlugin.info("AFP stdout closed");
}catch(IOException ioe){
AweConsolePlugin.debug(ioe.getLocalizedMessage());
}
}
};
errorThread.start();
outputThread.start();
/**
* poll the monitor to check if the process is over
* or if the user have terminated it.
*/
while (true) {
if (!errorThread.isAlive()) {
AweConsolePlugin.info("AFP Threads terminated, closing process...");
process.destroy();
break;
}
if (monitor.isCanceled()){
AweConsolePlugin.info("User cancelled worker, stopping AFP...");
process.destroy();
break;
}
if(jobFinished){
AweConsolePlugin.info("AFP Finished, closing process...");
process.destroy();
break;
}
//Thread.sleep(100);
try {
errorThread.join(1000);
outputThread.join(100);
} catch (Exception e) {
AweConsolePlugin.info("Interrupted waiting for threads: " + e);
}
}
}catch (Exception e){
e.printStackTrace();
AweConsolePlugin.exception(e);
return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getLocalizedMessage(), e);
}
return Status.OK_STATUS;
}
|
diff --git a/src/org/jruby/lexer/yacc/LexerSource.java b/src/org/jruby/lexer/yacc/LexerSource.java
index cfadcc690..84e372d55 100644
--- a/src/org/jruby/lexer/yacc/LexerSource.java
+++ b/src/org/jruby/lexer/yacc/LexerSource.java
@@ -1,488 +1,488 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common 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://www.eclipse.org/legal/cpl-v10.html
*
* 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) 2004-2006 Thomas E Enebo <[email protected]>
* Copyright (C) 2004 Jan Arne Petersen <[email protected]>
* Copyright (C) 2004 Stefan Matthias Aust <[email protected]>
* Copyright (C) 2005 Zach Dennis <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.lexer.yacc;
import java.io.IOException;
import java.io.Reader;
import org.jruby.util.ByteList;
/**
* This class is what feeds the lexer. It is primarily a wrapper around a
* Reader that can unread() data back onto the source. Originally, I thought
* about using the PushBackReader to handle read/unread, but I realized that
* some extremely pathological case could overflow the pushback buffer. Better
* safe than sorry. I could have combined this implementation with a
* PushbackBuffer, but the added complexity did not seem worth it.
*
* @author enebo
*/
public class LexerSource {
private static final int INITIAL_PUSHBACK_SIZE = 100;
private static final int INITIAL_LINEWIDTH_SIZE = 2048;
// Where we get new positions from.
private ISourcePositionFactory positionFactory;
// Where we get our newest char's
private final Reader reader;
// Our readback/pushback buffer.
private char buf[] = new char[INITIAL_PUSHBACK_SIZE];
// index of last character in pushback buffer
private int bufLength = -1;
// How long is every line we have run across. This makes it possible for us to unread()
// past a read() line and still know what column we are at.
private int lineWidths[] = new int[INITIAL_LINEWIDTH_SIZE];
// index of last line width in line widths list
private int lineWidthsLength = -1;
// The name of this source (e.g. a filename: foo.rb)
private final String sourceName;
// Number of newlines read from the reader
private int line = 0;
// Column of source.
private int column = 0;
// How many bytes into the source are we?
private int offset = 0;
// Flag to let us now in next read after a newline that we should reset column
private boolean nextCharIsOnANewLine = true;
/**
* Create our food-source for the lexer
*
* @param sourceName is the file we are reading
* @param reader is what represents the contents of file sourceName
*/
public LexerSource(String sourceName, Reader reader) {
this.sourceName = sourceName;
this.reader = reader;
this.positionFactory = new SourcePositionFactory(this);
}
public LexerSource(String sourceName, Reader reader, ISourcePositionFactory factory) {
this.sourceName = sourceName;
this.reader = reader;
this.positionFactory = factory;
}
/**
* Read next character from this source
*
* @return next character to viewed by the source
*/
public char read() throws IOException {
int length = bufLength;
char c;
if (length >= 0) {
c = buf[bufLength--];
} else {
c = wrappedRead();
// EOF...Do not advance column...Go straight to jail
if (c == 0) {
//offset++;
return c;
}
}
// Reset column back to zero on first read of a line (note it will be-
// come '1' by the time it leaves read().
if (nextCharIsOnANewLine) {
nextCharIsOnANewLine = false;
column = 0;
}
offset++;
column++;
if (c == '\n') {
line++;
// Since we are not reading off of unread buffer we must at the
// end of a new line for the first time. Add it.
if (length < 0) {
lineWidths[++lineWidthsLength] = column;
// If we outgrow our lineLength list then grow it
if (lineWidthsLength + 1 == lineWidths.length) {
int[] newLineWidths = new int[lineWidths.length + INITIAL_LINEWIDTH_SIZE];
System.arraycopy(lineWidths, 0, newLineWidths, 0, lineWidths.length);
lineWidths = newLineWidths;
}
}
nextCharIsOnANewLine = true;
}
return c;
}
/**
* Pushes char back onto this source. Note, this also
* allows us to push whatever is passes back into the source.
*
* @param c to be put back onto the source
*/
public void unread(char c) {
if (c != (char) 0) {
offset--;
if (c == '\n') {
line--;
column = lineWidths[line];
nextCharIsOnANewLine = true;
} else {
column--;
}
buf[++bufLength] = c;
// If we outgrow our pushback stack then grow it (this should only happen in
// pretty pathological cases).
if (bufLength + 1 == buf.length) {
char[] newBuf = new char[buf.length + INITIAL_PUSHBACK_SIZE];
System.arraycopy(buf, 0, newBuf, 0, buf.length);
buf = newBuf;
}
}
}
public boolean peek(char to) throws IOException {
char c = read();
unread(c);
return c == to;
}
/**
* What file are we lexing?
* @return the files name
*/
public String getFilename() {
return sourceName;
}
/**
* What line are we at?
* @return the line number 0...line_size-1
*/
public int getLine() {
return line;
}
/**
* Are we at beggining of line?
*
* @return the column (0..x)
*/
public int getColumn() {
return column;
}
/**
* The location of the last byte we read from the source.
*
* @return current location of source
*/
public int getOffset() {
return (offset <= 0 ? 0 : offset);
}
/**
* Where is the reader within the source {filename,row}
*
* @return the current position
*/
public ISourcePosition getPosition(ISourcePosition startPosition, boolean inclusive) {
return positionFactory.getPosition(startPosition, inclusive);
}
/**
* Where is the reader within the source {filename,row}
*
* @return the current position
*/
public ISourcePosition getPosition() {
return positionFactory.getPosition(null, false);
}
public ISourcePositionFactory getPositionFactory() {
return positionFactory;
}
/**
* Convenience method to hide exception. If we do hit an exception
* we will pretend we EOF'd.
*
* @return the current char or EOF (at EOF or on error)
*/
private char wrappedRead() throws IOException {
int c = reader.read();
// If \r\n then just pass along \n (windows)
// If \r[^\n] then pass along \n (MAC)
if (c == '\r') {
if ((c = reader.read()) != '\n') {
unread((char)c);
c = '\n';
} else {
// Position within source must reflect the actual offset and column. Since
// we ate an extra character here (this accounting is normally done in read
// ), we should update position info.
offset++;
column++;
}
}
return c != -1 ? (char) c : '\0';
}
/**
* Create a source.
*
* @param name the name of the source (e.g a filename: foo.rb)
* @param content the data of the source
* @return the new source
*/
public static LexerSource getSource(String name, Reader content) {
return new LexerSource(name, content);
}
public String readLine() throws IOException {
StringBuffer sb = new StringBuffer(80);
for (char c = read(); c != '\n' && c != '\0'; c = read()) {
sb.append(c);
}
return sb.toString();
}
public ByteList readLineBytes() throws IOException {
ByteList bytelist = new ByteList(80);
for (char c = read(); c != '\n' && c != '\0'; c = read()) {
bytelist.append(c);
}
return bytelist;
}
public void unreadMany(CharSequence buffer) {
int length = buffer.length();
for (int i = length - 1; i >= 0; i--) {
unread(buffer.charAt(i));
}
}
public boolean matchString(String match, boolean indent) throws IOException {
int length = match.length();
StringBuffer buffer = new StringBuffer(length + 20);
if (indent) {
char c;
while ((c = read()) != '\0') {
if (!Character.isWhitespace(c)) {
unread(c);
break;
}
buffer.append(c);
}
}
for (int i = 0; i < length; i++) {
char c = read();
buffer.append(c);
if (match.charAt(i) != c) {
unreadMany(buffer);
return false;
}
}
return true;
}
public boolean wasBeginOfLine() {
return getColumn() == 1;
}
public char readEscape() throws IOException {
char c = read();
switch (c) {
case '\\' : // backslash
return c;
case 'n' : // newline
return '\n';
case 't' : // horizontal tab
return '\t';
case 'r' : // carriage return
return '\r';
case 'f' : // form feed
return '\f';
case 'v' : // vertical tab
- return '\u0013';
+ return '\u000B';
case 'a' : // alarm(bell)
return '\u0007';
case 'e' : // escape
- return '\u0033';
+ return '\u001B';
case '0' : case '1' : case '2' : case '3' : // octal constant
case '4' : case '5' : case '6' : case '7' :
unread(c);
return scanOct(3);
case 'x' : // hex constant
int hexOffset = getColumn();
char hexValue = scanHex(2);
// No hex value after the 'x'.
if (hexOffset == getColumn()) {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return hexValue;
case 'b' : // backspace
return '\010';
case 's' : // space
return ' ';
case 'M' :
if ((c = read()) != '-') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
} else if ((c = read()) == '\\') {
return (char) (readEscape() | 0x80);
} else if (c == '\0') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return (char) ((c & 0xff) | 0x80);
case 'C' :
if ((c = read()) != '-') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
case 'c' :
if ((c = read()) == '\\') {
c = readEscape();
} else if (c == '?') {
return '\u0177';
} else if (c == '\0') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return (char) (c & 0x9f);
case '\0' :
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
default :
return c;
}
}
private char scanHex(int count) throws IOException {
char value = '\0';
for (int i = 0; i < count; i++) {
char c = read();
if (!RubyYaccLexer.isHexChar(c)) {
unread(c);
break;
}
value <<= 4;
value |= Integer.parseInt(""+c, 16) & 15;
}
return value;
}
private char scanOct(int count) throws IOException {
char value = '\0';
for (int i = 0; i < count; i++) {
char c = read();
if (!RubyYaccLexer.isOctChar(c)) {
unread(c);
break;
}
value <<= 3;
value |= Integer.parseInt(""+c, 8);
}
return value;
}
/**
* Get character ahead of current position by offset positions.
*
* @param anOffset is location past current position to get char at
* @return character index positions ahead of source location or EOF
*/
public char getCharAt(int anOffset) throws IOException {
StringBuffer buffer = new StringBuffer(anOffset);
// read next offset chars
for (int i = 0; i < anOffset; i++) {
buffer.append(read());
}
int length = buffer.length();
// Whoops not enough chars left EOF!
if (length == 0){
return '\0';
}
// Push chars back now that we found it
for (int i = 0; i < length; i++) {
unread(buffer.charAt(i));
}
return buffer.charAt(length - 1);
}
public String toString() {
try {
StringBuffer buffer = new StringBuffer(20);
for (int i = 0; i < 20; i++) {
buffer.append(read());
}
for (int i = 0; i < 20; i++) {
unread(buffer.charAt(buffer.length() - i - 1));
}
buffer.append(" ...");
return buffer.toString();
} catch(Exception e) {
return null;
}
}
}
| false | true | public char readEscape() throws IOException {
char c = read();
switch (c) {
case '\\' : // backslash
return c;
case 'n' : // newline
return '\n';
case 't' : // horizontal tab
return '\t';
case 'r' : // carriage return
return '\r';
case 'f' : // form feed
return '\f';
case 'v' : // vertical tab
return '\u0013';
case 'a' : // alarm(bell)
return '\u0007';
case 'e' : // escape
return '\u0033';
case '0' : case '1' : case '2' : case '3' : // octal constant
case '4' : case '5' : case '6' : case '7' :
unread(c);
return scanOct(3);
case 'x' : // hex constant
int hexOffset = getColumn();
char hexValue = scanHex(2);
// No hex value after the 'x'.
if (hexOffset == getColumn()) {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return hexValue;
case 'b' : // backspace
return '\010';
case 's' : // space
return ' ';
case 'M' :
if ((c = read()) != '-') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
} else if ((c = read()) == '\\') {
return (char) (readEscape() | 0x80);
} else if (c == '\0') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return (char) ((c & 0xff) | 0x80);
case 'C' :
if ((c = read()) != '-') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
case 'c' :
if ((c = read()) == '\\') {
c = readEscape();
} else if (c == '?') {
return '\u0177';
} else if (c == '\0') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return (char) (c & 0x9f);
case '\0' :
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
default :
return c;
}
}
| public char readEscape() throws IOException {
char c = read();
switch (c) {
case '\\' : // backslash
return c;
case 'n' : // newline
return '\n';
case 't' : // horizontal tab
return '\t';
case 'r' : // carriage return
return '\r';
case 'f' : // form feed
return '\f';
case 'v' : // vertical tab
return '\u000B';
case 'a' : // alarm(bell)
return '\u0007';
case 'e' : // escape
return '\u001B';
case '0' : case '1' : case '2' : case '3' : // octal constant
case '4' : case '5' : case '6' : case '7' :
unread(c);
return scanOct(3);
case 'x' : // hex constant
int hexOffset = getColumn();
char hexValue = scanHex(2);
// No hex value after the 'x'.
if (hexOffset == getColumn()) {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return hexValue;
case 'b' : // backspace
return '\010';
case 's' : // space
return ' ';
case 'M' :
if ((c = read()) != '-') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
} else if ((c = read()) == '\\') {
return (char) (readEscape() | 0x80);
} else if (c == '\0') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return (char) ((c & 0xff) | 0x80);
case 'C' :
if ((c = read()) != '-') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
case 'c' :
if ((c = read()) == '\\') {
c = readEscape();
} else if (c == '?') {
return '\u0177';
} else if (c == '\0') {
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
}
return (char) (c & 0x9f);
case '\0' :
throw new SyntaxException(getPosition(), "Invalid escape character syntax");
default :
return c;
}
}
|
diff --git a/weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java b/weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
index 7b49ae36d..e77a9f61d 100644
--- a/weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
+++ b/weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
@@ -1,407 +1,407 @@
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 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:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Test;
/**
*/
//XXX needs check that arguments contains no WildTypePatterns
public class ReferencePointcut extends Pointcut {
public UnresolvedType onType;
public TypePattern onTypeSymbolic;
public String name;
public TypePatternList arguments;
/**
* if this is non-null then when the pointcut is concretized the result will be parameterized too.
*/
private Map typeVariableMap;
//public ResolvedPointcut binding;
public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) {
this.onTypeSymbolic = onTypeSymbolic;
this.name = name;
this.arguments = arguments;
this.pointcutKind = REFERENCE;
}
public ReferencePointcut(UnresolvedType onType, String name, TypePatternList arguments) {
this.onType = onType;
this.name = name;
this.arguments = arguments;
this.pointcutKind = REFERENCE;
}
public int couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS_BITS;
}
//??? do either of these match methods make any sense???
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
/**
* Do I really match this shadow?
*/
protected FuzzyBoolean matchInternal(Shadow shadow) {
return FuzzyBoolean.NO;
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (onType != null) {
buf.append(onType);
buf.append(".");
// for (int i=0, len=fromType.length; i < len; i++) {
// buf.append(fromType[i]);
// buf.append(".");
// }
}
buf.append(name);
buf.append(arguments.toString());
return buf.toString();
}
public void write(DataOutputStream s) throws IOException {
//XXX ignores onType
s.writeByte(Pointcut.REFERENCE);
if (onType != null) {
s.writeBoolean(true);
onType.write(s);
} else {
s.writeBoolean(false);
}
s.writeUTF(name);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
UnresolvedType onType = null;
if (s.readBoolean()) {
onType = UnresolvedType.read(s);
}
ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(),
TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
if (onTypeSymbolic != null) {
onType = onTypeSymbolic.resolveExactType(scope, bindings);
// in this case we've already signalled an error
if (ResolvedType.isMissing(onType)) return;
}
ResolvedType searchType;
if (onType != null) {
searchType = scope.getWorld().resolve(onType);
} else {
searchType = scope.getEnclosingType();
}
if (searchType.isTypeVariableReference()) {
searchType = ((TypeVariableReference)searchType).getTypeVariable().getUpperBound().resolve(scope.getWorld());
}
arguments.resolveBindings(scope, bindings, true, true);
//XXX ensure that arguments has no ..'s in it
// check that I refer to a real pointcut declaration and that I match
ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name);
// if we're not a static reference, then do a lookup of outers
if (pointcutDef == null && onType == null) {
while (true) {
UnresolvedType declaringType = searchType.getDeclaringType();
if (declaringType == null) break;
searchType = declaringType.resolve(scope.getWorld());
pointcutDef = searchType.findPointcut(name);
if (pointcutDef != null) {
// make this a static reference
onType = searchType;
break;
}
}
}
if (pointcutDef == null) {
scope.message(IMessage.ERROR, this, "can't find referenced pointcut " + name);
return;
}
// check visibility
if (!pointcutDef.isVisible(scope.getEnclosingType())) {
scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible");
return;
}
if (Modifier.isAbstract(pointcutDef.getModifiers())) {
if (onType != null && !onType.isTypeVariableReference()) {
scope.message(IMessage.ERROR, this,
"can't make static reference to abstract pointcut");
return;
} else if (!searchType.isAbstract()) {
scope.message(IMessage.ERROR, this,
"can't use abstract pointcut in concrete context");
return;
}
}
ResolvedType[] parameterTypes =
scope.getWorld().resolve(pointcutDef.getParameterTypes());
if (parameterTypes.length != arguments.size()) {
scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " +
parameterTypes.length + " found " + arguments.size());
return;
}
//if (onType == null) onType = pointcutDef.getDeclaringType();
if (onType != null) {
if (onType.isParameterizedType()) {
// build a type map mapping type variable names in the generic type to
// the type parameters presented
typeVariableMap = new HashMap();
ResolvedType underlyingGenericType = ((ResolvedType) onType).getGenericType();
TypeVariable[] tVars = underlyingGenericType.getTypeVariables();
ResolvedType[] typeParams = ((ResolvedType)onType).getResolvedTypeParameters();
for (int i = 0; i < tVars.length; i++) {
typeVariableMap.put(tVars[i].getName(),typeParams[i]);
}
} else if (onType.isGenericType()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_REFERENCE_POINTCUT_IN_RAW_TYPE),
getSourceLocation()));
}
}
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (typeVariableMap != null) {
p = p.parameterizeWith(typeVariableMap,scope.getWorld());
}
if (p == TypePattern.NO) {
scope.message(IMessage.ERROR, this,
"bad parameter to pointcut reference");
return;
}
boolean reportProblem = false;
if (parameterTypes[i].isTypeVariableReference() && p.getExactType().isTypeVariableReference()) {
UnresolvedType One = ((TypeVariableReference)parameterTypes[i]).getTypeVariable().getFirstBound();
UnresolvedType Two = ((TypeVariableReference)p.getExactType()).getTypeVariable().getFirstBound();
reportProblem = !One.resolve(scope.getWorld()).isAssignableFrom(Two.resolve(scope.getWorld()));
} else {
reportProblem = !p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(UnresolvedType.OBJECT);
}
if (reportProblem) {
- scope.message(IMessage.ERROR, p, "incompatible type, expected " +
+ scope.message(IMessage.ERROR, this, "incompatible type, expected " +
parameterTypes[i].getName() + " found " + p +". Check the type specified in your pointcut");
return;
}
}
}
public void postRead(ResolvedType enclosingType) {
arguments.postRead(enclosingType);
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
throw new RuntimeException("shouldn't happen");
}
//??? This is not thread safe, but this class is not designed for multi-threading
private boolean concretizing = false;
// declaring type is the type that declared the member referencing this pointcut.
// If it declares a matching private pointcut, then that pointcut should be used
// and not one in a subtype that happens to have the same name.
public Pointcut concretize1(ResolvedType searchStart, ResolvedType declaringType, IntMap bindings) {
if (concretizing) {
//Thread.currentThread().dumpStack();
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CIRCULAR_POINTCUT,this),
getSourceLocation()));
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
try {
concretizing = true;
ResolvedPointcutDefinition pointcutDec;
if (onType != null) {
searchStart = onType.resolve(searchStart.getWorld());
if (searchStart.isMissing()) {
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (onType.isTypeVariableReference()) {
// need to replace on type with the binding for the type variable
// in the declaring type
if (declaringType.isParameterizedType()) {
TypeVariable[] tvs = declaringType.getGenericType().getTypeVariables();
String typeVariableName = ((TypeVariableReference)onType).getTypeVariable().getName();
for (int i = 0; i < tvs.length; i++) {
if (tvs[i].getName().equals(typeVariableName)) {
ResolvedType realOnType = declaringType.getTypeParameters()[i].resolve(declaringType.getWorld());
onType = realOnType;
searchStart = realOnType;
break;
}
}
}
}
}
if (declaringType == null) declaringType = searchStart;
pointcutDec = declaringType.findPointcut(name);
boolean foundMatchingPointcut = (pointcutDec != null && pointcutDec.isPrivate());
if (!foundMatchingPointcut) {
pointcutDec = searchStart.findPointcut(name);
if (pointcutDec == null) {
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_POINTCUT,name,searchStart.getName()),
getSourceLocation())
);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
}
if (pointcutDec.isAbstract()) {
//Thread.currentThread().dumpStack();
ShadowMunger enclosingAdvice = bindings.getEnclosingAdvice();
searchStart.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ABSTRACT_POINTCUT,pointcutDec),
getSourceLocation(),
(null == enclosingAdvice) ? null : enclosingAdvice.getSourceLocation());
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
//System.err.println("start: " + searchStart);
ResolvedType[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes());
TypePatternList arguments = this.arguments.resolveReferences(bindings);
IntMap newBindings = new IntMap();
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
if (p == TypePattern.NO) continue;
// we are allowed to bind to pointcuts which use subtypes as this is type safe
// this will be checked in ReferencePointcut.resolveBindings(). Can't check it here
// as we don't know about any new parents added via decp.
if (p instanceof BindingTypePattern) {
newBindings.put(i, ((BindingTypePattern)p).getFormalIndex());
}
}
if (searchStart.isParameterizedType()) {
// build a type map mapping type variable names in the generic type to
// the type parameters presented
typeVariableMap = new HashMap();
ResolvedType underlyingGenericType = searchStart.getGenericType();
TypeVariable[] tVars = underlyingGenericType.getTypeVariables();
ResolvedType[] typeParams = searchStart.getResolvedTypeParameters();
for (int i = 0; i < tVars.length; i++) {
typeVariableMap.put(tVars[i].getName(),typeParams[i]);
}
}
newBindings.copyContext(bindings);
newBindings.pushEnclosingDefinition(pointcutDec);
try {
Pointcut ret = pointcutDec.getPointcut();
if (typeVariableMap != null && !hasBeenParameterized) {
ret = ret.parameterizeWith(typeVariableMap,searchStart.getWorld());
ret.hasBeenParameterized=true;
}
return ret.concretize(searchStart, declaringType, newBindings);
} finally {
newBindings.popEnclosingDefinitition();
}
} finally {
concretizing = false;
}
}
/**
* make a version of this pointcut with any refs to typeVariables replaced by their entry in the map.
* Tricky thing is, we can't do this at the point in time this method will be called, so we make a
* version that will parameterize the pointcut it ultimately resolves to.
*/
public Pointcut parameterizeWith(Map typeVariableMap,World w) {
ReferencePointcut ret = new ReferencePointcut(onType,name,arguments);
ret.onTypeSymbolic = onTypeSymbolic;
ret.typeVariableMap = typeVariableMap;
return ret;
}
// We want to keep the original source location, not the reference location
protected boolean shouldCopyLocationForConcretize() {
return false;
}
public boolean equals(Object other) {
if (!(other instanceof ReferencePointcut)) return false;
if (this == other) return true;
ReferencePointcut o = (ReferencePointcut)other;
return o.name.equals(name) && o.arguments.equals(arguments)
&& ((o.onType == null) ? (onType == null) : o.onType.equals(onType));
}
public int hashCode() {
int result = 17;
result = 37*result + ((onType == null) ? 0 : onType.hashCode());
result = 37*result + arguments.hashCode();
result = 37*result + name.hashCode();
return result;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
| true | true | public void resolveBindings(IScope scope, Bindings bindings) {
if (onTypeSymbolic != null) {
onType = onTypeSymbolic.resolveExactType(scope, bindings);
// in this case we've already signalled an error
if (ResolvedType.isMissing(onType)) return;
}
ResolvedType searchType;
if (onType != null) {
searchType = scope.getWorld().resolve(onType);
} else {
searchType = scope.getEnclosingType();
}
if (searchType.isTypeVariableReference()) {
searchType = ((TypeVariableReference)searchType).getTypeVariable().getUpperBound().resolve(scope.getWorld());
}
arguments.resolveBindings(scope, bindings, true, true);
//XXX ensure that arguments has no ..'s in it
// check that I refer to a real pointcut declaration and that I match
ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name);
// if we're not a static reference, then do a lookup of outers
if (pointcutDef == null && onType == null) {
while (true) {
UnresolvedType declaringType = searchType.getDeclaringType();
if (declaringType == null) break;
searchType = declaringType.resolve(scope.getWorld());
pointcutDef = searchType.findPointcut(name);
if (pointcutDef != null) {
// make this a static reference
onType = searchType;
break;
}
}
}
if (pointcutDef == null) {
scope.message(IMessage.ERROR, this, "can't find referenced pointcut " + name);
return;
}
// check visibility
if (!pointcutDef.isVisible(scope.getEnclosingType())) {
scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible");
return;
}
if (Modifier.isAbstract(pointcutDef.getModifiers())) {
if (onType != null && !onType.isTypeVariableReference()) {
scope.message(IMessage.ERROR, this,
"can't make static reference to abstract pointcut");
return;
} else if (!searchType.isAbstract()) {
scope.message(IMessage.ERROR, this,
"can't use abstract pointcut in concrete context");
return;
}
}
ResolvedType[] parameterTypes =
scope.getWorld().resolve(pointcutDef.getParameterTypes());
if (parameterTypes.length != arguments.size()) {
scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " +
parameterTypes.length + " found " + arguments.size());
return;
}
//if (onType == null) onType = pointcutDef.getDeclaringType();
if (onType != null) {
if (onType.isParameterizedType()) {
// build a type map mapping type variable names in the generic type to
// the type parameters presented
typeVariableMap = new HashMap();
ResolvedType underlyingGenericType = ((ResolvedType) onType).getGenericType();
TypeVariable[] tVars = underlyingGenericType.getTypeVariables();
ResolvedType[] typeParams = ((ResolvedType)onType).getResolvedTypeParameters();
for (int i = 0; i < tVars.length; i++) {
typeVariableMap.put(tVars[i].getName(),typeParams[i]);
}
} else if (onType.isGenericType()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_REFERENCE_POINTCUT_IN_RAW_TYPE),
getSourceLocation()));
}
}
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (typeVariableMap != null) {
p = p.parameterizeWith(typeVariableMap,scope.getWorld());
}
if (p == TypePattern.NO) {
scope.message(IMessage.ERROR, this,
"bad parameter to pointcut reference");
return;
}
boolean reportProblem = false;
if (parameterTypes[i].isTypeVariableReference() && p.getExactType().isTypeVariableReference()) {
UnresolvedType One = ((TypeVariableReference)parameterTypes[i]).getTypeVariable().getFirstBound();
UnresolvedType Two = ((TypeVariableReference)p.getExactType()).getTypeVariable().getFirstBound();
reportProblem = !One.resolve(scope.getWorld()).isAssignableFrom(Two.resolve(scope.getWorld()));
} else {
reportProblem = !p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(UnresolvedType.OBJECT);
}
if (reportProblem) {
scope.message(IMessage.ERROR, p, "incompatible type, expected " +
parameterTypes[i].getName() + " found " + p +". Check the type specified in your pointcut");
return;
}
}
}
| public void resolveBindings(IScope scope, Bindings bindings) {
if (onTypeSymbolic != null) {
onType = onTypeSymbolic.resolveExactType(scope, bindings);
// in this case we've already signalled an error
if (ResolvedType.isMissing(onType)) return;
}
ResolvedType searchType;
if (onType != null) {
searchType = scope.getWorld().resolve(onType);
} else {
searchType = scope.getEnclosingType();
}
if (searchType.isTypeVariableReference()) {
searchType = ((TypeVariableReference)searchType).getTypeVariable().getUpperBound().resolve(scope.getWorld());
}
arguments.resolveBindings(scope, bindings, true, true);
//XXX ensure that arguments has no ..'s in it
// check that I refer to a real pointcut declaration and that I match
ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name);
// if we're not a static reference, then do a lookup of outers
if (pointcutDef == null && onType == null) {
while (true) {
UnresolvedType declaringType = searchType.getDeclaringType();
if (declaringType == null) break;
searchType = declaringType.resolve(scope.getWorld());
pointcutDef = searchType.findPointcut(name);
if (pointcutDef != null) {
// make this a static reference
onType = searchType;
break;
}
}
}
if (pointcutDef == null) {
scope.message(IMessage.ERROR, this, "can't find referenced pointcut " + name);
return;
}
// check visibility
if (!pointcutDef.isVisible(scope.getEnclosingType())) {
scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible");
return;
}
if (Modifier.isAbstract(pointcutDef.getModifiers())) {
if (onType != null && !onType.isTypeVariableReference()) {
scope.message(IMessage.ERROR, this,
"can't make static reference to abstract pointcut");
return;
} else if (!searchType.isAbstract()) {
scope.message(IMessage.ERROR, this,
"can't use abstract pointcut in concrete context");
return;
}
}
ResolvedType[] parameterTypes =
scope.getWorld().resolve(pointcutDef.getParameterTypes());
if (parameterTypes.length != arguments.size()) {
scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " +
parameterTypes.length + " found " + arguments.size());
return;
}
//if (onType == null) onType = pointcutDef.getDeclaringType();
if (onType != null) {
if (onType.isParameterizedType()) {
// build a type map mapping type variable names in the generic type to
// the type parameters presented
typeVariableMap = new HashMap();
ResolvedType underlyingGenericType = ((ResolvedType) onType).getGenericType();
TypeVariable[] tVars = underlyingGenericType.getTypeVariables();
ResolvedType[] typeParams = ((ResolvedType)onType).getResolvedTypeParameters();
for (int i = 0; i < tVars.length; i++) {
typeVariableMap.put(tVars[i].getName(),typeParams[i]);
}
} else if (onType.isGenericType()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_REFERENCE_POINTCUT_IN_RAW_TYPE),
getSourceLocation()));
}
}
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (typeVariableMap != null) {
p = p.parameterizeWith(typeVariableMap,scope.getWorld());
}
if (p == TypePattern.NO) {
scope.message(IMessage.ERROR, this,
"bad parameter to pointcut reference");
return;
}
boolean reportProblem = false;
if (parameterTypes[i].isTypeVariableReference() && p.getExactType().isTypeVariableReference()) {
UnresolvedType One = ((TypeVariableReference)parameterTypes[i]).getTypeVariable().getFirstBound();
UnresolvedType Two = ((TypeVariableReference)p.getExactType()).getTypeVariable().getFirstBound();
reportProblem = !One.resolve(scope.getWorld()).isAssignableFrom(Two.resolve(scope.getWorld()));
} else {
reportProblem = !p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(UnresolvedType.OBJECT);
}
if (reportProblem) {
scope.message(IMessage.ERROR, this, "incompatible type, expected " +
parameterTypes[i].getName() + " found " + p +". Check the type specified in your pointcut");
return;
}
}
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/editor/tabs/MemoryMapTab.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/editor/tabs/MemoryMapTab.java
index c316f997a..b78c29d12 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/editor/tabs/MemoryMapTab.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/editor/tabs/MemoryMapTab.java
@@ -1,97 +1,97 @@
/*******************************************************************************
* Copyright (c) 2012, 2013 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.launch.ui.editor.tabs;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.tcf.internal.debug.ui.commands.MemoryMapWidget;
import org.eclipse.tcf.internal.debug.ui.launch.TCFMemoryMapTab;
import org.eclipse.tcf.internal.debug.ui.model.TCFNode;
import org.eclipse.tcf.te.tcf.launch.ui.editor.AbstractTcfLaunchTabContainerEditorPage;
import org.eclipse.tcf.te.tcf.launch.ui.nls.Messages;
/**
* Customized TCF memory map launch configuration tab implementation to work better
* inside an configuration editor tab.
*/
public class MemoryMapTab extends TCFMemoryMapTab {
// Reference to the parent editor page
private final AbstractTcfLaunchTabContainerEditorPage parentEditorPage;
/**
* Local memory map widget implementation.
*/
protected static class MyMemoryMapWidget extends MemoryMapWidget {
/**
* Constructor
*
* @param composite The parent composite.
* @param node The TCF node
*/
public MyMemoryMapWidget(Composite composite, TCFNode node) {
super(composite, node);
}
@Override
protected String getColumnText(int column) {
String text = super.getColumnText(column);
if (text != null && text.trim().length() > 0) {
- String key = "MemoryMapEditorPage_column_" + text; //$NON-NLS-1$
+ String key = "MemoryMapTab_column_" + text; //$NON-NLS-1$
if (Messages.hasString(key))
text = Messages.getString(key);
else {
- key = "MemoryMapEditorPage_column_" + column; //$NON-NLS-1$
+ key = "MemoryMapTab_column_" + column; //$NON-NLS-1$
if (Messages.hasString(key))
text = Messages.getString(key);
}
}
return text != null ? text : ""; //$NON-NLS-1$
}
}
/**
* Constructor
*
* @param parentEditorPage The parent editor page. Must not be <code>null</code>.
*/
public MemoryMapTab(AbstractTcfLaunchTabContainerEditorPage parentEditorPage) {
super();
this.parentEditorPage = parentEditorPage;
}
/**
* Returns the parent editor page.
*
* @return The parent editor page.
*/
public final AbstractTcfLaunchTabContainerEditorPage getParentEditorPage() {
return parentEditorPage;
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.debug.ui.launch.TCFPathMapTab#updateLaunchConfigurationDialog()
*/
@Override
protected void updateLaunchConfigurationDialog() {
super.updateLaunchConfigurationDialog();
if (parentEditorPage != null) {
performApply(AbstractTcfLaunchTabContainerEditorPage.getLaunchConfig(parentEditorPage.getPeerModel(parentEditorPage.getEditorInput())));
parentEditorPage.checkLaunchConfigDirty();
}
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.debug.ui.launch.TCFMemoryMapTab#createWidget(org.eclipse.swt.widgets.Composite, org.eclipse.tcf.internal.debug.ui.model.TCFNode)
*/
@Override
protected MemoryMapWidget createWidget(Composite composite, TCFNode node) {
return new MyMemoryMapWidget(composite, node);
}
}
| false | true | protected String getColumnText(int column) {
String text = super.getColumnText(column);
if (text != null && text.trim().length() > 0) {
String key = "MemoryMapEditorPage_column_" + text; //$NON-NLS-1$
if (Messages.hasString(key))
text = Messages.getString(key);
else {
key = "MemoryMapEditorPage_column_" + column; //$NON-NLS-1$
if (Messages.hasString(key))
text = Messages.getString(key);
}
}
return text != null ? text : ""; //$NON-NLS-1$
}
| protected String getColumnText(int column) {
String text = super.getColumnText(column);
if (text != null && text.trim().length() > 0) {
String key = "MemoryMapTab_column_" + text; //$NON-NLS-1$
if (Messages.hasString(key))
text = Messages.getString(key);
else {
key = "MemoryMapTab_column_" + column; //$NON-NLS-1$
if (Messages.hasString(key))
text = Messages.getString(key);
}
}
return text != null ? text : ""; //$NON-NLS-1$
}
|
diff --git a/same-android/src/main/java/com/orbekk/same/GameView.java b/same-android/src/main/java/com/orbekk/same/GameView.java
index 31ac27c..d21d05d 100644
--- a/same-android/src/main/java/com/orbekk/same/GameView.java
+++ b/same-android/src/main/java/com/orbekk/same/GameView.java
@@ -1,177 +1,181 @@
package com.orbekk.same;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private Logger logger = LoggerFactory.getLogger(getClass());
private GameThread thread;
static class Player {
public Player() {
}
public Player(float posX, float posY) {
this.posX = posX;
this.posY = posY;
}
public float posX;
public float posY;
}
static class GameThread extends Thread
implements Variable.OnChangeListener<Player> {
private Logger logger = LoggerFactory.getLogger(getClass());
private int height = 0;
private int width = 0;
private SurfaceHolder holder;
private Context context;
private Paint background;
private Variable<Player> player;
private VariableUpdaterTask<Player> updater;
private AtomicBoolean shouldRedraw = new AtomicBoolean(true);
private Paint color = new Paint();
public GameThread(SurfaceHolder holder, Context context,
Variable<Player> player) {
this.holder = holder;
this.context = context;
this.player = player;
background = new Paint();
background.setARGB(255, 0, 0, 0);
color.setARGB(255, 255, 0, 0);
}
public void setUp() {
player.addOnChangeListener(this);
updater = new VariableUpdaterTask<Player>(player);
updater.set(new Player(0.5f, 0.5f));
updater.start();
}
public void tearDown() {
player.removeOnChangeListener(this);
updater.interrupt();
}
public void setSize(int width, int height) {
synchronized(holder) {
this.width = width;
this.height = height;
}
}
private void doDraw(Canvas c) {
c.drawRect(0.0f, 0.0f, width+1.0f, height+1.0f, background);
Player player_ = player.get();
if (player_ == null) {
return;
}
c.drawCircle(player_.posX * width, player_.posY * height,
20.0f, color);
}
@Override public void run() {
while (true) {
Canvas c = null;
try {
c = holder.lockCanvas();
- synchronized(holder) {
- doDraw(c);
+ if (c != null) {
+ synchronized(holder) {
+ doDraw(c);
+ }
}
} finally {
- holder.unlockCanvasAndPost(c);
+ if (c != null) {
+ holder.unlockCanvasAndPost(c);
+ }
}
synchronized (this) {
if (Thread.interrupted()) {
break;
}
try {
while (!shouldRedraw.get()) {
wait();
}
} catch (InterruptedException e) {
break;
}
}
}
}
private synchronized void setShouldRedraw() {
shouldRedraw.set(true);
notifyAll();
}
private synchronized void setPosition(final float x, final float y) {
if (player.get() == null || player.get().posX != x ||
player.get().posY != y) {
Player newPlayer = new Player(x / width, y / height);
updater.set(newPlayer);
}
}
@Override
public synchronized void valueChanged(Variable<Player> unused) {
logger.info("Variable updated.");
player.update();
setShouldRedraw();
}
}
public GameView(Context context, Variable<Player> player) {
super(context);
getHolder().addCallback(this);
thread = new GameThread(getHolder(), context, player);
}
public void setUp() {
thread.setUp();
}
public void tearDown() {
thread.tearDown();
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setARGB(255, 255, 0, 0);
canvas.drawCircle(50.0f, 50.0f, 50.0f, paint);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
logger.info("SurfaceChanged(w={}, h={})", width, height);
thread.setSize(width, height);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
logger.info("SurfaceCreated()");
thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
logger.info("SurfaceDestroyed()");
thread.interrupt();
}
@Override
public boolean onTouchEvent(MotionEvent e) {
thread.setPosition(e.getX(), e.getY());
return true;
}
}
| false | true | @Override public void run() {
while (true) {
Canvas c = null;
try {
c = holder.lockCanvas();
synchronized(holder) {
doDraw(c);
}
} finally {
holder.unlockCanvasAndPost(c);
}
synchronized (this) {
if (Thread.interrupted()) {
break;
}
try {
while (!shouldRedraw.get()) {
wait();
}
} catch (InterruptedException e) {
break;
}
}
}
}
| @Override public void run() {
while (true) {
Canvas c = null;
try {
c = holder.lockCanvas();
if (c != null) {
synchronized(holder) {
doDraw(c);
}
}
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);
}
}
synchronized (this) {
if (Thread.interrupted()) {
break;
}
try {
while (!shouldRedraw.get()) {
wait();
}
} catch (InterruptedException e) {
break;
}
}
}
}
|
diff --git a/illaclient/src/illarion/client/gui/ContainerHandler.java b/illaclient/src/illarion/client/gui/ContainerHandler.java
index 2cd8b519..4bb7a596 100644
--- a/illaclient/src/illarion/client/gui/ContainerHandler.java
+++ b/illaclient/src/illarion/client/gui/ContainerHandler.java
@@ -1,314 +1,314 @@
/*
* This file is part of the Illarion Client.
*
* Copyright © 2012 - Illarion e.V.
*
* The Illarion Client 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.
*
* The Illarion Client 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 the Illarion Client. If not, see <http://www.gnu.org/licenses/>.
*/
package illarion.client.gui;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.controls.DraggableDragCanceledEvent;
import de.lessvoid.nifty.controls.DraggableDragStartedEvent;
import de.lessvoid.nifty.controls.DroppableDroppedEvent;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.elements.events.NiftyMousePrimaryClickedEvent;
import de.lessvoid.nifty.render.NiftyImage;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.map.hash.TIntObjectHashMap;
import illarion.client.IllaClient;
import illarion.client.graphics.Item;
import illarion.client.gui.util.AbstractMultiActionHelper;
import illarion.client.net.server.events.OpenContainerEvent;
import illarion.client.resources.ItemFactory;
import illarion.client.world.World;
import illarion.client.world.items.ContainerSlot;
import illarion.client.world.items.ItemContainer;
import org.bushe.swing.event.EventBus;
import org.bushe.swing.event.EventSubscriber;
import org.illarion.nifty.controls.InventorySlot;
import org.illarion.nifty.controls.itemcontainer.builder.ItemContainerBuilder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This handler that care for properly managing the displaying of containers on the game screen.
*
* @author Martin Karing <[email protected]>
*/
public class ContainerHandler implements ScreenController {
private final EventSubscriber<OpenContainerEvent> eventSubscriberOpenContainer;
/**
* This class is used as drag end operation and used to move a object that was dragged out of the inventory back in
* so the server can send the commands to clean everything up.
*
* @author Martin Karing <[email protected]>
*/
private static class EndOfDragOperation implements Runnable {
/**
* The inventory slot that requires the reset.
*/
private final InventorySlot invSlot;
/**
* Create a new instance of this class and set the effected elements.
*
* @param slot the inventory slot to reset
*/
EndOfDragOperation(final InventorySlot slot) {
invSlot = slot;
}
/**
* Execute this operation.
*/
@Override
public void run() {
invSlot.retrieveDraggable();
}
}
/**
* This class is used to handle multiple clicks into a container.
*
* @author Martin Karing <[email protected]>
*/
private static final class ContainerClickActionHelper extends AbstractMultiActionHelper {
/**
* The ID of the slot that was clicked at.
*/
private int slotId;
/**
* The ID of the container that was clicked at.
*/
private int containerId;
/**
* The constructor for this class. The timeout time is set to the system default double click interval.
*/
ContainerClickActionHelper() {
super(IllaClient.getCfg().getInteger("doubleClickInterval"));
}
/**
* Set the data that is used for the click operations.
*
* @param slot the slot that is clicked
* @param container the container that is clicked
*/
public void setData(final int slot, final int container) {
slotId = slot;
containerId = container;
}
@Override
public void executeAction(final int count) {
final ItemContainer container;
final ContainerSlot slot;
switch (count) {
case 1:
container = World.getPlayer().getContainer(containerId);
slot = container.getSlot(slotId);
slot.getInteractive().lookAt();
break;
case 2:
container = World.getPlayer().getContainer(containerId);
slot = container.getSlot(slotId);
slot.getInteractive().use();
break;
}
}
}
/**
* The Nifty-GUI instance that is handling the GUI display currently.
*/
private Nifty activeNifty;
/**
* The screen that takes care for the display currently.
*/
private Screen activeScreen;
/**
* The click helper that is supposed to be used for handling clicks.
*/
private static final ContainerClickActionHelper clickHelper = new ContainerClickActionHelper();
private final TIntObjectHashMap<org.illarion.nifty.controls.ItemContainer> itemContainerMap;
public ContainerHandler() {
itemContainerMap = new TIntObjectHashMap<org.illarion.nifty.controls.ItemContainer>();
eventSubscriberOpenContainer = new EventSubscriber<OpenContainerEvent>() {
@Override
public void onEvent(final OpenContainerEvent event) {
try {
if ((activeNifty == null) || (activeScreen == null)) {
return;
}
if (!isContainerCreated(event.getContainerId())) {
createNewContainer(event);
}
updateContainer(event.getContainerId(), event.getItemIterator());
} catch (final RuntimeException e) {
e.printStackTrace();
throw e;
}
}
};
}
private boolean isContainerCreated(final int containerId) {
return itemContainerMap.containsKey(containerId);
}
private void createNewContainer(final OpenContainerEvent event) {
final ItemContainerBuilder builder = new ItemContainerBuilder("#container" + event.getContainerId(),
"Tasche");
builder.slots(event.getSlotCount());
builder.slotDim(48, 48);
builder.width(builder.pixels(288));
final Element container = builder.build(activeNifty, activeScreen,
activeScreen.findElementByName("windows"));
final org.illarion.nifty.controls.ItemContainer conControl = container.getNiftyControl(org.illarion.nifty.controls.ItemContainer.class);
itemContainerMap.put(event.getContainerId(), conControl);
}
private void updateContainer(final int containerId, final TIntObjectIterator<OpenContainerEvent.Item> itr) {
final org.illarion.nifty.controls.ItemContainer conControl = itemContainerMap.get(containerId);
final int slotCount = conControl.getSlotCount();
for (int i = 0; i < slotCount; i++) {
- final InventorySlot conSlot = conControl.getSlot(itr.key());
+ final InventorySlot conSlot = conControl.getSlot(i);
conSlot.setImage(null);
conSlot.hideLabel();
}
while (itr.hasNext()) {
itr.advance();
final InventorySlot conSlot = conControl.getSlot(itr.key());
final int itemId = itr.value().getItemId();
final int count = itr.value().getCount();
if (itemId > 0) {
final Item displayedItem = ItemFactory.getInstance().getPrototype(itemId);
final NiftyImage niftyImage = new NiftyImage(activeNifty.getRenderEngine(),
new EntitySlickRenderImage(displayedItem));
conSlot.setImage(niftyImage);
conSlot.setLabelText(Integer.toString(count));
if (count > 1) {
conSlot.showLabel();
} else {
conSlot.hideLabel();
}
} else {
conSlot.setImage(null);
conSlot.hideLabel();
}
}
conControl.getElement().getParent().layoutElements();
}
@Override
public void bind(final Nifty nifty, final Screen screen) {
activeNifty = nifty;
activeScreen = screen;
}
@Override
public void onStartScreen() {
EventBus.subscribe(OpenContainerEvent.class, eventSubscriberOpenContainer);
activeNifty.subscribeAnnotations(this);
}
@Override
public void onEndScreen() {
EventBus.unsubscribe(OpenContainerEvent.class, eventSubscriberOpenContainer);
}
@NiftyEventSubscriber(pattern = ".*container[0-9]+.*slot[0-9]+.*")
public void cancelDragging(final String topic, final DraggableDragCanceledEvent data) {
World.getInteractionManager().cancelDragging();
}
@NiftyEventSubscriber(pattern = ".*container[0-9]+.*slot[0-9]+.*")
public void clickInContainer(final String topic, final NiftyMousePrimaryClickedEvent data) {
final int slotId = getSlotId(topic);
final int containerId = getContainerId(topic);
clickHelper.setData(slotId, containerId);
clickHelper.pulse();
}
@NiftyEventSubscriber(pattern = ".*container[0-9]+.*slot[0-9]+.*")
public void dragFrom(final String topic, final DraggableDragStartedEvent data) {
final int slotId = getSlotId(topic);
final int containerId = getContainerId(topic);
World.getInteractionManager().notifyDraggingContainer(containerId, slotId,
new EndOfDragOperation(data.getSource().getElement().getNiftyControl(InventorySlot.class)));
}
@NiftyEventSubscriber(pattern = ".*container[0-9]+.*slot[0-9]+.*")
public void dropIn(final String topic, final DroppableDroppedEvent data) {
final int slotId = getSlotId(topic);
final int containerId = getContainerId(topic);
World.getInteractionManager().dropAtContainer(containerId, slotId);
}
private static final Pattern slotPattern = Pattern.compile("slot([0-9]+)");
private static final Pattern containerPattern = Pattern.compile("container([0-9]+)");
private static int getSlotId(final CharSequence key) {
final Matcher matcher = slotPattern.matcher(key);
if (!matcher.find()) {
return -1;
}
if (matcher.groupCount() == 0) {
return -1;
}
return Integer.parseInt(matcher.group(1));
}
private static int getContainerId(final CharSequence key) {
final Matcher matcher = containerPattern.matcher(key);
if (!matcher.find()) {
return -1;
}
if (matcher.groupCount() == 0) {
return -1;
}
return Integer.parseInt(matcher.group(1));
}
}
| true | true | private void updateContainer(final int containerId, final TIntObjectIterator<OpenContainerEvent.Item> itr) {
final org.illarion.nifty.controls.ItemContainer conControl = itemContainerMap.get(containerId);
final int slotCount = conControl.getSlotCount();
for (int i = 0; i < slotCount; i++) {
final InventorySlot conSlot = conControl.getSlot(itr.key());
conSlot.setImage(null);
conSlot.hideLabel();
}
while (itr.hasNext()) {
itr.advance();
final InventorySlot conSlot = conControl.getSlot(itr.key());
final int itemId = itr.value().getItemId();
final int count = itr.value().getCount();
if (itemId > 0) {
final Item displayedItem = ItemFactory.getInstance().getPrototype(itemId);
final NiftyImage niftyImage = new NiftyImage(activeNifty.getRenderEngine(),
new EntitySlickRenderImage(displayedItem));
conSlot.setImage(niftyImage);
conSlot.setLabelText(Integer.toString(count));
if (count > 1) {
conSlot.showLabel();
} else {
conSlot.hideLabel();
}
} else {
conSlot.setImage(null);
conSlot.hideLabel();
}
}
conControl.getElement().getParent().layoutElements();
}
| private void updateContainer(final int containerId, final TIntObjectIterator<OpenContainerEvent.Item> itr) {
final org.illarion.nifty.controls.ItemContainer conControl = itemContainerMap.get(containerId);
final int slotCount = conControl.getSlotCount();
for (int i = 0; i < slotCount; i++) {
final InventorySlot conSlot = conControl.getSlot(i);
conSlot.setImage(null);
conSlot.hideLabel();
}
while (itr.hasNext()) {
itr.advance();
final InventorySlot conSlot = conControl.getSlot(itr.key());
final int itemId = itr.value().getItemId();
final int count = itr.value().getCount();
if (itemId > 0) {
final Item displayedItem = ItemFactory.getInstance().getPrototype(itemId);
final NiftyImage niftyImage = new NiftyImage(activeNifty.getRenderEngine(),
new EntitySlickRenderImage(displayedItem));
conSlot.setImage(niftyImage);
conSlot.setLabelText(Integer.toString(count));
if (count > 1) {
conSlot.showLabel();
} else {
conSlot.hideLabel();
}
} else {
conSlot.setImage(null);
conSlot.hideLabel();
}
}
conControl.getElement().getParent().layoutElements();
}
|
diff --git a/backend/src/com/mymed/controller/core/manager/authentication/AuthenticationManager.java b/backend/src/com/mymed/controller/core/manager/authentication/AuthenticationManager.java
index 6aac67003..4284a2f88 100644
--- a/backend/src/com/mymed/controller/core/manager/authentication/AuthenticationManager.java
+++ b/backend/src/com/mymed/controller/core/manager/authentication/AuthenticationManager.java
@@ -1,87 +1,88 @@
package com.mymed.controller.core.manager.authentication;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import com.mymed.controller.core.exception.IOBackEndException;
import com.mymed.controller.core.exception.InternalBackEndException;
import com.mymed.controller.core.manager.AbstractManager;
import com.mymed.controller.core.manager.profile.ProfileManager;
import com.mymed.controller.core.manager.storage.StorageManager;
import com.mymed.model.data.session.MAuthenticationBean;
import com.mymed.model.data.user.MUserBean;
/**
* The manager for the authentication bean
*
* @author lvanni
* @author Milo Casagrande
*
*/
public class AuthenticationManager extends AbstractManager implements IAuthenticationManager {
public AuthenticationManager() throws InternalBackEndException {
this(new StorageManager());
}
public AuthenticationManager(final StorageManager storageManager) throws InternalBackEndException {
super(storageManager);
}
/**
* @throws IOBackEndException
* @see IAuthenticationManager#create(MUserBean, MAuthenticationBean)
*/
@Override
public MUserBean create(final MUserBean user, final MAuthenticationBean authentication)
throws InternalBackEndException, IOBackEndException {
final ProfileManager profileManager = new ProfileManager(storageManager);
profileManager.create(user);
insertColumn(authentication);
return user;
}
/**
* @see IAuthenticationManager#read(String, String)
*/
@Override
public MUserBean read(final String login, final String password) throws InternalBackEndException,
IOBackEndException {
final Map<byte[], byte[]> args = storageManager.selectAll(CF_AUTHENTICATION, login);
MAuthenticationBean authentication = new MAuthenticationBean();
authentication = (MAuthenticationBean) introspection(authentication, args);
if (authentication.getPassword().equals(password)) {
- return new ProfileManager().read(authentication.getUser());
+ final ProfileManager profileManager = new ProfileManager(storageManager);
+ return profileManager.read(authentication.getUser());
} else {
throw new IOBackEndException("Wrong password");
}
}
/**
* @see IAuthenticationManager#update(MAuthenticationBean)
*/
@Override
public void update(final MAuthenticationBean authentication) throws InternalBackEndException {
insertColumn(authentication);
}
/**
* Internally used to perform the real insertion into the database
*
* @param authentication
* @throws InternalBackEndException
*/
private void insertColumn(final MAuthenticationBean authentication) throws InternalBackEndException {
try {
final Map<String, byte[]> authMap = authentication.getAttributeToMap();
storageManager.insertSlice(CF_AUTHENTICATION, new String(authMap.get("login"), "UTF8"), authMap);
} catch (final UnsupportedEncodingException ex) {
throw new InternalBackEndException(ex.getMessage());
}
}
}
| true | true | public MUserBean read(final String login, final String password) throws InternalBackEndException,
IOBackEndException {
final Map<byte[], byte[]> args = storageManager.selectAll(CF_AUTHENTICATION, login);
MAuthenticationBean authentication = new MAuthenticationBean();
authentication = (MAuthenticationBean) introspection(authentication, args);
if (authentication.getPassword().equals(password)) {
return new ProfileManager().read(authentication.getUser());
} else {
throw new IOBackEndException("Wrong password");
}
}
| public MUserBean read(final String login, final String password) throws InternalBackEndException,
IOBackEndException {
final Map<byte[], byte[]> args = storageManager.selectAll(CF_AUTHENTICATION, login);
MAuthenticationBean authentication = new MAuthenticationBean();
authentication = (MAuthenticationBean) introspection(authentication, args);
if (authentication.getPassword().equals(password)) {
final ProfileManager profileManager = new ProfileManager(storageManager);
return profileManager.read(authentication.getUser());
} else {
throw new IOBackEndException("Wrong password");
}
}
|
diff --git a/src/org/apache/xalan/xsltc/compiler/LogicalExpr.java b/src/org/apache/xalan/xsltc/compiler/LogicalExpr.java
index 2d224554..ea287ccc 100644
--- a/src/org/apache/xalan/xsltc/compiler/LogicalExpr.java
+++ b/src/org/apache/xalan/xsltc/compiler/LogicalExpr.java
@@ -1,229 +1,229 @@
/*
* @(#)$Id$
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 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) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
*
*/
package org.apache.xalan.xsltc.compiler;
import org.apache.xalan.xsltc.compiler.util.Type;
import de.fub.bytecode.generic.*;
import org.apache.xalan.xsltc.compiler.util.*;
final class LogicalExpr extends Expression {
public static final int OR = 0;
public static final int AND = 1;
private final int _op;
private Expression _left, _right;
private static final String[] Ops = { "or", "and" };
/**
* Creates a new logical expression - either OR or AND. Note that the
* left- and right-hand side expressions can also be logical expressions,
* thus creating logical trees representing structures such as
* (a and (b or c) and d), etc...
*/
public LogicalExpr(int op, Expression left, Expression right) {
_op = op;
(_left = left).setParent(this);
(_right = right).setParent(this);
}
/**
* Returns this logical expression's operator - OR or AND represented
* by 0 and 1 respectively.
*/
public int getOp() {
return(_op);
}
/**
* Override the SyntaxTreeNode.setParser() method to make sure that the
* parser is set for sub-expressions
*/
public void setParser(Parser parser) {
super.setParser(parser);
_left.setParser(parser);
_right.setParser(parser);
}
/**
* Returns a string describing this expression
*/
public String toString() {
return Ops[_op] + '(' + _left + ", " + _right + ')';
}
/**
* Type-check this expression, and possibly child expressions.
*/
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
// Get the left and right operand types
Type tleft = _left.typeCheck(stable);
Type tright = _right.typeCheck(stable);
// Check if the operator supports the two operand types
MethodType wantType = new MethodType(Type.Void, tleft, tright);
MethodType haveType = lookupPrimop(stable, Ops[_op], wantType);
// Yes, the operation is supported
if (haveType != null) {
// Check if left-hand side operand must be type casted
Type arg1 = (Type)haveType.argsType().elementAt(0);
if (!arg1.identicalTo(tleft)) _left = new CastExpr(_left, arg1);
// Check if right-hand side operand must be type casted
Type arg2 = (Type) haveType.argsType().elementAt(1);
if (!arg2.identicalTo(tright)) _right = new CastExpr(_right, arg1);
// Return the result type for the operator we will use
return _type = haveType.resultType();
}
throw new TypeCheckError(this);
}
/**
* Compile the expression - leave boolean expression on stack
*/
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
translateDesynthesized(classGen, methodGen);
synthesize(classGen, methodGen);
}
/**
* Compile expression and update true/false-lists
*/
public void translateDesynthesized(ClassGenerator classGen,
MethodGenerator methodGen) {
final InstructionList il = methodGen.getInstructionList();
final SyntaxTreeNode parent = getParent();
// Compile AND-expression
if (_op == AND) {
// Translate left hand side - must be true
_left.translateDesynthesized(classGen, methodGen);
if ((_left instanceof FunctionCall) &&
(!(_left instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// Need this for chaining any OR-expression children
InstructionHandle middle = il.append(NOP);
// Translate left right side - must be true
_right.translateDesynthesized(classGen, methodGen);
if ((_right instanceof FunctionCall) &&
(!(_right instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// Need this for chaining any OR-expression children
InstructionHandle after = il.append(NOP);
// Append child expression false-lists to our false-list
_falseList.append(_right._falseList.append(_left._falseList));
// Special case for OR-expression as a left child of AND
- if (_left instanceof LogicalExpr) {
- LogicalExpr left = (LogicalExpr)_left;
- if (left.getOp() == OR) left.backPatchTrueList(middle);
+ if ((_left instanceof LogicalExpr) &&
+ (((LogicalExpr)_left).getOp() == OR)) {
+ ((LogicalExpr)_left).backPatchTrueList(middle);
}
else {
_trueList.append(_left._trueList);
}
// Special case for OR-expression as a right child of AND
- if (_right instanceof LogicalExpr) {
- LogicalExpr right = (LogicalExpr)_right;
- if (right.getOp() == OR) right.backPatchTrueList(after);
+ if ((_right instanceof LogicalExpr) &&
+ (((LogicalExpr)_right).getOp() == OR)) {
+ ((LogicalExpr)_right).backPatchTrueList(after);
}
else {
_trueList.append(_right._trueList);
}
}
// Compile OR-expression
else {
// Translate left-hand side expression and produce true/false list
_left.translateDesynthesized(classGen, methodGen);
if ((_left instanceof FunctionCall) &&
(!(_left instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// This GOTO is used to skip over the code for the last test
// in the case where the the first test succeeds
InstructionHandle ih = il.append(new GOTO(null));
// Translate right-hand side expression and produce true/false list
_right.translateDesynthesized(classGen, methodGen);
if ((_right instanceof FunctionCall) &&
(!(_right instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
_left._trueList.backPatch(ih);
_left._falseList.backPatch(ih.getNext());
_falseList.append(_right._falseList);
_trueList.add(ih).append(_right._trueList);
}
}
}
| false | true | public void translateDesynthesized(ClassGenerator classGen,
MethodGenerator methodGen) {
final InstructionList il = methodGen.getInstructionList();
final SyntaxTreeNode parent = getParent();
// Compile AND-expression
if (_op == AND) {
// Translate left hand side - must be true
_left.translateDesynthesized(classGen, methodGen);
if ((_left instanceof FunctionCall) &&
(!(_left instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// Need this for chaining any OR-expression children
InstructionHandle middle = il.append(NOP);
// Translate left right side - must be true
_right.translateDesynthesized(classGen, methodGen);
if ((_right instanceof FunctionCall) &&
(!(_right instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// Need this for chaining any OR-expression children
InstructionHandle after = il.append(NOP);
// Append child expression false-lists to our false-list
_falseList.append(_right._falseList.append(_left._falseList));
// Special case for OR-expression as a left child of AND
if (_left instanceof LogicalExpr) {
LogicalExpr left = (LogicalExpr)_left;
if (left.getOp() == OR) left.backPatchTrueList(middle);
}
else {
_trueList.append(_left._trueList);
}
// Special case for OR-expression as a right child of AND
if (_right instanceof LogicalExpr) {
LogicalExpr right = (LogicalExpr)_right;
if (right.getOp() == OR) right.backPatchTrueList(after);
}
else {
_trueList.append(_right._trueList);
}
}
// Compile OR-expression
else {
// Translate left-hand side expression and produce true/false list
_left.translateDesynthesized(classGen, methodGen);
if ((_left instanceof FunctionCall) &&
(!(_left instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// This GOTO is used to skip over the code for the last test
// in the case where the the first test succeeds
InstructionHandle ih = il.append(new GOTO(null));
// Translate right-hand side expression and produce true/false list
_right.translateDesynthesized(classGen, methodGen);
if ((_right instanceof FunctionCall) &&
(!(_right instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
_left._trueList.backPatch(ih);
_left._falseList.backPatch(ih.getNext());
_falseList.append(_right._falseList);
_trueList.add(ih).append(_right._trueList);
}
}
| public void translateDesynthesized(ClassGenerator classGen,
MethodGenerator methodGen) {
final InstructionList il = methodGen.getInstructionList();
final SyntaxTreeNode parent = getParent();
// Compile AND-expression
if (_op == AND) {
// Translate left hand side - must be true
_left.translateDesynthesized(classGen, methodGen);
if ((_left instanceof FunctionCall) &&
(!(_left instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// Need this for chaining any OR-expression children
InstructionHandle middle = il.append(NOP);
// Translate left right side - must be true
_right.translateDesynthesized(classGen, methodGen);
if ((_right instanceof FunctionCall) &&
(!(_right instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// Need this for chaining any OR-expression children
InstructionHandle after = il.append(NOP);
// Append child expression false-lists to our false-list
_falseList.append(_right._falseList.append(_left._falseList));
// Special case for OR-expression as a left child of AND
if ((_left instanceof LogicalExpr) &&
(((LogicalExpr)_left).getOp() == OR)) {
((LogicalExpr)_left).backPatchTrueList(middle);
}
else {
_trueList.append(_left._trueList);
}
// Special case for OR-expression as a right child of AND
if ((_right instanceof LogicalExpr) &&
(((LogicalExpr)_right).getOp() == OR)) {
((LogicalExpr)_right).backPatchTrueList(after);
}
else {
_trueList.append(_right._trueList);
}
}
// Compile OR-expression
else {
// Translate left-hand side expression and produce true/false list
_left.translateDesynthesized(classGen, methodGen);
if ((_left instanceof FunctionCall) &&
(!(_left instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
// This GOTO is used to skip over the code for the last test
// in the case where the the first test succeeds
InstructionHandle ih = il.append(new GOTO(null));
// Translate right-hand side expression and produce true/false list
_right.translateDesynthesized(classGen, methodGen);
if ((_right instanceof FunctionCall) &&
(!(_right instanceof ContainsCall)))
_falseList.add(il.append(new IFEQ(null)));
_left._trueList.backPatch(ih);
_left._falseList.backPatch(ih.getNext());
_falseList.append(_right._falseList);
_trueList.add(ih).append(_right._trueList);
}
}
|
diff --git a/gadgets/core/src/main/java/org/exoplatform/portal/gadget/core/ExoContainerConfig.java b/gadgets/core/src/main/java/org/exoplatform/portal/gadget/core/ExoContainerConfig.java
index 37a3e86eb..0758bf0fe 100644
--- a/gadgets/core/src/main/java/org/exoplatform/portal/gadget/core/ExoContainerConfig.java
+++ b/gadgets/core/src/main/java/org/exoplatform/portal/gadget/core/ExoContainerConfig.java
@@ -1,184 +1,176 @@
/*
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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.exoplatform.portal.gadget.core;
import org.apache.shindig.config.ContainerConfigException;
import org.apache.shindig.config.JsonContainerConfig;
import org.apache.shindig.expressions.Expressions;
import org.apache.shindig.auth.BlobCrypterSecurityTokenDecoder;
import org.exoplatform.services.log.Log;
import org.exoplatform.container.monitor.jvm.J2EEServerInfo;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.commons.utils.Safe;
import com.google.inject.name.Named;
import com.google.inject.Inject;
import java.io.File;
import java.io.Writer;
import java.io.FileWriter;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;
/**
* <p>The goal of the container config subclass is to integrate security key file along
* with exo configuration.</p>
*
* <p>The implementation first determine the most relevant directory for performing the key lookup.
* It will look for a <i>gadgets</i> directory under the configuration directory returned by the
* {@link org.exoplatform.container.monitor.jvm.J2EEServerInfo#getExoConfigurationDirectory()}
* method. If no such valid directory can be found then the implementation use the current execution directory
* (which should be /bin in tomcat and jboss).</p>
*
* <p>When the lookup directory is determined, the implementation looks for a file named key.txt.
* If no such file is found, then it will attempt to create it with a base 64 value encoded from
* a 32 bytes random sequence generated by {@link SecureRandom} seeded by the current time. If the
* file exist already but is a directory then no acton is done.<p>
*
* @author <a href="mailto:[email protected]">Julien Viet</a>
* @version $Revision$
*/
public class ExoContainerConfig extends JsonContainerConfig {
/** . */
private Log log = ExoLogger.getLogger(ExoContainerConfig.class);
/** . */
private static volatile String _keyPath;
@Inject
public ExoContainerConfig(@Named("shindig.containers.default") String s, Expressions expressions) throws ContainerConfigException {
super(s, expressions);
//
J2EEServerInfo info = new J2EEServerInfo();
//
String confPath = info.getExoConfigurationDirectory();
File keyFile = null;
if (confPath != null) {
File confDir = new File(confPath);
if (!confDir.exists()) {
log.debug("Exo conf directory (" + confPath + ") does not exist");
} else {
if (!confDir.isDirectory()) {
log.debug("Exo conf directory (" + confPath + ") is not a directory");
} else {
keyFile = new File(confDir, "gadgets/key.txt");
}
}
}
- //
if (keyFile == null) {
keyFile = new File("key.txt");
}
- // Check parent folder is exist or not. If not, create new.
String keyPath = keyFile.getAbsolutePath();
- File parentFolder = new File(keyFile.getParent());
- if (!parentFolder.exists()) {
- boolean created = parentFolder.mkdir();
- if (!created) {
- log.debug("Can not create folder " + keyFile.getParent());
- throw new RuntimeException("Can not create folder " + keyFile.getParent());
- }
- }
if (!keyFile.exists()) {
- log.debug("No key file found at path " + keyPath + " generating a new key and saving it");
+ log.debug("No key file found at path " + keyPath + " generating a new key and saving it");
+ File parentFolder = keyFile.getParentFile();
+ if(!parentFolder.exists()) parentFolder.mkdirs();
String key = generateKey();
Writer out = null;
try {
out = new FileWriter(keyFile);
out.write(key);
out.write('\n');
log.info("Generated key file " + keyPath + " for eXo Gadgets");
setKeyPath(keyPath);
} catch (IOException e) {
log.error("Coult not create key file " + keyPath, e);
} finally {
Safe.close(out);
}
} else if (!keyFile.isFile()) {
log.debug("Found key file " + keyPath + " but it's not a file");
} else {
log.info("Found key file " + keyPath + " for gadgets security");
setKeyPath(keyPath);
}
}
private void setKeyPath(String keyPath) {
// _keyPath is volatile so no concurrent writes and read are safe
synchronized (ExoContainerConfig.class) {
if (_keyPath != null && !_keyPath.equals(keyPath)) {
throw new IllegalStateException("There is already a configured key path old=" + _keyPath + " new=" + keyPath);
}
_keyPath = keyPath;
}
}
@Override
public Object getProperty(String container, String property) {
if (property.equals(BlobCrypterSecurityTokenDecoder.SECURITY_TOKEN_KEY_FILE) && _keyPath != null) {
return _keyPath;
}
return super.getProperty(container, property);
}
// @Override
// public Object getJson(String container, String parameter) {
// if (parameter.equals(BlobCrypterSecurityTokenDecoder.SECURITY_TOKEN_KEY_FILE) && _keyPath != null) {
// return _keyPath;
// }
// return super.getJson(container, parameter);
// }
/**
* It's not public as we don't want to expose it to the outter world. The fact that this class
* is instantiated by Guice and the ExoDefaultSecurityTokenGenerator is managed by exo kernel
* force us to use static reference to share the keyPath value.
*
* @return the key path
*/
static String getKeyPath() {
return _keyPath;
}
/**
* Generate a key of 32 bytes encoded in base64. The generation is based on
* {@link SecureRandom} seeded with the current time.
*
* @return the key
*/
private static String generateKey() {
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(System.currentTimeMillis());
byte bytes[] = new byte[32];
random.nextBytes(bytes);
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bytes);
}
catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}
| false | true | public ExoContainerConfig(@Named("shindig.containers.default") String s, Expressions expressions) throws ContainerConfigException {
super(s, expressions);
//
J2EEServerInfo info = new J2EEServerInfo();
//
String confPath = info.getExoConfigurationDirectory();
File keyFile = null;
if (confPath != null) {
File confDir = new File(confPath);
if (!confDir.exists()) {
log.debug("Exo conf directory (" + confPath + ") does not exist");
} else {
if (!confDir.isDirectory()) {
log.debug("Exo conf directory (" + confPath + ") is not a directory");
} else {
keyFile = new File(confDir, "gadgets/key.txt");
}
}
}
//
if (keyFile == null) {
keyFile = new File("key.txt");
}
// Check parent folder is exist or not. If not, create new.
String keyPath = keyFile.getAbsolutePath();
File parentFolder = new File(keyFile.getParent());
if (!parentFolder.exists()) {
boolean created = parentFolder.mkdir();
if (!created) {
log.debug("Can not create folder " + keyFile.getParent());
throw new RuntimeException("Can not create folder " + keyFile.getParent());
}
}
if (!keyFile.exists()) {
log.debug("No key file found at path " + keyPath + " generating a new key and saving it");
String key = generateKey();
Writer out = null;
try {
out = new FileWriter(keyFile);
out.write(key);
out.write('\n');
log.info("Generated key file " + keyPath + " for eXo Gadgets");
setKeyPath(keyPath);
} catch (IOException e) {
log.error("Coult not create key file " + keyPath, e);
} finally {
Safe.close(out);
}
} else if (!keyFile.isFile()) {
log.debug("Found key file " + keyPath + " but it's not a file");
} else {
log.info("Found key file " + keyPath + " for gadgets security");
setKeyPath(keyPath);
}
}
| public ExoContainerConfig(@Named("shindig.containers.default") String s, Expressions expressions) throws ContainerConfigException {
super(s, expressions);
//
J2EEServerInfo info = new J2EEServerInfo();
//
String confPath = info.getExoConfigurationDirectory();
File keyFile = null;
if (confPath != null) {
File confDir = new File(confPath);
if (!confDir.exists()) {
log.debug("Exo conf directory (" + confPath + ") does not exist");
} else {
if (!confDir.isDirectory()) {
log.debug("Exo conf directory (" + confPath + ") is not a directory");
} else {
keyFile = new File(confDir, "gadgets/key.txt");
}
}
}
if (keyFile == null) {
keyFile = new File("key.txt");
}
String keyPath = keyFile.getAbsolutePath();
if (!keyFile.exists()) {
log.debug("No key file found at path " + keyPath + " generating a new key and saving it");
File parentFolder = keyFile.getParentFile();
if(!parentFolder.exists()) parentFolder.mkdirs();
String key = generateKey();
Writer out = null;
try {
out = new FileWriter(keyFile);
out.write(key);
out.write('\n');
log.info("Generated key file " + keyPath + " for eXo Gadgets");
setKeyPath(keyPath);
} catch (IOException e) {
log.error("Coult not create key file " + keyPath, e);
} finally {
Safe.close(out);
}
} else if (!keyFile.isFile()) {
log.debug("Found key file " + keyPath + " but it's not a file");
} else {
log.info("Found key file " + keyPath + " for gadgets security");
setKeyPath(keyPath);
}
}
|
diff --git a/geoplatform-gui/core/geoplatform-widget/layer-widget/src/main/java/org/geosdi/geoplatform/gui/client/widget/LayerTreeWidget.java b/geoplatform-gui/core/geoplatform-widget/layer-widget/src/main/java/org/geosdi/geoplatform/gui/client/widget/LayerTreeWidget.java
index b2dc657c..57009bbe 100644
--- a/geoplatform-gui/core/geoplatform-widget/layer-widget/src/main/java/org/geosdi/geoplatform/gui/client/widget/LayerTreeWidget.java
+++ b/geoplatform-gui/core/geoplatform-widget/layer-widget/src/main/java/org/geosdi/geoplatform/gui/client/widget/LayerTreeWidget.java
@@ -1,379 +1,379 @@
/*
* geo-platform
* Rich webgis framework
* http://geo-plartform.org
* ====================================================================
*
* Copyright (C) 2008-2011 geoSDI Group (CNR IMAA - Potenza - ITALY).
*
* 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/
*
* ====================================================================
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you permission
* to link this library with independent modules to produce an executable, regardless
* of the license terms of these independent modules, and to copy and distribute
* the resulting executable under terms of your choice, provided that you also meet,
* for each linked independent module, the terms and conditions of the license of
* that module. An independent module is a module which is not derived from or
* based on this library. If you modify this library, you may extend this exception
* to your version of the library, but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version.
*
*/
package org.geosdi.geoplatform.gui.client.widget;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.TreeNode;
import org.geosdi.geoplatform.gui.client.widget.tree.GPTreePanel;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.store.TreeStore;
import org.geosdi.geoplatform.gui.client.listener.GPDNDListener;
import org.geosdi.geoplatform.gui.client.model.GPRootTreeNode;
import org.geosdi.geoplatform.gui.client.widget.tree.GeoPlatformTreeWidget;
import org.geosdi.geoplatform.gui.model.tree.GPBeanTreeModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelIconProvider;
import com.extjs.gxt.ui.client.data.ModelStringProvider;
import com.extjs.gxt.ui.client.dnd.DND.Feedback;
import com.extjs.gxt.ui.client.dnd.TreePanelDragSource;
import com.extjs.gxt.ui.client.dnd.TreePanelDropTarget;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.DNDEvent;
import com.extjs.gxt.ui.client.event.DNDListener;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.store.TreeStoreEvent;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.geosdi.geoplatform.gui.client.LayerEvents;
import org.geosdi.geoplatform.gui.client.LayerResources;
import org.geosdi.geoplatform.gui.client.action.menu.ZoomToLayerExtentAction;
import org.geosdi.geoplatform.gui.client.model.FolderTreeNode;
import org.geosdi.geoplatform.gui.client.model.visitor.VisitorDisplayHide;
import org.geosdi.geoplatform.gui.client.service.LayerRemoteAsync;
import org.geosdi.geoplatform.gui.client.widget.SearchStatus.EnumSearchStatus;
import org.geosdi.geoplatform.gui.client.widget.toolbar.mediator.MediatorToolbarTreeAction;
import org.geosdi.geoplatform.gui.configuration.map.client.layer.GPFolderClientInfo;
import org.geosdi.geoplatform.gui.configuration.map.client.layer.IGPFolderElements;
import org.geosdi.geoplatform.gui.configuration.message.GeoPlatformMessage;
import org.geosdi.geoplatform.gui.impl.view.LayoutManager;
import org.geosdi.geoplatform.gui.server.gwt.LayerRemoteImpl;
import org.geosdi.geoplatform.gui.view.event.GeoPlatformEvents;
/**
* @author Giuseppe La Scaleia - CNR IMAA geoSDI Group
* @email [email protected]
*
*/
public class LayerTreeWidget extends GeoPlatformTreeWidget<GPBeanTreeModel> {
private LayerRemoteAsync layerService = LayerRemoteImpl.Util.getInstance();
private VisitorDisplayHide visitorDisplay = new VisitorDisplayHide(this.tree);
private MediatorToolbarTreeAction actionMediator;
TreePanelDragSource dragSource;
private GPRootTreeNode root;
private boolean initialized;
/**
* @Constructor
*/
public LayerTreeWidget() {
super();
this.buildRoot();
this.setTreePanelProperties();
this.actionMediator = new MediatorToolbarTreeAction();
//TODO: After toolbar implementation remove this method
this.addMenuAddElement();
}
/*
* Create Root Composite Element
*
*/
private void buildRoot() {
this.root = new GPRootTreeNode(this.tree);
}
/**
* Build Tree
*/
public void buildTree() {
if (!initialized) {
// this.root.modelConverter(GeoPlatformUtils.getInstance().
// getGlobalConfiguration().getFolderStore().
// getFolders());
// store.add(root, true);
// initialized = true;
LayoutManager.get().getStatusMap().setBusy(
"Loading tree elements: please, wait untill contents fully loads.");
layerService.loadUserFolders("user_test_0",
new AsyncCallback<ArrayList<GPFolderClientInfo>>() {
@Override
public void onFailure(Throwable caught) {
GeoPlatformMessage.errorMessage("Error loading",
"An error occurred while making the requested connection.\n"
+ "Verify network connections and try again."
+ "\nIf the problem persists contact your system administrator.");
LayoutManager.get().getStatusMap().setStatus(
"Error loading tree elements.",
EnumSearchStatus.STATUS_NO_SEARCH.toString());
System.out.println("Errore avvenuto nel loader del tree: " + caught.toString()
+ " data: " + caught.getMessage());
}
@Override
public void onSuccess(
ArrayList<GPFolderClientInfo> result) {
root.modelConverter(result);
store.add(root, true);
visitorDisplay.enableCheckedComponent(root);
initialized = true;
tree.setExpanded(root, true);
LayoutManager.get().getStatusMap().setStatus(
"Tree elements loaded successfully.",
EnumSearchStatus.STATUS_SEARCH.toString());
}
});
}
}
/**
* Set Tree Properties
*/
@Override
public void setTreePanelProperties() {
this.addExpandListener();
this.setTreePresenter();
this.enableDDSupport();
this.enableCheckChange();
}
/*
* Define TreePresenter for both Icon and Label Presentation
*
*/
private void setTreePresenter() {
this.tree.setIconProvider(new ModelIconProvider<GPBeanTreeModel>() {
@Override
public AbstractImagePrototype getIcon(GPBeanTreeModel model) {
return model.getIcon();
}
});
this.tree.setLabelProvider(new ModelStringProvider<GPBeanTreeModel>() {
@Override
public String getStringValue(GPBeanTreeModel model, String property) {
return model.getLabel();
}
});
this.tree.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
this.tree.getSelectionModel().addSelectionChangedListener(new SelectionChangedListener<GPBeanTreeModel>() {
@Override
public void selectionChanged(
SelectionChangedEvent<GPBeanTreeModel> se) {
if (se.getSelectedItem() != null) {
actionMediator.elementChanged(se.getSelectedItem());
} else {
actionMediator.disableAllActions();
}
}
});
this.setCheckable(true);
this.setCheckStyle(CheckCascade.NONE);
this.tree.setAutoHeight(true);
}
/*
* Enable Check Box on Tree
*/
private void enableCheckChange() {
this.tree.addListener(Events.CheckChange,
new Listener<TreePanelEvent<GPBeanTreeModel>>() {
@Override
public void handleEvent(TreePanelEvent<GPBeanTreeModel> be) {
// System.out.println("Events.CheckChange from: " + be.getItem().getLabel());
be.getItem().accept(visitorDisplay);
}
});
}
/*
* Add Support for Drag and Drop
*
*/
private void enableDDSupport() {
dragSource = new TreePanelDragSource(super.tree);
dragSource.addDNDListener(new DNDListener() {
@Override
public void dragStart(DNDEvent e) {
ModelData sel = tree.getSelectionModel().getSelectedItem();
if (sel != null
&& sel == tree.getStore().getRootItems().get(0)) {
e.setCancelled(true);
e.getStatus().setStatus(false);
return;
}
super.dragStart(e);
((TreePanelDragSource) e.getSource()).fireEvent(
LayerEvents.GP_DRAG_START, new TreeStoreEvent<GPBeanTreeModel>(
tree.getStore()));
}
});
GPDNDListener gpDNDListener = new GPDNDListener(this.visitorDisplay);
dragSource.addListener(LayerEvents.GP_DRAG_START, gpDNDListener);
dragSource.addListener(LayerEvents.GP_DRAG_LOST, gpDNDListener);
//Listener for launch Drag Lost Events
Listener listenerDragLost = new Listener() {
@Override
public void handleEvent(BaseEvent be) {
((TreePanelDragSource) be.getSource()).fireEvent(
LayerEvents.GP_DRAG_LOST, new TreeStoreEvent<GPBeanTreeModel>(
tree.getStore()));
//System.out.println("DragSource: Ho intercettato il drag cancelled");
}
};
//Intercepting Drag Lost Events
dragSource.addListener(Events.DragCancel, listenerDragLost);
dragSource.addListener(Events.DragEnd, listenerDragLost);
dragSource.addListener(Events.DragFail, listenerDragLost);
TreePanelDropTarget dropTarget = new GPTreePanelDropTarget(super.tree);
dropTarget.setAllowSelfAsSource(true);
dropTarget.setAllowDropOnLeaf(false);
dropTarget.setFeedback(Feedback.BOTH);
dropTarget.addListener(LayerEvents.GP_DROP, gpDNDListener);
super.store.addListener(Store.Add, gpDNDListener);
}
private void addMenuAddElement() {
Menu contextMenu = new Menu();
// MenuItem insert = new MenuItem();
// insert.setText("Add Folder");
// insert.setIcon(LayerResources.ICONS.addFolder());
// insert.addSelectionListener(new AddLayerAction(tree));
// contextMenu.add(insert);
// add zoom to max extent
MenuItem zoomToMaxExtend = new MenuItem();
zoomToMaxExtend.setText("Zoom to layer extend");
zoomToMaxExtend.setIcon(LayerResources.ICONS.zoomToMaxExtend());
zoomToMaxExtend.addSelectionListener(new ZoomToLayerExtentAction(tree));
contextMenu.add(zoomToMaxExtend);
this.tree.setContextMenu(contextMenu);
}
@Override
public GPTreePanel<GPBeanTreeModel> createTreePanel(TreeStore store) {
return new GPTreePanel(store) {
@Override
protected boolean hasChildren(ModelData model) {
return model instanceof FolderTreeNode || model instanceof GPRootTreeNode;
}
};
}
private void addExpandListener() {
tree.addListener(Events.BeforeExpand, new Listener<TreePanelEvent<ModelData>>() {
@Override
public void handleEvent(TreePanelEvent<ModelData> be) {
if (be.getItem() instanceof FolderTreeNode && !((FolderTreeNode) be.getItem()).isLoaded()) {
final FolderTreeNode parentFolder = (FolderTreeNode) be.getItem();
parentFolder.setLoading(true);
LayoutManager.get().getStatusMap().setBusy(
"Loading tree elements: please, wait untill contents fully loads.");
layerService.loadFolderElements(
((FolderTreeNode) parentFolder).getId(), new AsyncCallback<ArrayList<IGPFolderElements>>() {
@Override
public void onFailure(Throwable caught) {
parentFolder.setLoading(false);
GeoPlatformMessage.errorMessage("Error loading",
"An error occurred while making the requested connection.\n"
+ "Verify network connections and try again.\n"
+ "If the problem persists contact your system administrator.");
LayoutManager.get().getStatusMap().setStatus(
"Error loading tree elements.",
EnumSearchStatus.STATUS_NO_SEARCH.toString());
System.out.println("Errore avvenuto nel loader del tree: " + caught.toString()
+ " data: " + caught.getMessage());
}
@Override
public void onSuccess(
ArrayList<IGPFolderElements> result) {
parentFolder.modelConverter(result);
List<GPBeanTreeModel> childrenList = new ArrayList<GPBeanTreeModel>();
for (Iterator<ModelData> it = parentFolder.getChildren().iterator(); it.hasNext();) {
childrenList.add((GPBeanTreeModel) it.next());
}
tree.getStore().insert(parentFolder, childrenList, 0,
true);
visitorDisplay.enableCheckedComponent(parentFolder);
parentFolder.setLoading(false);
parentFolder.setLoaded(true);
tree.fireEvent(GeoPlatformEvents.GP_NODE_EXPANDED);
tree.refresh(parentFolder);
LayoutManager.get().getStatusMap().setStatus(
"Tree elements loaded successfully.",
EnumSearchStatus.STATUS_SEARCH.toString());
}
});
}
}
});
tree.addListener(Events.Expand, new Listener<TreePanelEvent<ModelData>>() {
@Override
public void handleEvent(TreePanelEvent<ModelData> be) {
if (dragSource.getFiresEvents() && be.getItem() instanceof FolderTreeNode && !((FolderTreeNode) be.getItem()).isLoaded()) {
FolderTreeNode parentFolder = (FolderTreeNode) be.getItem();
tree.setExpanded(parentFolder, true);
dragSource.getDraggable().cancelDrag();
- } else if (((FolderTreeNode)be.getItem()).isLoaded()) {
+ } else if (be.getItem() instanceof FolderTreeNode && ((FolderTreeNode)be.getItem()).isLoaded()) {
tree.fireEvent(GeoPlatformEvents.GP_NODE_EXPANDED);
}
}
});
}
}
| true | true | private void addExpandListener() {
tree.addListener(Events.BeforeExpand, new Listener<TreePanelEvent<ModelData>>() {
@Override
public void handleEvent(TreePanelEvent<ModelData> be) {
if (be.getItem() instanceof FolderTreeNode && !((FolderTreeNode) be.getItem()).isLoaded()) {
final FolderTreeNode parentFolder = (FolderTreeNode) be.getItem();
parentFolder.setLoading(true);
LayoutManager.get().getStatusMap().setBusy(
"Loading tree elements: please, wait untill contents fully loads.");
layerService.loadFolderElements(
((FolderTreeNode) parentFolder).getId(), new AsyncCallback<ArrayList<IGPFolderElements>>() {
@Override
public void onFailure(Throwable caught) {
parentFolder.setLoading(false);
GeoPlatformMessage.errorMessage("Error loading",
"An error occurred while making the requested connection.\n"
+ "Verify network connections and try again.\n"
+ "If the problem persists contact your system administrator.");
LayoutManager.get().getStatusMap().setStatus(
"Error loading tree elements.",
EnumSearchStatus.STATUS_NO_SEARCH.toString());
System.out.println("Errore avvenuto nel loader del tree: " + caught.toString()
+ " data: " + caught.getMessage());
}
@Override
public void onSuccess(
ArrayList<IGPFolderElements> result) {
parentFolder.modelConverter(result);
List<GPBeanTreeModel> childrenList = new ArrayList<GPBeanTreeModel>();
for (Iterator<ModelData> it = parentFolder.getChildren().iterator(); it.hasNext();) {
childrenList.add((GPBeanTreeModel) it.next());
}
tree.getStore().insert(parentFolder, childrenList, 0,
true);
visitorDisplay.enableCheckedComponent(parentFolder);
parentFolder.setLoading(false);
parentFolder.setLoaded(true);
tree.fireEvent(GeoPlatformEvents.GP_NODE_EXPANDED);
tree.refresh(parentFolder);
LayoutManager.get().getStatusMap().setStatus(
"Tree elements loaded successfully.",
EnumSearchStatus.STATUS_SEARCH.toString());
}
});
}
}
});
tree.addListener(Events.Expand, new Listener<TreePanelEvent<ModelData>>() {
@Override
public void handleEvent(TreePanelEvent<ModelData> be) {
if (dragSource.getFiresEvents() && be.getItem() instanceof FolderTreeNode && !((FolderTreeNode) be.getItem()).isLoaded()) {
FolderTreeNode parentFolder = (FolderTreeNode) be.getItem();
tree.setExpanded(parentFolder, true);
dragSource.getDraggable().cancelDrag();
} else if (((FolderTreeNode)be.getItem()).isLoaded()) {
tree.fireEvent(GeoPlatformEvents.GP_NODE_EXPANDED);
}
}
});
}
| private void addExpandListener() {
tree.addListener(Events.BeforeExpand, new Listener<TreePanelEvent<ModelData>>() {
@Override
public void handleEvent(TreePanelEvent<ModelData> be) {
if (be.getItem() instanceof FolderTreeNode && !((FolderTreeNode) be.getItem()).isLoaded()) {
final FolderTreeNode parentFolder = (FolderTreeNode) be.getItem();
parentFolder.setLoading(true);
LayoutManager.get().getStatusMap().setBusy(
"Loading tree elements: please, wait untill contents fully loads.");
layerService.loadFolderElements(
((FolderTreeNode) parentFolder).getId(), new AsyncCallback<ArrayList<IGPFolderElements>>() {
@Override
public void onFailure(Throwable caught) {
parentFolder.setLoading(false);
GeoPlatformMessage.errorMessage("Error loading",
"An error occurred while making the requested connection.\n"
+ "Verify network connections and try again.\n"
+ "If the problem persists contact your system administrator.");
LayoutManager.get().getStatusMap().setStatus(
"Error loading tree elements.",
EnumSearchStatus.STATUS_NO_SEARCH.toString());
System.out.println("Errore avvenuto nel loader del tree: " + caught.toString()
+ " data: " + caught.getMessage());
}
@Override
public void onSuccess(
ArrayList<IGPFolderElements> result) {
parentFolder.modelConverter(result);
List<GPBeanTreeModel> childrenList = new ArrayList<GPBeanTreeModel>();
for (Iterator<ModelData> it = parentFolder.getChildren().iterator(); it.hasNext();) {
childrenList.add((GPBeanTreeModel) it.next());
}
tree.getStore().insert(parentFolder, childrenList, 0,
true);
visitorDisplay.enableCheckedComponent(parentFolder);
parentFolder.setLoading(false);
parentFolder.setLoaded(true);
tree.fireEvent(GeoPlatformEvents.GP_NODE_EXPANDED);
tree.refresh(parentFolder);
LayoutManager.get().getStatusMap().setStatus(
"Tree elements loaded successfully.",
EnumSearchStatus.STATUS_SEARCH.toString());
}
});
}
}
});
tree.addListener(Events.Expand, new Listener<TreePanelEvent<ModelData>>() {
@Override
public void handleEvent(TreePanelEvent<ModelData> be) {
if (dragSource.getFiresEvents() && be.getItem() instanceof FolderTreeNode && !((FolderTreeNode) be.getItem()).isLoaded()) {
FolderTreeNode parentFolder = (FolderTreeNode) be.getItem();
tree.setExpanded(parentFolder, true);
dragSource.getDraggable().cancelDrag();
} else if (be.getItem() instanceof FolderTreeNode && ((FolderTreeNode)be.getItem()).isLoaded()) {
tree.fireEvent(GeoPlatformEvents.GP_NODE_EXPANDED);
}
}
});
}
|
diff --git a/htroot/ConfigLanguage_p.java b/htroot/ConfigLanguage_p.java
index ab4c41dba..94981575d 100644
--- a/htroot/ConfigLanguage_p.java
+++ b/htroot/ConfigLanguage_p.java
@@ -1,153 +1,160 @@
// Language_p.java
// -----------------------
// part of YACY
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
//
// This File is contributed by Alexander Schier
// last change: 25.05.2005
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
// You must compile this file with
// javac -classpath .:../Classes Blacklist_p.java
// if the shell's current path is HTROOT
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import de.anomic.data.listManager;
import de.anomic.data.translator;
import de.anomic.http.httpHeader;
import de.anomic.http.httpc;
import de.anomic.net.URL;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.tools.nxTools;
public class ConfigLanguage_p {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
//listManager.switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
String langPath = new File(env.getRootPath(), env.getConfig("langPath", "DATA/LOCALE")).toString();
//Fallback
//prop.put("currentlang", ""); //is done by Translationtemplate
prop.put("status", 0);//nothing
String[] langFiles = listManager.getDirListing(langPath);
if(langFiles == null){
return prop;
}
if (post != null){
//change language
if(post.containsKey("use_button") && (String)post.get("language") != null){
translator.changeLang(env, langPath, (String)post.get("language"));
//delete language file
}else if(post.containsKey("delete")){
File langfile= new File(langPath, (String)post.get("language"));
langfile.delete();
//load language file from URL
} else if (post.containsKey("url")){
String url = (String)post.get("url");
ArrayList langVector;
try{
URL u = new URL(url);
langVector = nxTools.strings(httpc.wget(u, u.getHost(), 6000, null, null, switchboard.remoteProxyConfig), "UTF-8");
}catch(IOException e){
prop.put("status", 1);//unable to get url
prop.put("status_url", url);
return prop;
}
try{
Iterator it = langVector.iterator();
File langFile = new File(langPath, url.substring(url.lastIndexOf("/"), url.length()));
BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(langFile)));
while(it.hasNext()){
bw.write(it.next() + "\n");
}
bw.close();
}catch(IOException e){
prop.put("status", 2);//error saving the language file
return prop;
}
if(post.containsKey("use_lang") && ((String)post.get("use_lang")).equals("on")){
translator.changeLang(env, langPath, url.substring(url.lastIndexOf("/"), url.length()));
}
}
}
//reread language files
langFiles = listManager.getDirListing(langPath);
int i;
HashMap langNames = translator.langMap(env);
String langKey, langName;
//virtual entry
prop.put("langlist_0_file", "default");
prop.put("langlist_0_name", ((langNames.get("default") == null) ? "default" : (String) langNames.get("default")));
+ prop.put("langlist_0_selected", "selected");
for(i=0;i<= langFiles.length-1 ;i++){
if(langFiles[i].endsWith(".lng")){
//+1 because of the virtual entry "default" at top
langKey = langFiles[i].substring(0, langFiles[i].length() -4);
langName = (String) langNames.get(langKey);
prop.put("langlist_"+(i+1)+"_file", langFiles[i]);
prop.put("langlist_"+(i+1)+"_name", ((langName == null) ? langKey : langName));
+ if(env.getConfig("htLocaleSelection", "default").equals(langKey)) {
+ prop.put("langlist_"+(i+1)+"_selected", "selected");
+ prop.put("langlist_0_selected", " "); // reset Default
+ } else {
+ prop.put("langlist_"+(i+1)+"_selected", " ");
+ }
}
}
prop.put("langlist", (i+1));
//is done by Translationtemplate
//langName = (String) langNames.get(env.getConfig("htLocaleSelection", "default"));
//prop.put("currentlang", ((langName == null) ? "default" : langName));
return prop;
}
}
| false | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
//listManager.switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
String langPath = new File(env.getRootPath(), env.getConfig("langPath", "DATA/LOCALE")).toString();
//Fallback
//prop.put("currentlang", ""); //is done by Translationtemplate
prop.put("status", 0);//nothing
String[] langFiles = listManager.getDirListing(langPath);
if(langFiles == null){
return prop;
}
if (post != null){
//change language
if(post.containsKey("use_button") && (String)post.get("language") != null){
translator.changeLang(env, langPath, (String)post.get("language"));
//delete language file
}else if(post.containsKey("delete")){
File langfile= new File(langPath, (String)post.get("language"));
langfile.delete();
//load language file from URL
} else if (post.containsKey("url")){
String url = (String)post.get("url");
ArrayList langVector;
try{
URL u = new URL(url);
langVector = nxTools.strings(httpc.wget(u, u.getHost(), 6000, null, null, switchboard.remoteProxyConfig), "UTF-8");
}catch(IOException e){
prop.put("status", 1);//unable to get url
prop.put("status_url", url);
return prop;
}
try{
Iterator it = langVector.iterator();
File langFile = new File(langPath, url.substring(url.lastIndexOf("/"), url.length()));
BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(langFile)));
while(it.hasNext()){
bw.write(it.next() + "\n");
}
bw.close();
}catch(IOException e){
prop.put("status", 2);//error saving the language file
return prop;
}
if(post.containsKey("use_lang") && ((String)post.get("use_lang")).equals("on")){
translator.changeLang(env, langPath, url.substring(url.lastIndexOf("/"), url.length()));
}
}
}
//reread language files
langFiles = listManager.getDirListing(langPath);
int i;
HashMap langNames = translator.langMap(env);
String langKey, langName;
//virtual entry
prop.put("langlist_0_file", "default");
prop.put("langlist_0_name", ((langNames.get("default") == null) ? "default" : (String) langNames.get("default")));
for(i=0;i<= langFiles.length-1 ;i++){
if(langFiles[i].endsWith(".lng")){
//+1 because of the virtual entry "default" at top
langKey = langFiles[i].substring(0, langFiles[i].length() -4);
langName = (String) langNames.get(langKey);
prop.put("langlist_"+(i+1)+"_file", langFiles[i]);
prop.put("langlist_"+(i+1)+"_name", ((langName == null) ? langKey : langName));
}
}
prop.put("langlist", (i+1));
//is done by Translationtemplate
//langName = (String) langNames.get(env.getConfig("htLocaleSelection", "default"));
//prop.put("currentlang", ((langName == null) ? "default" : langName));
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
//listManager.switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
String langPath = new File(env.getRootPath(), env.getConfig("langPath", "DATA/LOCALE")).toString();
//Fallback
//prop.put("currentlang", ""); //is done by Translationtemplate
prop.put("status", 0);//nothing
String[] langFiles = listManager.getDirListing(langPath);
if(langFiles == null){
return prop;
}
if (post != null){
//change language
if(post.containsKey("use_button") && (String)post.get("language") != null){
translator.changeLang(env, langPath, (String)post.get("language"));
//delete language file
}else if(post.containsKey("delete")){
File langfile= new File(langPath, (String)post.get("language"));
langfile.delete();
//load language file from URL
} else if (post.containsKey("url")){
String url = (String)post.get("url");
ArrayList langVector;
try{
URL u = new URL(url);
langVector = nxTools.strings(httpc.wget(u, u.getHost(), 6000, null, null, switchboard.remoteProxyConfig), "UTF-8");
}catch(IOException e){
prop.put("status", 1);//unable to get url
prop.put("status_url", url);
return prop;
}
try{
Iterator it = langVector.iterator();
File langFile = new File(langPath, url.substring(url.lastIndexOf("/"), url.length()));
BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(langFile)));
while(it.hasNext()){
bw.write(it.next() + "\n");
}
bw.close();
}catch(IOException e){
prop.put("status", 2);//error saving the language file
return prop;
}
if(post.containsKey("use_lang") && ((String)post.get("use_lang")).equals("on")){
translator.changeLang(env, langPath, url.substring(url.lastIndexOf("/"), url.length()));
}
}
}
//reread language files
langFiles = listManager.getDirListing(langPath);
int i;
HashMap langNames = translator.langMap(env);
String langKey, langName;
//virtual entry
prop.put("langlist_0_file", "default");
prop.put("langlist_0_name", ((langNames.get("default") == null) ? "default" : (String) langNames.get("default")));
prop.put("langlist_0_selected", "selected");
for(i=0;i<= langFiles.length-1 ;i++){
if(langFiles[i].endsWith(".lng")){
//+1 because of the virtual entry "default" at top
langKey = langFiles[i].substring(0, langFiles[i].length() -4);
langName = (String) langNames.get(langKey);
prop.put("langlist_"+(i+1)+"_file", langFiles[i]);
prop.put("langlist_"+(i+1)+"_name", ((langName == null) ? langKey : langName));
if(env.getConfig("htLocaleSelection", "default").equals(langKey)) {
prop.put("langlist_"+(i+1)+"_selected", "selected");
prop.put("langlist_0_selected", " "); // reset Default
} else {
prop.put("langlist_"+(i+1)+"_selected", " ");
}
}
}
prop.put("langlist", (i+1));
//is done by Translationtemplate
//langName = (String) langNames.get(env.getConfig("htLocaleSelection", "default"));
//prop.put("currentlang", ((langName == null) ? "default" : langName));
return prop;
}
|
diff --git a/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/config/TwitterSendingMessageHandlerParser.java b/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/config/TwitterSendingMessageHandlerParser.java
index fb900b34cf..196e2622fb 100644
--- a/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/config/TwitterSendingMessageHandlerParser.java
+++ b/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/config/TwitterSendingMessageHandlerParser.java
@@ -1,53 +1,53 @@
/*
* Copyright 2002-2010 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.integration.twitter.config;
import static org.springframework.integration.twitter.config.TwitterNamespaceHandler.BASE_PACKAGE;
import org.w3c.dom.Element;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.integration.config.xml.AbstractOutboundChannelAdapterParser;
import org.springframework.integration.config.xml.IntegrationNamespaceUtils;
/**
* Parser for all outbound Twitter adapters
*
* @author Josh Long
* @author Oleg Zhurakousky
* @since 2.0
*/
public class TwitterSendingMessageHandlerParser extends AbstractOutboundChannelAdapterParser {
@Override
protected AbstractBeanDefinition parseConsumer(Element element, ParserContext parserContext) {
String elementName = element.getLocalName().trim();
String className = null;
if ("outbound-update-channel-adapter".equals(elementName)) {
- className = BASE_PACKAGE + ".outbound.OutboundTimelineUpdateMessageHandler";
+ className = BASE_PACKAGE + ".outbound.TimelineUpdateSendingMessageHandler";
}
else if ("outbound-dm-channel-adapter".equals(elementName)) {
- className = BASE_PACKAGE + ".outbound.OutboundDirectMessageMessageHandler";
+ className = BASE_PACKAGE + ".outbound.DirectMessageSendingMessageHandler";
}
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(className);
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "twitter-connection", "configuration");
return builder.getBeanDefinition();
}
}
| false | true | protected AbstractBeanDefinition parseConsumer(Element element, ParserContext parserContext) {
String elementName = element.getLocalName().trim();
String className = null;
if ("outbound-update-channel-adapter".equals(elementName)) {
className = BASE_PACKAGE + ".outbound.OutboundTimelineUpdateMessageHandler";
}
else if ("outbound-dm-channel-adapter".equals(elementName)) {
className = BASE_PACKAGE + ".outbound.OutboundDirectMessageMessageHandler";
}
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(className);
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "twitter-connection", "configuration");
return builder.getBeanDefinition();
}
| protected AbstractBeanDefinition parseConsumer(Element element, ParserContext parserContext) {
String elementName = element.getLocalName().trim();
String className = null;
if ("outbound-update-channel-adapter".equals(elementName)) {
className = BASE_PACKAGE + ".outbound.TimelineUpdateSendingMessageHandler";
}
else if ("outbound-dm-channel-adapter".equals(elementName)) {
className = BASE_PACKAGE + ".outbound.DirectMessageSendingMessageHandler";
}
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(className);
IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "twitter-connection", "configuration");
return builder.getBeanDefinition();
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/impl/InputConnectorImpl.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/impl/InputConnectorImpl.java
index 0ff5a02af..887331439 100644
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/impl/InputConnectorImpl.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/impl/InputConnectorImpl.java
@@ -1,208 +1,211 @@
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.wso2.developerstudio.eclipse.gmf.esb.impl;
import java.util.Collection;
import java.util.Iterator;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.wso2.developerstudio.eclipse.gmf.esb.AggregateMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.EndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbLink;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.InputConnector;
import org.wso2.developerstudio.eclipse.gmf.esb.OutputConnector;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbLink;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Input Connector</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.impl.InputConnectorImpl#getIncomingLinks <em>Incoming Links</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public abstract class InputConnectorImpl extends EsbConnectorImpl implements InputConnector {
/**
* The cached value of the '{@link #getIncomingLinks() <em>Incoming Links</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIncomingLinks()
* @generated
* @ordered
*/
protected EList<EsbLink> incomingLinks;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected InputConnectorImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return EsbPackage.Literals.INPUT_CONNECTOR;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<EsbLink> getIncomingLinks() {
if (incomingLinks == null) {
incomingLinks = new EObjectWithInverseResolvingEList<EsbLink>(EsbLink.class, this, EsbPackage.INPUT_CONNECTOR__INCOMING_LINKS, EsbPackage.ESB_LINK__TARGET);
}
return incomingLinks;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public boolean shouldConnect(OutputConnector sourceEnd) {
EObject container = sourceEnd.eContainer();
if (this.eContainer.equals(container)) {
return false;
} else if(sourceEnd.eContainer() instanceof EndPoint){
+ if(this.eContainer instanceof EndPoint){
+ return false;
+ }
if((getIncomingLinks().size() !=0) && (getIncomingLinks().get(0).getSource().eContainer() instanceof EndPoint)){
if(sourceEnd.equals(getIncomingLinks().get(0).getSource())){
/* Avoid connecting same nodes multiple times */
return false;
}
return true;
}
} else if(this.eContainer instanceof EndPoint){
for (Iterator<EsbLink> i = getIncomingLinks().iterator(); i.hasNext();){
if(i.next().getSource().equals(sourceEnd)){
/* Avoid connecting same nodes multiple times */
return false;
}
}
return true;
}
// By default we allow only one incoming connection from any source.
return getIncomingLinks().isEmpty();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case EsbPackage.INPUT_CONNECTOR__INCOMING_LINKS:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getIncomingLinks()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case EsbPackage.INPUT_CONNECTOR__INCOMING_LINKS:
return ((InternalEList<?>)getIncomingLinks()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case EsbPackage.INPUT_CONNECTOR__INCOMING_LINKS:
return getIncomingLinks();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case EsbPackage.INPUT_CONNECTOR__INCOMING_LINKS:
getIncomingLinks().clear();
getIncomingLinks().addAll((Collection<? extends EsbLink>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case EsbPackage.INPUT_CONNECTOR__INCOMING_LINKS:
getIncomingLinks().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case EsbPackage.INPUT_CONNECTOR__INCOMING_LINKS:
return incomingLinks != null && !incomingLinks.isEmpty();
}
return super.eIsSet(featureID);
}
} //InputConnectorImpl
| true | true | public boolean shouldConnect(OutputConnector sourceEnd) {
EObject container = sourceEnd.eContainer();
if (this.eContainer.equals(container)) {
return false;
} else if(sourceEnd.eContainer() instanceof EndPoint){
if((getIncomingLinks().size() !=0) && (getIncomingLinks().get(0).getSource().eContainer() instanceof EndPoint)){
if(sourceEnd.equals(getIncomingLinks().get(0).getSource())){
/* Avoid connecting same nodes multiple times */
return false;
}
return true;
}
} else if(this.eContainer instanceof EndPoint){
for (Iterator<EsbLink> i = getIncomingLinks().iterator(); i.hasNext();){
if(i.next().getSource().equals(sourceEnd)){
/* Avoid connecting same nodes multiple times */
return false;
}
}
return true;
}
// By default we allow only one incoming connection from any source.
return getIncomingLinks().isEmpty();
}
| public boolean shouldConnect(OutputConnector sourceEnd) {
EObject container = sourceEnd.eContainer();
if (this.eContainer.equals(container)) {
return false;
} else if(sourceEnd.eContainer() instanceof EndPoint){
if(this.eContainer instanceof EndPoint){
return false;
}
if((getIncomingLinks().size() !=0) && (getIncomingLinks().get(0).getSource().eContainer() instanceof EndPoint)){
if(sourceEnd.equals(getIncomingLinks().get(0).getSource())){
/* Avoid connecting same nodes multiple times */
return false;
}
return true;
}
} else if(this.eContainer instanceof EndPoint){
for (Iterator<EsbLink> i = getIncomingLinks().iterator(); i.hasNext();){
if(i.next().getSource().equals(sourceEnd)){
/* Avoid connecting same nodes multiple times */
return false;
}
}
return true;
}
// By default we allow only one incoming connection from any source.
return getIncomingLinks().isEmpty();
}
|
diff --git a/src/duke/cs/fall2012/catseverywhere/CustomLocationListener.java b/src/duke/cs/fall2012/catseverywhere/CustomLocationListener.java
index 0f7975e..a83b70a 100644
--- a/src/duke/cs/fall2012/catseverywhere/CustomLocationListener.java
+++ b/src/duke/cs/fall2012/catseverywhere/CustomLocationListener.java
@@ -1,59 +1,59 @@
package duke.cs.fall2012.catseverywhere;
import com.google.android.maps.GeoPoint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.Toast;
public class CustomLocationListener implements LocationListener {
private Context myParentContext;
private double myLatitude;
private double myLongitude;
private GeoPoint myGeoPoint;
public CustomLocationListener(Context context)
{
myParentContext = context;
myGeoPoint = new GeoPoint(0,0);
}
@Override
public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
String displayMessage = "Current location: Lat: " + myLatitude +
"\nLong: " + myLongitude;
- Toast.makeText(myParentContext, displayMessage, Toast.LENGTH_SHORT).show();
+ //Toast.makeText(myParentContext, displayMessage, Toast.LENGTH_SHORT).show();
myGeoPoint = new GeoPoint( (int) (myLatitude * 1E6), (int) (myLongitude * 1E6));
animateToCurrLoc();
}
private void animateToCurrLoc() {
GoogleMapsActivity.animateToLoc(myGeoPoint);
}
public GeoPoint getCurrentGeoP()
{
return myGeoPoint;
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(myParentContext,"GPS Disabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(myParentContext,"GPS Enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
| true | true | public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
String displayMessage = "Current location: Lat: " + myLatitude +
"\nLong: " + myLongitude;
Toast.makeText(myParentContext, displayMessage, Toast.LENGTH_SHORT).show();
myGeoPoint = new GeoPoint( (int) (myLatitude * 1E6), (int) (myLongitude * 1E6));
animateToCurrLoc();
}
| public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
String displayMessage = "Current location: Lat: " + myLatitude +
"\nLong: " + myLongitude;
//Toast.makeText(myParentContext, displayMessage, Toast.LENGTH_SHORT).show();
myGeoPoint = new GeoPoint( (int) (myLatitude * 1E6), (int) (myLongitude * 1E6));
animateToCurrLoc();
}
|
diff --git a/src/library/tests/TimeTest.java b/src/library/tests/TimeTest.java
index 593506f..0c9a640 100644
--- a/src/library/tests/TimeTest.java
+++ b/src/library/tests/TimeTest.java
@@ -1,67 +1,67 @@
package library.tests;
import static org.junit.Assert.*;
import library.Time;
import org.junit.Before;
import org.junit.Test;
/**
* // -------------------------------------------------------------------------
/**
* This class is for testing the Time class and its methods
*
* @author cmbuck
* @version Apr 15, 2012
*/
public class TimeTest
{
private Time astart, aend, bstart, bend, cstart, cend, dstart, dend;
/**
* This method sets up the testing environment
*/
@Before
public void setUp()
{
astart = new Time(2, 30);
aend = new Time(3, 45);
bstart = new Time(3, 30);
bend = new Time(4, 45);
cstart = new Time(2, 30);
cend = new Time(3, 45);
dstart = new Time(4, 0);
dend = new Time (5, 15);
}
/**
* This method tests the isOverlap() method
*/
@Test
public void testIsOverlap()
{
assertTrue(Time.isOverlap(astart, aend, bstart, bend));
assertTrue(Time.isOverlap(bstart, bend, astart, aend));
assertFalse(Time.isOverlap(cstart, cend, dstart, dend));
- assertTrue(astart.isOverlap(astart, aend, cstart, cend));
- assertTrue(astart.isOverlap(dstart, dend, bstart, bend));
- assertFalse(astart.isOverlap(dstart, dend, astart, aend));
- assertFalse(astart.isOverlap(astart, aend, dstart, dend));
+ assertTrue(Time.isOverlap(astart, aend, cstart, cend));
+ assertTrue(Time.isOverlap(dstart, dend, bstart, bend));
+ assertFalse(Time.isOverlap(dstart, dend, astart, aend));
+ assertFalse(Time.isOverlap(astart, aend, dstart, dend));
//tests Chris added
assertFalse(Time.isOverlap(new Time(8,00), new Time(8,50),
new Time(9,05), new Time(9,55)));
assertFalse(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(8,50))); //swap above
assertTrue(Time.isOverlap(new Time(8,00), new Time(9,30),
new Time(9,05), new Time(9,55)));
assertTrue(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(9,30))); //swap above
assertTrue(Time.isOverlap(new Time(8,00), new Time(11,00),
new Time(9,05), new Time(9,55)));
assertTrue(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(11,00))); //swap above
}
}
| true | true | public void testIsOverlap()
{
assertTrue(Time.isOverlap(astart, aend, bstart, bend));
assertTrue(Time.isOverlap(bstart, bend, astart, aend));
assertFalse(Time.isOverlap(cstart, cend, dstart, dend));
assertTrue(astart.isOverlap(astart, aend, cstart, cend));
assertTrue(astart.isOverlap(dstart, dend, bstart, bend));
assertFalse(astart.isOverlap(dstart, dend, astart, aend));
assertFalse(astart.isOverlap(astart, aend, dstart, dend));
//tests Chris added
assertFalse(Time.isOverlap(new Time(8,00), new Time(8,50),
new Time(9,05), new Time(9,55)));
assertFalse(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(8,50))); //swap above
assertTrue(Time.isOverlap(new Time(8,00), new Time(9,30),
new Time(9,05), new Time(9,55)));
assertTrue(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(9,30))); //swap above
assertTrue(Time.isOverlap(new Time(8,00), new Time(11,00),
new Time(9,05), new Time(9,55)));
assertTrue(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(11,00))); //swap above
}
| public void testIsOverlap()
{
assertTrue(Time.isOverlap(astart, aend, bstart, bend));
assertTrue(Time.isOverlap(bstart, bend, astart, aend));
assertFalse(Time.isOverlap(cstart, cend, dstart, dend));
assertTrue(Time.isOverlap(astart, aend, cstart, cend));
assertTrue(Time.isOverlap(dstart, dend, bstart, bend));
assertFalse(Time.isOverlap(dstart, dend, astart, aend));
assertFalse(Time.isOverlap(astart, aend, dstart, dend));
//tests Chris added
assertFalse(Time.isOverlap(new Time(8,00), new Time(8,50),
new Time(9,05), new Time(9,55)));
assertFalse(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(8,50))); //swap above
assertTrue(Time.isOverlap(new Time(8,00), new Time(9,30),
new Time(9,05), new Time(9,55)));
assertTrue(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(9,30))); //swap above
assertTrue(Time.isOverlap(new Time(8,00), new Time(11,00),
new Time(9,05), new Time(9,55)));
assertTrue(Time.isOverlap(new Time(9,05), new Time(9,55),
new Time(8,00), new Time(11,00))); //swap above
}
|
diff --git a/src/main/java/org/nnsoft/guice/rocoto/configuration/ConfigurationModule.java b/src/main/java/org/nnsoft/guice/rocoto/configuration/ConfigurationModule.java
index a6fdf47..30bcd61 100644
--- a/src/main/java/org/nnsoft/guice/rocoto/configuration/ConfigurationModule.java
+++ b/src/main/java/org/nnsoft/guice/rocoto/configuration/ConfigurationModule.java
@@ -1,290 +1,290 @@
/*
* Copyright 2009-2011 The 99 Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nnsoft.guice.rocoto.configuration;
import static com.google.inject.internal.util.$Preconditions.checkNotNull;
import static com.google.inject.internal.util.$Preconditions.checkState;
import static com.google.inject.name.Names.named;
import static java.lang.String.format;
import static org.nnsoft.guice.rocoto.configuration.PropertiesIterator.newPropertiesIterator;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.nnsoft.guice.rocoto.configuration.binder.PropertyValueBindingBuilder;
import org.nnsoft.guice.rocoto.configuration.binder.XMLPropertiesFormatBindingBuilder;
import org.nnsoft.guice.rocoto.configuration.resolver.PropertiesResolverProvider;
import com.google.inject.AbstractModule;
import com.google.inject.ProvisionException;
import com.google.inject.binder.ConstantBindingBuilder;
/**
* The ConfigurationModule simplifies the task of loading configurations in Google Guice.
*/
public abstract class ConfigurationModule
extends AbstractModule
{
/**
* The environment variable prefix, {@code env.}
*/
private static final String ENV_PREFIX = "env.";
/**
* The {@code classpath} URL scheme constant
*/
private static final String CLASSPATH_SCHEME = "classpath";
private List<PropertiesURLReader> readers;
@Override
protected final void configure()
{
- checkState( readers != null, "Re-entry not allowed" );
+ checkState( readers == null, "Re-entry not allowed" );
readers = new LinkedList<PropertiesURLReader>();
bindConfigurations();
try
{
for ( PropertiesURLReader reader : readers )
{
try
{
bindProperties( reader.readConfiguration() );
}
catch ( Exception e )
{
addError( "An error occurred while reading properties from '%s': %s", reader.getUrl(),
e.getMessage() );
}
}
}
finally
{
readers = null;
}
}
/**
*
*/
protected abstract void bindConfigurations();
/**
* Binds to a property with the given name.
*
* @param name The property name
* @return The property value binder
*/
protected PropertyValueBindingBuilder bindProperty( final String name )
{
checkNotNull( name, "Property name cannot be null." );
return new PropertyValueBindingBuilder()
{
public void toValue( final String value )
{
checkNotNull( value, "Null value not admitted for property '%s's", name );
ConstantBindingBuilder builder = bindConstant().annotatedWith( named( name ) );
PropertiesResolverProvider formatter = new PropertiesResolverProvider( value );
if ( formatter.containsKeys() )
{
requestInjection( formatter );
builder.to( formatter.get() );
}
else
{
builder.to( value );
}
}
};
}
/**
*
* @param properties
* @return
*/
protected void bindProperties( Properties properties )
{
checkNotNull( properties, "Parameter 'properties' must be not null" );
bindProperties( newPropertiesIterator( properties ) );
}
/**
*
* @param properties
*/
protected void bindProperties( Iterable<Entry<String, String>> properties )
{
checkNotNull( properties, "Parameter 'properties' must be not null" );
bindProperties( properties.iterator() );
}
/**
*
* @param properties
*/
protected void bindProperties( Iterator<Entry<String, String>> properties )
{
checkNotNull( properties, "Parameter 'properties' must be not null" );
while ( properties.hasNext() )
{
Entry<String, String> property = properties.next();
bindProperty( property.getKey() ).toValue( property.getValue() );
}
}
/**
* Add the Environment Variables properties, prefixed by {@code env.}.
*/
protected void bindSystemProperties()
{
bindProperties( System.getProperties() );
}
/**
*
* @param properties
* @return
*/
protected void bindProperties( Map<String, String> properties )
{
checkNotNull( properties, "Parameter 'properties' must be not null" );
bindProperties( newPropertiesIterator( properties ) );
}
/**
* Add the System Variables properties.
*/
protected void bindEnvironmentVariables()
{
bindProperties( newPropertiesIterator( ENV_PREFIX, System.getenv() ) );
}
/**
*
*
* @param propertiesResource
* @return
*/
protected XMLPropertiesFormatBindingBuilder bindProperties( final File propertiesResource )
{
checkNotNull( propertiesResource, "Parameter 'propertiesResource' must be not null" );
return bindProperties( propertiesResource.toURI() );
}
/**
*
*
* @param propertiesResource
* @return
*/
protected XMLPropertiesFormatBindingBuilder bindProperties( final URI propertiesResource )
{
checkNotNull( propertiesResource, "Parameter 'propertiesResource' must be not null" );
if ( CLASSPATH_SCHEME.equals( propertiesResource.getScheme() ) )
{
String path = propertiesResource.getPath();
if ( propertiesResource.getHost() != null )
{
path = propertiesResource.getHost() + path;
}
return bindProperties( path );
}
try
{
return bindProperties( propertiesResource.toURL() );
}
catch ( MalformedURLException e )
{
throw new ProvisionException( format( "URI '%s' not supported: %s", propertiesResource, e.getMessage() ) );
}
}
/**
*
* @param classPathResource
* @return
*/
protected XMLPropertiesFormatBindingBuilder bindProperties( final String classPathResource )
{
return bindProperties( classPathResource, getClass().getClassLoader() );
}
/**
*
* @param classPathResource
* @param classLoader
* @return
*/
protected XMLPropertiesFormatBindingBuilder bindProperties( final String classPathResource,
final ClassLoader classLoader )
{
checkNotNull( classPathResource, "Parameter 'classPathResource' must be not null" );
checkNotNull( classLoader, "Parameter 'classLoader' must be not null" );
String resourceURL = classPathResource;
if ( '/' == classPathResource.charAt( 0 ) )
{
resourceURL = classPathResource.substring( 1 );
}
URL url = classLoader.getResource( resourceURL );
checkNotNull( url,
"ClassPath resource '%s' not found, make sure it is in the ClassPath or you're using the right ClassLoader",
classPathResource );
return bindProperties( url );
}
/**
*
* @param propertiesResource
* @return
*/
protected XMLPropertiesFormatBindingBuilder bindProperties( final URL propertiesResource )
{
checkNotNull( propertiesResource, "parameter 'propertiesResource' must not be null" );
PropertiesURLReader reader = new PropertiesURLReader( propertiesResource );
readers.add( reader );
return reader;
}
}
| true | true | protected final void configure()
{
checkState( readers != null, "Re-entry not allowed" );
readers = new LinkedList<PropertiesURLReader>();
bindConfigurations();
try
{
for ( PropertiesURLReader reader : readers )
{
try
{
bindProperties( reader.readConfiguration() );
}
catch ( Exception e )
{
addError( "An error occurred while reading properties from '%s': %s", reader.getUrl(),
e.getMessage() );
}
}
}
finally
{
readers = null;
}
}
| protected final void configure()
{
checkState( readers == null, "Re-entry not allowed" );
readers = new LinkedList<PropertiesURLReader>();
bindConfigurations();
try
{
for ( PropertiesURLReader reader : readers )
{
try
{
bindProperties( reader.readConfiguration() );
}
catch ( Exception e )
{
addError( "An error occurred while reading properties from '%s': %s", reader.getUrl(),
e.getMessage() );
}
}
}
finally
{
readers = null;
}
}
|
diff --git a/src/model/Processor.java b/src/model/Processor.java
index b517a82..3880c14 100644
--- a/src/model/Processor.java
+++ b/src/model/Processor.java
@@ -1,77 +1,78 @@
/**
*
*/
package model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import interfaces.IALU;
import interfaces.IFetchUnit;
import interfaces.IInstruction;
import interfaces.IIssueUnit;
import interfaces.IMemoryAccess;
import interfaces.IProcessor;
import interfaces.IWriteBack;
/**
* @author Chester
*
*/
public class Processor extends AbstractModel implements IProcessor {
private List<IALU> alus;
private IFetchUnit fetch;
private IIssueUnit issue;
private IMemoryAccess memory;
private IWriteBack writeBack;
private Memory memoryBanks;
private Registry registers;
private Map<String, Integer> cycleMapping;
private List<IInstruction> instructions;
private List<IMemoryAccess> memories;
public Processor(int aluCount, Map<String, Integer> opCycles, List<IInstruction> instrs)
{
alus = new ArrayList<IALU>(aluCount);
//memories = new ArrayList<IMemoryAccess>(memCount); //This should probably also receive a memCount variable, so the processor knows how many mems it has
+ memories = new ArrayList<IMemoryAccess>(1);
for(int i = 0; i < aluCount; i++)
{
alus.add(new ALU(i, 1, opCycles));
}
registers = new Registry();
memoryBanks = new Memory(1000000);
instructions = instrs;
fetch = new FetchUnit(instructions, issue, registers);
memory = new MemoryAccess(memoryBanks, 1, opCycles);
memories.add(memory);
issue = new Issue(alus, memories, registers);
writeBack = new WriteBack(memory, alus, registers);
}
@Override
public Registry getRegistry() {
return registers;
}
@Override
public void Cycle()
{
// We cycle from the end of the pipeline towards the front.
writeBack.Cycle();
for(IALU alu : alus)
{
alu.Cycle();
}
memory.Cycle();
issue.Cycle();
fetch.Cycle();
}
}
| true | true | public Processor(int aluCount, Map<String, Integer> opCycles, List<IInstruction> instrs)
{
alus = new ArrayList<IALU>(aluCount);
//memories = new ArrayList<IMemoryAccess>(memCount); //This should probably also receive a memCount variable, so the processor knows how many mems it has
for(int i = 0; i < aluCount; i++)
{
alus.add(new ALU(i, 1, opCycles));
}
registers = new Registry();
memoryBanks = new Memory(1000000);
instructions = instrs;
fetch = new FetchUnit(instructions, issue, registers);
memory = new MemoryAccess(memoryBanks, 1, opCycles);
memories.add(memory);
issue = new Issue(alus, memories, registers);
writeBack = new WriteBack(memory, alus, registers);
}
| public Processor(int aluCount, Map<String, Integer> opCycles, List<IInstruction> instrs)
{
alus = new ArrayList<IALU>(aluCount);
//memories = new ArrayList<IMemoryAccess>(memCount); //This should probably also receive a memCount variable, so the processor knows how many mems it has
memories = new ArrayList<IMemoryAccess>(1);
for(int i = 0; i < aluCount; i++)
{
alus.add(new ALU(i, 1, opCycles));
}
registers = new Registry();
memoryBanks = new Memory(1000000);
instructions = instrs;
fetch = new FetchUnit(instructions, issue, registers);
memory = new MemoryAccess(memoryBanks, 1, opCycles);
memories.add(memory);
issue = new Issue(alus, memories, registers);
writeBack = new WriteBack(memory, alus, registers);
}
|
diff --git a/src/main/java/ru/urbancamper/audiobookmarker/text/BitapSubtextFinding.java b/src/main/java/ru/urbancamper/audiobookmarker/text/BitapSubtextFinding.java
index ce9af82..f284d64 100644
--- a/src/main/java/ru/urbancamper/audiobookmarker/text/BitapSubtextFinding.java
+++ b/src/main/java/ru/urbancamper/audiobookmarker/text/BitapSubtextFinding.java
@@ -1,231 +1,232 @@
/*
* This class is supposed to find snippet of text in full text pattern
* by means of Bitap algorithm
*/
package ru.urbancamper.audiobookmarker.text;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.TreeMap;
/**
*
* @author pozpl
*/
public class BitapSubtextFinding {
public BitSet fillBitSetFromWordsNumberArray(Integer[] text, Integer wordToMark){
BitSet textVectorBitSet = new BitSet(text.length);
for(Integer wordsCounter = 0; wordsCounter < text.length; wordsCounter++){
if(text[wordsCounter] == wordToMark){
textVectorBitSet.set(wordsCounter);
}else{
textVectorBitSet.set(wordsCounter, false);
}
}
return textVectorBitSet;
}
@Deprecated
public Byte[] fillByteArrayFromWordsNumbersArray(Integer[] text, Integer wordTomark){
Integer bytesArrayLength = text.length / 8;
bytesArrayLength = text.length % 8 == 0 ? bytesArrayLength : bytesArrayLength + 1;
Byte[] byteArray = new Byte[bytesArrayLength];
Byte byteOne = 1;
for(Integer bytesCounter = 0; bytesCounter < bytesArrayLength; bytesCounter++){
Integer textArrayIndex = bytesCounter * 8;
byteArray[bytesCounter] = 0;
for(Integer bitCounter = 0; bitCounter < 8; bitCounter++){
if(text.length >= textArrayIndex + bitCounter + 1){
if ( text[textArrayIndex + bitCounter] == wordTomark){
byteArray[bytesCounter] = (byte)(byteArray[bytesCounter] | byteOne << bitCounter);
}
}
}
}
return byteArray;
}
// /**
// * Shift bytes array on n positions to the right
// * @param bytes
// * @param rightShifts
// */
// public static void shiftBitsRight(Byte[] bytes, final Integer rightShifts) {
// assert rightShifts >= 1 && rightShifts <= 7;
//
// final Integer leftShifts = 8 - rightShifts;
//
// Byte previousByte = bytes[0]; // keep the byte before modification
// bytes[0] = (byte) (((bytes[0] & 0xff) >> rightShifts) | ((bytes[bytes.length - 1] & 0xff) << leftShifts));
// for (Integer i = 1; i < bytes.length; i++) {
// Byte tmp = bytes[i];
// bytes[i] = (byte) (((bytes[i] & 0xff) >> rightShifts) | ((previousByte & 0xff) << leftShifts));
// previousByte = tmp;
// }
// }
/**
* Shifts bytes array for one bit. Last bit from previous byte
* is tranmitted to current
* @param bytes
* @return Shifted vector of bytes
*/
@Deprecated
private Byte[] shiftBitsLeft(Byte[] bytes) {
Byte previousBit = 0;
Byte currentBit = 0;
previousBit = (byte)(bytes[0] & (1 << 7));
for(Integer bytesCounter = 0; bytesCounter < bytes.length; bytesCounter++){
currentBit = (byte)(bytes[bytesCounter] & (1 << 7));
bytes[bytesCounter] = (byte)(bytes[bytesCounter] << 1);
if(bytesCounter > 0){
bytes[bytesCounter] = (byte)(bytes[bytesCounter] | previousBit);
}
previousBit = (byte)((currentBit >> 7) & 1);
}
return bytes;
}
/**
* Shifts Bit set for on bit to the left
* @param bitSet
* @return
*/
public BitSet shiftBitSetLeft(BitSet bitSet) {
final long maskOfCarry = 0x8000000000000000L;
long[] aLong = bitSet.toLongArray();
boolean carry = false;
for (int i = 0; i < aLong.length; ++i) {
if (carry) {
carry = ((aLong[i] & maskOfCarry) != 0);
aLong[i] <<= 1;
++aLong[i];
} else {
carry = ((aLong[i] & maskOfCarry) != 0);
aLong[i] <<= 1;
}
}
if (carry) {
long[] tmp = new long[aLong.length + 1];
System.arraycopy(aLong, 0, tmp, 0, aLong.length);
++tmp[aLong.length];
aLong = tmp;
}
return BitSet.valueOf(aLong);
}
@Deprecated
private Byte[] byteArrayAnd(Byte[] firstArray, Byte[] secondArray){
assert firstArray.length == secondArray.length;
Byte[] resultArray = new Byte[firstArray.length];
for(Integer indexCounter = 0; indexCounter < firstArray.length; indexCounter++){
resultArray[indexCounter] = (byte)(firstArray[indexCounter] & secondArray[indexCounter]);
}
return resultArray;
}
/**
* Return the list of indexes where the pattern was found.
*
* The indexes are not exacts because of the addition and deletion : Example
* : the text "aa bb cc" with the pattern "bb" and k=1 will match "
* b","b","bb","b ". and only the index of the first result " b" is added to
* the list even if "bb" have q lower error rate.
*
* @param doc
* @param pattern
* @param k
* @return
*/
public List<Integer> find(Integer[] doc, Integer[] pattern, int k) {
// Range of the alphabet
// 128 is enough if we stay in the ASCII range (0-127)
int alphabetRange = 128;
int firstMatchedText = -1;
// Indexes where the pattern was found
ArrayList<Integer> indexes = new ArrayList<Integer>();
BitSet[] r = new BitSet[k + 1];
// BitSet patternMask = new BitSet(pattern.length);
for (int i = 0; i <= k; i++) {
r[i] = new BitSet();
r[i].set(0);
}
// Example : The mask for the letter 'e' and the pattern "hello" is
// 11101 (0 means this letter is at this place in the pattern)
TreeMap<Integer, BitSet> patternMask = new TreeMap<Integer, BitSet>();
// BitSet[] patternMask = new BitSet[pattern.length];
for (int i = 0; i < pattern.length; ++i) {
if(! patternMask.containsKey(pattern[i])){
BitSet patternMaskForWord = this.fillBitSetFromWordsNumberArray(pattern, pattern[i]);
patternMask.put(pattern[i], patternMaskForWord);
}
}
int i = 0;
while (i < doc.length) {
BitSet textMask = this.fillBitSetFromWordsNumberArray(doc, doc[i]);
BitSet symbolMask = (patternMask.containsKey(doc[i])) ? patternMask.get(doc[i])
:new BitSet();
BitSet old = new BitSet();
BitSet nextOld = new BitSet();
for (int d = 0; d <= k; ++d) {
- BitSet rDShifted = this.shiftBitSetLeft(r[d]);
- rDShifted.and(symbolMask);
+ BitSet rD = (BitSet)(r[d].clone());//this.shiftBitSetLeft(r[d]);
+ rD.and(symbolMask);
+ BitSet rDShifted = this.shiftBitSetLeft(rD);
BitSet ins = (BitSet)(rDShifted.clone());
- BitSet del = (BitSet)(rDShifted.clone());
- BitSet sub = (BitSet)(rDShifted.clone());
+ BitSet del = (BitSet)(rD.clone());
+ BitSet sub = (BitSet)(rD.clone());
ins.or(old);
- BitSet oldShifted = this.shiftBitSetLeft(old);
- sub.or(oldShifted);
- BitSet nextOldShifted = this.shiftBitSetLeft(nextOld);
- del.or(nextOldShifted);
+ sub.or(old);
+ sub = this.shiftBitSetLeft(sub);
+ del.or(nextOld);
+ del = this.shiftBitSetLeft(del);
old = (BitSet)(r[d].clone());
nextOld = (BitSet)(ins.clone());
nextOld.or(sub);
nextOld.or(del);
r[d] = nextOld;
// Three operations of the Levenshtein distance
// long sub = (old | (r[d] & patternMask[doc.charAt(i)])) << 1;
// long ins = old | ((r[d] & patternMask[doc.charAt(i)]) << 1);
// long del = (nextOld | (r[d] & patternMask[doc.charAt(i)])) << 1;
// old = r[d];
// r[d] = sub | ins | del | 1;
// nextOld = r[d];
}
// When r[k] is full of zeros, it means we matched the pattern
// (modulo k errors)
if(r[k].get(pattern.length)){
// if (0 < (r[k] & (1 << pattern.length()))) {
// The pattern "aaa" for the document "bbaaavv" with k=2
// will slide from "bba","baa","aaa","aav","avv"
// Because we allow two errors !
// This test keep only the first one and skip all the others.
// (We can't skip by increasing i otherwise the r[d] will be
// wrong)
if ((firstMatchedText == -1) || (i - firstMatchedText > pattern.length)) {
firstMatchedText = i;
indexes.add(firstMatchedText - pattern.length + 1);
}
}
i++;
}
return indexes;
}
}
| false | true | public List<Integer> find(Integer[] doc, Integer[] pattern, int k) {
// Range of the alphabet
// 128 is enough if we stay in the ASCII range (0-127)
int alphabetRange = 128;
int firstMatchedText = -1;
// Indexes where the pattern was found
ArrayList<Integer> indexes = new ArrayList<Integer>();
BitSet[] r = new BitSet[k + 1];
// BitSet patternMask = new BitSet(pattern.length);
for (int i = 0; i <= k; i++) {
r[i] = new BitSet();
r[i].set(0);
}
// Example : The mask for the letter 'e' and the pattern "hello" is
// 11101 (0 means this letter is at this place in the pattern)
TreeMap<Integer, BitSet> patternMask = new TreeMap<Integer, BitSet>();
// BitSet[] patternMask = new BitSet[pattern.length];
for (int i = 0; i < pattern.length; ++i) {
if(! patternMask.containsKey(pattern[i])){
BitSet patternMaskForWord = this.fillBitSetFromWordsNumberArray(pattern, pattern[i]);
patternMask.put(pattern[i], patternMaskForWord);
}
}
int i = 0;
while (i < doc.length) {
BitSet textMask = this.fillBitSetFromWordsNumberArray(doc, doc[i]);
BitSet symbolMask = (patternMask.containsKey(doc[i])) ? patternMask.get(doc[i])
:new BitSet();
BitSet old = new BitSet();
BitSet nextOld = new BitSet();
for (int d = 0; d <= k; ++d) {
BitSet rDShifted = this.shiftBitSetLeft(r[d]);
rDShifted.and(symbolMask);
BitSet ins = (BitSet)(rDShifted.clone());
BitSet del = (BitSet)(rDShifted.clone());
BitSet sub = (BitSet)(rDShifted.clone());
ins.or(old);
BitSet oldShifted = this.shiftBitSetLeft(old);
sub.or(oldShifted);
BitSet nextOldShifted = this.shiftBitSetLeft(nextOld);
del.or(nextOldShifted);
old = (BitSet)(r[d].clone());
nextOld = (BitSet)(ins.clone());
nextOld.or(sub);
nextOld.or(del);
r[d] = nextOld;
// Three operations of the Levenshtein distance
// long sub = (old | (r[d] & patternMask[doc.charAt(i)])) << 1;
// long ins = old | ((r[d] & patternMask[doc.charAt(i)]) << 1);
// long del = (nextOld | (r[d] & patternMask[doc.charAt(i)])) << 1;
// old = r[d];
// r[d] = sub | ins | del | 1;
// nextOld = r[d];
}
// When r[k] is full of zeros, it means we matched the pattern
// (modulo k errors)
if(r[k].get(pattern.length)){
// if (0 < (r[k] & (1 << pattern.length()))) {
// The pattern "aaa" for the document "bbaaavv" with k=2
// will slide from "bba","baa","aaa","aav","avv"
// Because we allow two errors !
// This test keep only the first one and skip all the others.
// (We can't skip by increasing i otherwise the r[d] will be
// wrong)
if ((firstMatchedText == -1) || (i - firstMatchedText > pattern.length)) {
firstMatchedText = i;
indexes.add(firstMatchedText - pattern.length + 1);
}
}
i++;
}
return indexes;
}
| public List<Integer> find(Integer[] doc, Integer[] pattern, int k) {
// Range of the alphabet
// 128 is enough if we stay in the ASCII range (0-127)
int alphabetRange = 128;
int firstMatchedText = -1;
// Indexes where the pattern was found
ArrayList<Integer> indexes = new ArrayList<Integer>();
BitSet[] r = new BitSet[k + 1];
// BitSet patternMask = new BitSet(pattern.length);
for (int i = 0; i <= k; i++) {
r[i] = new BitSet();
r[i].set(0);
}
// Example : The mask for the letter 'e' and the pattern "hello" is
// 11101 (0 means this letter is at this place in the pattern)
TreeMap<Integer, BitSet> patternMask = new TreeMap<Integer, BitSet>();
// BitSet[] patternMask = new BitSet[pattern.length];
for (int i = 0; i < pattern.length; ++i) {
if(! patternMask.containsKey(pattern[i])){
BitSet patternMaskForWord = this.fillBitSetFromWordsNumberArray(pattern, pattern[i]);
patternMask.put(pattern[i], patternMaskForWord);
}
}
int i = 0;
while (i < doc.length) {
BitSet textMask = this.fillBitSetFromWordsNumberArray(doc, doc[i]);
BitSet symbolMask = (patternMask.containsKey(doc[i])) ? patternMask.get(doc[i])
:new BitSet();
BitSet old = new BitSet();
BitSet nextOld = new BitSet();
for (int d = 0; d <= k; ++d) {
BitSet rD = (BitSet)(r[d].clone());//this.shiftBitSetLeft(r[d]);
rD.and(symbolMask);
BitSet rDShifted = this.shiftBitSetLeft(rD);
BitSet ins = (BitSet)(rDShifted.clone());
BitSet del = (BitSet)(rD.clone());
BitSet sub = (BitSet)(rD.clone());
ins.or(old);
sub.or(old);
sub = this.shiftBitSetLeft(sub);
del.or(nextOld);
del = this.shiftBitSetLeft(del);
old = (BitSet)(r[d].clone());
nextOld = (BitSet)(ins.clone());
nextOld.or(sub);
nextOld.or(del);
r[d] = nextOld;
// Three operations of the Levenshtein distance
// long sub = (old | (r[d] & patternMask[doc.charAt(i)])) << 1;
// long ins = old | ((r[d] & patternMask[doc.charAt(i)]) << 1);
// long del = (nextOld | (r[d] & patternMask[doc.charAt(i)])) << 1;
// old = r[d];
// r[d] = sub | ins | del | 1;
// nextOld = r[d];
}
// When r[k] is full of zeros, it means we matched the pattern
// (modulo k errors)
if(r[k].get(pattern.length)){
// if (0 < (r[k] & (1 << pattern.length()))) {
// The pattern "aaa" for the document "bbaaavv" with k=2
// will slide from "bba","baa","aaa","aav","avv"
// Because we allow two errors !
// This test keep only the first one and skip all the others.
// (We can't skip by increasing i otherwise the r[d] will be
// wrong)
if ((firstMatchedText == -1) || (i - firstMatchedText > pattern.length)) {
firstMatchedText = i;
indexes.add(firstMatchedText - pattern.length + 1);
}
}
i++;
}
return indexes;
}
|
diff --git a/src/jpcsp/util/FileLocator.java b/src/jpcsp/util/FileLocator.java
index b99a9f02..c22975bb 100644
--- a/src/jpcsp/util/FileLocator.java
+++ b/src/jpcsp/util/FileLocator.java
@@ -1,563 +1,572 @@
/*
This file is part of jpcsp.
Jpcsp 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.
Jpcsp 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 Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp.util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;
import jpcsp.Memory;
import jpcsp.HLE.Modules;
import jpcsp.HLE.VFS.ByteArrayVirtualFile;
import jpcsp.HLE.VFS.IVirtualFile;
import jpcsp.HLE.VFS.PartialVirtualFile;
import jpcsp.HLE.VFS.iso.UmdIsoVirtualFile;
import jpcsp.HLE.modules.sceAtrac3plus;
import jpcsp.HLE.modules.sceMpeg;
import jpcsp.HLE.modules150.IoFileMgrForUser.IIoListener;
import jpcsp.filesystems.SeekableDataInput;
import jpcsp.filesystems.umdiso.UmdIsoFile;
import jpcsp.memory.IMemoryReader;
import jpcsp.memory.MemoryReader;
import org.apache.log4j.Logger;
/**
* @author gid15
*
*/
public class FileLocator {
private static Logger log = Logger.getLogger("fileLocator");
private static FileLocator instance;
private static boolean scanAllFileMagicOffsets = true;
private IoListener ioListener;
public static FileLocator getInstance() {
if (instance == null) {
instance = new FileLocator();
}
return instance;
}
private FileLocator() {
ioListener = new IoListener();
Modules.IoFileMgrForUserModule.registerIoListener(ioListener);
}
public void setFileData(SeekableDataInput dataInput, IVirtualFile vFile, int address, long startPosition, int length) {
ioListener.setFileData(dataInput, vFile, address, startPosition, length);
}
public IVirtualFile getVirtualFile(int address, int length, int fileSize, byte[] checkData) {
return ioListener.getVirtualFile(address, length, fileSize, checkData);
}
private static class IoListener implements IIoListener {
private static class ReadInfo {
public int address;
public int size;
public SeekableDataInput dataInput;
public IVirtualFile vFile;
public long position;
public ReadInfo(int address, int size, SeekableDataInput dataInput, IVirtualFile vFile, long position) {
this.address = address;
this.size = size;
this.dataInput = dataInput;
this.vFile = vFile;
this.position = position;
}
@Override
public String toString() {
return String.format("ReadInfo(0x%08X-0x%08X(size=0x%X), position=%d, %s)", address, address + size, size, position, dataInput.toString());
}
}
private HashMap<Integer, ReadInfo> readInfos;
private HashMap<Integer, ReadInfo> readMagics;
private static final int MAGIC_HASH_LENGTH = sceAtrac3plus.ATRAC_HEADER_HASH_LENGTH;
private static final int[] fileMagics = {
sceAtrac3plus.RIFF_MAGIC,
sceMpeg.PSMF_MAGIC
};
public IoListener() {
readInfos = new HashMap<Integer, ReadInfo>();
readMagics = new HashMap<Integer, ReadInfo>();
}
private static boolean memcmp(byte[] data, int address, int length) {
IMemoryReader memoryReader = MemoryReader.getMemoryReader(address, length, 1);
for (int i = 0; i < length; i++) {
if (memoryReader.readNext() != (data[i] & 0xFF)) {
return false;
}
}
return true;
}
private static boolean cmp(byte[] data, byte[] checkData, int length) {
length = Math.min(length, checkData.length);
for (int i = 0; i < length; i++) {
if (data[i] != checkData[i]) {
return false;
}
}
return true;
}
private static int getMagicHash(int address) {
return Hash.getHashCodeFloatingMemory(0, address, MAGIC_HASH_LENGTH);
}
private static int getMagicHash(byte[] data) {
IMemoryReader memoryReader = MemoryReader.getMemoryReader(data, 0, MAGIC_HASH_LENGTH, 4);
return Hash.getHashCodeFloatingMemory(0, memoryReader, MAGIC_HASH_LENGTH);
}
private byte[] readData(ReadInfo readInfo, int positionOffset, int length) {
byte[] fileData;
try {
fileData = new byte[length];
if (readInfo.vFile != null) {
long currentPosition = readInfo.vFile.getPosition();
if (currentPosition < 0) {
// File is already closed
return null;
}
readInfo.vFile.ioLseek(readInfo.position + positionOffset);
readInfo.vFile.ioRead(fileData, 0, fileData.length);
readInfo.vFile.ioLseek(currentPosition);
} else if (readInfo.dataInput != null) {
long currentPosition = readInfo.dataInput.getFilePointer();
if (currentPosition < 0) {
// File is already closed
return null;
}
readInfo.dataInput.seek(readInfo.position + positionOffset);
readInfo.dataInput.readFully(fileData);
readInfo.dataInput.seek(currentPosition);
} else {
return null;
}
} catch (IOException e) {
return null;
}
return fileData;
}
public IVirtualFile getVirtualFile(int address, int length, int fileSize, byte[] checkData) {
int positionOffset = 0;
ReadInfo readInfo = readInfos.get(address);
if (readInfo == null) {
// The file data has not been read at this address.
// Search for files having the same size and content
for (ReadInfo ri : readInfos.values()) {
try {
if (ri.vFile != null && ri.vFile.length() == fileSize) {
// Both file have the same length, check the content
byte[] fileData = new byte[length];
long currentPosition = ri.vFile.getPosition();
ri.vFile.ioLseek(ri.position);
ri.vFile.ioRead(fileData, 0, length);
ri.vFile.ioLseek(currentPosition);
if (memcmp(fileData, address, length)) {
// Both files have the same content, we have found it!
readInfo = ri;
break;
}
} else if (ri.dataInput != null && ri.dataInput.length() == fileSize) {
// Both file have the same length, check the content
byte[] fileData = new byte[length];
long currentPosition = ri.dataInput.getFilePointer();
ri.dataInput.seek(ri.position);
ri.dataInput.readFully(fileData);
ri.dataInput.seek(currentPosition);
if (memcmp(fileData, address, length)) {
// Both files have the same content, we have found it!
readInfo = ri;
break;
}
} else if (ri.address < address && ri.address + ri.size >= address + length) {
positionOffset = address - ri.address;
readInfo = ri;
break;
}
} catch (IOException e) {
// Ignore the exception
}
}
if (readInfo == null) {
// Search for a file having the same magic hash value
ReadInfo ri = readMagics.get(getMagicHash(address));
// If not found at the given address
// (e.g. the memory has already been overwritten),
// try with the checkData.
if (ri == null && checkData != null && checkData.length >= MAGIC_HASH_LENGTH) {
ri = readMagics.get(getMagicHash(checkData));
}
if (ri != null) {
try {
// Check if the file length is large enough
if (ri.vFile != null && ri.vFile.length() >= fileSize) {
// Check if the file contents are matching our buffer
int checkLength = Math.min(length, fileSize);
byte[] fileData = new byte[checkLength];
long currentPosition = ri.vFile.getPosition();
ri.vFile.ioLseek(ri.position);
ri.vFile.ioRead(fileData, 0, checkLength);
ri.vFile.ioLseek(currentPosition);
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (match) {
// Both files have the same content, we have found it!
readInfo = ri;
}
} else if (ri.dataInput != null && ri.dataInput.length() >= fileSize) {
// Check if the file contents are matching our buffer
int checkLength = Math.min(length, fileSize);
byte[] fileData = new byte[checkLength];
long currentPosition = ri.dataInput.getFilePointer();
ri.dataInput.seek(ri.position);
ri.dataInput.readFully(fileData);
ri.dataInput.seek(currentPosition);
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (match) {
// Both files have the same content, we have found it!
readInfo = ri;
}
}
} catch (IOException e) {
// Ignore exception
}
}
if (readInfo == null) {
return null;
}
}
}
int checkLength = Math.min(length, MAGIC_HASH_LENGTH);
byte[] fileData = readData(readInfo, positionOffset, checkLength);
if (fileData == null) {
// Could not read the file data...
return null;
}
// Check if the file data is really matching the data in memory
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (!match) {
// This is the wrong file...
return null;
}
if (readInfo.vFile != null) {
IVirtualFile vFile = readInfo.vFile.duplicate();
if (vFile == null) {
vFile = readInfo.vFile;
+ } else {
+ vFile.ioLseek(readInfo.position);
}
if (fileSize > vFile.length()) {
if (vFile instanceof UmdIsoVirtualFile) {
// Extend the UMD file to at least the requested file size
UmdIsoVirtualFile umdIsoVirtualFile = (UmdIsoVirtualFile) vFile;
umdIsoVirtualFile.setLength(fileSize);
}
}
- return new PartialVirtualFile(vFile, readInfo.position + positionOffset, fileSize);
+ if (readInfo.position + positionOffset != 0 || vFile.length() != fileSize) {
+ vFile = new PartialVirtualFile(vFile, readInfo.position + positionOffset, fileSize);
+ }
+ return vFile;
}
if (readInfo.dataInput != null) {
if (readInfo.dataInput instanceof UmdIsoFile) {
UmdIsoFile umdIsoFile = (UmdIsoFile) readInfo.dataInput;
try {
UmdIsoFile duplicate = umdIsoFile.duplicate();
if (duplicate != null) {
+ duplicate.seek(readInfo.position);
umdIsoFile = duplicate;
}
} catch (IOException e) {
log.warn("Cannot duplicate UmdIsoFile", e);
}
if (fileSize > umdIsoFile.length()) {
// Extend the UMD file to at least the requested file size
umdIsoFile.setLength(fileSize);
}
IVirtualFile vFile = new UmdIsoVirtualFile(umdIsoFile, false, umdIsoFile.getUmdIsoReader());
- return new PartialVirtualFile(vFile, readInfo.position + positionOffset, fileSize);
+ if (readInfo.position + positionOffset != 0 || vFile.length() != fileSize) {
+ vFile = new PartialVirtualFile(vFile, readInfo.position + positionOffset, fileSize);
+ }
+ return vFile;
}
}
try {
fileData = readData(readInfo, positionOffset, fileSize);
} catch (OutOfMemoryError e) {
log.error(String.format("Error '%s' while decoding external audio file (fileSize=%d, position=%d, dataInput=%s)", e.toString(), fileSize, readInfo.position + positionOffset, readInfo.dataInput.toString()));
return null;
}
if (fileData == null) {
return null;
}
return new ByteArrayVirtualFile(fileData, 0, fileData.length);
}
public void setFileData(SeekableDataInput dataInput, IVirtualFile vFile, int address, long startPosition, int length) {
ReadInfo ri = new ReadInfo(address, length, dataInput, vFile, startPosition);
readInfos.put(address, ri);
}
private static boolean isFileMagicValue(int magicValue) {
for (int i = 0; i < fileMagics.length; i++) {
if (magicValue == fileMagics[i]) {
return true;
}
}
return false;
}
/**
* Search for the first File Magic into a specified memory buffer.
* For performance reason, file magic are checked only at the beginning
* of UMD sectors (i.e. every 2048 bytes).
*
* @param address the base address where to start searching
* @param size the length of the memory buffer where to search
* @return the offset of the first file magic value, relative to
* the start address, or -1 if no file magic was found.
*/
private static int getFirstFileMagicOffset(int address, int size) {
if (Memory.isAddressGood(address)) {
IMemoryReader memoryReader = MemoryReader.getMemoryReader(address, size, 4);
final int stepSize = UmdIsoFile.sectorLength;
final int skip = (stepSize / 4) - 1;
for (int i = 0; i < size; i += stepSize) {
int magicValue = memoryReader.readNext();
if (isFileMagicValue(magicValue)) {
return i;
}
memoryReader.skip(skip);
}
}
return -1;
}
/**
* Search for all the File Magic into a specified memory buffer.
* For performance reason, file magics are checked only every 16 bytes.
*
* @param address the base address where to start searching
* @param size the length of the memory buffer where to search
* @return the list of offsets of the file magic values found,
* relative to the start address.
* Returns null if no file magic was found.
*/
private static int[] getAllFileMagicOffsets(int address, int size) {
if (!Memory.isAddressGood(address)) {
return null;
}
Vector<Integer> magicOffsets = new Vector<Integer>();
IMemoryReader memoryReader = MemoryReader.getMemoryReader(address, size, 4);
final int stepSize = 16;
final int skip = (stepSize / 4) - 1;
final int endSize = (size / stepSize) * stepSize;
for (int i = 0; i < endSize; i += stepSize) {
int magicValue = memoryReader.readNext();
if (isFileMagicValue(magicValue)) {
magicOffsets.add(i);
}
memoryReader.skip(skip);
}
if (magicOffsets.size() <= 0) {
return null;
}
int[] fileMagicOffsets = new int[magicOffsets.size()];
for (int i = 0; i < fileMagicOffsets.length; i++) {
fileMagicOffsets[i] = magicOffsets.get(i);
}
return fileMagicOffsets;
}
@Override
public void sceIoRead(int result, int uid, int data_addr, int size, int bytesRead, long position, SeekableDataInput dataInput, IVirtualFile vFile) {
if (result >= 0 && (dataInput != null || vFile != null)) {
ReadInfo readInfo = readInfos.get(data_addr);
boolean processed = false;
if (scanAllFileMagicOffsets) {
// Accurate but also time intensive search method
int[] magicOffsets = getAllFileMagicOffsets(data_addr, bytesRead);
if (magicOffsets != null && magicOffsets.length > 0) {
for (int i = 0; i < magicOffsets.length; i++) {
int magicOffset = magicOffsets[i];
int nextMagicOffset = i + 1 < magicOffsets.length ? magicOffsets[i + 1] : bytesRead;
int magicAddress = data_addr + magicOffset;
readInfo = new ReadInfo(magicAddress, nextMagicOffset - magicOffset, dataInput, vFile, position + magicOffset);
readInfos.put(magicAddress, readInfo);
readMagics.put(getMagicHash(magicAddress), readInfo);
}
processed = true;
}
} else {
// Simple but fast search method
int magicOffset = getFirstFileMagicOffset(data_addr, bytesRead);
if (magicOffset >= 0) {
int magicAddress = data_addr + magicOffset;
readInfo = new ReadInfo(magicAddress, bytesRead - magicOffset, dataInput, vFile, position + magicOffset);
readInfos.put(magicAddress, readInfo);
readMagics.put(getMagicHash(magicAddress), readInfo);
processed = true;
}
}
if (!processed) {
if (readInfo == null) {
readInfo = new ReadInfo(data_addr, bytesRead, dataInput, vFile, position);
readInfos.put(data_addr, readInfo);
}
}
}
}
@Override
public void sceIoAssign(int result, int dev1_addr, String dev1, int dev2_addr, String dev2, int dev3_addr, String dev3, int mode, int unk1, int unk2) {
}
@Override
public void sceIoCancel(int result, int uid) {
}
@Override
public void sceIoChdir(int result, int path_addr, String path) {
}
@Override
public void sceIoChstat(int result, int path_addr, String path, int stat_addr, int bits) {
}
@Override
public void sceIoClose(int result, int uid) {
}
@Override
public void sceIoDclose(int result, int uid) {
}
@Override
public void sceIoDevctl(int result, int device_addr, String device, int cmd, int indata_addr, int inlen, int outdata_addr, int outlen) {
}
@Override
public void sceIoDopen(int result, int path_addr, String path) {
}
@Override
public void sceIoDread(int result, int uid, int dirent_addr) {
}
@Override
public void sceIoGetStat(int result, int path_addr, String path, int stat_addr) {
}
@Override
public void sceIoIoctl(int result, int uid, int cmd, int indata_addr, int inlen, int outdata_addr, int outlen) {
}
@Override
public void sceIoMkdir(int result, int path_addr, String path, int permissions) {
}
@Override
public void sceIoOpen(int result, int filename_addr, String filename, int flags, int permissions, String mode) {
}
@Override
public void sceIoPollAsync(int result, int uid, int res_addr) {
}
@Override
public void sceIoRemove(int result, int path_addr, String path) {
}
@Override
public void sceIoRename(int result, int path_addr, String path, int new_path_addr, String newpath) {
}
@Override
public void sceIoRmdir(int result, int path_addr, String path) {
}
@Override
public void sceIoSeek32(int result, int uid, int offset, int whence) {
}
@Override
public void sceIoSeek64(long result, int uid, long offset, int whence) {
}
@Override
public void sceIoSync(int result, int device_addr, String device, int unknown) {
}
@Override
public void sceIoWaitAsync(int result, int uid, int res_addr) {
}
@Override
public void sceIoWrite(int result, int uid, int data_addr, int size, int bytesWritten) {
}
}
}
| false | true | public IVirtualFile getVirtualFile(int address, int length, int fileSize, byte[] checkData) {
int positionOffset = 0;
ReadInfo readInfo = readInfos.get(address);
if (readInfo == null) {
// The file data has not been read at this address.
// Search for files having the same size and content
for (ReadInfo ri : readInfos.values()) {
try {
if (ri.vFile != null && ri.vFile.length() == fileSize) {
// Both file have the same length, check the content
byte[] fileData = new byte[length];
long currentPosition = ri.vFile.getPosition();
ri.vFile.ioLseek(ri.position);
ri.vFile.ioRead(fileData, 0, length);
ri.vFile.ioLseek(currentPosition);
if (memcmp(fileData, address, length)) {
// Both files have the same content, we have found it!
readInfo = ri;
break;
}
} else if (ri.dataInput != null && ri.dataInput.length() == fileSize) {
// Both file have the same length, check the content
byte[] fileData = new byte[length];
long currentPosition = ri.dataInput.getFilePointer();
ri.dataInput.seek(ri.position);
ri.dataInput.readFully(fileData);
ri.dataInput.seek(currentPosition);
if (memcmp(fileData, address, length)) {
// Both files have the same content, we have found it!
readInfo = ri;
break;
}
} else if (ri.address < address && ri.address + ri.size >= address + length) {
positionOffset = address - ri.address;
readInfo = ri;
break;
}
} catch (IOException e) {
// Ignore the exception
}
}
if (readInfo == null) {
// Search for a file having the same magic hash value
ReadInfo ri = readMagics.get(getMagicHash(address));
// If not found at the given address
// (e.g. the memory has already been overwritten),
// try with the checkData.
if (ri == null && checkData != null && checkData.length >= MAGIC_HASH_LENGTH) {
ri = readMagics.get(getMagicHash(checkData));
}
if (ri != null) {
try {
// Check if the file length is large enough
if (ri.vFile != null && ri.vFile.length() >= fileSize) {
// Check if the file contents are matching our buffer
int checkLength = Math.min(length, fileSize);
byte[] fileData = new byte[checkLength];
long currentPosition = ri.vFile.getPosition();
ri.vFile.ioLseek(ri.position);
ri.vFile.ioRead(fileData, 0, checkLength);
ri.vFile.ioLseek(currentPosition);
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (match) {
// Both files have the same content, we have found it!
readInfo = ri;
}
} else if (ri.dataInput != null && ri.dataInput.length() >= fileSize) {
// Check if the file contents are matching our buffer
int checkLength = Math.min(length, fileSize);
byte[] fileData = new byte[checkLength];
long currentPosition = ri.dataInput.getFilePointer();
ri.dataInput.seek(ri.position);
ri.dataInput.readFully(fileData);
ri.dataInput.seek(currentPosition);
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (match) {
// Both files have the same content, we have found it!
readInfo = ri;
}
}
} catch (IOException e) {
// Ignore exception
}
}
if (readInfo == null) {
return null;
}
}
}
int checkLength = Math.min(length, MAGIC_HASH_LENGTH);
byte[] fileData = readData(readInfo, positionOffset, checkLength);
if (fileData == null) {
// Could not read the file data...
return null;
}
// Check if the file data is really matching the data in memory
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (!match) {
// This is the wrong file...
return null;
}
if (readInfo.vFile != null) {
IVirtualFile vFile = readInfo.vFile.duplicate();
if (vFile == null) {
vFile = readInfo.vFile;
}
if (fileSize > vFile.length()) {
if (vFile instanceof UmdIsoVirtualFile) {
// Extend the UMD file to at least the requested file size
UmdIsoVirtualFile umdIsoVirtualFile = (UmdIsoVirtualFile) vFile;
umdIsoVirtualFile.setLength(fileSize);
}
}
return new PartialVirtualFile(vFile, readInfo.position + positionOffset, fileSize);
}
if (readInfo.dataInput != null) {
if (readInfo.dataInput instanceof UmdIsoFile) {
UmdIsoFile umdIsoFile = (UmdIsoFile) readInfo.dataInput;
try {
UmdIsoFile duplicate = umdIsoFile.duplicate();
if (duplicate != null) {
umdIsoFile = duplicate;
}
} catch (IOException e) {
log.warn("Cannot duplicate UmdIsoFile", e);
}
if (fileSize > umdIsoFile.length()) {
// Extend the UMD file to at least the requested file size
umdIsoFile.setLength(fileSize);
}
IVirtualFile vFile = new UmdIsoVirtualFile(umdIsoFile, false, umdIsoFile.getUmdIsoReader());
return new PartialVirtualFile(vFile, readInfo.position + positionOffset, fileSize);
}
}
try {
fileData = readData(readInfo, positionOffset, fileSize);
} catch (OutOfMemoryError e) {
log.error(String.format("Error '%s' while decoding external audio file (fileSize=%d, position=%d, dataInput=%s)", e.toString(), fileSize, readInfo.position + positionOffset, readInfo.dataInput.toString()));
return null;
}
if (fileData == null) {
return null;
}
return new ByteArrayVirtualFile(fileData, 0, fileData.length);
}
| public IVirtualFile getVirtualFile(int address, int length, int fileSize, byte[] checkData) {
int positionOffset = 0;
ReadInfo readInfo = readInfos.get(address);
if (readInfo == null) {
// The file data has not been read at this address.
// Search for files having the same size and content
for (ReadInfo ri : readInfos.values()) {
try {
if (ri.vFile != null && ri.vFile.length() == fileSize) {
// Both file have the same length, check the content
byte[] fileData = new byte[length];
long currentPosition = ri.vFile.getPosition();
ri.vFile.ioLseek(ri.position);
ri.vFile.ioRead(fileData, 0, length);
ri.vFile.ioLseek(currentPosition);
if (memcmp(fileData, address, length)) {
// Both files have the same content, we have found it!
readInfo = ri;
break;
}
} else if (ri.dataInput != null && ri.dataInput.length() == fileSize) {
// Both file have the same length, check the content
byte[] fileData = new byte[length];
long currentPosition = ri.dataInput.getFilePointer();
ri.dataInput.seek(ri.position);
ri.dataInput.readFully(fileData);
ri.dataInput.seek(currentPosition);
if (memcmp(fileData, address, length)) {
// Both files have the same content, we have found it!
readInfo = ri;
break;
}
} else if (ri.address < address && ri.address + ri.size >= address + length) {
positionOffset = address - ri.address;
readInfo = ri;
break;
}
} catch (IOException e) {
// Ignore the exception
}
}
if (readInfo == null) {
// Search for a file having the same magic hash value
ReadInfo ri = readMagics.get(getMagicHash(address));
// If not found at the given address
// (e.g. the memory has already been overwritten),
// try with the checkData.
if (ri == null && checkData != null && checkData.length >= MAGIC_HASH_LENGTH) {
ri = readMagics.get(getMagicHash(checkData));
}
if (ri != null) {
try {
// Check if the file length is large enough
if (ri.vFile != null && ri.vFile.length() >= fileSize) {
// Check if the file contents are matching our buffer
int checkLength = Math.min(length, fileSize);
byte[] fileData = new byte[checkLength];
long currentPosition = ri.vFile.getPosition();
ri.vFile.ioLseek(ri.position);
ri.vFile.ioRead(fileData, 0, checkLength);
ri.vFile.ioLseek(currentPosition);
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (match) {
// Both files have the same content, we have found it!
readInfo = ri;
}
} else if (ri.dataInput != null && ri.dataInput.length() >= fileSize) {
// Check if the file contents are matching our buffer
int checkLength = Math.min(length, fileSize);
byte[] fileData = new byte[checkLength];
long currentPosition = ri.dataInput.getFilePointer();
ri.dataInput.seek(ri.position);
ri.dataInput.readFully(fileData);
ri.dataInput.seek(currentPosition);
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (match) {
// Both files have the same content, we have found it!
readInfo = ri;
}
}
} catch (IOException e) {
// Ignore exception
}
}
if (readInfo == null) {
return null;
}
}
}
int checkLength = Math.min(length, MAGIC_HASH_LENGTH);
byte[] fileData = readData(readInfo, positionOffset, checkLength);
if (fileData == null) {
// Could not read the file data...
return null;
}
// Check if the file data is really matching the data in memory
boolean match;
if (checkData != null) {
// Check against checkData
match = cmp(fileData, checkData, checkLength);
} else {
// Check against memory data located at "address"
match = memcmp(fileData, address, checkLength);
}
if (!match) {
// This is the wrong file...
return null;
}
if (readInfo.vFile != null) {
IVirtualFile vFile = readInfo.vFile.duplicate();
if (vFile == null) {
vFile = readInfo.vFile;
} else {
vFile.ioLseek(readInfo.position);
}
if (fileSize > vFile.length()) {
if (vFile instanceof UmdIsoVirtualFile) {
// Extend the UMD file to at least the requested file size
UmdIsoVirtualFile umdIsoVirtualFile = (UmdIsoVirtualFile) vFile;
umdIsoVirtualFile.setLength(fileSize);
}
}
if (readInfo.position + positionOffset != 0 || vFile.length() != fileSize) {
vFile = new PartialVirtualFile(vFile, readInfo.position + positionOffset, fileSize);
}
return vFile;
}
if (readInfo.dataInput != null) {
if (readInfo.dataInput instanceof UmdIsoFile) {
UmdIsoFile umdIsoFile = (UmdIsoFile) readInfo.dataInput;
try {
UmdIsoFile duplicate = umdIsoFile.duplicate();
if (duplicate != null) {
duplicate.seek(readInfo.position);
umdIsoFile = duplicate;
}
} catch (IOException e) {
log.warn("Cannot duplicate UmdIsoFile", e);
}
if (fileSize > umdIsoFile.length()) {
// Extend the UMD file to at least the requested file size
umdIsoFile.setLength(fileSize);
}
IVirtualFile vFile = new UmdIsoVirtualFile(umdIsoFile, false, umdIsoFile.getUmdIsoReader());
if (readInfo.position + positionOffset != 0 || vFile.length() != fileSize) {
vFile = new PartialVirtualFile(vFile, readInfo.position + positionOffset, fileSize);
}
return vFile;
}
}
try {
fileData = readData(readInfo, positionOffset, fileSize);
} catch (OutOfMemoryError e) {
log.error(String.format("Error '%s' while decoding external audio file (fileSize=%d, position=%d, dataInput=%s)", e.toString(), fileSize, readInfo.position + positionOffset, readInfo.dataInput.toString()));
return null;
}
if (fileData == null) {
return null;
}
return new ByteArrayVirtualFile(fileData, 0, fileData.length);
}
|
diff --git a/web/src/main/java/ar/noxit/ehockey/service/impl/ClubService.java b/web/src/main/java/ar/noxit/ehockey/service/impl/ClubService.java
index db3392c..49f1280 100644
--- a/web/src/main/java/ar/noxit/ehockey/service/impl/ClubService.java
+++ b/web/src/main/java/ar/noxit/ehockey/service/impl/ClubService.java
@@ -1,162 +1,161 @@
package ar.noxit.ehockey.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import ar.noxit.ehockey.dao.IClubDao;
import ar.noxit.ehockey.dao.IEquipoDao;
import ar.noxit.ehockey.dao.IJugadorDao;
import ar.noxit.ehockey.exception.ClubYaExistenteException;
import ar.noxit.ehockey.model.Club;
import ar.noxit.ehockey.model.Equipo;
import ar.noxit.ehockey.model.Jugador;
import ar.noxit.ehockey.service.IClubService;
import ar.noxit.ehockey.web.pages.clubes.ClubPlano;
import ar.noxit.exceptions.NoxitException;
import ar.noxit.exceptions.persistence.PersistenceException;
public class ClubService implements IClubService {
private IClubDao clubDao;
private IJugadorDao jugadorDao;
private IEquipoDao equipoDao;
@Transactional(readOnly = true)
private List<Jugador> getJugadoresPorClub(Integer clubId) throws NoxitException {
Club club = clubDao.get(clubId);
return new ArrayList<Jugador>(club.getJugadores());
}
@Override
@Transactional(readOnly = true)
public List<Jugador> getJugadoresParaEquipo(Integer equipoId) throws NoxitException {
Equipo equipo = equipoDao.get(equipoId);
List<Jugador> jugadores = getJugadoresPorClub(equipo.getClub().getId());
List<Jugador> nueva = new ArrayList<Jugador>();
for (Jugador jug : jugadores) {
if (jug.getDivision().equals(equipo.getDivision()) && jug.getSector().equals(equipo.getSector())) {
nueva.add(jug);
}
}
return nueva;
}
@Override
@Transactional(readOnly = true)
public Club get(Integer id) throws NoxitException {
return clubDao.get(id);
}
@Override
@Transactional(readOnly = true)
public List<Club> getAll() throws NoxitException {
return clubDao.getAll();
}
@Override
@Transactional(readOnly = true)
public List<Jugador> getJugadoresPorClub(Integer clubId, List<Integer> idJugadores) throws NoxitException {
return jugadorDao.getJugadoresFromClub(clubId, idJugadores);
}
@Override
@Transactional(readOnly = true)
public List<Equipo> getEquiposPorClub(Integer clubId) throws NoxitException {
Club club = clubDao.get(clubId);
return new ArrayList<Equipo>(club.getEquiposActivos());
}
@Override
@Transactional(readOnly = true)
public List<ClubPlano> getAllPlano() throws NoxitException {
List<ClubPlano> clubes = new ArrayList<ClubPlano>();
for (Club each : clubDao.getAll()) {
clubes.add(aplanar(each));
}
return clubes;
}
private ClubPlano aplanar(Club club) {
ClubPlano clb = new ClubPlano();
clb.setId(club.getId());
clb.setNombre(club.getNombre());
return clb;
}
@Override
@Transactional
public void save(ClubPlano clubPlano) throws NoxitException {
Club club = new Club(clubPlano.getNombreCompleto());
BeanUtils.copyProperties(clubPlano, club);
clubDao.save(club);
}
@Override
@Transactional
public void update(ClubPlano clubPlano) throws NoxitException {
Club club = clubDao.get(clubPlano.getId());
// Modifico los valores del club.
BeanUtils.copyProperties(clubPlano, club);
}
@Override
public IModel<ClubPlano> aplanar(IModel<Club> model) {
ClubPlano clubPlano = new ClubPlano();
BeanUtils.copyProperties(model.getObject(), clubPlano);
return new Model<ClubPlano>(clubPlano);
}
@Override
@Transactional(readOnly = true)
public void verificarNombreClub(ClubPlano clubPlano) throws ClubYaExistenteException {
String nombre = clubPlano.getNombre();
String nombreCompleto = clubPlano.getNombreCompleto();
if (clubDao.getClubPorNombre(nombre, nombreCompleto).size() != 0)
throw new ClubYaExistenteException("Club de nombre: " + nombre + " ya existente.");
}
@Override
@Transactional(readOnly = true)
public void verificarCambioNombre(ClubPlano clubPlano) throws ClubYaExistenteException {
try {
Club club = clubDao.get(clubPlano.getId());
String nombre = clubPlano.getNombre();
String nombreCompleto = clubPlano.getNombreCompleto();
List<Club> clubPorNombre = clubDao.getClubPorNombre(nombre, nombreCompleto);
boolean actualizando = false;
for (Club each : clubPorNombre) {
- if ((each.getNombre().equals(nombre) && !each.getNombreCompleto().equals(nombreCompleto))
- || (!each.getNombre().equals(nombre) && each.getNombreCompleto().equals(nombreCompleto))) {
+ if (each.getId().equals(club.getId())) {
actualizando = true;
}
}
if (!club.getNombre().equals(nombre) || !club.getNombreCompleto().equals(nombreCompleto)) {
if (clubPorNombre.size() != 0 && !actualizando)
throw new ClubYaExistenteException("Club de nombre: " + nombre + " ya existente.");
} else {
if (actualizando) {
throw new ClubYaExistenteException("Club de nombre: " + nombre + " ya existente.");
}
}
} catch (PersistenceException e) {
throw new ClubYaExistenteException(e);
}
}
public void setClubDao(IClubDao clubDao) {
this.clubDao = clubDao;
}
public void setJugadorDao(IJugadorDao jugadorDao) {
this.jugadorDao = jugadorDao;
}
public void setEquipoDao(IEquipoDao equipoDao) {
this.equipoDao = equipoDao;
}
}
| true | true | public void verificarCambioNombre(ClubPlano clubPlano) throws ClubYaExistenteException {
try {
Club club = clubDao.get(clubPlano.getId());
String nombre = clubPlano.getNombre();
String nombreCompleto = clubPlano.getNombreCompleto();
List<Club> clubPorNombre = clubDao.getClubPorNombre(nombre, nombreCompleto);
boolean actualizando = false;
for (Club each : clubPorNombre) {
if ((each.getNombre().equals(nombre) && !each.getNombreCompleto().equals(nombreCompleto))
|| (!each.getNombre().equals(nombre) && each.getNombreCompleto().equals(nombreCompleto))) {
actualizando = true;
}
}
if (!club.getNombre().equals(nombre) || !club.getNombreCompleto().equals(nombreCompleto)) {
if (clubPorNombre.size() != 0 && !actualizando)
throw new ClubYaExistenteException("Club de nombre: " + nombre + " ya existente.");
} else {
if (actualizando) {
throw new ClubYaExistenteException("Club de nombre: " + nombre + " ya existente.");
}
}
} catch (PersistenceException e) {
throw new ClubYaExistenteException(e);
}
}
| public void verificarCambioNombre(ClubPlano clubPlano) throws ClubYaExistenteException {
try {
Club club = clubDao.get(clubPlano.getId());
String nombre = clubPlano.getNombre();
String nombreCompleto = clubPlano.getNombreCompleto();
List<Club> clubPorNombre = clubDao.getClubPorNombre(nombre, nombreCompleto);
boolean actualizando = false;
for (Club each : clubPorNombre) {
if (each.getId().equals(club.getId())) {
actualizando = true;
}
}
if (!club.getNombre().equals(nombre) || !club.getNombreCompleto().equals(nombreCompleto)) {
if (clubPorNombre.size() != 0 && !actualizando)
throw new ClubYaExistenteException("Club de nombre: " + nombre + " ya existente.");
} else {
if (actualizando) {
throw new ClubYaExistenteException("Club de nombre: " + nombre + " ya existente.");
}
}
} catch (PersistenceException e) {
throw new ClubYaExistenteException(e);
}
}
|
diff --git a/drools-compiler/src/main/java/org/drools/guvnor/server/util/SuggestionCompletionEngineBuilder.java b/drools-compiler/src/main/java/org/drools/guvnor/server/util/SuggestionCompletionEngineBuilder.java
index c856f8985c..34ecb171ba 100644
--- a/drools-compiler/src/main/java/org/drools/guvnor/server/util/SuggestionCompletionEngineBuilder.java
+++ b/drools-compiler/src/main/java/org/drools/guvnor/server/util/SuggestionCompletionEngineBuilder.java
@@ -1,273 +1,273 @@
/*
* Copyright 2006 JBoss 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.drools.guvnor.server.util;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.drools.guvnor.client.modeldriven.ModelField;
import org.drools.guvnor.client.modeldriven.SuggestionCompletionEngine;
import org.drools.guvnor.client.modeldriven.brl.DSLSentence;
import org.drools.lang.dsl.DSLMappingEntry;
/**
* A builder to incrementally populate a SuggestionCompletionEngine
*
* @author etirelli
*/
public class SuggestionCompletionEngineBuilder {
private SuggestionCompletionEngine instance = new SuggestionCompletionEngine();
private List<String> factTypes = new ArrayList<String>();
private Map<String, String[]> fieldsForType = new HashMap<String, String[]>();
private Map<String, String[]> modifiersForType = new HashMap<String, String[]>();
private Map<String, String> fieldTypes = new HashMap<String, String>();
private Map<String, Class<?>> fieldClasses = new HashMap<String, Class<?>>();
private Map<String, Field> fieldTypesField = new HashMap<String, Field>();
private Map<String, String> globalTypes = new HashMap<String, String>();
private List<DSLSentence> actionDSLSentences = new ArrayList<DSLSentence>();
private List<DSLSentence> conditionDSLSentences = new ArrayList<DSLSentence>();
private List<DSLSentence> keywordDSLItems = new ArrayList<DSLSentence>();
private List<DSLSentence> anyScopeDSLItems = new ArrayList<DSLSentence>();
private List<String> globalCollections = new ArrayList<String>();
public SuggestionCompletionEngineBuilder() {
}
/**
* Start the creation of a new SuggestionCompletionEngine
*/
public void newCompletionEngine() {
this.instance = new SuggestionCompletionEngine();
this.factTypes = new ArrayList<String>();
this.fieldsForType = new HashMap<String, String[]>();
this.modifiersForType = new HashMap<String, String[]>();
this.fieldTypes = new HashMap<String, String>();
this.fieldTypesField = new HashMap<String, Field>();
this.globalTypes = new HashMap<String, String>();
this.actionDSLSentences = new ArrayList<DSLSentence>();
this.conditionDSLSentences = new ArrayList<DSLSentence>();
this.keywordDSLItems = new ArrayList<DSLSentence>();
this.anyScopeDSLItems = new ArrayList<DSLSentence>();
this.globalCollections = new ArrayList<String>();
}
/**
* Adds a fact type to the engine
*
* @param factType
*/
public void addFactType(final String factType) {
this.factTypes.add(factType);
}
/**
* Adds the list of fields for a given type
*
* @param type
* @param fields
*/
public void addFieldsForType(final String type,
final String[] fields) {
this.fieldsForType.put(type,
fields);
}
/**
* Adds the list of modifiers for a given type
*
* @param type
* @param fields
*/
public void addModifiersForType(final String type,
final String[] fields) {
this.modifiersForType.put(type,
fields);
}
/**
* @return true if this has the type already registered (field information).
*/
public boolean hasFieldsForType(final String type) {
return this.fieldsForType.containsKey(type);
}
/**
* Adds a type declaration for a field
*
* @param field format: class.field
* @param type parametrized type of clazz
* @param clazz the class of field
*/
public void addFieldType(final String field, final String type,
final Class<?> clazz) {
this.fieldTypes.put(field, type);
this.fieldClasses.put(field, clazz);
}
/**
* Adds a type declaration for a field
*
* @param field format: class.field
* @param type
*/
public void addFieldTypeField(final String field, final Field type) {
this.fieldTypesField.put(field, type);
}
/**
* Adds a global and its corresponding type to the engine
*
* @param global
* @param type
*/
public void addGlobalType(final String global,
final String type) {
this.globalTypes.put(global, type);
}
public void addGlobalCollection(String global) {
this.globalCollections.add(global);
}
/**
* Add a DSL sentence for an action.
*/
public void addDSLActionSentence(final String sentence) {
final DSLSentence sen = new DSLSentence();
sen.sentence = sentence;
this.actionDSLSentences.add(sen);
}
/**
* Add a DSL sentence for a condition.
*/
public void addDSLConditionSentence(final String sentence) {
final DSLSentence sen = new DSLSentence();
sen.sentence = sentence;
this.conditionDSLSentences.add(sen);
}
static public String obtainGenericType(Type type) {
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type goodType = null;
for (Type t : pt.getActualTypeArguments()) {
goodType = t;
}
int index = goodType.toString().lastIndexOf(".");
return goodType.toString().substring(index + 1);
}
return null;
}
public void putParametricFieldType(String fieldName, String genericType) {
this.instance.putParametricFieldType(fieldName, genericType);
}
/**
* Returns a SuggestionCompletionEngine instance populated with
* all the data since last call to newCompletionEngine() method
*
* @return
*/
public SuggestionCompletionEngine getInstance() {
this.instance.setFactTypes(this.factTypes.toArray(new String[this.factTypes.size()]));
this.instance.setModifiers(this.modifiersForType);
//convert this.fieldsForType, this.fieldClasses and this.fieldTypes into Map<String,ModelField[]>.
Map<String, ModelField[]> modelMap = new HashMap<String, ModelField[]>();
for (Map.Entry<String, String[]> typeEntry : this.fieldsForType.entrySet()) {
List<ModelField> fields = new ArrayList<ModelField>();
for (String field : typeEntry.getValue()) {
String fieldName = field;
String fieldType = this.fieldTypes.get(typeEntry.getKey() + "." + field);
Class<?> fieldClazz = this.fieldClasses.get(typeEntry.getKey() + "." + field);
fields.add(new ModelField(
- fieldName, fieldClazz.getName(), fieldType));
+ fieldName, fieldClazz == null ? null : fieldClazz.getName(), fieldType));
}
modelMap.put(typeEntry.getKey(), fields.toArray(new ModelField[fields.size()]));
}
this.instance.setFieldsForTypes(modelMap);
for (String fieldName : this.fieldTypesField.keySet()) {
Field field = this.fieldTypesField.get(fieldName);
if (field != null) {
String genericType = obtainGenericType(field.getGenericType());
if (genericType != null) {
this.instance.putParametricFieldType(fieldName, genericType);
}
Class<?> fieldClass = field.getType();
if (fieldClass.isEnum()) {
Field[] flds = fieldClass.getDeclaredFields();
List<String> listEnum = new ArrayList<String>();
int i = 0;
for (Field f : flds) {
if (f.isEnumConstant()) {
listEnum.add(i + "=" + f.getName());
i++;
}
}
String a[] = new String[listEnum.size()];
i = 0;
for (String value : listEnum) {
a[i] = value;
i++;
}
this.instance.putDataEnumList(fieldName, a);
}
}
}
this.instance.setGlobalVariables(this.globalTypes);
this.instance.actionDSLSentences = makeArray(this.actionDSLSentences);
this.instance.conditionDSLSentences = makeArray(this.conditionDSLSentences);
this.instance.keywordDSLItems = makeArray(this.keywordDSLItems);
this.instance.anyScopeDSLItems = makeArray(this.anyScopeDSLItems);
this.instance.setGlobalCollections(this.globalCollections.toArray(new String[globalCollections.size()]));
return this.instance;
}
private DSLSentence[] makeArray(List<DSLSentence> ls) {
return ls.toArray(new DSLSentence[ls.size()]);
}
public void addDSLMapping(DSLMappingEntry entry) {
DSLSentence sen = new DSLSentence();
sen.sentence = entry.getMappingKey();
if (entry.getSection() == DSLMappingEntry.CONDITION) {
this.conditionDSLSentences.add(sen);
} else if (entry.getSection() == DSLMappingEntry.CONSEQUENCE) {
this.actionDSLSentences.add(sen);
} else if (entry.getSection() == DSLMappingEntry.KEYWORD) {
this.keywordDSLItems.add(sen);
} else if (entry.getSection() == DSLMappingEntry.ANY) {
this.anyScopeDSLItems.add(sen);
}
}
}
| true | true | public SuggestionCompletionEngine getInstance() {
this.instance.setFactTypes(this.factTypes.toArray(new String[this.factTypes.size()]));
this.instance.setModifiers(this.modifiersForType);
//convert this.fieldsForType, this.fieldClasses and this.fieldTypes into Map<String,ModelField[]>.
Map<String, ModelField[]> modelMap = new HashMap<String, ModelField[]>();
for (Map.Entry<String, String[]> typeEntry : this.fieldsForType.entrySet()) {
List<ModelField> fields = new ArrayList<ModelField>();
for (String field : typeEntry.getValue()) {
String fieldName = field;
String fieldType = this.fieldTypes.get(typeEntry.getKey() + "." + field);
Class<?> fieldClazz = this.fieldClasses.get(typeEntry.getKey() + "." + field);
fields.add(new ModelField(
fieldName, fieldClazz.getName(), fieldType));
}
modelMap.put(typeEntry.getKey(), fields.toArray(new ModelField[fields.size()]));
}
this.instance.setFieldsForTypes(modelMap);
for (String fieldName : this.fieldTypesField.keySet()) {
Field field = this.fieldTypesField.get(fieldName);
if (field != null) {
String genericType = obtainGenericType(field.getGenericType());
if (genericType != null) {
this.instance.putParametricFieldType(fieldName, genericType);
}
Class<?> fieldClass = field.getType();
if (fieldClass.isEnum()) {
Field[] flds = fieldClass.getDeclaredFields();
List<String> listEnum = new ArrayList<String>();
int i = 0;
for (Field f : flds) {
if (f.isEnumConstant()) {
listEnum.add(i + "=" + f.getName());
i++;
}
}
String a[] = new String[listEnum.size()];
i = 0;
for (String value : listEnum) {
a[i] = value;
i++;
}
this.instance.putDataEnumList(fieldName, a);
}
}
}
this.instance.setGlobalVariables(this.globalTypes);
this.instance.actionDSLSentences = makeArray(this.actionDSLSentences);
this.instance.conditionDSLSentences = makeArray(this.conditionDSLSentences);
this.instance.keywordDSLItems = makeArray(this.keywordDSLItems);
this.instance.anyScopeDSLItems = makeArray(this.anyScopeDSLItems);
this.instance.setGlobalCollections(this.globalCollections.toArray(new String[globalCollections.size()]));
return this.instance;
}
| public SuggestionCompletionEngine getInstance() {
this.instance.setFactTypes(this.factTypes.toArray(new String[this.factTypes.size()]));
this.instance.setModifiers(this.modifiersForType);
//convert this.fieldsForType, this.fieldClasses and this.fieldTypes into Map<String,ModelField[]>.
Map<String, ModelField[]> modelMap = new HashMap<String, ModelField[]>();
for (Map.Entry<String, String[]> typeEntry : this.fieldsForType.entrySet()) {
List<ModelField> fields = new ArrayList<ModelField>();
for (String field : typeEntry.getValue()) {
String fieldName = field;
String fieldType = this.fieldTypes.get(typeEntry.getKey() + "." + field);
Class<?> fieldClazz = this.fieldClasses.get(typeEntry.getKey() + "." + field);
fields.add(new ModelField(
fieldName, fieldClazz == null ? null : fieldClazz.getName(), fieldType));
}
modelMap.put(typeEntry.getKey(), fields.toArray(new ModelField[fields.size()]));
}
this.instance.setFieldsForTypes(modelMap);
for (String fieldName : this.fieldTypesField.keySet()) {
Field field = this.fieldTypesField.get(fieldName);
if (field != null) {
String genericType = obtainGenericType(field.getGenericType());
if (genericType != null) {
this.instance.putParametricFieldType(fieldName, genericType);
}
Class<?> fieldClass = field.getType();
if (fieldClass.isEnum()) {
Field[] flds = fieldClass.getDeclaredFields();
List<String> listEnum = new ArrayList<String>();
int i = 0;
for (Field f : flds) {
if (f.isEnumConstant()) {
listEnum.add(i + "=" + f.getName());
i++;
}
}
String a[] = new String[listEnum.size()];
i = 0;
for (String value : listEnum) {
a[i] = value;
i++;
}
this.instance.putDataEnumList(fieldName, a);
}
}
}
this.instance.setGlobalVariables(this.globalTypes);
this.instance.actionDSLSentences = makeArray(this.actionDSLSentences);
this.instance.conditionDSLSentences = makeArray(this.conditionDSLSentences);
this.instance.keywordDSLItems = makeArray(this.keywordDSLItems);
this.instance.anyScopeDSLItems = makeArray(this.anyScopeDSLItems);
this.instance.setGlobalCollections(this.globalCollections.toArray(new String[globalCollections.size()]));
return this.instance;
}
|
diff --git a/src/CameraViewerImpl.java b/src/CameraViewerImpl.java
index d15a407..681ccf4 100644
--- a/src/CameraViewerImpl.java
+++ b/src/CameraViewerImpl.java
@@ -1,302 +1,302 @@
// -*- Java -*-
/*!
* @file CameraViewerImpl.java
* @brief Camera Viewer
* @date $Date$
*
* $Id$
*/
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import jp.go.aist.rtm.RTC.DataFlowComponentBase;
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.port.InPort;
import jp.go.aist.rtm.RTC.util.DataRef;
import RTC.CameraImage;
import RTC.ReturnCode_t;
/*!
* @class CameraViewerImpl
* @brief Camera Viewer
*
*/
public class CameraViewerImpl extends DataFlowComponentBase {
private JFrame frame;
private CameraViewPanel panel;
private BufferedImage img;
/*!
* @brief constructor
* @param manager Maneger Object
*/
public CameraViewerImpl(Manager manager) {
super(manager);
// <rtc-template block="initializer">
m_in_val = new CameraImage();
m_in = new DataRef<CameraImage>(m_in_val);
m_inIn = new InPort<CameraImage>("in", m_in);
// </rtc-template>
}
/**
*
* The initialize action (on CREATED->ALIVE transition)
* formaer rtc_init_entry()
*
* @return RTC::ReturnCode_t
*
*
*/
@Override
protected ReturnCode_t onInitialize() {
// Registration: InPort/OutPort/Service
// <rtc-template block="registration">
// Set InPort buffers
addInPort("in", m_inIn);
// </rtc-template>
return super.onInitialize();
}
/***
*
* The finalize action (on ALIVE->END transition)
* formaer rtc_exiting_entry()
*
* @return RTC::ReturnCode_t
*
*
*/
// @Override
// protected ReturnCode_t onFinalize() {
// return super.onFinalize();
// }
/***
*
* The startup action when ExecutionContext startup
* former rtc_starting_entry()
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
// @Override
// protected ReturnCode_t onStartup(int ec_id) {
// return super.onStartup(ec_id);
// }
/***
*
* The shutdown action when ExecutionContext stop
* former rtc_stopping_entry()
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
// @Override
// protected ReturnCode_t onShutdown(int ec_id) {
// return super.onShutdown(ec_id);
// }
/***
*
* The activated action (Active state entry action)
* former rtc_active_entry()
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
@Override
protected ReturnCode_t onActivated(int ec_id) {
frame = new JFrame("CapturedImage");
panel = new CameraViewPanel();
frame.setContentPane(panel);
panel.setSize(new Dimension(480, 360));
frame.setSize(new Dimension(500, 400));
frame.setVisible(true);
return super.onActivated(ec_id);
}
/***
*
* The deactivated action (Active state exit action)
* former rtc_active_exit()
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
@Override
protected ReturnCode_t onDeactivated(int ec_id) {
frame.setVisible(false);
frame = null;
img = null;
return super.onDeactivated(ec_id);
}
/***
*
* The execution action that is invoked periodically
* former rtc_active_do()
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
@Override
protected ReturnCode_t onExecute(int ec_id) {
if (this.m_inIn.isNew()) {
m_inIn.read();
- System.out.println("Width =" + m_in.v.width);
- System.out.println("Height =" + m_in.v.height);
+ //System.out.println("Width =" + m_in.v.width);
+ //System.out.println("Height =" + m_in.v.height);
if (img == null) {
img = new BufferedImage(m_in.v.width, m_in.v.height, BufferedImage.TYPE_INT_RGB);
}
for (int y = 0;y < m_in.v.height;y++) {
for (int x = 0;x < m_in.v.width;x++) {
int index = y * m_in.v.width + x;
- byte r = m_in.v.pixels[index*3 + 2];
+ byte r = m_in.v.pixels[index*3 + 0];
byte g = m_in.v.pixels[index*3 + 1];
- byte b = m_in.v.pixels[index*3 + 0];
- int rgb = (int)r << 16 | (int)g << 8 | (int)b;
+ byte b = m_in.v.pixels[index*3 + 2];
+ int rgb = (0x00FF & (int)r) << 16 | (0x00FF & (int)g) << 8 | (0x00FF & (int)b);
img.setRGB(x, y, rgb);
}
}
panel.img = img;
panel.repaint();
}
return super.onExecute(ec_id);
}
/***
*
* The aborting action when main logic error occurred.
* former rtc_aborting_entry()
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
// @Override
// public ReturnCode_t onAborting(int ec_id) {
// return super.onAborting(ec_id);
// }
/***
*
* The error action in ERROR state
* former rtc_error_do()
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
// @Override
// public ReturnCode_t onError(int ec_id) {
// return super.onError(ec_id);
// }
/***
*
* The reset action that is invoked resetting
* This is same but different the former rtc_init_entry()
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
// @Override
// protected ReturnCode_t onReset(int ec_id) {
// return super.onReset(ec_id);
// }
/***
*
* The state update action that is invoked after onExecute() action
* no corresponding operation exists in OpenRTm-aist-0.2.0
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
// @Override
// protected ReturnCode_t onStateUpdate(int ec_id) {
// return super.onStateUpdate(ec_id);
// }
/***
*
* The action that is invoked when execution context's rate is changed
* no corresponding operation exists in OpenRTm-aist-0.2.0
*
* @param ec_id target ExecutionContext Id
*
* @return RTC::ReturnCode_t
*
*
*/
// @Override
// protected ReturnCode_t onRateChanged(int ec_id) {
// return super.onRateChanged(ec_id);
// }
//
// DataInPort declaration
// <rtc-template block="inport_declare">
protected CameraImage m_in_val;
protected DataRef<CameraImage> m_in;
/*!
*/
protected InPort<CameraImage> m_inIn;
// </rtc-template>
// DataOutPort declaration
// <rtc-template block="outport_declare">
// </rtc-template>
// CORBA Port declaration
// <rtc-template block="corbaport_declare">
// </rtc-template>
// Service declaration
// <rtc-template block="service_declare">
// </rtc-template>
// Consumer declaration
// <rtc-template block="consumer_declare">
// </rtc-template>
}
| false | true | protected ReturnCode_t onExecute(int ec_id) {
if (this.m_inIn.isNew()) {
m_inIn.read();
System.out.println("Width =" + m_in.v.width);
System.out.println("Height =" + m_in.v.height);
if (img == null) {
img = new BufferedImage(m_in.v.width, m_in.v.height, BufferedImage.TYPE_INT_RGB);
}
for (int y = 0;y < m_in.v.height;y++) {
for (int x = 0;x < m_in.v.width;x++) {
int index = y * m_in.v.width + x;
byte r = m_in.v.pixels[index*3 + 2];
byte g = m_in.v.pixels[index*3 + 1];
byte b = m_in.v.pixels[index*3 + 0];
int rgb = (int)r << 16 | (int)g << 8 | (int)b;
img.setRGB(x, y, rgb);
}
}
panel.img = img;
panel.repaint();
}
return super.onExecute(ec_id);
}
| protected ReturnCode_t onExecute(int ec_id) {
if (this.m_inIn.isNew()) {
m_inIn.read();
//System.out.println("Width =" + m_in.v.width);
//System.out.println("Height =" + m_in.v.height);
if (img == null) {
img = new BufferedImage(m_in.v.width, m_in.v.height, BufferedImage.TYPE_INT_RGB);
}
for (int y = 0;y < m_in.v.height;y++) {
for (int x = 0;x < m_in.v.width;x++) {
int index = y * m_in.v.width + x;
byte r = m_in.v.pixels[index*3 + 0];
byte g = m_in.v.pixels[index*3 + 1];
byte b = m_in.v.pixels[index*3 + 2];
int rgb = (0x00FF & (int)r) << 16 | (0x00FF & (int)g) << 8 | (0x00FF & (int)b);
img.setRGB(x, y, rgb);
}
}
panel.img = img;
panel.repaint();
}
return super.onExecute(ec_id);
}
|
diff --git a/tests/mil.jpeojtrs.sca.prf.tests/src/mil/jpeojtrs/sca/prf/tests/StructTest.java b/tests/mil.jpeojtrs.sca.prf.tests/src/mil/jpeojtrs/sca/prf/tests/StructTest.java
index 657808a0..b5c2ebed 100644
--- a/tests/mil.jpeojtrs.sca.prf.tests/src/mil/jpeojtrs/sca/prf/tests/StructTest.java
+++ b/tests/mil.jpeojtrs.sca.prf.tests/src/mil/jpeojtrs/sca/prf/tests/StructTest.java
@@ -1,160 +1,161 @@
/*******************************************************************************
* This file is protected by Copyright.
* Please refer to the COPYRIGHT file distributed with this source distribution.
*
* This file is part of REDHAWK IDE.
*
* 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
*******************************************************************************/
// BEGIN GENERATED CODE
package mil.jpeojtrs.sca.prf.tests;
import junit.framework.Assert;
import junit.textui.TestRunner;
import mil.jpeojtrs.sca.prf.AccessType;
import mil.jpeojtrs.sca.prf.ConfigurationKind;
import mil.jpeojtrs.sca.prf.PrfFactory;
import mil.jpeojtrs.sca.prf.Properties;
import mil.jpeojtrs.sca.prf.PropertyValueType;
import mil.jpeojtrs.sca.prf.Struct;
import mil.jpeojtrs.sca.prf.StructPropertyConfigurationType;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
/**
* <!-- begin-user-doc --> A test case for the model object '
* <em><b>Struct</b></em>'. <!-- end-user-doc -->
* <p>
* The following operations are tested:
* <ul>
* <li>{@link mil.jpeojtrs.sca.prf.PropertyContainer#getProperty(java.lang.String) <em>Get Property</em>}</li>
* </ul>
* </p>
* @generated
*/
public class StructTest extends AbstractPropertyTest {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(StructTest.class);
}
/**
* Constructs a new Struct test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public StructTest(String name) {
super(name);
}
/**
* Returns the fixture for this Struct test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected Struct getFixture() {
return (Struct)fixture;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see junit.framework.TestCase#setUp()
* @generated NOT
*/
@Override
protected void setUp() throws Exception {
final ResourceSet resourceSet = new ResourceSetImpl();
final Properties props = Properties.Util.getProperties(resourceSet.getResource(PrfTests.getURI("testFiles/StructTest.prf.xml"), true));
final Struct struct = props.getStruct().get(0);
Assert.assertNotNull(struct);
setFixture(struct);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see junit.framework.TestCase#tearDown()
* @generated NOT
*/
@Override
protected void tearDown() throws Exception {
setFixture(null);
}
/**
* Tests the '{@link mil.jpeojtrs.sca.prf.PropertyContainer#getProperty(java.lang.String) <em>Get Property</em>}' operation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see mil.jpeojtrs.sca.prf.PropertyContainer#getProperty(java.lang.String)
* @generated NOT
*/
public void testGetProperty__String() {
// END GENERATED CODE
Assert.assertNull(getFixture().getProperty(null));
// BEGIN GENERATED CODE
}
public void test_parse() throws Exception {
final ResourceSet resourceSet = new ResourceSetImpl();
final Properties props = Properties.Util.getProperties(resourceSet.getResource(PrfTests.getURI("testFiles/StructTest.prf.xml"), true));
final Struct struct = props.getStruct().get(0);
Assert.assertNotNull(struct);
Assert.assertEquals("DCE:24acefac-62eb-4b7f-9177-cc7d78c76aca", struct.getId());
Assert.assertEquals(AccessType.READONLY, struct.getMode());
Assert.assertEquals("Name", struct.getName());
Assert.assertEquals("Sample Description", struct.getDescription());
Assert.assertEquals(1, struct.getSimple().size());
Assert.assertEquals(PropertyValueType.BOOLEAN, struct.getSimple().get(0).getType());
Assert.assertEquals("DCE:24acefac-62eb-4b7f-9177-cc7d78c76acb", struct.getSimple().get(0).getId());
Assert.assertNotNull(struct.getConfigurationKind());
Assert.assertEquals(StructPropertyConfigurationType.FACTORYPARAM, struct.getConfigurationKind().get(0).getType());
}
public void testExtra() throws Exception {
final ResourceSet resourceSet = new ResourceSetImpl();
final Properties props = Properties.Util.getProperties(resourceSet.getResource(PrfTests.getURI("testFiles/StructTest.prf.xml"), true));
Assert.assertNotNull(props);
final Struct struct = props.getStruct().get(0);
Assert.assertNotNull(struct);
// test unsetMode
struct.unsetMode();
Assert.assertFalse(struct.isSetMode());
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
struct.setMode(AccessType.WRITEONLY);
Assert.assertEquals(AccessType.WRITEONLY, struct.getMode());
struct.setMode(null);
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
struct.setMode(AccessType.READWRITE);
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
// test set null and non null type
final ConfigurationKind ck = PrfFactory.eINSTANCE.createConfigurationKind();
ck.setType(StructPropertyConfigurationType.ALLOCATION);
+ struct.getConfigurationKind().clear();
struct.getConfigurationKind().add(ck);
Assert.assertEquals(StructPropertyConfigurationType.ALLOCATION, struct.getConfigurationKind().get(0).getType());
struct.getConfigurationKind().set(0, ck);
Assert.assertEquals(StructPropertyConfigurationType.ALLOCATION, struct.getConfigurationKind().get(0).getType());
struct.getConfigurationKind().clear();
Assert.assertTrue(struct.getConfigurationKind().isEmpty());
}
} //StructTest
| true | true | public void testExtra() throws Exception {
final ResourceSet resourceSet = new ResourceSetImpl();
final Properties props = Properties.Util.getProperties(resourceSet.getResource(PrfTests.getURI("testFiles/StructTest.prf.xml"), true));
Assert.assertNotNull(props);
final Struct struct = props.getStruct().get(0);
Assert.assertNotNull(struct);
// test unsetMode
struct.unsetMode();
Assert.assertFalse(struct.isSetMode());
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
struct.setMode(AccessType.WRITEONLY);
Assert.assertEquals(AccessType.WRITEONLY, struct.getMode());
struct.setMode(null);
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
struct.setMode(AccessType.READWRITE);
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
// test set null and non null type
final ConfigurationKind ck = PrfFactory.eINSTANCE.createConfigurationKind();
ck.setType(StructPropertyConfigurationType.ALLOCATION);
struct.getConfigurationKind().add(ck);
Assert.assertEquals(StructPropertyConfigurationType.ALLOCATION, struct.getConfigurationKind().get(0).getType());
struct.getConfigurationKind().set(0, ck);
Assert.assertEquals(StructPropertyConfigurationType.ALLOCATION, struct.getConfigurationKind().get(0).getType());
struct.getConfigurationKind().clear();
Assert.assertTrue(struct.getConfigurationKind().isEmpty());
}
| public void testExtra() throws Exception {
final ResourceSet resourceSet = new ResourceSetImpl();
final Properties props = Properties.Util.getProperties(resourceSet.getResource(PrfTests.getURI("testFiles/StructTest.prf.xml"), true));
Assert.assertNotNull(props);
final Struct struct = props.getStruct().get(0);
Assert.assertNotNull(struct);
// test unsetMode
struct.unsetMode();
Assert.assertFalse(struct.isSetMode());
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
struct.setMode(AccessType.WRITEONLY);
Assert.assertEquals(AccessType.WRITEONLY, struct.getMode());
struct.setMode(null);
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
struct.setMode(AccessType.READWRITE);
Assert.assertEquals(AccessType.READWRITE, struct.getMode());
// test set null and non null type
final ConfigurationKind ck = PrfFactory.eINSTANCE.createConfigurationKind();
ck.setType(StructPropertyConfigurationType.ALLOCATION);
struct.getConfigurationKind().clear();
struct.getConfigurationKind().add(ck);
Assert.assertEquals(StructPropertyConfigurationType.ALLOCATION, struct.getConfigurationKind().get(0).getType());
struct.getConfigurationKind().set(0, ck);
Assert.assertEquals(StructPropertyConfigurationType.ALLOCATION, struct.getConfigurationKind().get(0).getType());
struct.getConfigurationKind().clear();
Assert.assertTrue(struct.getConfigurationKind().isEmpty());
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/XMLConfigurationBuilder.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/XMLConfigurationBuilder.java
index 5f4f5dbaa..1c5642038 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/XMLConfigurationBuilder.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/XMLConfigurationBuilder.java
@@ -1,222 +1,226 @@
/*
* 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.synapse.config.xml;
import org.apache.axiom.om.*;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseException;
import org.apache.synapse.Mediator;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.config.Entry;
import org.apache.synapse.config.Util;
import org.apache.synapse.config.xml.endpoints.EndpointAbstractFactory;
import org.apache.synapse.core.axis2.ProxyService;
import org.apache.synapse.mediators.base.SequenceMediator;
import org.apache.synapse.mediators.builtin.SendMediator;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.mediators.builtin.LogMediator;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
/**
* Builds a Synapse Configuration from an XML input stream
*/
public class XMLConfigurationBuilder {
private static Log log = LogFactory.getLog(XMLConfigurationBuilder.class);
public static SynapseConfiguration getConfiguration(InputStream is) {
log.info("Generating the Synapse configuration model by parsing the XML configuration");
SynapseConfiguration config = new SynapseConfiguration();
SequenceMediator rootSequence = new SequenceMediator();
rootSequence.setName(org.apache.synapse.Constants.MAIN_SEQUENCE_KEY);
OMElement definitions = null;
try {
definitions = new StAXOMBuilder(is).getDocumentElement();
definitions.build();
if (Constants.SYNAPSE_NAMESPACE.equals(definitions.getNamespace().getNamespaceURI())
&& Constants.DEFINITIONS_ELT.getLocalPart()
.equals(definitions.getQName().getLocalPart())) {
Iterator iter = definitions.getChildren();
while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof OMElement) {
OMElement elt = (OMElement) o;
if (Constants.SEQUENCE_ELT.equals(elt.getQName())) {
String key = elt.getAttributeValue(
new QName(Constants.NULL_NAMESPACE, "key"));
// this could be a sequence def or a mediator of the main sequence
if (key != null) {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
} else {
defineSequence(config, elt);
}
} else if (Constants.ENDPOINT_ELT.equals(elt.getQName())) {
defineEndpoint(config, elt);
} else if (Constants.ENTRY_ELT.equals(elt.getQName())) {
defineEntry(config, elt);
} else if (Constants.PROXY_ELT.equals(elt.getQName())) {
defineProxy(config, elt);
} else if (Constants.REGISTRY_ELT.equals(elt.getQName())) {
defineRegistry(config, elt);
} else {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
}
}
}
} else {
handleException("Invalid Synapse Configuration : No definition element found");
}
} catch (XMLStreamException e) {
handleException("Error parsing Synapse configuration : " + e.getMessage(), e);
}
if (is != null) {
try {
is.close();
} catch (IOException ignore) {}
}
- if (config.getLocalRegistry().isEmpty() && config
- .getProxyServices().isEmpty() && config.getRegistry() != null) {
+ if (config.getLocalRegistry().isEmpty() && config.getProxyServices().isEmpty() &&
+ rootSequence.getList().isEmpty() && config.getRegistry() != null) {
OMNode remoteConfigNode = config.getRegistry().lookup("synapse.xml");
config = getConfiguration(Util.getStreamSource(remoteConfigNode).getInputStream());
}
if (config.getMainSequence() == null) {
if (rootSequence.getList().isEmpty()) {
setDefaultMainSequence(config);
} else {
config.addSequence(rootSequence.getName(), rootSequence);
}
+ } else if (!rootSequence.getList().isEmpty()) {
+ handleException("Invalid Synapse Configuration : Conflict in resolving the \"main\" " +
+ "mediator\n\tSynapse Configuration cannot have sequence named \"main\" and " +
+ "toplevel mediators simultaniously");
}
if (config.getFaultSequence() == null) {
setDefaultFaultSequence(config);
}
return config;
}
private static void defineRegistry(SynapseConfiguration config, OMElement elem) {
if (config.getRegistry() != null) {
handleException("Only one remote registry can be defined within a configuration");
}
config.setRegistry(RegistryFactory.createRegistry(elem));
}
private static void defineProxy(SynapseConfiguration config, OMElement elem) {
ProxyService proxy = ProxyServiceFactory.createProxy(elem);
if (config.getProxyService(proxy.getName()) != null) {
handleException("Duplicate proxy service with name : " + proxy.getName());
}
config.addProxyService(proxy.getName(), proxy);
}
private static void defineEntry(SynapseConfiguration config, OMElement elem) {
Entry entry = EntryFactory.createEntry(elem);
if (config.getLocalRegistry().get(entry.getKey()) != null) {
handleException("Duplicate registry entry definition for key : " + entry.getKey());
}
config.addEntry(entry.getKey(), entry);
}
public static void defineSequence(SynapseConfiguration config, OMElement ele) {
String name = ele.getAttributeValue(new QName(Constants.NULL_NAMESPACE, "name"));
if (name != null) {
if (config.getLocalRegistry().get(name) != null) {
handleException("Duplicate sequence definition : " + name);
}
config.addSequence(name, MediatorFactoryFinder.getInstance().getMediator(ele));
} else {
handleException("Invalid sequence definition without a name");
}
}
public static void defineEndpoint(SynapseConfiguration config, OMElement ele) {
String name = ele.getAttributeValue(new QName(Constants.NULL_NAMESPACE, "name"));
if (name != null) {
if (config.getLocalRegistry().get(name) != null) {
handleException("Duplicate endpoint definition : " + name);
}
Endpoint endpoint =
EndpointAbstractFactory.getEndpointFactroy(ele).createEndpoint(ele, false);
config.addEndpoint(name, endpoint);
} else {
handleException("Invalid endpoint definition without a name");
}
}
/**
* Return the main sequence if one is not defined. This implementation defaults to
* a simple sequence with a <send/>
*
* @param config the configuration to be updated
*/
private static void setDefaultMainSequence(SynapseConfiguration config) {
SequenceMediator main = new SequenceMediator();
main.setName(org.apache.synapse.Constants.MAIN_SEQUENCE_KEY);
main.addChild(new SendMediator());
config.addSequence(org.apache.synapse.Constants.MAIN_SEQUENCE_KEY, main);
}
/**
* Return the fault sequence if one is not defined. This implementation defaults to
* a simple sequence with a <log level="full"/>
*
* @param config the configuration to be updated
*/
private static void setDefaultFaultSequence(SynapseConfiguration config) {
SequenceMediator fault = new SequenceMediator();
fault.setName(org.apache.synapse.Constants.FAULT_SEQUENCE_KEY);
LogMediator log = new LogMediator();
log.setLogLevel(LogMediator.FULL);
fault.addChild(log);
config.addSequence(org.apache.synapse.Constants.FAULT_SEQUENCE_KEY, fault);
}
private static void handleException(String msg) {
log.error(msg);
throw new SynapseException(msg);
}
private static void handleException(String msg, Exception e) {
log.error(msg, e);
throw new SynapseException(msg, e);
}
}
| false | true | public static SynapseConfiguration getConfiguration(InputStream is) {
log.info("Generating the Synapse configuration model by parsing the XML configuration");
SynapseConfiguration config = new SynapseConfiguration();
SequenceMediator rootSequence = new SequenceMediator();
rootSequence.setName(org.apache.synapse.Constants.MAIN_SEQUENCE_KEY);
OMElement definitions = null;
try {
definitions = new StAXOMBuilder(is).getDocumentElement();
definitions.build();
if (Constants.SYNAPSE_NAMESPACE.equals(definitions.getNamespace().getNamespaceURI())
&& Constants.DEFINITIONS_ELT.getLocalPart()
.equals(definitions.getQName().getLocalPart())) {
Iterator iter = definitions.getChildren();
while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof OMElement) {
OMElement elt = (OMElement) o;
if (Constants.SEQUENCE_ELT.equals(elt.getQName())) {
String key = elt.getAttributeValue(
new QName(Constants.NULL_NAMESPACE, "key"));
// this could be a sequence def or a mediator of the main sequence
if (key != null) {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
} else {
defineSequence(config, elt);
}
} else if (Constants.ENDPOINT_ELT.equals(elt.getQName())) {
defineEndpoint(config, elt);
} else if (Constants.ENTRY_ELT.equals(elt.getQName())) {
defineEntry(config, elt);
} else if (Constants.PROXY_ELT.equals(elt.getQName())) {
defineProxy(config, elt);
} else if (Constants.REGISTRY_ELT.equals(elt.getQName())) {
defineRegistry(config, elt);
} else {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
}
}
}
} else {
handleException("Invalid Synapse Configuration : No definition element found");
}
} catch (XMLStreamException e) {
handleException("Error parsing Synapse configuration : " + e.getMessage(), e);
}
if (is != null) {
try {
is.close();
} catch (IOException ignore) {}
}
if (config.getLocalRegistry().isEmpty() && config
.getProxyServices().isEmpty() && config.getRegistry() != null) {
OMNode remoteConfigNode = config.getRegistry().lookup("synapse.xml");
config = getConfiguration(Util.getStreamSource(remoteConfigNode).getInputStream());
}
if (config.getMainSequence() == null) {
if (rootSequence.getList().isEmpty()) {
setDefaultMainSequence(config);
} else {
config.addSequence(rootSequence.getName(), rootSequence);
}
}
if (config.getFaultSequence() == null) {
setDefaultFaultSequence(config);
}
return config;
}
| public static SynapseConfiguration getConfiguration(InputStream is) {
log.info("Generating the Synapse configuration model by parsing the XML configuration");
SynapseConfiguration config = new SynapseConfiguration();
SequenceMediator rootSequence = new SequenceMediator();
rootSequence.setName(org.apache.synapse.Constants.MAIN_SEQUENCE_KEY);
OMElement definitions = null;
try {
definitions = new StAXOMBuilder(is).getDocumentElement();
definitions.build();
if (Constants.SYNAPSE_NAMESPACE.equals(definitions.getNamespace().getNamespaceURI())
&& Constants.DEFINITIONS_ELT.getLocalPart()
.equals(definitions.getQName().getLocalPart())) {
Iterator iter = definitions.getChildren();
while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof OMElement) {
OMElement elt = (OMElement) o;
if (Constants.SEQUENCE_ELT.equals(elt.getQName())) {
String key = elt.getAttributeValue(
new QName(Constants.NULL_NAMESPACE, "key"));
// this could be a sequence def or a mediator of the main sequence
if (key != null) {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
} else {
defineSequence(config, elt);
}
} else if (Constants.ENDPOINT_ELT.equals(elt.getQName())) {
defineEndpoint(config, elt);
} else if (Constants.ENTRY_ELT.equals(elt.getQName())) {
defineEntry(config, elt);
} else if (Constants.PROXY_ELT.equals(elt.getQName())) {
defineProxy(config, elt);
} else if (Constants.REGISTRY_ELT.equals(elt.getQName())) {
defineRegistry(config, elt);
} else {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
}
}
}
} else {
handleException("Invalid Synapse Configuration : No definition element found");
}
} catch (XMLStreamException e) {
handleException("Error parsing Synapse configuration : " + e.getMessage(), e);
}
if (is != null) {
try {
is.close();
} catch (IOException ignore) {}
}
if (config.getLocalRegistry().isEmpty() && config.getProxyServices().isEmpty() &&
rootSequence.getList().isEmpty() && config.getRegistry() != null) {
OMNode remoteConfigNode = config.getRegistry().lookup("synapse.xml");
config = getConfiguration(Util.getStreamSource(remoteConfigNode).getInputStream());
}
if (config.getMainSequence() == null) {
if (rootSequence.getList().isEmpty()) {
setDefaultMainSequence(config);
} else {
config.addSequence(rootSequence.getName(), rootSequence);
}
} else if (!rootSequence.getList().isEmpty()) {
handleException("Invalid Synapse Configuration : Conflict in resolving the \"main\" " +
"mediator\n\tSynapse Configuration cannot have sequence named \"main\" and " +
"toplevel mediators simultaniously");
}
if (config.getFaultSequence() == null) {
setDefaultFaultSequence(config);
}
return config;
}
|
diff --git a/src/main/java/org/springframework/web/servlet/view/jangod/JangodViewResolver.java b/src/main/java/org/springframework/web/servlet/view/jangod/JangodViewResolver.java
index 6a109e3..d29155c 100644
--- a/src/main/java/org/springframework/web/servlet/view/jangod/JangodViewResolver.java
+++ b/src/main/java/org/springframework/web/servlet/view/jangod/JangodViewResolver.java
@@ -1,80 +1,80 @@
/**********************************************************************
Copyright (c) 2010 Asfun Net.
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.web.servlet.view.jangod;
import java.io.File;
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
import org.springframework.web.util.WebUtils;
public class JangodViewResolver extends AbstractTemplateViewResolver {
private JangodConfig jangodConfig;
protected boolean isConfigUnset = true;
private ModelDataProvider commonAttributes;
public JangodViewResolver() {
setViewClass(requiredViewClass());
}
@Override
protected Class<?> requiredViewClass() {
return JangodView.class;
}
@Override
protected AbstractUrlBasedView buildView(String viewName) throws Exception {
JangodView view = (JangodView) super.buildView(viewName);
if (isConfigUnset) {
try {
- String webRoot = WebUtils.getRealPath(getServletContext(), "/");
+ String webRoot = WebUtils.getRealPath(getServletContext(), getPrefix());
if (!webRoot.endsWith(File.separator)) {
webRoot += File.separator;
}
- this.jangodConfig.setRoot(webRoot + getPrefix());
+ this.jangodConfig.setRoot(webRoot);
} catch (Exception e) {
logger.error("set web root to template engine error.",
e.getCause());
}
if (commonAttributes != null) {
jangodConfig.getEngine().setEngineBindings(
commonAttributes.getModel());
}
isConfigUnset = false;
}
view.setJangodConfig(jangodConfig);
view.setUrl(viewName + getSuffix());
return view;
}
public JangodConfig getJangodConfig() {
return jangodConfig;
}
public void setJangodConfig(JangodConfig jangodConfig) {
this.jangodConfig = jangodConfig;
}
public ModelDataProvider getCommonAttributes() {
return commonAttributes;
}
public void setCommonAttributes(ModelDataProvider commonAttributes) {
this.commonAttributes = commonAttributes;
}
}
| false | true | protected AbstractUrlBasedView buildView(String viewName) throws Exception {
JangodView view = (JangodView) super.buildView(viewName);
if (isConfigUnset) {
try {
String webRoot = WebUtils.getRealPath(getServletContext(), "/");
if (!webRoot.endsWith(File.separator)) {
webRoot += File.separator;
}
this.jangodConfig.setRoot(webRoot + getPrefix());
} catch (Exception e) {
logger.error("set web root to template engine error.",
e.getCause());
}
if (commonAttributes != null) {
jangodConfig.getEngine().setEngineBindings(
commonAttributes.getModel());
}
isConfigUnset = false;
}
view.setJangodConfig(jangodConfig);
view.setUrl(viewName + getSuffix());
return view;
}
| protected AbstractUrlBasedView buildView(String viewName) throws Exception {
JangodView view = (JangodView) super.buildView(viewName);
if (isConfigUnset) {
try {
String webRoot = WebUtils.getRealPath(getServletContext(), getPrefix());
if (!webRoot.endsWith(File.separator)) {
webRoot += File.separator;
}
this.jangodConfig.setRoot(webRoot);
} catch (Exception e) {
logger.error("set web root to template engine error.",
e.getCause());
}
if (commonAttributes != null) {
jangodConfig.getEngine().setEngineBindings(
commonAttributes.getModel());
}
isConfigUnset = false;
}
view.setJangodConfig(jangodConfig);
view.setUrl(viewName + getSuffix());
return view;
}
|
diff --git a/atlas-web/src/main/java/uk/ac/ebi/gxa/tasks/RepairExperimentTask.java b/atlas-web/src/main/java/uk/ac/ebi/gxa/tasks/RepairExperimentTask.java
index 252652725..e342afdee 100644
--- a/atlas-web/src/main/java/uk/ac/ebi/gxa/tasks/RepairExperimentTask.java
+++ b/atlas-web/src/main/java/uk/ac/ebi/gxa/tasks/RepairExperimentTask.java
@@ -1,91 +1,94 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.tasks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author pashky
*/
public class RepairExperimentTask extends AbstractWorkingTask {
private static Logger log = LoggerFactory.getLogger(RepairExperimentTask.class);
public static final String TYPE = "repairexperiment";
public void start() {
final String accession = getTaskSpec().getAccession();
log.info("Repair experiment - task started, checking NetCDF");
final TaskSpec netcdfSpec = LoaderTask.SPEC_UPDATEEXPERIMENT(accession);
final TaskStatus netcdfState = taskMan.getTaskStatus(netcdfSpec);
if(TaskStatus.DONE != netcdfState) {
taskMan.scheduleTask(this, netcdfSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
+ taskMan.notifyTaskFinished(this);
return;
}
log.info("Repair experiment - NetCDF is complete, checking analytics");
final TaskSpec analyticsSpec = AnalyticsTask.SPEC_ANALYTICS(accession);
final TaskStatus analyticsState = taskMan.getTaskStatus(analyticsSpec);
if(TaskStatus.DONE != analyticsState) {
taskMan.scheduleTask(this, analyticsSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
+ taskMan.notifyTaskFinished(this);
return;
}
log.info("Repair experiment - analytics is complete, checking index");
final TaskSpec indexSpec = IndexTask.SPEC_INDEXEXPERIMENT(accession);
final TaskStatus indexState = taskMan.getTaskStatus(indexSpec);
if(TaskStatus.DONE != indexState) {
taskMan.scheduleTask(this, indexSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
+ taskMan.notifyTaskFinished(this);
return;
}
log.info("Repair experiment - index is complete, nothing to do");
taskMan.notifyTaskFinished(this);
}
public void stop() {
}
public RepairExperimentTask(TaskManager taskMan, long taskId, TaskSpec taskSpec, TaskRunMode runMode, TaskUser user, boolean runningAutoDependencies) {
super(taskMan, taskId, taskSpec, runMode, user, runningAutoDependencies);
}
public boolean isBlockedBy(Task otherTask) {
return false;
}
public static final TaskFactory FACTORY = new TaskFactory() {
public QueuedTask createTask(TaskManager taskMan, long taskId, TaskSpec taskSpec, TaskRunMode runMode, TaskUser user, boolean runningAutoDependencies) {
return new RepairExperimentTask(taskMan, taskId, taskSpec, runMode, user, runningAutoDependencies);
}
public boolean isFor(TaskSpec taskSpec) {
return TYPE.equals(taskSpec.getType());
}
};
}
| false | true | public void start() {
final String accession = getTaskSpec().getAccession();
log.info("Repair experiment - task started, checking NetCDF");
final TaskSpec netcdfSpec = LoaderTask.SPEC_UPDATEEXPERIMENT(accession);
final TaskStatus netcdfState = taskMan.getTaskStatus(netcdfSpec);
if(TaskStatus.DONE != netcdfState) {
taskMan.scheduleTask(this, netcdfSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
return;
}
log.info("Repair experiment - NetCDF is complete, checking analytics");
final TaskSpec analyticsSpec = AnalyticsTask.SPEC_ANALYTICS(accession);
final TaskStatus analyticsState = taskMan.getTaskStatus(analyticsSpec);
if(TaskStatus.DONE != analyticsState) {
taskMan.scheduleTask(this, analyticsSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
return;
}
log.info("Repair experiment - analytics is complete, checking index");
final TaskSpec indexSpec = IndexTask.SPEC_INDEXEXPERIMENT(accession);
final TaskStatus indexState = taskMan.getTaskStatus(indexSpec);
if(TaskStatus.DONE != indexState) {
taskMan.scheduleTask(this, indexSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
return;
}
log.info("Repair experiment - index is complete, nothing to do");
taskMan.notifyTaskFinished(this);
}
| public void start() {
final String accession = getTaskSpec().getAccession();
log.info("Repair experiment - task started, checking NetCDF");
final TaskSpec netcdfSpec = LoaderTask.SPEC_UPDATEEXPERIMENT(accession);
final TaskStatus netcdfState = taskMan.getTaskStatus(netcdfSpec);
if(TaskStatus.DONE != netcdfState) {
taskMan.scheduleTask(this, netcdfSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
taskMan.notifyTaskFinished(this);
return;
}
log.info("Repair experiment - NetCDF is complete, checking analytics");
final TaskSpec analyticsSpec = AnalyticsTask.SPEC_ANALYTICS(accession);
final TaskStatus analyticsState = taskMan.getTaskStatus(analyticsSpec);
if(TaskStatus.DONE != analyticsState) {
taskMan.scheduleTask(this, analyticsSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
taskMan.notifyTaskFinished(this);
return;
}
log.info("Repair experiment - analytics is complete, checking index");
final TaskSpec indexSpec = IndexTask.SPEC_INDEXEXPERIMENT(accession);
final TaskStatus indexState = taskMan.getTaskStatus(indexSpec);
if(TaskStatus.DONE != indexState) {
taskMan.scheduleTask(this, indexSpec, TaskRunMode.CONTINUE, getUser(), true,
"Automatically added by experiment " + accession + " repair task");
taskMan.notifyTaskFinished(this);
return;
}
log.info("Repair experiment - index is complete, nothing to do");
taskMan.notifyTaskFinished(this);
}
|
diff --git a/src/org/opensolaris/opengrok/web/DirectoryListing.java b/src/org/opensolaris/opengrok/web/DirectoryListing.java
index 26e5038..b5fabbd 100644
--- a/src/org/opensolaris/opengrok/web/DirectoryListing.java
+++ b/src/org/opensolaris/opengrok/web/DirectoryListing.java
@@ -1,150 +1,150 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.web;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import org.opensolaris.opengrok.OpenGrokLogger;
import org.opensolaris.opengrok.configuration.RuntimeEnvironment;
import org.opensolaris.opengrok.index.IgnoredNames;
/**
* Generates HTML listing of a Directory
*/
public class DirectoryListing {
private final EftarFileReader desc;
private final long now;
public DirectoryListing() {
desc = null;
now = System.currentTimeMillis();
}
public DirectoryListing(EftarFileReader desc) {
this.desc = desc;
now = System.currentTimeMillis();
}
public void listTo(File dir, Writer out) throws IOException {
String[] files = dir.list();
if (files != null) {
listTo(dir, out, dir.getPath(), files);
}
}
/**
* Write a listing of "dir" to "out"
*
* @param dir to be Listed
* @param out writer to write
* @param path Virtual Path of the directory
* @param files childred of dir
* @return a list of READMEs
* @throws java.io.IOException
*
*/
- public List listTo(File dir, Writer out, String path, String[] files) throws IOException {
+ public List<String> listTo(File dir, Writer out, String path, String[] files) throws IOException {
Arrays.sort(files, String.CASE_INSENSITIVE_ORDER);
boolean alt = true;
Format dateFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
out.write("<table cellspacing=\"0\" border=\"0\" id=\"dirlist\">");
EftarFileReader.FNode parentFNode = null;
if (!"".equals(path)) {
out.write("<tr><td colspan=\"4\"><a href=\"..\"><i>Up to higher level directory</i></a></td></tr>");
}
if (desc != null) {
parentFNode = desc.getNode(path);
}
out.write("<tr class=\"thead\"><th><tt>Name</tt></th><th><tt>Date</tt></th><th><tt>Size</tt></th>");
if (parentFNode != null && parentFNode.childOffset > 0) {
out.write("<th><tt>Description</tt></th>");
}
out.write("</tr>");
ArrayList<String> readMes = new ArrayList<String>();
IgnoredNames ignoredNames = RuntimeEnvironment.getInstance().getIgnoredNames();
for (String file : files) {
if (!ignoredNames.ignore(file)) {
File child = new File(dir, file);
if (file.startsWith("README") || file.endsWith("README") || file.startsWith("readme")) {
readMes.add(file);
}
alt = !alt;
out.write("<tr align=\"right\"");
out.write(alt ? " class=\"alt\"" : "");
boolean isDir = child.isDirectory();
out.write("><td align=\"left\"><tt><a href=\"" + Util.URIEncodePath(file) + (isDir ? "/\" class=\"r\"" : "\" class=\"p\"") + ">");
if (isDir) {
out.write("<b>" + file + "</b></a>/");
} else {
out.write(file + "</a>");
}
Date lastm = new Date(child.lastModified());
out.write("</tt></td><td>" + ((now - lastm.getTime()) < 86400000 ? "Today" : dateFormatter.format(lastm)) + "</td>");
out.write("<td><tt>" + (isDir ? "" : Util.redableSize(child.length())) + "</tt></td>");
if (parentFNode != null && parentFNode.childOffset > 0) {
String briefDesc = desc.getChildTag(parentFNode, file);
if (briefDesc == null) {
out.write("<td></td>");
} else {
out.write("<td align=\"left\">");
out.write(briefDesc);
out.write("</td>");
}
}
out.write("</tr>");
}
}
out.write("</table>");
return readMes;
}
public static void main(String[] args) {
try {
DirectoryListing dl = new DirectoryListing();
File tolist = new File(args[0]);
File outFile = new File(args[1]);
BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
dl.listTo(tolist, out);
out.close();
} catch (Exception e) {
OpenGrokLogger.getLogger().log(Level.WARNING, "Usage DirListing <dir> <output.html>", e);
}
}
}
| true | true | public List listTo(File dir, Writer out, String path, String[] files) throws IOException {
Arrays.sort(files, String.CASE_INSENSITIVE_ORDER);
boolean alt = true;
Format dateFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
out.write("<table cellspacing=\"0\" border=\"0\" id=\"dirlist\">");
EftarFileReader.FNode parentFNode = null;
if (!"".equals(path)) {
out.write("<tr><td colspan=\"4\"><a href=\"..\"><i>Up to higher level directory</i></a></td></tr>");
}
if (desc != null) {
parentFNode = desc.getNode(path);
}
out.write("<tr class=\"thead\"><th><tt>Name</tt></th><th><tt>Date</tt></th><th><tt>Size</tt></th>");
if (parentFNode != null && parentFNode.childOffset > 0) {
out.write("<th><tt>Description</tt></th>");
}
out.write("</tr>");
ArrayList<String> readMes = new ArrayList<String>();
IgnoredNames ignoredNames = RuntimeEnvironment.getInstance().getIgnoredNames();
for (String file : files) {
if (!ignoredNames.ignore(file)) {
File child = new File(dir, file);
if (file.startsWith("README") || file.endsWith("README") || file.startsWith("readme")) {
readMes.add(file);
}
alt = !alt;
out.write("<tr align=\"right\"");
out.write(alt ? " class=\"alt\"" : "");
boolean isDir = child.isDirectory();
out.write("><td align=\"left\"><tt><a href=\"" + Util.URIEncodePath(file) + (isDir ? "/\" class=\"r\"" : "\" class=\"p\"") + ">");
if (isDir) {
out.write("<b>" + file + "</b></a>/");
} else {
out.write(file + "</a>");
}
Date lastm = new Date(child.lastModified());
out.write("</tt></td><td>" + ((now - lastm.getTime()) < 86400000 ? "Today" : dateFormatter.format(lastm)) + "</td>");
out.write("<td><tt>" + (isDir ? "" : Util.redableSize(child.length())) + "</tt></td>");
if (parentFNode != null && parentFNode.childOffset > 0) {
String briefDesc = desc.getChildTag(parentFNode, file);
if (briefDesc == null) {
out.write("<td></td>");
} else {
out.write("<td align=\"left\">");
out.write(briefDesc);
out.write("</td>");
}
}
out.write("</tr>");
}
}
out.write("</table>");
return readMes;
}
| public List<String> listTo(File dir, Writer out, String path, String[] files) throws IOException {
Arrays.sort(files, String.CASE_INSENSITIVE_ORDER);
boolean alt = true;
Format dateFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
out.write("<table cellspacing=\"0\" border=\"0\" id=\"dirlist\">");
EftarFileReader.FNode parentFNode = null;
if (!"".equals(path)) {
out.write("<tr><td colspan=\"4\"><a href=\"..\"><i>Up to higher level directory</i></a></td></tr>");
}
if (desc != null) {
parentFNode = desc.getNode(path);
}
out.write("<tr class=\"thead\"><th><tt>Name</tt></th><th><tt>Date</tt></th><th><tt>Size</tt></th>");
if (parentFNode != null && parentFNode.childOffset > 0) {
out.write("<th><tt>Description</tt></th>");
}
out.write("</tr>");
ArrayList<String> readMes = new ArrayList<String>();
IgnoredNames ignoredNames = RuntimeEnvironment.getInstance().getIgnoredNames();
for (String file : files) {
if (!ignoredNames.ignore(file)) {
File child = new File(dir, file);
if (file.startsWith("README") || file.endsWith("README") || file.startsWith("readme")) {
readMes.add(file);
}
alt = !alt;
out.write("<tr align=\"right\"");
out.write(alt ? " class=\"alt\"" : "");
boolean isDir = child.isDirectory();
out.write("><td align=\"left\"><tt><a href=\"" + Util.URIEncodePath(file) + (isDir ? "/\" class=\"r\"" : "\" class=\"p\"") + ">");
if (isDir) {
out.write("<b>" + file + "</b></a>/");
} else {
out.write(file + "</a>");
}
Date lastm = new Date(child.lastModified());
out.write("</tt></td><td>" + ((now - lastm.getTime()) < 86400000 ? "Today" : dateFormatter.format(lastm)) + "</td>");
out.write("<td><tt>" + (isDir ? "" : Util.redableSize(child.length())) + "</tt></td>");
if (parentFNode != null && parentFNode.childOffset > 0) {
String briefDesc = desc.getChildTag(parentFNode, file);
if (briefDesc == null) {
out.write("<td></td>");
} else {
out.write("<td align=\"left\">");
out.write(briefDesc);
out.write("</td>");
}
}
out.write("</tr>");
}
}
out.write("</table>");
return readMes;
}
|
diff --git a/src/org/subsurface/ws/json/DiveParser.java b/src/org/subsurface/ws/json/DiveParser.java
index e0268ed..60ee087 100644
--- a/src/org/subsurface/ws/json/DiveParser.java
+++ b/src/org/subsurface/ws/json/DiveParser.java
@@ -1,54 +1,54 @@
package org.subsurface.ws.json;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.subsurface.model.DiveLocationLog;
import org.subsurface.util.DateUtils;
public class DiveParser {
public static List<DiveLocationLog> parseDives(InputStream in) throws JSONException, IOException {
ArrayList<DiveLocationLog> dives = new ArrayList<DiveLocationLog>();
// Get stream content
ByteArrayOutputStream streamContent = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int readBytes;
while ((readBytes = in.read(buff)) != -1) {
streamContent.write(buff, 0, readBytes);
}
// Parse dives
JSONObject jsonRoot = new JSONObject(new String(streamContent.toByteArray()));
JSONArray jsonDives = jsonRoot.optJSONArray("dives");
if (jsonDives != null) {
int diveLength = jsonDives.length();
for (int i = 0; i < diveLength; ++i) {
JSONObject jsonDive = jsonDives.getJSONObject(i);
DiveLocationLog dive = new DiveLocationLog();
dive.setSent(true);
dive.setName(jsonDive.optString("name", ""));
- dive.setLongitude(jsonDive.getLong("longitude"));
- dive.setLatitude(jsonDive.getLong("latitude"));
+ dive.setLongitude(jsonDive.getDouble("longitude"));
+ dive.setLatitude(jsonDive.getDouble("latitude"));
try {
long timestamp = DateUtils.initGMT("yyyy-MM-dd").parse(jsonDive.getString("date")).getTime();
timestamp += DateUtils.initGMT("HH:mm").parse(jsonDive.getString("time")).getTime();
dive.setTimestamp(timestamp);
dives.add(dive);
} catch (ParseException pe) {
throw new JSONException("Could not parse date");
}
}
}
return dives;
}
}
| true | true | public static List<DiveLocationLog> parseDives(InputStream in) throws JSONException, IOException {
ArrayList<DiveLocationLog> dives = new ArrayList<DiveLocationLog>();
// Get stream content
ByteArrayOutputStream streamContent = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int readBytes;
while ((readBytes = in.read(buff)) != -1) {
streamContent.write(buff, 0, readBytes);
}
// Parse dives
JSONObject jsonRoot = new JSONObject(new String(streamContent.toByteArray()));
JSONArray jsonDives = jsonRoot.optJSONArray("dives");
if (jsonDives != null) {
int diveLength = jsonDives.length();
for (int i = 0; i < diveLength; ++i) {
JSONObject jsonDive = jsonDives.getJSONObject(i);
DiveLocationLog dive = new DiveLocationLog();
dive.setSent(true);
dive.setName(jsonDive.optString("name", ""));
dive.setLongitude(jsonDive.getLong("longitude"));
dive.setLatitude(jsonDive.getLong("latitude"));
try {
long timestamp = DateUtils.initGMT("yyyy-MM-dd").parse(jsonDive.getString("date")).getTime();
timestamp += DateUtils.initGMT("HH:mm").parse(jsonDive.getString("time")).getTime();
dive.setTimestamp(timestamp);
dives.add(dive);
} catch (ParseException pe) {
throw new JSONException("Could not parse date");
}
}
}
return dives;
}
| public static List<DiveLocationLog> parseDives(InputStream in) throws JSONException, IOException {
ArrayList<DiveLocationLog> dives = new ArrayList<DiveLocationLog>();
// Get stream content
ByteArrayOutputStream streamContent = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int readBytes;
while ((readBytes = in.read(buff)) != -1) {
streamContent.write(buff, 0, readBytes);
}
// Parse dives
JSONObject jsonRoot = new JSONObject(new String(streamContent.toByteArray()));
JSONArray jsonDives = jsonRoot.optJSONArray("dives");
if (jsonDives != null) {
int diveLength = jsonDives.length();
for (int i = 0; i < diveLength; ++i) {
JSONObject jsonDive = jsonDives.getJSONObject(i);
DiveLocationLog dive = new DiveLocationLog();
dive.setSent(true);
dive.setName(jsonDive.optString("name", ""));
dive.setLongitude(jsonDive.getDouble("longitude"));
dive.setLatitude(jsonDive.getDouble("latitude"));
try {
long timestamp = DateUtils.initGMT("yyyy-MM-dd").parse(jsonDive.getString("date")).getTime();
timestamp += DateUtils.initGMT("HH:mm").parse(jsonDive.getString("time")).getTime();
dive.setTimestamp(timestamp);
dives.add(dive);
} catch (ParseException pe) {
throw new JSONException("Could not parse date");
}
}
}
return dives;
}
|
diff --git a/src/Game.java b/src/Game.java
index 1c8d1ed..6a94ae7 100644
--- a/src/Game.java
+++ b/src/Game.java
@@ -1,180 +1,180 @@
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends JFrame implements MouseListener {
/**
* @param args
*/
Monster ghost;
Map map;
List path;
boolean walkAllowed;
public Game()
{
super("CIn Walking Ghost!");
setSize(640, 480);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loadAssets();
ghost.x = 80;
ghost.y = 80;
this.addMouseListener(this);
walkAllowed = false;
}
public void loadAssets()
{
try {
ghost = new Monster("ghost.png");
map = new Map("tileSet.txt", "Mapa.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Nao usado
public Graphics2D getContext(Graphics g)
{
/***********CONFIGURING PAINTING CONTEXT************************/
//Criamos um contexto gr�fico com a �rea de pintura restrita
//ao interior da janela.
Graphics2D clip = (Graphics2D) g.create(getInsets().left,
getInsets().top,
getWidth() - getInsets().right,
getHeight() - getInsets().bottom);
//Pintamos o fundo do frame de preto
clip.setColor(Color.BLACK);
clip.fill(clip.getClipBounds());
//Pintamos a snake
clip.setColor(Color.WHITE);
/***********CONFIGURING PAINTING CONTEXT************************/
return clip;
}
public void paint(Graphics g)
{
Graphics clip = g;
map.paint(clip);
if( walkAllowed && path != null && !path.isEmpty())
{
- ghost.x = path.head.a;
- ghost.y = path.head.b;
+ ghost.x = path.head.b*map.tileW;
+ ghost.y = path.head.a*map.tileH;
path.removeFront();
}
else if (path != null && path.isEmpty())
{
walkAllowed = false;
map.reload();
}
ghost.paint(clip);
this.repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void mouseClicked(MouseEvent event) {
// TODO Auto-generated method stub
System.out.println("Mouse clicked Point: " + event.getPoint());
path = ghost.computePath(map, event.getPoint());
/*
Node it = path.head;
while( it != null )
{
map.setTile(it.x, it.y, 2);
it = it.next;
}
System.out.println("Path length: " + path.size);
*/
walkAllowed = true;
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("Mouse entered");
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("mouse exited");
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("mouse pressed");
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("mouse released");
}
}
| true | true | public void paint(Graphics g)
{
Graphics clip = g;
map.paint(clip);
if( walkAllowed && path != null && !path.isEmpty())
{
ghost.x = path.head.a;
ghost.y = path.head.b;
path.removeFront();
}
else if (path != null && path.isEmpty())
{
walkAllowed = false;
map.reload();
}
ghost.paint(clip);
this.repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void paint(Graphics g)
{
Graphics clip = g;
map.paint(clip);
if( walkAllowed && path != null && !path.isEmpty())
{
ghost.x = path.head.b*map.tileW;
ghost.y = path.head.a*map.tileH;
path.removeFront();
}
else if (path != null && path.isEmpty())
{
walkAllowed = false;
map.reload();
}
ghost.paint(clip);
this.repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/WEB-INF/src/edu/wustl/catissuecore/action/CreateSpecimenAction.java b/WEB-INF/src/edu/wustl/catissuecore/action/CreateSpecimenAction.java
index 67bd27b80..d620eb517 100644
--- a/WEB-INF/src/edu/wustl/catissuecore/action/CreateSpecimenAction.java
+++ b/WEB-INF/src/edu/wustl/catissuecore/action/CreateSpecimenAction.java
@@ -1,77 +1,78 @@
/**
* <p>Title: CreateSpecimenAction Class>
* <p>Description: CreateSpecimenAction initializes the fields in the Create Specimen page.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Aniruddha Phadnis
* @version 1.00
*/
package edu.wustl.catissuecore.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.CreateSpecimenForm;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.CreateSpecimenBizLogic;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.cde.CDEManager;
/**
* CreateSpecimenAction initializes the fields in the Create Specimen page.
* @author aniruddha_phadnis
*/
public class CreateSpecimenAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
*/
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
//Gets the value of the operation parameter.
String operation = request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Add/Edit User Page.
request.setAttribute(Constants.OPERATION, operation);
String pageOf = request.getParameter(Constants.PAGEOF);
request.setAttribute(Constants.PAGEOF,pageOf);
CreateSpecimenBizLogic dao = (CreateSpecimenBizLogic)BizLogicFactory.getBizLogic(Constants.CREATE_SPECIMEN_FORM_ID);
CreateSpecimenForm createForm = (CreateSpecimenForm) form;
try
{
String [] fields = {"systemIdentifier"};
List parentSpecimenList = dao.getList(Specimen.class.getName(), fields, fields[0]);
request.setAttribute(Constants.PARENT_SPECIMEN_ID_LIST,parentSpecimenList);
List specimenClassList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_SPECIMEN_CLASS);
request.setAttribute(Constants.SPECIMEN_CLASS_LIST, specimenClassList);
List specimenTypeList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_SPECIMEN_TYPE);
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
- request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, Constants.BIOHAZARD_TYPE_ARRAY);
+ List biohazardList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_BIOHAZARD);
+ request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, biohazardList);
}
catch(Exception e)
{
e.printStackTrace();
}
return mapping.findForward(Constants.SUCCESS);
}
}
| true | true | public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
//Gets the value of the operation parameter.
String operation = request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Add/Edit User Page.
request.setAttribute(Constants.OPERATION, operation);
String pageOf = request.getParameter(Constants.PAGEOF);
request.setAttribute(Constants.PAGEOF,pageOf);
CreateSpecimenBizLogic dao = (CreateSpecimenBizLogic)BizLogicFactory.getBizLogic(Constants.CREATE_SPECIMEN_FORM_ID);
CreateSpecimenForm createForm = (CreateSpecimenForm) form;
try
{
String [] fields = {"systemIdentifier"};
List parentSpecimenList = dao.getList(Specimen.class.getName(), fields, fields[0]);
request.setAttribute(Constants.PARENT_SPECIMEN_ID_LIST,parentSpecimenList);
List specimenClassList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_SPECIMEN_CLASS);
request.setAttribute(Constants.SPECIMEN_CLASS_LIST, specimenClassList);
List specimenTypeList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_SPECIMEN_TYPE);
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, Constants.BIOHAZARD_TYPE_ARRAY);
}
catch(Exception e)
{
e.printStackTrace();
}
return mapping.findForward(Constants.SUCCESS);
}
| public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
//Gets the value of the operation parameter.
String operation = request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Add/Edit User Page.
request.setAttribute(Constants.OPERATION, operation);
String pageOf = request.getParameter(Constants.PAGEOF);
request.setAttribute(Constants.PAGEOF,pageOf);
CreateSpecimenBizLogic dao = (CreateSpecimenBizLogic)BizLogicFactory.getBizLogic(Constants.CREATE_SPECIMEN_FORM_ID);
CreateSpecimenForm createForm = (CreateSpecimenForm) form;
try
{
String [] fields = {"systemIdentifier"};
List parentSpecimenList = dao.getList(Specimen.class.getName(), fields, fields[0]);
request.setAttribute(Constants.PARENT_SPECIMEN_ID_LIST,parentSpecimenList);
List specimenClassList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_SPECIMEN_CLASS);
request.setAttribute(Constants.SPECIMEN_CLASS_LIST, specimenClassList);
List specimenTypeList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_SPECIMEN_TYPE);
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
List biohazardList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_BIOHAZARD);
request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, biohazardList);
}
catch(Exception e)
{
e.printStackTrace();
}
return mapping.findForward(Constants.SUCCESS);
}
|
diff --git a/RandomizedQueuesAndDeques/Subset.java b/RandomizedQueuesAndDeques/Subset.java
index a7f3be3..1e9856e 100644
--- a/RandomizedQueuesAndDeques/Subset.java
+++ b/RandomizedQueuesAndDeques/Subset.java
@@ -1,12 +1,16 @@
public class Subset {
public static void main(String[] args) {
int K = Integer.parseInt(args[0]);
RandomizedQueue<String> queue = new RandomizedQueue<String>();
for (String s : StdIn.readAllStrings())
queue.enqueue(s);
+ int i = 0;
for (String s : queue) {
+ if (i == K)
+ break;
StdOut.println(s);
+ i += 1;
}
}
}
| false | true | public static void main(String[] args) {
int K = Integer.parseInt(args[0]);
RandomizedQueue<String> queue = new RandomizedQueue<String>();
for (String s : StdIn.readAllStrings())
queue.enqueue(s);
for (String s : queue) {
StdOut.println(s);
}
}
| public static void main(String[] args) {
int K = Integer.parseInt(args[0]);
RandomizedQueue<String> queue = new RandomizedQueue<String>();
for (String s : StdIn.readAllStrings())
queue.enqueue(s);
int i = 0;
for (String s : queue) {
if (i == K)
break;
StdOut.println(s);
i += 1;
}
}
|
diff --git a/baixing_quanleimu/src/com/quanleimu/view/PersonalCenterView.java b/baixing_quanleimu/src/com/quanleimu/view/PersonalCenterView.java
index b09a4a65..a7cb03d7 100644
--- a/baixing_quanleimu/src/com/quanleimu/view/PersonalCenterView.java
+++ b/baixing_quanleimu/src/com/quanleimu/view/PersonalCenterView.java
@@ -1,745 +1,746 @@
package com.quanleimu.view;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.quanleimu.entity.GoodsDetail;
import com.quanleimu.entity.GoodsList;
import com.quanleimu.entity.UserBean;
import com.quanleimu.jsonutil.JsonUtil;
import com.quanleimu.util.Communication;
import com.quanleimu.util.Helper;
import com.quanleimu.util.Util;
import com.quanleimu.adapter.GoodsListAdapter;
import com.quanleimu.view.BaseView;
import com.quanleimu.widget.PullToRefreshListView;
import com.quanleimu.activity.QuanleimuApplication;
import com.quanleimu.activity.R;
import android.widget.LinearLayout;
public class PersonalCenterView extends BaseView implements OnScrollListener, View.OnClickListener, PullToRefreshListView.OnRefreshListener, PullToRefreshListView.OnGetmoreListener{
private final int MCMESSAGE_MYPOST_SUCCESS = 0;
private final int MCMESSAGE_MYPOST_FAIL = 1;
private final int MCMESSAGE_DELETE = 2;
private final int MCMESSAGE_DELETE_SUCCESS = 3;
private final int MCMESSAGE_DELETE_FAIL = 4;
private final int MCMESSAGE_DELETEALL = 5;
private final int MCMESSAGE_MYHISTORY_UPDATE_SUCCESS = 6;
private final int MCMESSAGE_MYHISTORY_UPDATE_FAIL = 7;
private final int MCMESSAGE_MYFAV_UPDATE_SUCCESS = 8;
private final int MCMESSAGE_MYFAV_UPDATE_FAIL = 9;
private final int MCMESSAGE_NETWORKERROR = 10;
private final int MCMESSAGE_MYPOST_GETMORE_SUCCESS = 11;
private final int MCMESSAGE_MYPOST_GETMORE_FAIL = 12;
private final int MCMESSAGE_MYHISTORY_GETMORE_SUCCESS = 13;
private final int MCMESSAGE_MYHISTORY_GETMORE_FAIL = 14;
private final int MCMESSAGE_MYFAV_GETMORE_SUCCESS = 15;
private final int MCMESSAGE_MYFAV_GETMORE_FAIL = 16;
private final int MCMESSAGE_MYFAV_UPDATE_NOTNECESSARY = 20;
private final int MCMESSAGE_MYFAV_GETMORE_NOTNECESSARY = 21;
public PullToRefreshListView lvGoodsList;
public ImageView ivMyads, ivMyfav, ivMyhistory;
private List<GoodsDetail> listMyPost = new ArrayList<GoodsDetail>();
private List<GoodsDetail> goodsList = new ArrayList<GoodsDetail>();
public GoodsListAdapter adapter = null;
private String mobile;
private String json;
private String password;
UserBean user;
private int currentPage = -1;//-1:mypost, 0:myfav, 1:history
private Bundle bundle;
private int buttonStatus = -1;//-1:edit 0:finish
private View loginItem = null;
private boolean loginTried = false;
public PersonalCenterView(Context context, Bundle bundle){
super(context, bundle);
this.bundle = bundle;
init();
}
private void rebuildPage(boolean onResult){
LinearLayout lView = (LinearLayout)this.findViewById(R.id.linearListView);
if(-1 == currentPage){
ivMyads.setImageResource(R.drawable.btn_posted_press);
ivMyfav.setImageResource(R.drawable.btn_fav_normal);
ivMyhistory.setImageResource(R.drawable.btn_history_normal);
if(m_viewInfoListener != null){
TitleDef title = getTitleDef();
title.m_title = "我发布的信息";
m_viewInfoListener.onTitleChanged(title);
}
UserBean tmpBean = (UserBean) Util.loadDataFromLocate(this.getContext(), "user");
if(onResult ||
(tmpBean != null
&& user != null && tmpBean.getPhone().equals(user.getPhone()))){
adapter.setList(listMyPost);
adapter.notifyDataSetChanged();
}
else{
user = (UserBean) Util.loadDataFromLocate(this.getContext(), "user");
if (user != null) {
if(loginItem != null){
lView.removeView(loginItem);
}
lvGoodsList.setVisibility(View.VISIBLE);
mobile = user.getPhone();
password = user.getPassword();
pd = ProgressDialog.show(this.getContext(), "提示", "正在下载数据,请稍候...");
pd.setCancelable(true);
new Thread(new UpdateAndGetmoreThread(currentPage, true)).start();
} else {
if(null == loginItem){
LayoutInflater inflater = LayoutInflater.from(this.getContext());
loginItem = inflater.inflate(R.layout.item_post_select, null);
loginItem.setClickable(true);
TextView show = (TextView)loginItem.findViewById(R.id.postshow);
show.setText("登录或注册");
loginItem.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
bundle.putInt("type", 1);
bundle.putString("backPageName", "");
m_viewInfoListener.onNewView(new LoginView(getContext(), bundle));
}
});
}
if(loginItem.getParent() == null){
lView.addView(loginItem);
}
lvGoodsList.setVisibility(View.GONE);
}
}
// lvGoodsList.setPullToRefreshEnabled(true);
lvGoodsList.setAdapter(adapter);
}
else if(0 == currentPage){
if(loginItem != null){
lView.removeView(loginItem);
}
lvGoodsList.setVisibility(View.VISIBLE);
ivMyads.setImageResource(R.drawable.btn_posted_normal);
ivMyfav.setImageResource(R.drawable.btn_fav_press);
ivMyhistory.setImageResource(R.drawable.btn_history_normal);
if(m_viewInfoListener != null){
TitleDef title = getTitleDef();
title.m_title = "我的收藏";
title.m_rightActionHint = "编辑";
// title.m_leftActionHint = "更新";
m_viewInfoListener.onTitleChanged(title);
}
goodsList = QuanleimuApplication.getApplication().getListMyStore();
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
// lvGoodsList.setPullToRefreshEnabled(false);
}
else{
if(loginItem != null){
lView.removeView(loginItem);
}
lvGoodsList.setVisibility(View.VISIBLE);
ivMyads.setImageResource(R.drawable.btn_posted_normal);
ivMyfav.setImageResource(R.drawable.btn_fav_normal);
ivMyhistory.setImageResource(R.drawable.btn_history_press);
if(m_viewInfoListener != null){
TitleDef title = getTitleDef();
title.m_title = "我的历史";
title.m_rightActionHint = "编辑";
// title.m_leftActionHint = "更新";
m_viewInfoListener.onTitleChanged(title);
}
goodsList = QuanleimuApplication.getApplication().getListLookHistory();
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
// lvGoodsList.setPullToRefreshEnabled(false);
}
lvGoodsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg2 - lvGoodsList.getHeaderViewsCount();
if(index < 0)
return;
GoodsDetail detail = null;
if(currentPage == -1 && index < listMyPost.size() ){
detail = listMyPost.get(index);
}
else if(index < goodsList.size() && (0 == currentPage || 1 == currentPage)){
detail = goodsList.get(index);
}
if(null != detail){
GoodDetailView detailView = new GoodDetailView(detail, getContext(), bundle);
detailView.setInfoChangeListener(m_viewInfoListener);
m_viewInfoListener.onNewView(detailView);
}
}
});
lvGoodsList.setOnRefreshListener(this);
lvGoodsList.setOnGetMoreListener(this);
}
@Override
protected void onAttachedToWindow(){
super.onAttachedToWindow();
this.rebuildPage(false);
}
@Override
public void onPause(){
if(adapter != null){
adapter.setHasDelBtn(false);
adapter.notifyDataSetChanged();
}
buttonStatus = -1;
}
private void init(){
LayoutInflater inflater = LayoutInflater.from(this.getContext());
View v = inflater.inflate(R.layout.personalcenterview, null);
this.addView(v);
try {
if (Util.JadgeConnection(this.getContext()) == false) {
Toast.makeText(this.getContext(), "网络连接异常", 3).show();
// isConnect = 0;
myHandler.sendEmptyMessage(MCMESSAGE_NETWORKERROR);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lvGoodsList = (PullToRefreshListView) findViewById(R.id.lvGoodsList);
ivMyads = (ImageView) findViewById(R.id.ivMyads);
ivMyfav = (ImageView) findViewById(R.id.ivMyfav);
ivMyhistory = (ImageView) findViewById(R.id.ivMyhistory);
// lvGoodsList.setDivider(null);
lvGoodsList.setOnScrollListener(this);
ivMyads.setOnClickListener(this);
ivMyfav.setOnClickListener(this);
ivMyhistory.setOnClickListener(this);
adapter = new GoodsListAdapter(this.getContext(), this.listMyPost);
adapter.setMessageOutOnDelete(myHandler, MCMESSAGE_DELETE);
lvGoodsList.setAdapter(adapter);
}
class UpdateAndGetmoreThread implements Runnable{
private int currentPage = -1;
private boolean update = false;
public UpdateAndGetmoreThread(int currentPage, boolean update_){
this.currentPage = currentPage;
this.update = update_;
}
@Override
public void run(){
String apiName = "ad_list";
ArrayList<String>list = new ArrayList<String>();
int msgToSend = -1;
int msgToSendOnFail = -1;
boolean needUpdateOrGetmore = true;
if(currentPage == -1){
list.add("query=userId:" + user.getId() + " AND status:0");
if(update){
list.add("start=0");
msgToSend = MCMESSAGE_MYPOST_SUCCESS;
msgToSendOnFail = MCMESSAGE_MYPOST_FAIL;
}
// else{
// list.add("start="+PersonalCenterView.this.listMyPost.size());
// msgToSend = MCMESSAGE_MYPOST_GETMORE_SUCCESS;
// msgToSendOnFail = MCMESSAGE_MYPOST_GETMORE_FAIL;
// }
}
else{
List<GoodsDetail> details = null;
if(currentPage == 0){
details = QuanleimuApplication.getApplication().getListMyStore();
if(update){
list.add("start=0");
msgToSend = MCMESSAGE_MYFAV_UPDATE_SUCCESS;
msgToSendOnFail = MCMESSAGE_MYFAV_UPDATE_FAIL;
}
// else{
// list.add("start="+PersonalCenterView.this.goodsList.size());
// msgToSend = MCMESSAGE_MYFAV_GETMORE_SUCCESS;
// msgToSendOnFail = MCMESSAGE_MYFAV_GETMORE_FAIL;
// }
}
else if(currentPage == 1){
details = QuanleimuApplication.getApplication().getListLookHistory();
if(update){
list.add("start=0");
msgToSend = MCMESSAGE_MYHISTORY_UPDATE_SUCCESS;
msgToSendOnFail = MCMESSAGE_MYHISTORY_UPDATE_FAIL;
}
// else{
// list.add("start="+PersonalCenterView.this.goodsList.size());
// msgToSend = MCMESSAGE_MYHISTORY_GETMORE_SUCCESS;
// msgToSendOnFail = MCMESSAGE_MYHISTORY_GETMORE_FAIL;
// }
}
if(details != null && details.size() > 0){
String ids = "id:" + details.get(0).getValueByKey(GoodsDetail.EDATAKEYS.EDATAKEYS_ID);
for(int i = 1; i < details.size(); ++ i){
ids += " OR " + "id:" + details.get(i).getValueByKey(GoodsDetail.EDATAKEYS.EDATAKEYS_ID);
}
list.add("query=(" + ids + ")");
}
else{
needUpdateOrGetmore = false;
}
}
list.add("rt=1");
list.add("rows=30");
if(needUpdateOrGetmore){
String url = Communication.getApiUrl(apiName, list);
try {
json = Communication.getDataByUrl(url);
if (json != null) {
myHandler.sendEmptyMessage(msgToSend);
} else {
myHandler.sendEmptyMessage(msgToSendOnFail);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
myHandler.sendEmptyMessage(MCMESSAGE_NETWORKERROR);
}
}else{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(update){
myHandler.sendEmptyMessage(MCMESSAGE_MYFAV_UPDATE_NOTNECESSARY);
}else{
myHandler.sendEmptyMessage(MCMESSAGE_MYFAV_GETMORE_NOTNECESSARY);
}
}
}
}
Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MCMESSAGE_MYPOST_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList gl = JsonUtil.getGoodsListFromJson(json);
if (gl == null || gl.getCount() == 0) {
// Toast.makeText(PersonalCenterView.this.getContext(), "您尚未发布信息,", 0).show();
// TODO:how to check if delay occurred or there's really no info
listMyPost.clear();
}
else{
listMyPost = gl.getData();
}
QuanleimuApplication.getApplication().setListMyPost(listMyPost);
rebuildPage(true);
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYPOST_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
// GoodsList glGetMore = JsonUtil.getGoodsListFromJson(json);
// if (glGetMore == null || glGetMore.getCount() == 0) {
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
// else{
// List<GoodsDetail> listData = glGetMore.getData();
// for (int i = 0; i < listData.size(); i++) {
// listMyPost.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListMyPost(listMyPost);
// }
// break;
case MCMESSAGE_MYFAV_UPDATE_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList glFav = JsonUtil.getGoodsListFromJson(json);
if (glFav != null && glFav.getCount() > 0) {
QuanleimuApplication.getApplication().setListMyStore(glFav.getData());
rebuildPage(true);
}
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYFAV_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
// GoodsList glFavGetMore = JsonUtil.getGoodsListFromJson(json);
// if (glFavGetMore != null && glFavGetMore.getCount() > 0) {
// List<GoodsDetail> listData = glFavGetMore.getData();
// for (int i = 0; i < listData.size(); i++) {
// goodsList.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListMyStore(goodsList);
//
// }else{
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
//
// break;
case MCMESSAGE_MYHISTORY_UPDATE_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList glHistory = JsonUtil.getGoodsListFromJson(json);
if (glHistory != null && glHistory.getCount() > 0) {
QuanleimuApplication.getApplication().setListLookHistory(glHistory.getData());
rebuildPage(true);
}
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYHISTORY_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
//
// GoodsList glHistoryGetmore = JsonUtil.getGoodsListFromJson(json);
// if (glHistoryGetmore != null && glHistoryGetmore.getCount() > 0) {
// List<GoodsDetail> listData = glHistoryGetmore.getData();
// for (int i = 0; i < listData.size(); i++) {
// goodsList.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListLookHistory(goodsList);
// }else{
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
//
// lvGoodsList.onRefreshComplete();
//
// break;
case MCMESSAGE_MYPOST_FAIL:
case MCMESSAGE_MYFAV_UPDATE_FAIL:
case MCMESSAGE_MYHISTORY_UPDATE_FAIL:
// case MCMESSAGE_MYPOST_GETMORE_FAIL:
// case MCMESSAGE_MYFAV_GETMORE_FAIL:
// case MCMESSAGE_MYHISTORY_GETMORE_FAIL:
if (pd != null) {
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "数据获取失败,请检查网络连接后重试!", 3).show();
lvGoodsList.onRefreshComplete();
break;
case MCMESSAGE_MYFAV_UPDATE_NOTNECESSARY:
PersonalCenterView.this.lvGoodsList.onRefreshComplete();
break;
case MCMESSAGE_MYFAV_GETMORE_NOTNECESSARY:
PersonalCenterView.this.lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
break;
case MCMESSAGE_DELETE:
int pos = msg.arg2;
if(PersonalCenterView.this.currentPage == -1){
pd = ProgressDialog.show(PersonalCenterView.this.getContext(), "提示", "请稍候...");
pd.setCancelable(true);
pd.show();
new Thread(new MyMessageDeleteThread(pos)).start();
}
else if(0 == PersonalCenterView.this.currentPage){
goodsList.remove(pos);
QuanleimuApplication.getApplication().setListMyStore(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listMyStore", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
adapter.setUiHold(false);
}
else if(1 == PersonalCenterView.this.currentPage){
goodsList.remove(pos);
QuanleimuApplication.getApplication().setListLookHistory(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listLookHistory", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
adapter.setUiHold(false);
}
break;
case MCMESSAGE_DELETEALL:
if(PersonalCenterView.this.currentPage != -1){
+ if(null == goodsList) break;
goodsList.clear();
QuanleimuApplication.getApplication().setListMyStore(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listMyStore", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
if(PersonalCenterView.this.m_viewInfoListener != null){
TitleDef title = getTitleDef();
title.m_rightActionHint = "编辑";
title.m_leftActionHint = "设置";
m_viewInfoListener.onTitleChanged(title);
}
adapter.setHasDelBtn(false);
buttonStatus = -1;
}
break;
case MCMESSAGE_DELETE_SUCCESS:
if(pd != null){
pd.dismiss();
}
int pos2 = msg.arg2;
try {
JSONObject jb = new JSONObject(json);
JSONObject js = jb.getJSONObject("error");
String message = js.getString("message");
int code = js.getInt("code");
if (code == 0) {
// 删除成功
listMyPost.remove(pos2);
QuanleimuApplication.getApplication().setListMyPost(listMyPost);
adapter.setList(listMyPost);
adapter.notifyDataSetChanged();
Toast.makeText(PersonalCenterView.this.getContext(), message, 0).show();
} else {
// 删除失败
Toast.makeText(PersonalCenterView.this.getContext(), "删除失败,请稍后重试!", 0).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter.setUiHold(false);
break;
case MCMESSAGE_DELETE_FAIL:
if(pd != null){
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "删除失败,请稍后重试!", 0).show();
adapter.setUiHold(false);
break;
case MCMESSAGE_NETWORKERROR:
if (pd != null) {
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "网络连接失败,请检查设置!", 3).show();
lvGoodsList.onRefreshComplete();
break;
}
super.handleMessage(msg);
}
};
class MyMessageDeleteThread implements Runnable {
private int position;
public MyMessageDeleteThread(int position) {
this.position = position;
}
@Override
public void run() {
// TODO Auto-generated method stub
json = "";
String apiName = "ad_delete";
ArrayList<String> list = new ArrayList<String>();
list.add("mobile=" + mobile);
String password1 = Communication.getMD5(password);
password1 += Communication.apiSecret;
String userToken = Communication.getMD5(password1);
list.add("userToken=" + userToken);
list.add("adId=" + listMyPost.get(position).getValueByKey(GoodsDetail.EDATAKEYS.EDATAKEYS_ID));
String url = Communication.getApiUrl(apiName, list);
try {
json = Communication.getDataByUrl(url);
if (json != null) {
Message msg = myHandler.obtainMessage();
msg.arg2 = position;
msg.what = MCMESSAGE_DELETE_SUCCESS;
myHandler.sendMessage(msg);
// myHandler.sendEmptyMessageDelayed(5, 3000);5
} else {
myHandler.sendEmptyMessage(MCMESSAGE_DELETE_FAIL);
}
} catch (UnsupportedEncodingException e) {
myHandler.sendEmptyMessage(MCMESSAGE_NETWORKERROR);
} catch (IOException e) {
myHandler.sendEmptyMessage(MCMESSAGE_NETWORKERROR);
}
}
}
@Override
public boolean onLeftActionPressed(){
if(currentPage != -1 && 0 == buttonStatus){
myHandler.sendEmptyMessage(MCMESSAGE_DELETEALL);
}else{
m_viewInfoListener.onNewView(new SetMainView(getContext()));
}
return true;
}
@Override
public boolean onRightActionPressed(){
if(-1 == buttonStatus){
// btnEdit.setBackgroundResource(R.drawable.btn_clearall);
if(this.m_viewInfoListener != null){
TitleDef title = getTitleDef();
title.m_rightActionHint = "完成";
if(currentPage != -1){
title.m_leftActionHint = "清空";
}
m_viewInfoListener.onTitleChanged(title);
}
if(adapter != null){
adapter.setHasDelBtn(true);
}
buttonStatus = 0;
}
else{
// btnEdit.setBackgroundResource(R.drawable.btn_search);
if(this.m_viewInfoListener != null){
TitleDef title = getTitleDef();
title.m_rightActionHint = "编辑";
// title.m_leftActionHint = "更新";
m_viewInfoListener.onTitleChanged(title);
}
adapter.setHasDelBtn(false);
buttonStatus = -1;
}
if(adapter != null)
{
adapter.notifyDataSetChanged();
}
return true;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ivMyads:
this.currentPage = -1;
buttonStatus = -1;
adapter.setHasDelBtn(false);
rebuildPage(false);
break;
case R.id.ivMyfav:
buttonStatus = -1;
adapter.setHasDelBtn(false);
this.currentPage = 0;
rebuildPage(false);
break;
case R.id.ivMyhistory:
buttonStatus = -1;
adapter.setHasDelBtn(false);
this.currentPage = 1;
rebuildPage(false);
break;
default:
break;
}
// super.onClick(v);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if(scrollState == SCROLL_STATE_IDLE)
{
// LoadImage.doTask();
}
}
@Override
public TitleDef getTitleDef(){
TitleDef title = new TitleDef();
title.m_leftActionHint = "设置";
title.m_leftActionStyle = EBUTT_STYLE.EBUTT_STYLE_NORMAL;
title.m_rightActionHint = "编辑";
title.m_title = "个人中心";
title.m_visible = true;
return title;
}
@Override
public TabDef getTabDef(){
TabDef tab = new TabDef();
tab.m_visible = true;
tab.m_tabSelected = ETAB_TYPE.ETAB_TYPE_MINE;
return tab;
}
@Override
public void onRefresh() {
new Thread(new UpdateAndGetmoreThread(currentPage, true)).start();
}
@Override
public void onGetMore() {
// TODO Auto-generated method stub
//new Thread(new UpdateAndGetmoreThread(currentPage, false)).start();
}
}
| true | true | public void handleMessage(Message msg) {
switch (msg.what) {
case MCMESSAGE_MYPOST_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList gl = JsonUtil.getGoodsListFromJson(json);
if (gl == null || gl.getCount() == 0) {
// Toast.makeText(PersonalCenterView.this.getContext(), "您尚未发布信息,", 0).show();
// TODO:how to check if delay occurred or there's really no info
listMyPost.clear();
}
else{
listMyPost = gl.getData();
}
QuanleimuApplication.getApplication().setListMyPost(listMyPost);
rebuildPage(true);
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYPOST_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
// GoodsList glGetMore = JsonUtil.getGoodsListFromJson(json);
// if (glGetMore == null || glGetMore.getCount() == 0) {
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
// else{
// List<GoodsDetail> listData = glGetMore.getData();
// for (int i = 0; i < listData.size(); i++) {
// listMyPost.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListMyPost(listMyPost);
// }
// break;
case MCMESSAGE_MYFAV_UPDATE_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList glFav = JsonUtil.getGoodsListFromJson(json);
if (glFav != null && glFav.getCount() > 0) {
QuanleimuApplication.getApplication().setListMyStore(glFav.getData());
rebuildPage(true);
}
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYFAV_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
// GoodsList glFavGetMore = JsonUtil.getGoodsListFromJson(json);
// if (glFavGetMore != null && glFavGetMore.getCount() > 0) {
// List<GoodsDetail> listData = glFavGetMore.getData();
// for (int i = 0; i < listData.size(); i++) {
// goodsList.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListMyStore(goodsList);
//
// }else{
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
//
// break;
case MCMESSAGE_MYHISTORY_UPDATE_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList glHistory = JsonUtil.getGoodsListFromJson(json);
if (glHistory != null && glHistory.getCount() > 0) {
QuanleimuApplication.getApplication().setListLookHistory(glHistory.getData());
rebuildPage(true);
}
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYHISTORY_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
//
// GoodsList glHistoryGetmore = JsonUtil.getGoodsListFromJson(json);
// if (glHistoryGetmore != null && glHistoryGetmore.getCount() > 0) {
// List<GoodsDetail> listData = glHistoryGetmore.getData();
// for (int i = 0; i < listData.size(); i++) {
// goodsList.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListLookHistory(goodsList);
// }else{
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
//
// lvGoodsList.onRefreshComplete();
//
// break;
case MCMESSAGE_MYPOST_FAIL:
case MCMESSAGE_MYFAV_UPDATE_FAIL:
case MCMESSAGE_MYHISTORY_UPDATE_FAIL:
// case MCMESSAGE_MYPOST_GETMORE_FAIL:
// case MCMESSAGE_MYFAV_GETMORE_FAIL:
// case MCMESSAGE_MYHISTORY_GETMORE_FAIL:
if (pd != null) {
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "数据获取失败,请检查网络连接后重试!", 3).show();
lvGoodsList.onRefreshComplete();
break;
case MCMESSAGE_MYFAV_UPDATE_NOTNECESSARY:
PersonalCenterView.this.lvGoodsList.onRefreshComplete();
break;
case MCMESSAGE_MYFAV_GETMORE_NOTNECESSARY:
PersonalCenterView.this.lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
break;
case MCMESSAGE_DELETE:
int pos = msg.arg2;
if(PersonalCenterView.this.currentPage == -1){
pd = ProgressDialog.show(PersonalCenterView.this.getContext(), "提示", "请稍候...");
pd.setCancelable(true);
pd.show();
new Thread(new MyMessageDeleteThread(pos)).start();
}
else if(0 == PersonalCenterView.this.currentPage){
goodsList.remove(pos);
QuanleimuApplication.getApplication().setListMyStore(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listMyStore", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
adapter.setUiHold(false);
}
else if(1 == PersonalCenterView.this.currentPage){
goodsList.remove(pos);
QuanleimuApplication.getApplication().setListLookHistory(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listLookHistory", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
adapter.setUiHold(false);
}
break;
case MCMESSAGE_DELETEALL:
if(PersonalCenterView.this.currentPage != -1){
goodsList.clear();
QuanleimuApplication.getApplication().setListMyStore(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listMyStore", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
if(PersonalCenterView.this.m_viewInfoListener != null){
TitleDef title = getTitleDef();
title.m_rightActionHint = "编辑";
title.m_leftActionHint = "设置";
m_viewInfoListener.onTitleChanged(title);
}
adapter.setHasDelBtn(false);
buttonStatus = -1;
}
break;
case MCMESSAGE_DELETE_SUCCESS:
if(pd != null){
pd.dismiss();
}
int pos2 = msg.arg2;
try {
JSONObject jb = new JSONObject(json);
JSONObject js = jb.getJSONObject("error");
String message = js.getString("message");
int code = js.getInt("code");
if (code == 0) {
// 删除成功
listMyPost.remove(pos2);
QuanleimuApplication.getApplication().setListMyPost(listMyPost);
adapter.setList(listMyPost);
adapter.notifyDataSetChanged();
Toast.makeText(PersonalCenterView.this.getContext(), message, 0).show();
} else {
// 删除失败
Toast.makeText(PersonalCenterView.this.getContext(), "删除失败,请稍后重试!", 0).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter.setUiHold(false);
break;
case MCMESSAGE_DELETE_FAIL:
if(pd != null){
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "删除失败,请稍后重试!", 0).show();
adapter.setUiHold(false);
break;
case MCMESSAGE_NETWORKERROR:
if (pd != null) {
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "网络连接失败,请检查设置!", 3).show();
lvGoodsList.onRefreshComplete();
break;
}
super.handleMessage(msg);
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case MCMESSAGE_MYPOST_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList gl = JsonUtil.getGoodsListFromJson(json);
if (gl == null || gl.getCount() == 0) {
// Toast.makeText(PersonalCenterView.this.getContext(), "您尚未发布信息,", 0).show();
// TODO:how to check if delay occurred or there's really no info
listMyPost.clear();
}
else{
listMyPost = gl.getData();
}
QuanleimuApplication.getApplication().setListMyPost(listMyPost);
rebuildPage(true);
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYPOST_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
// GoodsList glGetMore = JsonUtil.getGoodsListFromJson(json);
// if (glGetMore == null || glGetMore.getCount() == 0) {
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
// else{
// List<GoodsDetail> listData = glGetMore.getData();
// for (int i = 0; i < listData.size(); i++) {
// listMyPost.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListMyPost(listMyPost);
// }
// break;
case MCMESSAGE_MYFAV_UPDATE_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList glFav = JsonUtil.getGoodsListFromJson(json);
if (glFav != null && glFav.getCount() > 0) {
QuanleimuApplication.getApplication().setListMyStore(glFav.getData());
rebuildPage(true);
}
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYFAV_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
// GoodsList glFavGetMore = JsonUtil.getGoodsListFromJson(json);
// if (glFavGetMore != null && glFavGetMore.getCount() > 0) {
// List<GoodsDetail> listData = glFavGetMore.getData();
// for (int i = 0; i < listData.size(); i++) {
// goodsList.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListMyStore(goodsList);
//
// }else{
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
//
// break;
case MCMESSAGE_MYHISTORY_UPDATE_SUCCESS:
if (pd != null) {
pd.dismiss();
}
GoodsList glHistory = JsonUtil.getGoodsListFromJson(json);
if (glHistory != null && glHistory.getCount() > 0) {
QuanleimuApplication.getApplication().setListLookHistory(glHistory.getData());
rebuildPage(true);
}
lvGoodsList.onRefreshComplete();
break;
// case MCMESSAGE_MYHISTORY_GETMORE_SUCCESS:
// if (pd != null) {
// pd.dismiss();
// }
//
// GoodsList glHistoryGetmore = JsonUtil.getGoodsListFromJson(json);
// if (glHistoryGetmore != null && glHistoryGetmore.getCount() > 0) {
// List<GoodsDetail> listData = glHistoryGetmore.getData();
// for (int i = 0; i < listData.size(); i++) {
// goodsList.add(listData.get(i));
// }
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_OK);
// QuanleimuApplication.getApplication().setListLookHistory(goodsList);
// }else{
// lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
// }
//
// lvGoodsList.onRefreshComplete();
//
// break;
case MCMESSAGE_MYPOST_FAIL:
case MCMESSAGE_MYFAV_UPDATE_FAIL:
case MCMESSAGE_MYHISTORY_UPDATE_FAIL:
// case MCMESSAGE_MYPOST_GETMORE_FAIL:
// case MCMESSAGE_MYFAV_GETMORE_FAIL:
// case MCMESSAGE_MYHISTORY_GETMORE_FAIL:
if (pd != null) {
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "数据获取失败,请检查网络连接后重试!", 3).show();
lvGoodsList.onRefreshComplete();
break;
case MCMESSAGE_MYFAV_UPDATE_NOTNECESSARY:
PersonalCenterView.this.lvGoodsList.onRefreshComplete();
break;
case MCMESSAGE_MYFAV_GETMORE_NOTNECESSARY:
PersonalCenterView.this.lvGoodsList.onGetMoreCompleted(PullToRefreshListView.E_GETMORE.E_GETMORE_NO_MORE);
break;
case MCMESSAGE_DELETE:
int pos = msg.arg2;
if(PersonalCenterView.this.currentPage == -1){
pd = ProgressDialog.show(PersonalCenterView.this.getContext(), "提示", "请稍候...");
pd.setCancelable(true);
pd.show();
new Thread(new MyMessageDeleteThread(pos)).start();
}
else if(0 == PersonalCenterView.this.currentPage){
goodsList.remove(pos);
QuanleimuApplication.getApplication().setListMyStore(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listMyStore", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
adapter.setUiHold(false);
}
else if(1 == PersonalCenterView.this.currentPage){
goodsList.remove(pos);
QuanleimuApplication.getApplication().setListLookHistory(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listLookHistory", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
adapter.setUiHold(false);
}
break;
case MCMESSAGE_DELETEALL:
if(PersonalCenterView.this.currentPage != -1){
if(null == goodsList) break;
goodsList.clear();
QuanleimuApplication.getApplication().setListMyStore(goodsList);
Helper.saveDataToLocate(PersonalCenterView.this.getContext(), "listMyStore", goodsList);
adapter.setList(goodsList);
adapter.notifyDataSetChanged();
if(PersonalCenterView.this.m_viewInfoListener != null){
TitleDef title = getTitleDef();
title.m_rightActionHint = "编辑";
title.m_leftActionHint = "设置";
m_viewInfoListener.onTitleChanged(title);
}
adapter.setHasDelBtn(false);
buttonStatus = -1;
}
break;
case MCMESSAGE_DELETE_SUCCESS:
if(pd != null){
pd.dismiss();
}
int pos2 = msg.arg2;
try {
JSONObject jb = new JSONObject(json);
JSONObject js = jb.getJSONObject("error");
String message = js.getString("message");
int code = js.getInt("code");
if (code == 0) {
// 删除成功
listMyPost.remove(pos2);
QuanleimuApplication.getApplication().setListMyPost(listMyPost);
adapter.setList(listMyPost);
adapter.notifyDataSetChanged();
Toast.makeText(PersonalCenterView.this.getContext(), message, 0).show();
} else {
// 删除失败
Toast.makeText(PersonalCenterView.this.getContext(), "删除失败,请稍后重试!", 0).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter.setUiHold(false);
break;
case MCMESSAGE_DELETE_FAIL:
if(pd != null){
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "删除失败,请稍后重试!", 0).show();
adapter.setUiHold(false);
break;
case MCMESSAGE_NETWORKERROR:
if (pd != null) {
pd.dismiss();
}
Toast.makeText(PersonalCenterView.this.getContext(), "网络连接失败,请检查设置!", 3).show();
lvGoodsList.onRefreshComplete();
break;
}
super.handleMessage(msg);
}
|
diff --git a/ini/trakem2/display/SnapshotPanel.java b/ini/trakem2/display/SnapshotPanel.java
index 74502dd2..4cfc4fc9 100644
--- a/ini/trakem2/display/SnapshotPanel.java
+++ b/ini/trakem2/display/SnapshotPanel.java
@@ -1,124 +1,128 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005,2006 Albert Cardona and Rodney Douglas.
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 (http://www.gnu.org/licenses/gpl.txt )
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.display;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import ini.trakem2.persistence.FSLoader;
public class SnapshotPanel extends JPanel implements MouseListener {
private Display display;
private Displayable d;
static public final int FIXED_HEIGHT = 50;
public SnapshotPanel(Display display, Displayable d) {
this.display = display;
this.d = d;
remake();
}
public void set(final Displayable d) {
if (this.d.getLayer().getParent().equals(d.getLayer().getParent())) {
this.d = d;
repaint();
} else {
this.d = d;
remake();
}
}
/** Redefine dimensions, which are defined by the LayerSet dimensions. */
public void remake() {
final int width = (int)(FIXED_HEIGHT / d.getLayer().getLayerHeight() * d.getLayer().getLayerWidth());
Dimension dim = new Dimension(width, FIXED_HEIGHT);
setMinimumSize(dim);
setMaximumSize(dim);
setPreferredSize(dim);
}
public void update(Graphics g) {
paint(g);
}
private BufferedImage img = null;
/** Paint the snapshot image over a black background that represents a scaled Layer. */
public void paint(final Graphics g) {
if (null == g) return; // happens if not visible
synchronized (this) {
if (null != img) {
// Paint and flush
g.drawImage(img, 0, 0, null);
this.img.flush();
this.img = null;
return;
}
}
// Else, repaint background to avoid flickering
g.setColor(Color.black);
g.fillRect(0, 0, SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight());
// ... and create the image in a separate thread and repaint again
FSLoader.repainter.submit(new Runnable() { public void run() {
if (!display.isPartiallyWithinViewport(d)) return;
final BufferedImage img = new BufferedImage(SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2 = img.createGraphics();
g2.setColor(Color.black);
g2.fillRect(0, 0, SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight());
final double scale = FIXED_HEIGHT / d.getLayer().getLayerHeight();
g2.scale(scale, scale);
- // Avoid painting images that have an alpha mask: takes forever.
- //if (d.getClass() == Patch.class && ((Patch)d).hasAlphaChannel()) {
- // d.paintAsBox(g2);
- //} else {
- d.paintSnapshot(g2, scale);
- //}
+ try {
+ // Avoid painting images that have an alpha mask: takes forever.
+ //if (d.getClass() == Patch.class && ((Patch)d).hasAlphaChannel()) {
+ // d.paintAsBox(g2);
+ //} else {
+ d.paintSnapshot(g2, scale);
+ //}
+ } catch (Exception e) {
+ d.paintAsBox(g2);
+ }
synchronized (this) {
SnapshotPanel.this.img = img;
}
repaint();
}});
}
public void mousePressed(MouseEvent me) {
//must enable cancel!//if (display.isTransforming()) return;
display.setActive(d);
if (me.isPopupTrigger() || (ij.IJ.isMacOSX() && me.isControlDown()) || MouseEvent.BUTTON2 == me.getButton()) {
Display.showPopup(this, me.getX(), me.getY());
}
}
public void mouseReleased(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited (MouseEvent me) {}
public void mouseClicked(MouseEvent me) {}
}
| true | true | public void paint(final Graphics g) {
if (null == g) return; // happens if not visible
synchronized (this) {
if (null != img) {
// Paint and flush
g.drawImage(img, 0, 0, null);
this.img.flush();
this.img = null;
return;
}
}
// Else, repaint background to avoid flickering
g.setColor(Color.black);
g.fillRect(0, 0, SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight());
// ... and create the image in a separate thread and repaint again
FSLoader.repainter.submit(new Runnable() { public void run() {
if (!display.isPartiallyWithinViewport(d)) return;
final BufferedImage img = new BufferedImage(SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2 = img.createGraphics();
g2.setColor(Color.black);
g2.fillRect(0, 0, SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight());
final double scale = FIXED_HEIGHT / d.getLayer().getLayerHeight();
g2.scale(scale, scale);
// Avoid painting images that have an alpha mask: takes forever.
//if (d.getClass() == Patch.class && ((Patch)d).hasAlphaChannel()) {
// d.paintAsBox(g2);
//} else {
d.paintSnapshot(g2, scale);
//}
synchronized (this) {
SnapshotPanel.this.img = img;
}
repaint();
}});
}
| public void paint(final Graphics g) {
if (null == g) return; // happens if not visible
synchronized (this) {
if (null != img) {
// Paint and flush
g.drawImage(img, 0, 0, null);
this.img.flush();
this.img = null;
return;
}
}
// Else, repaint background to avoid flickering
g.setColor(Color.black);
g.fillRect(0, 0, SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight());
// ... and create the image in a separate thread and repaint again
FSLoader.repainter.submit(new Runnable() { public void run() {
if (!display.isPartiallyWithinViewport(d)) return;
final BufferedImage img = new BufferedImage(SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2 = img.createGraphics();
g2.setColor(Color.black);
g2.fillRect(0, 0, SnapshotPanel.this.getWidth(), SnapshotPanel.this.getHeight());
final double scale = FIXED_HEIGHT / d.getLayer().getLayerHeight();
g2.scale(scale, scale);
try {
// Avoid painting images that have an alpha mask: takes forever.
//if (d.getClass() == Patch.class && ((Patch)d).hasAlphaChannel()) {
// d.paintAsBox(g2);
//} else {
d.paintSnapshot(g2, scale);
//}
} catch (Exception e) {
d.paintAsBox(g2);
}
synchronized (this) {
SnapshotPanel.this.img = img;
}
repaint();
}});
}
|
diff --git a/module-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimitedDecoder.java b/module-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimitedDecoder.java
index e159a01ca..2d3507bfd 100644
--- a/module-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimitedDecoder.java
+++ b/module-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimitedDecoder.java
@@ -1,100 +1,104 @@
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.impl.nio.reactor.SessionInputBuffer;
public class LengthDelimitedDecoder extends AbstractContentDecoder {
private final long contentLength;
private long len;
public LengthDelimitedDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
long contentLength) {
super(channel, buffer);
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.contentLength = contentLength;
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int lenRemaining = (int) (this.contentLength - this.len);
int bytesRead;
if (this.buffer.hasData()) {
int maxLen = Math.min(lenRemaining, this.buffer.length());
bytesRead = this.buffer.read(dst, maxLen);
} else {
if (dst.remaining() > lenRemaining) {
int oldLimit = dst.limit();
int newLimit = oldLimit - (dst.remaining() - lenRemaining);
dst.limit(newLimit);
bytesRead = this.channel.read(dst);
dst.limit(oldLimit);
} else {
bytesRead = this.channel.read(dst);
}
}
+ if (bytesRead == -1) {
+ this.completed = true;
+ return -1;
+ }
this.len += bytesRead;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesRead;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[content length: ");
buffer.append(this.contentLength);
buffer.append("; pos: ");
buffer.append(this.len);
buffer.append("; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
| true | true | public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int lenRemaining = (int) (this.contentLength - this.len);
int bytesRead;
if (this.buffer.hasData()) {
int maxLen = Math.min(lenRemaining, this.buffer.length());
bytesRead = this.buffer.read(dst, maxLen);
} else {
if (dst.remaining() > lenRemaining) {
int oldLimit = dst.limit();
int newLimit = oldLimit - (dst.remaining() - lenRemaining);
dst.limit(newLimit);
bytesRead = this.channel.read(dst);
dst.limit(oldLimit);
} else {
bytesRead = this.channel.read(dst);
}
}
this.len += bytesRead;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesRead;
}
| public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int lenRemaining = (int) (this.contentLength - this.len);
int bytesRead;
if (this.buffer.hasData()) {
int maxLen = Math.min(lenRemaining, this.buffer.length());
bytesRead = this.buffer.read(dst, maxLen);
} else {
if (dst.remaining() > lenRemaining) {
int oldLimit = dst.limit();
int newLimit = oldLimit - (dst.remaining() - lenRemaining);
dst.limit(newLimit);
bytesRead = this.channel.read(dst);
dst.limit(oldLimit);
} else {
bytesRead = this.channel.read(dst);
}
}
if (bytesRead == -1) {
this.completed = true;
return -1;
}
this.len += bytesRead;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesRead;
}
|
diff --git a/gnu/testlet/locales/LocaleTest.java b/gnu/testlet/locales/LocaleTest.java
index 62fb2b85..87634d5b 100755
--- a/gnu/testlet/locales/LocaleTest.java
+++ b/gnu/testlet/locales/LocaleTest.java
@@ -1,437 +1,448 @@
// Tags: JDK1.0
// Copyright (C) 2004 Michael Koch <[email protected]>
// This file is part of Mauve.
// Mauve 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, or (at your option)
// any later version.
// Mauve 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 Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA. */
package gnu.testlet.locales;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import java.text.*;
import java.util.*;
public class LocaleTest
implements Testlet
{
public class ExpectedValues
{
String language;
String country;
String variant;
String localeStr;
String iso3language;
String iso3country;
String displayLanguage;
String displayCountry;
String displayVariant;
String displayName;
String currencyCode;
int currencyFractionDigits;
String currencySymbol;
public ExpectedValues(String language, String country, String variant, String localeStr,
String iso3language, String iso3country,
String displayLanguage, String displayCountry,
String displayVariant, String displayName,
String currencyCode, int currencyFractionDigits,
String currencySymbol)
{
this.language = language;
this.country = country;
this.variant = variant;
this.localeStr = localeStr;
this.iso3language = iso3language;
this.iso3country = iso3country;
this.displayLanguage = displayLanguage;
this.displayCountry = displayCountry;
this.displayVariant = displayVariant;
this.displayName = displayName;
this.currencyCode = currencyCode;
this.currencyFractionDigits = currencyFractionDigits;
this.currencySymbol = currencySymbol;
}
}
public class ExpectedDateValues
{
String a, b, c, d, e, f, g, h;
public ExpectedDateValues(String a, String b, String c, String d, String e, String f, String g, String h)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
this.g = g;
this.h = h;
}
}
public class ExpectedNumberValues
{
String a, b, c, d, e;
public ExpectedNumberValues(String a, String b, String c, String d, String e)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
}
private void checkLocale(TestHarness h, Locale locale,
ExpectedValues expected,
ExpectedDateValues expectedDate,
ExpectedNumberValues expectedNumber1,
ExpectedNumberValues expectedNumber2,
ExpectedNumberValues expectedNumber3,
ExpectedNumberValues expectedNumber4,
ExpectedNumberValues expectedNumber5)
{
h.debug("Locale " + locale);
// Force GERMAN as default locale.
Locale.setDefault(Locale.GERMAN);
// Locale
if (expected != null)
{
h.check(locale.getLanguage(), expected.language, "");
h.check(locale.getCountry(), expected.country, "");
h.check(locale.getVariant(), expected.variant, "");
h.check(locale.toString(), expected.localeStr, "");
h.check(locale.getISO3Language(), expected.iso3language, "");
h.check(locale.getISO3Country(), expected.iso3country, "");
h.check(locale.getDisplayLanguage(), expected.displayLanguage, "");
h.check(locale.getDisplayCountry(), expected.displayCountry, "");
h.check(locale.getDisplayVariant(), expected.displayVariant, "");
h.check(locale.getDisplayName(), expected.displayName, "");
}
// Date and time formats
h.debug("Locale " + locale + " date/time formats");
if (expectedDate != null)
{
DateFormat df;
Date date1 = new Date(74, 2, 18, 17, 20, 30);
// Date instance.
df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
h.check(df.format(date1), expectedDate.a, "DateFormat.DEFAULT");
df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
h.check(df.format(date1), expectedDate.b, "DateFormat.SHORT");
df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
h.check(df.format(date1), expectedDate.c, "DateFormat.MEDIUM");
df = DateFormat.getDateInstance(DateFormat.LONG, locale);
h.check(df.format(date1), expectedDate.d, "DateFormat.LONG");
// Assume DEFAULT == MEDIUM
df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
h.check(df.format(date1), expectedDate.c, "DateFormat.DEFAULT == DateFormat.MEDIUM");
// Time instance.
df = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
h.check(df.format(date1), expectedDate.e, "DateFormat.DEFAULT");
df = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
h.check(df.format(date1), expectedDate.f, "DateFormat.SHORT");
df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
h.check(df.format(date1), expectedDate.g, "DateFormat.MEDIUM");
df = DateFormat.getTimeInstance(DateFormat.LONG, locale);
h.check(df.format(date1), expectedDate.h, "DateFormat.LONG");
// Assume DEFAULT == MEDIUM
df = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
h.check(df.format(date1), expectedDate.g, "DateFormat.DEFAULT == DateFormat.MEDIUM");
}
// Number formats
NumberFormat nf;
if (expectedNumber1 != null)
{
nf = NumberFormat.getInstance(locale);
h.check(nf.format(1000L), expectedNumber1.a, "");
h.check(nf.format(1000000L), expectedNumber1.b, "");
h.check(nf.format(100d), expectedNumber1.c, "");
h.check(nf.format(100.1234d), expectedNumber1.d, "");
h.check(nf.format(10000000.1234d), expectedNumber1.e, "");
}
if (expectedNumber2 != null)
{
nf = NumberFormat.getCurrencyInstance(locale);
h.check(nf.format(1000L), expectedNumber2.a, "");
h.check(nf.format(1000000L), expectedNumber2.b, "");
h.check(nf.format(100d), expectedNumber2.c, "");
h.check(nf.format(100.1234d), expectedNumber2.d, "");
h.check(nf.format(10000000.1234d), expectedNumber2.e, "");
}
if (expectedNumber3 != null)
{
nf = NumberFormat.getIntegerInstance(locale);
h.check(nf.format(1000L), expectedNumber3.a, "");
h.check(nf.format(1000000L), expectedNumber3.b, "");
h.check(nf.format(100d), expectedNumber3.c, "");
h.check(nf.format(100.1234d), expectedNumber3.d, "");
h.check(nf.format(10000000.1234d), expectedNumber3.e, "");
}
if (expectedNumber4 != null)
{
nf = NumberFormat.getNumberInstance(locale);
h.check(nf.format(1000L), expectedNumber4.a, "");
h.check(nf.format(1000000L), expectedNumber4.b, "");
h.check(nf.format(100d), expectedNumber4.c, "");
h.check(nf.format(100.1234d), expectedNumber4.d, "");
h.check(nf.format(10000000.1234d), expectedNumber4.e, "");
}
if (expectedNumber5 != null)
{
nf = NumberFormat.getPercentInstance(locale);
h.check(nf.format(1000L), expectedNumber5.a, "");
h.check(nf.format(1000000L), expectedNumber5.b, "");
h.check(nf.format(100d), expectedNumber5.c, "");
h.check(nf.format(100.1234d), expectedNumber5.d, "");
h.check(nf.format(10000000.1234d), expectedNumber5.e, "");
}
// Currencies
if (expected != null)
{
Currency currency = Currency.getInstance(locale);
h.check(currency.getCurrencyCode(), expected.currencyCode, "");
h.check(currency.getDefaultFractionDigits(), expected.currencyFractionDigits, "");
h.check(currency.getSymbol(), expected.currencySymbol, "");
try
{
Currency byCode = Currency.getInstance(currency.getCurrencyCode());
h.check(currency.getCurrencyCode(), byCode.getCurrencyCode(), "");
h.check(currency.getDefaultFractionDigits(), byCode.getDefaultFractionDigits(), "");
h.check(currency.getSymbol(), byCode.getSymbol(), "");
}
catch (IllegalArgumentException e)
{
h.fail("Currency code not supported: " + currency.getCurrencyCode());
}
}
}
public void test(TestHarness h)
{
// Check all supported locales.
// FIXME: Add all EURO countries.
// Locale: Germany
checkLocale(h, new Locale("de", "DE"),
new ExpectedValues("de", "DE", "", "de_DE", "deu", "DEU",
"Deutsch", "Deutschland", "", "Deutsch (Deutschland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Belgium
checkLocale(h, new Locale("fr", "BE"),
new ExpectedValues("fr", "BE", "", "fr_BE", "fra", "BEL",
"Franz\u00f6sisch", "Belgien", "", "Franz\u00f6sisch (Belgien)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Greece
// FIXME: Disabled for now due to pattern problems.
/*
checkLocale(h, new Locale("el", "GR"),
new ExpectedValues("el", "GR", "", "el_GR", "ell", "GRC",
"Griechisch", "Griechenland", "", "Griechisch (Griechenland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
*/
// Locale: Ireland
checkLocale(h, new Locale("en", "IE"),
new ExpectedValues("en", "IE", "", "en_IE", "eng", "IRL",
"Englisch", "Irland", "", "Englisch (Irland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: France
checkLocale(h, new Locale("fr", "FR"),
new ExpectedValues("fr", "FR", "", "fr_FR", "fra", "FRA",
"Franz\u00f6sisch", "Frankreich", "", "Franz\u00f6sisch (Frankreich)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Spain
checkLocale(h, new Locale("es", "ES"),
new ExpectedValues("es", "ES", "", "es_ES", "spa", "ESP",
"Spanisch", "Spanien", "", "Spanisch (Spanien)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Portugal
checkLocale(h, new Locale("pt", "PT"),
new ExpectedValues("pt", "PT", "", "pt_PT", "por", "PRT",
"Portugiesisch", "Portugal", "", "Portugiesisch (Portugal)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Italy
checkLocale(h, new Locale("it", "IT"),
new ExpectedValues("it", "IT", "", "it_IT", "ita", "ITA",
"Italienisch", "Italien", "", "Italienisch (Italien)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: The Netherlands
checkLocale(h, new Locale("nl", "NL"),
new ExpectedValues("nl", "NL", "", "nl_NL", "nld", "NLD",
"Niederl\u00e4ndisch", "Niederlande", "", "Niederl\u00e4ndisch (Niederlande)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18-mrt-1974", "18-3-74", "18-mrt-1974", "18 maart 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("\u20ac 1.000,00", "\u20ac 1.000.000,00", "\u20ac 100,00", "\u20ac 100,12", "\u20ac 10.000.000,12"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Luxemborg
checkLocale(h, new Locale("fr", "LU"),
new ExpectedValues("fr", "LU", "", "fr_LU", "fra", "LUX",
"Franz\u00f6sisch", "Luxemburg", "", "Franz\u00f6sisch (Luxemburg)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: United Kingdom
checkLocale(h, Locale.UK,
new ExpectedValues("en", "GB", "", "en_GB", "eng", "GBR",
"Englisch", "Vereinigtes K\u00f6nigreich", "", "Englisch (Vereinigtes K\u00f6nigreich)",
"GBP", 2, "GBP"),
new ExpectedDateValues("18-Mar-1974", "18/03/74", "18-Mar-1974", "18 March 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("\u00a31,000.00", "\u00a31,000,000.00", "\u00a3100.00", "\u00a3100.12", "\u00a310,000,000.12"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100", "10,000,000"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("100,000%", "100,000,000%", "10,000%", "10,012%", "1,000,000,012%"));
// Locale: United States
checkLocale(h, Locale.US,
new ExpectedValues("en", "US", "", "en_US", "eng", "USA",
"Englisch", "Vereinigte Staaten von Amerika", "", "Englisch (Vereinigte Staaten von Amerika)",
- "USD", 2, "USD"),
+ "USD", 2, "US$"),
new ExpectedDateValues("Mar 18, 1974", "3/18/74", "Mar 18, 1974", "March 18, 1974", "5:20:30 PM", "5:20 PM", "5:20:30 PM", "5:20:30 PM CET"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("$1,000.00", "$1,000,000.00", "$100.00", "$100.12", "$10,000,000.12"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100", "10,000,000"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("100,000%", "100,000,000%", "10,000%", "10,012%", "1,000,000,012%"));
// Locale: Finland
checkLocale(h, new Locale("fi", "FI"),
new ExpectedValues("fi", "FI", "", "fi_FI", "fin", "FIN",
"Finnisch", "Finnland", "", "Finnisch (Finnland)",
"EUR", 2, "EUR"),
new ExpectedDateValues("18.3.1974", "18.3.1974", "18.3.1974", "18. maaliskuuta 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100,123", "10\u00a0000\u00a0000,123"),
new ExpectedNumberValues("1\u00a0000,00 \u20ac", "1\u00a0000\u00a0000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10\u00a0000\u00a0000,12 \u20ac"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100", "10\u00a0000\u00a0000"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100,123", "10\u00a0000\u00a0000,123"),
new ExpectedNumberValues("100\u00a0000%", "100\u00a0000\u00a0000%", "10\u00a0000%", "10\u00a0012%", "1\u00a0000\u00a0000\u00a0012%"));
// Locale: Turkey
checkLocale(h, new Locale("tr", "TR"),
new ExpectedValues("tr", "TR", "", "tr_TR", "tur", "TUR",
"T\u00fcrkisch", "T\u00fcrkei", "", "T\u00fcrkisch (T\u00fcrkei)",
- "TRL", 2, "TRL"),
+ "TRL", 0, "TRL"),
new ExpectedDateValues("18.Mar.1974", "18.03.1974", "18.Mar.1974", "18 Mart 1974 Pazartesi", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
- new ExpectedNumberValues("1.000 TL", "1.000.000 TL", "100 TL", "100 TL", "10.000.000 TL"),
+ new ExpectedNumberValues("1.000 TRL", "1.000.000 TRL", "100 TRL", "100 TRL", "10.000.000 TRL"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Kazakstan
checkLocale(h, new Locale("kk", "KZ"),
null,
null,
null,
null,
null,
null,
null);
+ // Locale: Estonia
+ checkLocale(h, new Locale("et", "EE"),
+ new ExpectedValues("et", "EE", "", "et_EE", "est", "EST",
+ "Estnisch", "Estland", "", "Estnisch (Estland)",
+ "EEK", 2, "kr"),
+ new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "esmasp�ev, 18. M�rts 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
+ new ExpectedNumberValues("1�000", "1�000�000", "100", "100,123", "10�000�000,123"),
+ new ExpectedNumberValues("1�000 kr", "1�000�000 kr", "100 kr", "100,12 kr", "10�000�000,12 kr"),
+ new ExpectedNumberValues("1�000", "1�000�000", "100", "100", "10�000�000"),
+ new ExpectedNumberValues("1�000", "1�000�000", "100", "100,123", "10�000�000,123"),
+ new ExpectedNumberValues("100�000%", "100�000�000%", "10�000%", "10�012%", "1�000�000�012%"));
}
}
| false | true | public void test(TestHarness h)
{
// Check all supported locales.
// FIXME: Add all EURO countries.
// Locale: Germany
checkLocale(h, new Locale("de", "DE"),
new ExpectedValues("de", "DE", "", "de_DE", "deu", "DEU",
"Deutsch", "Deutschland", "", "Deutsch (Deutschland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Belgium
checkLocale(h, new Locale("fr", "BE"),
new ExpectedValues("fr", "BE", "", "fr_BE", "fra", "BEL",
"Franz\u00f6sisch", "Belgien", "", "Franz\u00f6sisch (Belgien)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Greece
// FIXME: Disabled for now due to pattern problems.
/*
checkLocale(h, new Locale("el", "GR"),
new ExpectedValues("el", "GR", "", "el_GR", "ell", "GRC",
"Griechisch", "Griechenland", "", "Griechisch (Griechenland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
*/
// Locale: Ireland
checkLocale(h, new Locale("en", "IE"),
new ExpectedValues("en", "IE", "", "en_IE", "eng", "IRL",
"Englisch", "Irland", "", "Englisch (Irland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: France
checkLocale(h, new Locale("fr", "FR"),
new ExpectedValues("fr", "FR", "", "fr_FR", "fra", "FRA",
"Franz\u00f6sisch", "Frankreich", "", "Franz\u00f6sisch (Frankreich)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Spain
checkLocale(h, new Locale("es", "ES"),
new ExpectedValues("es", "ES", "", "es_ES", "spa", "ESP",
"Spanisch", "Spanien", "", "Spanisch (Spanien)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Portugal
checkLocale(h, new Locale("pt", "PT"),
new ExpectedValues("pt", "PT", "", "pt_PT", "por", "PRT",
"Portugiesisch", "Portugal", "", "Portugiesisch (Portugal)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Italy
checkLocale(h, new Locale("it", "IT"),
new ExpectedValues("it", "IT", "", "it_IT", "ita", "ITA",
"Italienisch", "Italien", "", "Italienisch (Italien)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: The Netherlands
checkLocale(h, new Locale("nl", "NL"),
new ExpectedValues("nl", "NL", "", "nl_NL", "nld", "NLD",
"Niederl\u00e4ndisch", "Niederlande", "", "Niederl\u00e4ndisch (Niederlande)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18-mrt-1974", "18-3-74", "18-mrt-1974", "18 maart 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("\u20ac 1.000,00", "\u20ac 1.000.000,00", "\u20ac 100,00", "\u20ac 100,12", "\u20ac 10.000.000,12"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Luxemborg
checkLocale(h, new Locale("fr", "LU"),
new ExpectedValues("fr", "LU", "", "fr_LU", "fra", "LUX",
"Franz\u00f6sisch", "Luxemburg", "", "Franz\u00f6sisch (Luxemburg)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: United Kingdom
checkLocale(h, Locale.UK,
new ExpectedValues("en", "GB", "", "en_GB", "eng", "GBR",
"Englisch", "Vereinigtes K\u00f6nigreich", "", "Englisch (Vereinigtes K\u00f6nigreich)",
"GBP", 2, "GBP"),
new ExpectedDateValues("18-Mar-1974", "18/03/74", "18-Mar-1974", "18 March 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("\u00a31,000.00", "\u00a31,000,000.00", "\u00a3100.00", "\u00a3100.12", "\u00a310,000,000.12"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100", "10,000,000"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("100,000%", "100,000,000%", "10,000%", "10,012%", "1,000,000,012%"));
// Locale: United States
checkLocale(h, Locale.US,
new ExpectedValues("en", "US", "", "en_US", "eng", "USA",
"Englisch", "Vereinigte Staaten von Amerika", "", "Englisch (Vereinigte Staaten von Amerika)",
"USD", 2, "USD"),
new ExpectedDateValues("Mar 18, 1974", "3/18/74", "Mar 18, 1974", "March 18, 1974", "5:20:30 PM", "5:20 PM", "5:20:30 PM", "5:20:30 PM CET"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("$1,000.00", "$1,000,000.00", "$100.00", "$100.12", "$10,000,000.12"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100", "10,000,000"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("100,000%", "100,000,000%", "10,000%", "10,012%", "1,000,000,012%"));
// Locale: Finland
checkLocale(h, new Locale("fi", "FI"),
new ExpectedValues("fi", "FI", "", "fi_FI", "fin", "FIN",
"Finnisch", "Finnland", "", "Finnisch (Finnland)",
"EUR", 2, "EUR"),
new ExpectedDateValues("18.3.1974", "18.3.1974", "18.3.1974", "18. maaliskuuta 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100,123", "10\u00a0000\u00a0000,123"),
new ExpectedNumberValues("1\u00a0000,00 \u20ac", "1\u00a0000\u00a0000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10\u00a0000\u00a0000,12 \u20ac"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100", "10\u00a0000\u00a0000"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100,123", "10\u00a0000\u00a0000,123"),
new ExpectedNumberValues("100\u00a0000%", "100\u00a0000\u00a0000%", "10\u00a0000%", "10\u00a0012%", "1\u00a0000\u00a0000\u00a0012%"));
// Locale: Turkey
checkLocale(h, new Locale("tr", "TR"),
new ExpectedValues("tr", "TR", "", "tr_TR", "tur", "TUR",
"T\u00fcrkisch", "T\u00fcrkei", "", "T\u00fcrkisch (T\u00fcrkei)",
"TRL", 2, "TRL"),
new ExpectedDateValues("18.Mar.1974", "18.03.1974", "18.Mar.1974", "18 Mart 1974 Pazartesi", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000 TL", "1.000.000 TL", "100 TL", "100 TL", "10.000.000 TL"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Kazakstan
checkLocale(h, new Locale("kk", "KZ"),
null,
null,
null,
null,
null,
null,
null);
}
| public void test(TestHarness h)
{
// Check all supported locales.
// FIXME: Add all EURO countries.
// Locale: Germany
checkLocale(h, new Locale("de", "DE"),
new ExpectedValues("de", "DE", "", "de_DE", "deu", "DEU",
"Deutsch", "Deutschland", "", "Deutsch (Deutschland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Belgium
checkLocale(h, new Locale("fr", "BE"),
new ExpectedValues("fr", "BE", "", "fr_BE", "fra", "BEL",
"Franz\u00f6sisch", "Belgien", "", "Franz\u00f6sisch (Belgien)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Greece
// FIXME: Disabled for now due to pattern problems.
/*
checkLocale(h, new Locale("el", "GR"),
new ExpectedValues("el", "GR", "", "el_GR", "ell", "GRC",
"Griechisch", "Griechenland", "", "Griechisch (Griechenland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
*/
// Locale: Ireland
checkLocale(h, new Locale("en", "IE"),
new ExpectedValues("en", "IE", "", "en_IE", "eng", "IRL",
"Englisch", "Irland", "", "Englisch (Irland)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "18. M\u00e4rz 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000,00 \u20ac", "1.000.000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10.000.000,12 \u20ac"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: France
checkLocale(h, new Locale("fr", "FR"),
new ExpectedValues("fr", "FR", "", "fr_FR", "fra", "FRA",
"Franz\u00f6sisch", "Frankreich", "", "Franz\u00f6sisch (Frankreich)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Spain
checkLocale(h, new Locale("es", "ES"),
new ExpectedValues("es", "ES", "", "es_ES", "spa", "ESP",
"Spanisch", "Spanien", "", "Spanisch (Spanien)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Portugal
checkLocale(h, new Locale("pt", "PT"),
new ExpectedValues("pt", "PT", "", "pt_PT", "por", "PRT",
"Portugiesisch", "Portugal", "", "Portugiesisch (Portugal)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: Italy
checkLocale(h, new Locale("it", "IT"),
new ExpectedValues("it", "IT", "", "it_IT", "ita", "ITA",
"Italienisch", "Italien", "", "Italienisch (Italien)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: The Netherlands
checkLocale(h, new Locale("nl", "NL"),
new ExpectedValues("nl", "NL", "", "nl_NL", "nld", "NLD",
"Niederl\u00e4ndisch", "Niederlande", "", "Niederl\u00e4ndisch (Niederlande)",
"EUR", 2, "\u20ac"),
new ExpectedDateValues("18-mrt-1974", "18-3-74", "18-mrt-1974", "18 maart 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("\u20ac 1.000,00", "\u20ac 1.000.000,00", "\u20ac 100,00", "\u20ac 100,12", "\u20ac 10.000.000,12"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Luxemborg
checkLocale(h, new Locale("fr", "LU"),
new ExpectedValues("fr", "LU", "", "fr_LU", "fra", "LUX",
"Franz\u00f6sisch", "Luxemburg", "", "Franz\u00f6sisch (Luxemburg)",
"EUR", 2, "\u20ac"),
null,
null,
null,
null,
null,
null);
// Locale: United Kingdom
checkLocale(h, Locale.UK,
new ExpectedValues("en", "GB", "", "en_GB", "eng", "GBR",
"Englisch", "Vereinigtes K\u00f6nigreich", "", "Englisch (Vereinigtes K\u00f6nigreich)",
"GBP", 2, "GBP"),
new ExpectedDateValues("18-Mar-1974", "18/03/74", "18-Mar-1974", "18 March 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("\u00a31,000.00", "\u00a31,000,000.00", "\u00a3100.00", "\u00a3100.12", "\u00a310,000,000.12"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100", "10,000,000"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("100,000%", "100,000,000%", "10,000%", "10,012%", "1,000,000,012%"));
// Locale: United States
checkLocale(h, Locale.US,
new ExpectedValues("en", "US", "", "en_US", "eng", "USA",
"Englisch", "Vereinigte Staaten von Amerika", "", "Englisch (Vereinigte Staaten von Amerika)",
"USD", 2, "US$"),
new ExpectedDateValues("Mar 18, 1974", "3/18/74", "Mar 18, 1974", "March 18, 1974", "5:20:30 PM", "5:20 PM", "5:20:30 PM", "5:20:30 PM CET"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("$1,000.00", "$1,000,000.00", "$100.00", "$100.12", "$10,000,000.12"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100", "10,000,000"),
new ExpectedNumberValues("1,000", "1,000,000", "100", "100.123", "10,000,000.123"),
new ExpectedNumberValues("100,000%", "100,000,000%", "10,000%", "10,012%", "1,000,000,012%"));
// Locale: Finland
checkLocale(h, new Locale("fi", "FI"),
new ExpectedValues("fi", "FI", "", "fi_FI", "fin", "FIN",
"Finnisch", "Finnland", "", "Finnisch (Finnland)",
"EUR", 2, "EUR"),
new ExpectedDateValues("18.3.1974", "18.3.1974", "18.3.1974", "18. maaliskuuta 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100,123", "10\u00a0000\u00a0000,123"),
new ExpectedNumberValues("1\u00a0000,00 \u20ac", "1\u00a0000\u00a0000,00 \u20ac", "100,00 \u20ac", "100,12 \u20ac", "10\u00a0000\u00a0000,12 \u20ac"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100", "10\u00a0000\u00a0000"),
new ExpectedNumberValues("1\u00a0000", "1\u00a0000\u00a0000", "100", "100,123", "10\u00a0000\u00a0000,123"),
new ExpectedNumberValues("100\u00a0000%", "100\u00a0000\u00a0000%", "10\u00a0000%", "10\u00a0012%", "1\u00a0000\u00a0000\u00a0012%"));
// Locale: Turkey
checkLocale(h, new Locale("tr", "TR"),
new ExpectedValues("tr", "TR", "", "tr_TR", "tur", "TUR",
"T\u00fcrkisch", "T\u00fcrkei", "", "T\u00fcrkisch (T\u00fcrkei)",
"TRL", 0, "TRL"),
new ExpectedDateValues("18.Mar.1974", "18.03.1974", "18.Mar.1974", "18 Mart 1974 Pazartesi", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("1.000 TRL", "1.000.000 TRL", "100 TRL", "100 TRL", "10.000.000 TRL"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100", "10.000.000"),
new ExpectedNumberValues("1.000", "1.000.000", "100", "100,123", "10.000.000,123"),
new ExpectedNumberValues("100.000%", "100.000.000%", "10.000%", "10.012%", "1.000.000.012%"));
// Locale: Kazakstan
checkLocale(h, new Locale("kk", "KZ"),
null,
null,
null,
null,
null,
null,
null);
// Locale: Estonia
checkLocale(h, new Locale("et", "EE"),
new ExpectedValues("et", "EE", "", "et_EE", "est", "EST",
"Estnisch", "Estland", "", "Estnisch (Estland)",
"EEK", 2, "kr"),
new ExpectedDateValues("18.03.1974", "18.03.74", "18.03.1974", "esmasp�ev, 18. M�rts 1974", "17:20:30", "17:20", "17:20:30", "17:20:30 CET"),
new ExpectedNumberValues("1�000", "1�000�000", "100", "100,123", "10�000�000,123"),
new ExpectedNumberValues("1�000 kr", "1�000�000 kr", "100 kr", "100,12 kr", "10�000�000,12 kr"),
new ExpectedNumberValues("1�000", "1�000�000", "100", "100", "10�000�000"),
new ExpectedNumberValues("1�000", "1�000�000", "100", "100,123", "10�000�000,123"),
new ExpectedNumberValues("100�000%", "100�000�000%", "10�000%", "10�012%", "1�000�000�012%"));
}
|
diff --git a/morphia/src/main/java/com/google/code/morphia/converters/IterableConverter.java b/morphia/src/main/java/com/google/code/morphia/converters/IterableConverter.java
index 69d9fa1..4b50930 100644
--- a/morphia/src/main/java/com/google/code/morphia/converters/IterableConverter.java
+++ b/morphia/src/main/java/com/google/code/morphia/converters/IterableConverter.java
@@ -1,114 +1,114 @@
/**
*
*/
package com.google.code.morphia.converters;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.google.code.morphia.ObjectFactory;
import com.google.code.morphia.mapping.MappedField;
import com.google.code.morphia.mapping.MappingException;
import com.google.code.morphia.utils.ReflectionUtils;
/**
* @author Uwe Schaefer, ([email protected])
* @author scotthernandez
*/
@SuppressWarnings({"unchecked","rawtypes"})
public class IterableConverter extends TypeConverter {
private final DefaultConverters chain;
public IterableConverter(DefaultConverters chain) {
this.chain = chain;
}
@Override
protected
boolean isSupported(Class c, MappedField mf) {
if (mf != null)
return mf.isMultipleValues() && !mf.isMap(); //&& !mf.isTypeMongoCompatible();
else
return c.isArray() || ReflectionUtils.implementsInterface(c, Iterable.class);
}
@Override
public Object decode(Class targetClass, Object fromDBObject, MappedField mf) throws MappingException {
if (mf == null || fromDBObject == null) return fromDBObject;
Class subtypeDest = mf.getSubClass();
Collection vals = createNewCollection(mf);
if (fromDBObject.getClass().isArray()) {
//This should never happen. The driver always returns list/arrays as a List
for(Object o : (Object[])fromDBObject)
vals.add(chain.decode( (subtypeDest != null) ? subtypeDest : o.getClass(), o));
} else if (fromDBObject instanceof Iterable) {
// map back to the java datatype
// (List/Set/Array[])
for (Object o : (Iterable) fromDBObject)
vals.add(chain.decode((subtypeDest != null) ? subtypeDest : o.getClass(), o));
} else {
//Single value case.
vals.add(chain.decode((subtypeDest != null) ? subtypeDest : fromDBObject.getClass(), fromDBObject));
}
//convert to and array if that is the destination type (not a list/set)
if (mf.getType().isArray()) {
return ReflectionUtils.convertToArray(subtypeDest, (ArrayList)vals);
} else
return vals;
}
private Collection<?> createNewCollection(final MappedField mf) {
ObjectFactory of = mapr.getOptions().objectFactory;
return mf.isSet() ? of.createSet(mf) : of.createList(mf);
}
@Override
public
Object encode(Object value, MappedField mf) {
if (value == null)
return null;
Iterable<?> iterableValues = null;
if (value.getClass().isArray()) {
if (Array.getLength(value) == 0) {
return value;
}
if (value.getClass().getComponentType().isPrimitive())
return value;
iterableValues = Arrays.asList((Object[]) value);
} else {
if (!(value instanceof Iterable))
throw new ConverterException("Cannot cast " + value.getClass() + " to Iterable for MappedField: " + mf);
// cast value to a common interface
iterableValues = (Iterable<?>) value;
}
List values = new ArrayList();
if (mf != null && mf.getSubClass() != null) {
for (Object o : iterableValues) {
values.add(chain.encode(mf.getSubClass(), o));
}
} else {
for (Object o : iterableValues) {
values.add(chain.encode(o));
}
}
- if (values.size() > 0) {
+ if (values.size() > 0 || mapr.getOptions().storeEmpties) {
return values;
} else
return null;
}
}
| true | true | Object encode(Object value, MappedField mf) {
if (value == null)
return null;
Iterable<?> iterableValues = null;
if (value.getClass().isArray()) {
if (Array.getLength(value) == 0) {
return value;
}
if (value.getClass().getComponentType().isPrimitive())
return value;
iterableValues = Arrays.asList((Object[]) value);
} else {
if (!(value instanceof Iterable))
throw new ConverterException("Cannot cast " + value.getClass() + " to Iterable for MappedField: " + mf);
// cast value to a common interface
iterableValues = (Iterable<?>) value;
}
List values = new ArrayList();
if (mf != null && mf.getSubClass() != null) {
for (Object o : iterableValues) {
values.add(chain.encode(mf.getSubClass(), o));
}
} else {
for (Object o : iterableValues) {
values.add(chain.encode(o));
}
}
if (values.size() > 0) {
return values;
} else
return null;
}
| Object encode(Object value, MappedField mf) {
if (value == null)
return null;
Iterable<?> iterableValues = null;
if (value.getClass().isArray()) {
if (Array.getLength(value) == 0) {
return value;
}
if (value.getClass().getComponentType().isPrimitive())
return value;
iterableValues = Arrays.asList((Object[]) value);
} else {
if (!(value instanceof Iterable))
throw new ConverterException("Cannot cast " + value.getClass() + " to Iterable for MappedField: " + mf);
// cast value to a common interface
iterableValues = (Iterable<?>) value;
}
List values = new ArrayList();
if (mf != null && mf.getSubClass() != null) {
for (Object o : iterableValues) {
values.add(chain.encode(mf.getSubClass(), o));
}
} else {
for (Object o : iterableValues) {
values.add(chain.encode(o));
}
}
if (values.size() > 0 || mapr.getOptions().storeEmpties) {
return values;
} else
return null;
}
|
diff --git a/pregelix/pregelix-core/src/main/java/edu/uci/ics/pregelix/core/driver/Driver.java b/pregelix/pregelix-core/src/main/java/edu/uci/ics/pregelix/core/driver/Driver.java
index 3a344d907..1f071bf79 100644
--- a/pregelix/pregelix-core/src/main/java/edu/uci/ics/pregelix/core/driver/Driver.java
+++ b/pregelix/pregelix-core/src/main/java/edu/uci/ics/pregelix/core/driver/Driver.java
@@ -1,245 +1,235 @@
/*
* Copyright 2009-2010 by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* 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 edu.uci.ics.pregelix.core.driver;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import edu.uci.ics.hyracks.api.client.HyracksConnection;
import edu.uci.ics.hyracks.api.client.IHyracksClientConnection;
import edu.uci.ics.hyracks.api.deployment.DeploymentId;
import edu.uci.ics.hyracks.api.exceptions.HyracksException;
import edu.uci.ics.hyracks.api.job.JobFlag;
import edu.uci.ics.hyracks.api.job.JobId;
import edu.uci.ics.hyracks.api.job.JobSpecification;
import edu.uci.ics.pregelix.api.job.PregelixJob;
import edu.uci.ics.pregelix.core.base.IDriver;
import edu.uci.ics.pregelix.core.jobgen.JobGen;
import edu.uci.ics.pregelix.core.jobgen.JobGenInnerJoin;
import edu.uci.ics.pregelix.core.jobgen.JobGenOuterJoin;
import edu.uci.ics.pregelix.core.jobgen.JobGenOuterJoinSingleSort;
import edu.uci.ics.pregelix.core.jobgen.JobGenOuterJoinSort;
import edu.uci.ics.pregelix.core.jobgen.clusterconfig.ClusterConfig;
import edu.uci.ics.pregelix.dataflow.util.IterationUtils;
@SuppressWarnings("rawtypes")
public class Driver implements IDriver {
private static final Log LOG = LogFactory.getLog(Driver.class);
private JobGen jobGen;
private boolean profiling;
private IHyracksClientConnection hcc;
private Class exampleClass;
public Driver(Class exampleClass) {
this.exampleClass = exampleClass;
}
@Override
public void runJob(PregelixJob job, String ipAddress, int port) throws HyracksException {
runJob(job, Plan.OUTER_JOIN, ipAddress, port, false);
}
@Override
public void runJob(PregelixJob job, Plan planChoice, String ipAddress, int port, boolean profiling)
throws HyracksException {
try {
/** add hadoop configurations */
URL hadoopCore = job.getClass().getClassLoader().getResource("core-site.xml");
if (hadoopCore != null) {
job.getConfiguration().addResource(hadoopCore);
}
URL hadoopMapRed = job.getClass().getClassLoader().getResource("mapred-site.xml");
if (hadoopMapRed != null) {
job.getConfiguration().addResource(hadoopMapRed);
}
URL hadoopHdfs = job.getClass().getClassLoader().getResource("hdfs-site.xml");
if (hadoopHdfs != null) {
job.getConfiguration().addResource(hadoopHdfs);
}
ClusterConfig.loadClusterConfig(ipAddress, port);
LOG.info("job started");
long start = System.currentTimeMillis();
long end = start;
long time = 0;
this.profiling = profiling;
switch (planChoice) {
case INNER_JOIN:
jobGen = new JobGenInnerJoin(job);
break;
case OUTER_JOIN:
jobGen = new JobGenOuterJoin(job);
break;
case OUTER_JOIN_SORT:
jobGen = new JobGenOuterJoinSort(job);
break;
case OUTER_JOIN_SINGLE_SORT:
jobGen = new JobGenOuterJoinSingleSort(job);
break;
default:
jobGen = new JobGenInnerJoin(job);
}
if (hcc == null)
hcc = new HyracksConnection(ipAddress, port);
URLClassLoader classLoader = (URLClassLoader) exampleClass.getClassLoader();
List<File> jars = new ArrayList<File>();
URL[] urls = classLoader.getURLs();
for (URL url : urls)
if (url.toString().endsWith(".jar"))
jars.add(new File(url.getPath()));
DeploymentId deploymentId = installApplication(jars);
start = System.currentTimeMillis();
FileSystem dfs = FileSystem.get(job.getConfiguration());
dfs.delete(FileOutputFormat.getOutputPath(job), true);
runCreate(deploymentId, jobGen);
runDataLoad(deploymentId, jobGen);
end = System.currentTimeMillis();
time = end - start;
LOG.info("data loading finished " + time + "ms");
int i = 1;
boolean terminate = false;
do {
start = System.currentTimeMillis();
runLoopBodyIteration(deploymentId, jobGen, i);
end = System.currentTimeMillis();
time = end - start;
LOG.info("iteration " + i + " finished " + time + "ms");
terminate = IterationUtils.readTerminationState(job.getConfiguration(), jobGen.getJobId())
|| IterationUtils.readForceTerminationState(job.getConfiguration(), jobGen.getJobId());
i++;
} while (!terminate);
start = System.currentTimeMillis();
runHDFSWRite(deploymentId, jobGen);
runCleanup(deploymentId, jobGen);
end = System.currentTimeMillis();
time = end - start;
LOG.info("result writing finished " + time + "ms");
hcc.unDeployBinary(deploymentId);
LOG.info("job finished");
} catch (Exception e) {
- try {
- /**
- * destroy application if there is any exception
- */
- if (hcc != null && deploymentId == null) {
- hcc.unDeployBinary(deploymentId);
- }
- } catch (Exception e2) {
- throw new HyracksException(e2);
- }
throw new HyracksException(e);
}
}
private void runCreate(DeploymentId deploymentId, JobGen jobGen) throws Exception {
try {
JobSpecification treeCreateSpec = jobGen.generateCreatingJob();
execute(deploymentId, treeCreateSpec);
} catch (Exception e) {
throw e;
}
}
private void runDataLoad(DeploymentId deploymentId, JobGen jobGen) throws Exception {
try {
JobSpecification bulkLoadJobSpec = jobGen.generateLoadingJob();
execute(deploymentId, bulkLoadJobSpec);
} catch (Exception e) {
throw e;
}
}
private void runLoopBodyIteration(DeploymentId deploymentId, JobGen jobGen, int iteration) throws Exception {
try {
JobSpecification loopBody = jobGen.generateJob(iteration);
execute(deploymentId, loopBody);
} catch (Exception e) {
throw e;
}
}
private void runHDFSWRite(DeploymentId deploymentId, JobGen jobGen) throws Exception {
try {
JobSpecification scanSortPrintJobSpec = jobGen.scanIndexWriteGraph();
execute(deploymentId, scanSortPrintJobSpec);
} catch (Exception e) {
throw e;
}
}
private void runCleanup(DeploymentId deploymentId, JobGen jobGen) throws Exception {
try {
JobSpecification[] cleanups = jobGen.generateCleanup();
runJobArray(deploymentId, cleanups);
} catch (Exception e) {
throw e;
}
}
private void runJobArray(DeploymentId deploymentId, JobSpecification[] jobs) throws Exception {
for (JobSpecification job : jobs) {
execute(deploymentId, job);
}
}
private void execute(DeploymentId deploymentId, JobSpecification job) throws Exception {
job.setUseConnectorPolicyForScheduling(false);
JobId jobId = hcc.startJob(deploymentId, job,
profiling ? EnumSet.of(JobFlag.PROFILE_RUNTIME) : EnumSet.noneOf(JobFlag.class));
hcc.waitForCompletion(jobId);
}
public DeploymentId installApplication(List<File> jars) throws Exception {
List<String> allJars = new ArrayList<String>();
for (File jar : jars) {
allJars.add(jar.getAbsolutePath());
}
long start = System.currentTimeMillis();
DeploymentId deploymentId = hcc.deployBinary(allJars);
long end = System.currentTimeMillis();
LOG.info("jar deployment finished " + (end - start) + "ms");
return deploymentId;
}
}
class FileFilter implements FilenameFilter {
private String ext;
public FileFilter(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
| true | true | public void runJob(PregelixJob job, Plan planChoice, String ipAddress, int port, boolean profiling)
throws HyracksException {
try {
/** add hadoop configurations */
URL hadoopCore = job.getClass().getClassLoader().getResource("core-site.xml");
if (hadoopCore != null) {
job.getConfiguration().addResource(hadoopCore);
}
URL hadoopMapRed = job.getClass().getClassLoader().getResource("mapred-site.xml");
if (hadoopMapRed != null) {
job.getConfiguration().addResource(hadoopMapRed);
}
URL hadoopHdfs = job.getClass().getClassLoader().getResource("hdfs-site.xml");
if (hadoopHdfs != null) {
job.getConfiguration().addResource(hadoopHdfs);
}
ClusterConfig.loadClusterConfig(ipAddress, port);
LOG.info("job started");
long start = System.currentTimeMillis();
long end = start;
long time = 0;
this.profiling = profiling;
switch (planChoice) {
case INNER_JOIN:
jobGen = new JobGenInnerJoin(job);
break;
case OUTER_JOIN:
jobGen = new JobGenOuterJoin(job);
break;
case OUTER_JOIN_SORT:
jobGen = new JobGenOuterJoinSort(job);
break;
case OUTER_JOIN_SINGLE_SORT:
jobGen = new JobGenOuterJoinSingleSort(job);
break;
default:
jobGen = new JobGenInnerJoin(job);
}
if (hcc == null)
hcc = new HyracksConnection(ipAddress, port);
URLClassLoader classLoader = (URLClassLoader) exampleClass.getClassLoader();
List<File> jars = new ArrayList<File>();
URL[] urls = classLoader.getURLs();
for (URL url : urls)
if (url.toString().endsWith(".jar"))
jars.add(new File(url.getPath()));
DeploymentId deploymentId = installApplication(jars);
start = System.currentTimeMillis();
FileSystem dfs = FileSystem.get(job.getConfiguration());
dfs.delete(FileOutputFormat.getOutputPath(job), true);
runCreate(deploymentId, jobGen);
runDataLoad(deploymentId, jobGen);
end = System.currentTimeMillis();
time = end - start;
LOG.info("data loading finished " + time + "ms");
int i = 1;
boolean terminate = false;
do {
start = System.currentTimeMillis();
runLoopBodyIteration(deploymentId, jobGen, i);
end = System.currentTimeMillis();
time = end - start;
LOG.info("iteration " + i + " finished " + time + "ms");
terminate = IterationUtils.readTerminationState(job.getConfiguration(), jobGen.getJobId())
|| IterationUtils.readForceTerminationState(job.getConfiguration(), jobGen.getJobId());
i++;
} while (!terminate);
start = System.currentTimeMillis();
runHDFSWRite(deploymentId, jobGen);
runCleanup(deploymentId, jobGen);
end = System.currentTimeMillis();
time = end - start;
LOG.info("result writing finished " + time + "ms");
hcc.unDeployBinary(deploymentId);
LOG.info("job finished");
} catch (Exception e) {
try {
/**
* destroy application if there is any exception
*/
if (hcc != null && deploymentId == null) {
hcc.unDeployBinary(deploymentId);
}
} catch (Exception e2) {
throw new HyracksException(e2);
}
throw new HyracksException(e);
}
}
| public void runJob(PregelixJob job, Plan planChoice, String ipAddress, int port, boolean profiling)
throws HyracksException {
try {
/** add hadoop configurations */
URL hadoopCore = job.getClass().getClassLoader().getResource("core-site.xml");
if (hadoopCore != null) {
job.getConfiguration().addResource(hadoopCore);
}
URL hadoopMapRed = job.getClass().getClassLoader().getResource("mapred-site.xml");
if (hadoopMapRed != null) {
job.getConfiguration().addResource(hadoopMapRed);
}
URL hadoopHdfs = job.getClass().getClassLoader().getResource("hdfs-site.xml");
if (hadoopHdfs != null) {
job.getConfiguration().addResource(hadoopHdfs);
}
ClusterConfig.loadClusterConfig(ipAddress, port);
LOG.info("job started");
long start = System.currentTimeMillis();
long end = start;
long time = 0;
this.profiling = profiling;
switch (planChoice) {
case INNER_JOIN:
jobGen = new JobGenInnerJoin(job);
break;
case OUTER_JOIN:
jobGen = new JobGenOuterJoin(job);
break;
case OUTER_JOIN_SORT:
jobGen = new JobGenOuterJoinSort(job);
break;
case OUTER_JOIN_SINGLE_SORT:
jobGen = new JobGenOuterJoinSingleSort(job);
break;
default:
jobGen = new JobGenInnerJoin(job);
}
if (hcc == null)
hcc = new HyracksConnection(ipAddress, port);
URLClassLoader classLoader = (URLClassLoader) exampleClass.getClassLoader();
List<File> jars = new ArrayList<File>();
URL[] urls = classLoader.getURLs();
for (URL url : urls)
if (url.toString().endsWith(".jar"))
jars.add(new File(url.getPath()));
DeploymentId deploymentId = installApplication(jars);
start = System.currentTimeMillis();
FileSystem dfs = FileSystem.get(job.getConfiguration());
dfs.delete(FileOutputFormat.getOutputPath(job), true);
runCreate(deploymentId, jobGen);
runDataLoad(deploymentId, jobGen);
end = System.currentTimeMillis();
time = end - start;
LOG.info("data loading finished " + time + "ms");
int i = 1;
boolean terminate = false;
do {
start = System.currentTimeMillis();
runLoopBodyIteration(deploymentId, jobGen, i);
end = System.currentTimeMillis();
time = end - start;
LOG.info("iteration " + i + " finished " + time + "ms");
terminate = IterationUtils.readTerminationState(job.getConfiguration(), jobGen.getJobId())
|| IterationUtils.readForceTerminationState(job.getConfiguration(), jobGen.getJobId());
i++;
} while (!terminate);
start = System.currentTimeMillis();
runHDFSWRite(deploymentId, jobGen);
runCleanup(deploymentId, jobGen);
end = System.currentTimeMillis();
time = end - start;
LOG.info("result writing finished " + time + "ms");
hcc.unDeployBinary(deploymentId);
LOG.info("job finished");
} catch (Exception e) {
throw new HyracksException(e);
}
}
|
diff --git a/src/html2windows/dom/NamedNodeMap.java b/src/html2windows/dom/NamedNodeMap.java
index 034168e..1c83363 100644
--- a/src/html2windows/dom/NamedNodeMap.java
+++ b/src/html2windows/dom/NamedNodeMap.java
@@ -1,70 +1,70 @@
package html2windows.dom;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.w3c.dom.DOMException;
public class NamedNodeMap extends HashMap<String, Node> {
/*
* 目的:取得名稱為name的Node
*
* 參數: name => 要取得的Node名稱
*/
public Node getNamedItem(String name) {
return get(name);
}
/*
* 目的:將傳入的Node加入到Map中
*
* 參數:arg => 要加入的Node
*/
public Node setNamedItem(Node arg) throws DOMException {
Node returnNode = null;
String nodeName = arg.nodeName();
if (containsKey(nodeName))
returnNode = get(nodeName);
put(nodeName, arg);
return returnNode;
}
/*
* 目的:Removes a node specified by name
*
* 參數:name => 要刪除的Node Name
*/
public Node removeNamedItem(String name) throws DOMException {
if (containsKey(name) == false) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"There is no node named name in this map.");
} else {
Node returnNode = get(name);
remove(name);
return returnNode;
}
}
public Node item(long index) {
- Collection collection = values();
- Iterator iterator = collection.iterator();
+ Collection<Node> collection = values();
+ Iterator<Node> iterator = collection.iterator();
int i = 0;
Node returnNode = null;
while (iterator.hasNext()) {
if (i == (int) index)
- returnNode = (Node) iterator.next();
+ returnNode = iterator.next();
else
iterator.next();
}
return returnNode;
}
// 目的:回傳此Map的Size
public long length() {
return size();
}
}
| false | true | public Node item(long index) {
Collection collection = values();
Iterator iterator = collection.iterator();
int i = 0;
Node returnNode = null;
while (iterator.hasNext()) {
if (i == (int) index)
returnNode = (Node) iterator.next();
else
iterator.next();
}
return returnNode;
}
| public Node item(long index) {
Collection<Node> collection = values();
Iterator<Node> iterator = collection.iterator();
int i = 0;
Node returnNode = null;
while (iterator.hasNext()) {
if (i == (int) index)
returnNode = iterator.next();
else
iterator.next();
}
return returnNode;
}
|
diff --git a/src/contrib/gridmix/src/test/org/apache/hadoop/mapred/gridmix/TestUserResolve.java b/src/contrib/gridmix/src/test/org/apache/hadoop/mapred/gridmix/TestUserResolve.java
index 171264058..abcfe7fa3 100644
--- a/src/contrib/gridmix/src/test/org/apache/hadoop/mapred/gridmix/TestUserResolve.java
+++ b/src/contrib/gridmix/src/test/org/apache/hadoop/mapred/gridmix/TestUserResolve.java
@@ -1,97 +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.
*/
package org.apache.hadoop.mapred.gridmix;
import java.io.IOException;
import java.net.URI;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.UnixUserGroupInformation;
import org.apache.hadoop.security.UserGroupInformation;
public class TestUserResolve {
static Path userlist;
@BeforeClass
public static void writeUserList() throws IOException {
final Configuration conf = new Configuration();
final FileSystem fs = FileSystem.getLocal(conf);
final Path wd = new Path(new Path(
System.getProperty("test.build.data", "/tmp")).makeQualified(fs),
"gridmixUserResolve");
userlist = new Path(wd, "users");
FSDataOutputStream out = null;
try {
out = fs.create(userlist, true);
out.writeBytes("user0,groupA,groupB,groupC\n");
out.writeBytes("user1,groupA,groupC\n");
out.writeBytes("user2,groupB\n");
out.writeBytes("user3,groupA,groupB,groupC\n");
} finally {
if (out != null) {
out.close();
}
}
}
@Test
public void testRoundRobinResolver() throws Exception {
final Configuration conf = new Configuration();
final UserResolver rslv = new RoundRobinUserResolver();
boolean fail = false;
try {
rslv.setTargetUsers(null, conf);
} catch (IOException e) {
fail = true;
}
assertTrue("User list required for RoundRobinUserResolver", fail);
rslv.setTargetUsers(new URI(userlist.toString()), conf);
- assertEquals("user0", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre0")).getUserName());
+ UserGroupInformation ugi1;
+ assertEquals("user0",
+ rslv.getTargetUgi((ugi1 =
+ UserGroupInformation.createRemoteUser("hfre0"))).getUserName());
assertEquals("user1", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre1")).getUserName());
assertEquals("user2", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre2")).getUserName());
- assertEquals("user0", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre0")).getUserName());
+ assertEquals("user0", rslv.getTargetUgi(ugi1).getUserName());
assertEquals("user3", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre3")).getUserName());
- assertEquals("user0", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre0")).getUserName());
- assertEquals("user0", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre4")).getUserName());
+ assertEquals("user0", rslv.getTargetUgi(ugi1).getUserName());
}
@Test
public void testSubmitterResolver() throws Exception {
final Configuration conf = new Configuration();
final UserResolver rslv = new SubmitterUserResolver();
rslv.setTargetUsers(null, conf);
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
assertEquals(ugi, rslv.getTargetUgi((UserGroupInformation)null));
System.out.println(" Submitter current user " + ugi);
System.out.println(
" Target ugi " + rslv.getTargetUgi(
(UserGroupInformation) null));
}
}
| false | true | public void testRoundRobinResolver() throws Exception {
final Configuration conf = new Configuration();
final UserResolver rslv = new RoundRobinUserResolver();
boolean fail = false;
try {
rslv.setTargetUsers(null, conf);
} catch (IOException e) {
fail = true;
}
assertTrue("User list required for RoundRobinUserResolver", fail);
rslv.setTargetUsers(new URI(userlist.toString()), conf);
assertEquals("user0", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre0")).getUserName());
assertEquals("user1", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre1")).getUserName());
assertEquals("user2", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre2")).getUserName());
assertEquals("user0", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre0")).getUserName());
assertEquals("user3", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre3")).getUserName());
assertEquals("user0", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre0")).getUserName());
assertEquals("user0", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre4")).getUserName());
}
| public void testRoundRobinResolver() throws Exception {
final Configuration conf = new Configuration();
final UserResolver rslv = new RoundRobinUserResolver();
boolean fail = false;
try {
rslv.setTargetUsers(null, conf);
} catch (IOException e) {
fail = true;
}
assertTrue("User list required for RoundRobinUserResolver", fail);
rslv.setTargetUsers(new URI(userlist.toString()), conf);
UserGroupInformation ugi1;
assertEquals("user0",
rslv.getTargetUgi((ugi1 =
UserGroupInformation.createRemoteUser("hfre0"))).getUserName());
assertEquals("user1", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre1")).getUserName());
assertEquals("user2", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre2")).getUserName());
assertEquals("user0", rslv.getTargetUgi(ugi1).getUserName());
assertEquals("user3", rslv.getTargetUgi(UserGroupInformation.createRemoteUser("hfre3")).getUserName());
assertEquals("user0", rslv.getTargetUgi(ugi1).getUserName());
}
|
diff --git a/soundcloud-mediasupport/src/main/java/com/senselessweb/soundcloud/mediasupport/gstreamer/pipeline/FileSrcPipeline.java b/soundcloud-mediasupport/src/main/java/com/senselessweb/soundcloud/mediasupport/gstreamer/pipeline/FileSrcPipeline.java
index 6dd87b0..0fcb5fe 100644
--- a/soundcloud-mediasupport/src/main/java/com/senselessweb/soundcloud/mediasupport/gstreamer/pipeline/FileSrcPipeline.java
+++ b/soundcloud-mediasupport/src/main/java/com/senselessweb/soundcloud/mediasupport/gstreamer/pipeline/FileSrcPipeline.java
@@ -1,61 +1,62 @@
package com.senselessweb.soundcloud.mediasupport.gstreamer.pipeline;
import java.io.File;
import com.senselessweb.soundcloud.mediasupport.gstreamer.elements.EqualizerBridge;
import com.senselessweb.soundcloud.mediasupport.gstreamer.elements.PanoramaBridge;
import com.senselessweb.soundcloud.mediasupport.gstreamer.elements.VolumeBridge;
import com.senselessweb.soundcloud.mediasupport.service.MessageListenerService;
import com.senselessweb.soundcloud.mediasupport.service.VolumeControl;
/**
* Pipeline bridge that uses a file source.
*
* @author thomas
*/
public class FileSrcPipeline extends AbstractPipeline
{
/**
* Constructor
*
* @param file The file that is used as source.
* @param volume The {@link VolumeControl}.
* @param equalizer The current {@link EqualizerBridge}.
* @param panoramaBridge The {@link PanoramaBridge}.
* @param messageListener The {@link MessageListenerService}.
*/
public FileSrcPipeline(final File file, final VolumeBridge volume, final EqualizerBridge equalizer,
final PanoramaBridge panoramaBridge, final MessageListenerService messageListener)
{
- super(createDefaultPipeline("filesrc location=file.getAbsolutePath()"), volume, equalizer, panoramaBridge, messageListener);
+ super(createDefaultPipeline("filesrc name=src"), volume, equalizer, panoramaBridge, messageListener);
+ this.pipeline.getElementByName("src").set("location", file.getAbsolutePath());
}
/**
* @see com.senselessweb.soundcloud.mediasupport.gstreamer.PipelineBridge#resetInErrorCase()
*/
@Override
public boolean resetInErrorCase()
{
return false;
}
/**
* @see com.senselessweb.soundcloud.mediasupport.gstreamer.PipelineBridge#isPausable()
*/
@Override
public boolean isPausable()
{
return true;
}
/**
* @see com.senselessweb.soundcloud.mediasupport.gstreamer.PipelineBridge#isSeekSupported()
*/
@Override
public boolean isSeekSupported()
{
return true;
}
}
| true | true | public FileSrcPipeline(final File file, final VolumeBridge volume, final EqualizerBridge equalizer,
final PanoramaBridge panoramaBridge, final MessageListenerService messageListener)
{
super(createDefaultPipeline("filesrc location=file.getAbsolutePath()"), volume, equalizer, panoramaBridge, messageListener);
}
| public FileSrcPipeline(final File file, final VolumeBridge volume, final EqualizerBridge equalizer,
final PanoramaBridge panoramaBridge, final MessageListenerService messageListener)
{
super(createDefaultPipeline("filesrc name=src"), volume, equalizer, panoramaBridge, messageListener);
this.pipeline.getElementByName("src").set("location", file.getAbsolutePath());
}
|
diff --git a/src/joueur/PlateauJoueur.java b/src/joueur/PlateauJoueur.java
index 0ee9477..6eb3ec8 100644
--- a/src/joueur/PlateauJoueur.java
+++ b/src/joueur/PlateauJoueur.java
@@ -1,115 +1,115 @@
package joueur;
import java.util.ArrayList;
public class PlateauJoueur {
private Case[][] cases;
private Boolean[][] clotures_lignes;
private Boolean[][] clotures_colonnes;
public PlateauJoueur(){
this.cases = new Case[5][3];
int numero_case = 1;
for(int i = 0; i < this.cases.length; i++){
for(int j = 0; j < this.cases[i].length; j++){
this.cases[i][j] = new Case(numero_case);
numero_case++;
}
}
- this.cases[0][1] = new CaseHabitation(true);
- this.cases[0][2] = new CaseHabitation(true);
+ this.cases[0][1] = new CaseHabitation(true,6);
+ this.cases[0][2] = new CaseHabitation(true,11);
this.clotures_lignes = new Boolean[5][4];
for(int i = 0; i < this.clotures_lignes.length; i++)
for(int j = 0; j < this.clotures_lignes[i].length; j++)
this.clotures_lignes[i][j] = false;
this.clotures_colonnes = new Boolean[6][3];
for(int i = 0; i < this.clotures_colonnes.length; i++)
for(int j = 0; j < this.clotures_colonnes[i].length; j++)
this.clotures_colonnes[i][j] = false;
}
/*
public int nombredePaturage(){
int nombre_de_paturage = 0;
int nombre_de_cloture_col = 0;
int nombre_de_cloture_ligne = 0;
//recuperation du nombre de cloture en colonne
for(Boolean[] bool_col : this.clotures_colonnes){
for(Boolean bool_current_col : bool_col){
if(bool_current_col==true){
nombre_de_cloture_col ++;
}
}
}
//recuperation du nombre de cloture en ligne
for(Boolean[] bool_ligne : this.clotures_lignes){
for(Boolean bool_current_ligne : bool_ligne){
if(bool_current_ligne==true){
nombre_de_cloture_ligne ++;
}
}
}
//test si 0 paturage
if((nombre_de_cloture_col==0)||(nombre_de_cloture_ligne==0)){
return 0;
}
int num_ligne = 0;
int num_col = 0;
int num_case = 1;
ArrayList<Case> liste_marquee = new ArrayList<Case>();
Boolean[][] temp = null;
for(Case[] cases : this.cases){
for(Case case_actuelle : cases){
Boolean bordure_haute = clotures_lignes[num_col][num_ligne];
Boolean bordure_gauche = clotures_colonnes[num_col][num_ligne];
Boolean bordure_droite = clotures_colonnes[num_col+1][num_ligne];
Boolean bordure_basse = clotures_lignes[num_col][num_ligne+1];
if((bordure_haute == true) || (bordure_basse == true) || (bordure_gauche == true) || (bordure_droite == true)){
temp[num_ligne][num_col] = true;
liste_marquee.add(new Case(num_case));
}
num_col++;
num_case++;
}
num_ligne++;
}
int num = 1;
for(Case case_marquee_actuelle : liste_marquee){
case_marquee_actuelle.getNumeroCase();
}
//sinon (paturage)
return 0;
}*/
public int nombredePaturage(){
ArrayList<Case> liste_marquee = new ArrayList<Case>();
for(Case[] cases : this.cases){
for(Case cases_actuelle : cases){
if(!(cases_actuelle instanceof CasePaturage)){
liste_marquee.add(cases_actuelle);
}else{
}
}
}
return 0;
}
public int[] placeParPaturage(){
if(this.nombredePaturage()==0){
return null;
}else{
return null;
}
}
}
| true | true | public PlateauJoueur(){
this.cases = new Case[5][3];
int numero_case = 1;
for(int i = 0; i < this.cases.length; i++){
for(int j = 0; j < this.cases[i].length; j++){
this.cases[i][j] = new Case(numero_case);
numero_case++;
}
}
this.cases[0][1] = new CaseHabitation(true);
this.cases[0][2] = new CaseHabitation(true);
this.clotures_lignes = new Boolean[5][4];
for(int i = 0; i < this.clotures_lignes.length; i++)
for(int j = 0; j < this.clotures_lignes[i].length; j++)
this.clotures_lignes[i][j] = false;
this.clotures_colonnes = new Boolean[6][3];
for(int i = 0; i < this.clotures_colonnes.length; i++)
for(int j = 0; j < this.clotures_colonnes[i].length; j++)
this.clotures_colonnes[i][j] = false;
}
| public PlateauJoueur(){
this.cases = new Case[5][3];
int numero_case = 1;
for(int i = 0; i < this.cases.length; i++){
for(int j = 0; j < this.cases[i].length; j++){
this.cases[i][j] = new Case(numero_case);
numero_case++;
}
}
this.cases[0][1] = new CaseHabitation(true,6);
this.cases[0][2] = new CaseHabitation(true,11);
this.clotures_lignes = new Boolean[5][4];
for(int i = 0; i < this.clotures_lignes.length; i++)
for(int j = 0; j < this.clotures_lignes[i].length; j++)
this.clotures_lignes[i][j] = false;
this.clotures_colonnes = new Boolean[6][3];
for(int i = 0; i < this.clotures_colonnes.length; i++)
for(int j = 0; j < this.clotures_colonnes[i].length; j++)
this.clotures_colonnes[i][j] = false;
}
|
diff --git a/GraoPara-BD2/src/main/java/business/EJB/documents/KeyWordEJB.java b/GraoPara-BD2/src/main/java/business/EJB/documents/KeyWordEJB.java
index ec8ba6f..935e052 100644
--- a/GraoPara-BD2/src/main/java/business/EJB/documents/KeyWordEJB.java
+++ b/GraoPara-BD2/src/main/java/business/EJB/documents/KeyWordEJB.java
@@ -1,127 +1,127 @@
package business.EJB.documents;
import java.util.List;
import persistence.dto.DTO;
import persistence.dto.Documento;
import persistence.dto.PalavraChave;
import persistence.exceptions.UpdateEntityException;
import business.DAO.document.PalavraChaveDAO;
import business.exceptions.documents.DocumentNotFoundException;
import business.exceptions.documents.KeywordNotFoundException;
import business.exceptions.documents.ThemeNotFoundException;
import business.exceptions.login.UnreachableDataBaseException;
public class KeyWordEJB {
PalavraChaveDAO keyWordDAO;
public KeyWordEJB() {
keyWordDAO = new PalavraChaveDAO();
}
public PalavraChave findByString(String searchKeyWord) throws UnreachableDataBaseException, KeywordNotFoundException, IllegalArgumentException {
if(searchKeyWord == null || searchKeyWord.isEmpty())
throw new IllegalArgumentException("Nenhuma palavra chave informado");
searchKeyWord = searchKeyWord.toLowerCase();
List<DTO> list = keyWordDAO.findKeyWordByString(searchKeyWord);
PalavraChave keyWord;
for(DTO dto : list){
keyWord = (PalavraChave) dto;
if(keyWord != null && searchKeyWord.equals(keyWord.getPalavra()))
return keyWord;
}
throw new KeywordNotFoundException("Palavra chave "+ searchKeyWord +" não encontrado.");
}
public List<DTO> getAllKeyWords() throws UnreachableDataBaseException, KeywordNotFoundException{
return keyWordDAO.getAllKeys();
}
public List<DTO> findByTheme(String theme) throws UnreachableDataBaseException, KeywordNotFoundException{
return keyWordDAO.findKeyWordByTheme(theme);
}
public List<DTO> buscaPalavrasChaves() throws UnreachableDataBaseException, KeywordNotFoundException {
return keyWordDAO.getAllKeys();
}
public synchronized void addKeyWord(String palavra, String tema) throws IllegalArgumentException, UnreachableDataBaseException, ThemeNotFoundException {
PalavraChaveDAO kwDao = new PalavraChaveDAO();
palavra = palavra.toLowerCase();
try {
List<DTO> check = kwDao.findKeyWordByString(palavra);
for (DTO dto : check) {
if (((PalavraChave) dto).getPalavra().equals(palavra))
throw new IllegalArgumentException("Palavra já existe");
}
try {
kwDao.addKeyWord(palavra.toLowerCase(), tema);
} catch (UnreachableDataBaseException e1) {
e1.printStackTrace();
}
} catch (KeywordNotFoundException e) {
try {
kwDao.addKeyWord(palavra.toLowerCase(), tema);
} catch (UnreachableDataBaseException e1) {
e1.printStackTrace();
}
}
}
public synchronized void removeKeyWord(String keyWord) throws UnreachableDataBaseException, KeywordNotFoundException{
DocumentEJB docEJB = new DocumentEJB();
List<DTO> results = null;
- keyWord = keyWord.toLowerCase();
+// keyWord = keyWord.toLowerCase();
try {
results = docEJB.findByKeyWord(keyWord);
for(DTO dto : results){
Documento doc = (Documento) dto;
if(doc.getPalavraChave1() != null && doc.getPalavraChave1().getPalavra().equals(keyWord)){
doc.setPalavraChave1(null);
}
if(doc.getPalavraChave2() != null && doc.getPalavraChave2().getPalavra().equals(keyWord)){
doc.setPalavraChave2(null);
}
if(doc.getPalavraChave3() != null && doc.getPalavraChave3().getPalavra().equals(keyWord)){
doc.setPalavraChave3(null);
}
docEJB.modifyDocument(doc);
}
} catch (DocumentNotFoundException e) {
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (UpdateEntityException e) {
e.printStackTrace();
} finally {
keyWordDAO.removeKeyWord(keyWord);
}
}
public synchronized void updateKeyWord(String oldKey, String newKey, String newTheme) throws UnreachableDataBaseException, IllegalArgumentException, UpdateEntityException, KeywordNotFoundException {
if(oldKey == null || newKey == null || oldKey.equals("") || newKey.equals("") || newTheme == null || newTheme.isEmpty())
throw new IllegalArgumentException("Argumentos não podem ser null/vazio");
oldKey = oldKey.toLowerCase();
newKey = newKey.toLowerCase();
try{
List<DTO> check = keyWordDAO.findKeyWordByString(newKey);
for (DTO dto : check) {
if (((PalavraChave) dto).getPalavra().equals(newKey))
throw new IllegalArgumentException("Palavra já existe");
}
} catch (KeywordNotFoundException e){
keyWordDAO.updateKeyWord(oldKey.toLowerCase(), newKey.toLowerCase(), newTheme);
}
}
}
| true | true | public synchronized void removeKeyWord(String keyWord) throws UnreachableDataBaseException, KeywordNotFoundException{
DocumentEJB docEJB = new DocumentEJB();
List<DTO> results = null;
keyWord = keyWord.toLowerCase();
try {
results = docEJB.findByKeyWord(keyWord);
for(DTO dto : results){
Documento doc = (Documento) dto;
if(doc.getPalavraChave1() != null && doc.getPalavraChave1().getPalavra().equals(keyWord)){
doc.setPalavraChave1(null);
}
if(doc.getPalavraChave2() != null && doc.getPalavraChave2().getPalavra().equals(keyWord)){
doc.setPalavraChave2(null);
}
if(doc.getPalavraChave3() != null && doc.getPalavraChave3().getPalavra().equals(keyWord)){
doc.setPalavraChave3(null);
}
docEJB.modifyDocument(doc);
}
} catch (DocumentNotFoundException e) {
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (UpdateEntityException e) {
e.printStackTrace();
} finally {
keyWordDAO.removeKeyWord(keyWord);
}
}
| public synchronized void removeKeyWord(String keyWord) throws UnreachableDataBaseException, KeywordNotFoundException{
DocumentEJB docEJB = new DocumentEJB();
List<DTO> results = null;
// keyWord = keyWord.toLowerCase();
try {
results = docEJB.findByKeyWord(keyWord);
for(DTO dto : results){
Documento doc = (Documento) dto;
if(doc.getPalavraChave1() != null && doc.getPalavraChave1().getPalavra().equals(keyWord)){
doc.setPalavraChave1(null);
}
if(doc.getPalavraChave2() != null && doc.getPalavraChave2().getPalavra().equals(keyWord)){
doc.setPalavraChave2(null);
}
if(doc.getPalavraChave3() != null && doc.getPalavraChave3().getPalavra().equals(keyWord)){
doc.setPalavraChave3(null);
}
docEJB.modifyDocument(doc);
}
} catch (DocumentNotFoundException e) {
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (UpdateEntityException e) {
e.printStackTrace();
} finally {
keyWordDAO.removeKeyWord(keyWord);
}
}
|
diff --git a/src/com/google/bitcoin/core/NetworkConnection.java b/src/com/google/bitcoin/core/NetworkConnection.java
index 34c15dc..d78cc18 100644
--- a/src/com/google/bitcoin/core/NetworkConnection.java
+++ b/src/com/google/bitcoin/core/NetworkConnection.java
@@ -1,189 +1,194 @@
/**
* Copyright 2011 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.bitcoin.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
/**
* A NetworkConnection handles talking to a remote BitCoin peer at a low level. It understands how to read and write
* messages off the network, but doesn't asynchronously communicate with the peer or handle the higher level details
* of the protocol. After constructing a NetworkConnection, use a {@link Peer} to hand off communication to a
* background thread.<p>
*
* Multiple NetworkConnections will, by default, wait if another NetworkConnection instance is deserializing a
* message and discard duplicates before reading them. This is intended to avoid memory usage spikes in constrained
* environments like Android where deserializing a large message (like a block) on multiple threads simultaneously is
* both wasteful and can cause OOM failures.<p>
*
* Construction is blocking whilst the protocol version is negotiated.
*/
public class NetworkConnection {
private static final Logger log = LoggerFactory.getLogger(NetworkConnection.class);
private final Socket socket;
private final OutputStream out;
private final InputStream in;
// The IP address to which we are connecting.
private final InetAddress remoteIp;
private final NetworkParameters params;
private final VersionMessage versionMessage;
// Given to the BitcoinSerializer to de-duplicate messages.
private static final LinkedHashMap<Sha256Hash, Integer> dedupeList = BitcoinSerializer.createDedupeList();
private BitcoinSerializer serializer = null;
/**
* Connect to the given IP address using the port specified as part of the network parameters. Once construction
* is complete a functioning network channel is set up and running.
*
* @param peerAddress address to connect to. IPv6 is not currently supported by BitCoin. If
* port is not positive the default port from params is used.
* @param params Defines which network to connect to and details of the protocol.
* @param bestHeight How many blocks are in our best chain
* @param connectTimeout Timeout in milliseconds when initially connecting to peer
* @param dedupe Whether to avoid parsing duplicate messages from the network (ie from other peers).
* @throws IOException if there is a network related failure.
* @throws ProtocolException if the version negotiation failed.
*/
public NetworkConnection(PeerAddress peerAddress, NetworkParameters params,
int bestHeight, int connectTimeout, boolean dedupe)
throws IOException, ProtocolException {
this.params = params;
this.remoteIp = peerAddress.addr;
int port = (peerAddress.port > 0) ? peerAddress.port : params.port;
InetSocketAddress address = new InetSocketAddress(remoteIp, port);
socket = new Socket();
socket.connect(address, connectTimeout);
out = socket.getOutputStream();
in = socket.getInputStream();
// The version message never uses checksumming. Update checkumming property after version is read.
this.serializer = new BitcoinSerializer(params, false, dedupe ? dedupeList : null);
// Announce ourselves. This has to come first to connect to clients beyond v0.30.20.2 which wait to hear
// from us until they send their version message back.
writeMessage(new VersionMessage(params, bestHeight));
// When connecting, the remote peer sends us a version message with various bits of
// useful data in it. We need to know the peer protocol version before we can talk to it.
- versionMessage = (VersionMessage) readMessage();
+ Message m = readMessage();
+ if (!(m instanceof VersionMessage)) {
+ // Bad peers might not follow the protocol. This has been seen in the wild (issue 81).
+ throw new ProtocolException("First message received was not a version message but rather " + m);
+ }
+ versionMessage = (VersionMessage) m;
// Now it's our turn ...
// Send an ACK message stating we accept the peers protocol version.
writeMessage(new VersionAck());
// And get one back ...
readMessage();
// Switch to the new protocol version.
int peerVersion = versionMessage.clientVersion;
log.info("Connected to peer: version={}, subVer='{}', services=0x{}, time={}, blocks={}", new Object[] {
peerVersion,
versionMessage.subVer,
versionMessage.localServices,
new Date(versionMessage.time * 1000),
versionMessage.bestHeight
});
// BitCoinJ is a client mode implementation. That means there's not much point in us talking to other client
// mode nodes because we can't download the data from them we need to find/verify transactions.
if (!versionMessage.hasBlockChain()) {
// Shut down the socket
try {
shutdown();
} catch (IOException ex) {
// ignore exceptions while aborting
}
throw new ProtocolException("Peer does not have a copy of the block chain.");
}
// newer clients use checksumming
serializer.setUseChecksumming(peerVersion >= 209);
// Handshake is done!
}
public NetworkConnection(InetAddress inetAddress, NetworkParameters params, int bestHeight, int connectTimeout)
throws IOException, ProtocolException {
this(new PeerAddress(inetAddress), params, bestHeight, connectTimeout, true);
}
/**
* Sends a "ping" message to the remote node. The protocol doesn't presently use this feature much.
* @throws IOException
*/
public void ping() throws IOException {
writeMessage(new Ping());
}
/**
* Shuts down the network socket. Note that there's no way to wait for a socket to be fully flushed out to the
* wire, so if you call this immediately after sending a message it might not get sent.
*/
public void shutdown() throws IOException {
socket.shutdownOutput();
socket.shutdownInput();
socket.close();
}
@Override
public String toString() {
return "[" + remoteIp.getHostAddress() + "]:" + params.port + " (" + (socket.isConnected() ? "connected" :
"disconnected") + ")";
}
/**
* Reads a network message from the wire, blocking until the message is fully received.
*
* @return An instance of a Message subclass
* @throws ProtocolException if the message is badly formatted, failed checksum or there was a TCP failure.
*/
public Message readMessage() throws IOException, ProtocolException {
Message message;
do {
message = serializer.deserialize(in);
// If message is null, it means deduping was enabled, we read a duplicated message and skipped parsing to
// avoid doing redundant work. So go around and wait for another message.
} while (message == null);
return message;
}
/**
* Writes the given message out over the network using the protocol tag. For a Transaction
* this should be "tx" for example. It's safe to call this from multiple threads simultaneously,
* the actual writing will be serialized.
*
* @throws IOException
*/
public void writeMessage(Message message) throws IOException {
synchronized (out) {
serializer.serialize(message, out);
}
}
/** Returns the version message received from the other end of the connection during the handshake. */
public VersionMessage getVersionMessage() {
return versionMessage;
}
}
| true | true | public NetworkConnection(PeerAddress peerAddress, NetworkParameters params,
int bestHeight, int connectTimeout, boolean dedupe)
throws IOException, ProtocolException {
this.params = params;
this.remoteIp = peerAddress.addr;
int port = (peerAddress.port > 0) ? peerAddress.port : params.port;
InetSocketAddress address = new InetSocketAddress(remoteIp, port);
socket = new Socket();
socket.connect(address, connectTimeout);
out = socket.getOutputStream();
in = socket.getInputStream();
// The version message never uses checksumming. Update checkumming property after version is read.
this.serializer = new BitcoinSerializer(params, false, dedupe ? dedupeList : null);
// Announce ourselves. This has to come first to connect to clients beyond v0.30.20.2 which wait to hear
// from us until they send their version message back.
writeMessage(new VersionMessage(params, bestHeight));
// When connecting, the remote peer sends us a version message with various bits of
// useful data in it. We need to know the peer protocol version before we can talk to it.
versionMessage = (VersionMessage) readMessage();
// Now it's our turn ...
// Send an ACK message stating we accept the peers protocol version.
writeMessage(new VersionAck());
// And get one back ...
readMessage();
// Switch to the new protocol version.
int peerVersion = versionMessage.clientVersion;
log.info("Connected to peer: version={}, subVer='{}', services=0x{}, time={}, blocks={}", new Object[] {
peerVersion,
versionMessage.subVer,
versionMessage.localServices,
new Date(versionMessage.time * 1000),
versionMessage.bestHeight
});
// BitCoinJ is a client mode implementation. That means there's not much point in us talking to other client
// mode nodes because we can't download the data from them we need to find/verify transactions.
if (!versionMessage.hasBlockChain()) {
// Shut down the socket
try {
shutdown();
} catch (IOException ex) {
// ignore exceptions while aborting
}
throw new ProtocolException("Peer does not have a copy of the block chain.");
}
// newer clients use checksumming
serializer.setUseChecksumming(peerVersion >= 209);
// Handshake is done!
}
| public NetworkConnection(PeerAddress peerAddress, NetworkParameters params,
int bestHeight, int connectTimeout, boolean dedupe)
throws IOException, ProtocolException {
this.params = params;
this.remoteIp = peerAddress.addr;
int port = (peerAddress.port > 0) ? peerAddress.port : params.port;
InetSocketAddress address = new InetSocketAddress(remoteIp, port);
socket = new Socket();
socket.connect(address, connectTimeout);
out = socket.getOutputStream();
in = socket.getInputStream();
// The version message never uses checksumming. Update checkumming property after version is read.
this.serializer = new BitcoinSerializer(params, false, dedupe ? dedupeList : null);
// Announce ourselves. This has to come first to connect to clients beyond v0.30.20.2 which wait to hear
// from us until they send their version message back.
writeMessage(new VersionMessage(params, bestHeight));
// When connecting, the remote peer sends us a version message with various bits of
// useful data in it. We need to know the peer protocol version before we can talk to it.
Message m = readMessage();
if (!(m instanceof VersionMessage)) {
// Bad peers might not follow the protocol. This has been seen in the wild (issue 81).
throw new ProtocolException("First message received was not a version message but rather " + m);
}
versionMessage = (VersionMessage) m;
// Now it's our turn ...
// Send an ACK message stating we accept the peers protocol version.
writeMessage(new VersionAck());
// And get one back ...
readMessage();
// Switch to the new protocol version.
int peerVersion = versionMessage.clientVersion;
log.info("Connected to peer: version={}, subVer='{}', services=0x{}, time={}, blocks={}", new Object[] {
peerVersion,
versionMessage.subVer,
versionMessage.localServices,
new Date(versionMessage.time * 1000),
versionMessage.bestHeight
});
// BitCoinJ is a client mode implementation. That means there's not much point in us talking to other client
// mode nodes because we can't download the data from them we need to find/verify transactions.
if (!versionMessage.hasBlockChain()) {
// Shut down the socket
try {
shutdown();
} catch (IOException ex) {
// ignore exceptions while aborting
}
throw new ProtocolException("Peer does not have a copy of the block chain.");
}
// newer clients use checksumming
serializer.setUseChecksumming(peerVersion >= 209);
// Handshake is done!
}
|
diff --git a/webapp/src/main/java/uk/ac/ebi/arrayexpress/utils/saxon/search/Indexer.java b/webapp/src/main/java/uk/ac/ebi/arrayexpress/utils/saxon/search/Indexer.java
index 15f31a7e..1b081196 100644
--- a/webapp/src/main/java/uk/ac/ebi/arrayexpress/utils/saxon/search/Indexer.java
+++ b/webapp/src/main/java/uk/ac/ebi/arrayexpress/utils/saxon/search/Indexer.java
@@ -1,153 +1,153 @@
package uk.ac.ebi.arrayexpress.utils.saxon.search;
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.xpath.XPathEvaluator;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Indexer
{
// logging machinery
private final Logger logger = LoggerFactory.getLogger(getClass());
private IndexEnvironment env;
private Map<String,XPathExpression> fieldXpe = new HashMap<String,XPathExpression>();
public Indexer( IndexEnvironment env )
{
this.env = env;
}
public List<NodeInfo> index( DocumentInfo document )
{
List<NodeInfo> indexedNodes = null;
try {
XPath xp = new XPathEvaluator(document.getConfiguration());
XPathExpression xpe = xp.compile(this.env.indexDocumentPath);
List documentNodes = (List)xpe.evaluate(document, XPathConstants.NODESET);
indexedNodes = new ArrayList<NodeInfo>(documentNodes.size());
for (IndexEnvironment.FieldInfo field : this.env.fields.values()) {
fieldXpe.put( field.name, xp.compile(field.path));
}
IndexWriter w = createIndex(this.env.indexDirectory, this.env.indexAnalyzer);
for (Object node : documentNodes) {
Document d = new Document();
// get all the fields taken care of
for (IndexEnvironment.FieldInfo field : this.env.fields.values()) {
try {
List values = (List)fieldXpe.get(field.name).evaluate(node, XPathConstants.NODESET);
for (Object v : values) {
if ("integer".equals(field.type)) {
addIntIndexField(d, field.name, v);
} else {
addIndexField(d, field.name, v, field.shouldAnalyze, field.shouldStore);
}
}
} catch (XPathExpressionException x) {
- logger.error("Caught an exception [" + x.getMessage() + "] while indexing expression [{}] for document [{}...]", field.path, ((NodeInfo)node).getStringValue().substring(0, 20));
+ logger.error("Caught an exception while indexing expression [" + field.path + "] for document [" + ((NodeInfo)node).getStringValue().substring(0, 20) + "...]", x);
}
}
addIndexDocument(w, d);
// append node to the list
indexedNodes.add((NodeInfo)node);
}
commitIndex(w);
} catch (Throwable x) {
logger.error("Caught an exception:", x);
}
return indexedNodes;
}
private IndexWriter createIndex( Directory indexDirectory, Analyzer analyzer )
{
IndexWriter iwriter = null;
try {
iwriter = new IndexWriter(indexDirectory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
} catch (Throwable x) {
logger.error("Caught an exception:", x);
}
return iwriter;
}
private void addIndexField( Document document, String name, Object value, boolean shouldAnalyze, boolean shouldStore )
{
String stringValue;
if (value instanceof String) {
stringValue = (String)value;
} else if (value instanceof NodeInfo) {
stringValue = ((NodeInfo)value).getStringValue();
} else {
stringValue = value.toString();
logger.warn("Not sure if I handle string value of [{}] for the field [{}] correctly, relying on Object.toString()", value.getClass().getName(), name);
}
document.add(new Field(name, stringValue, shouldStore ? Field.Store.YES : Field.Store.NO, shouldAnalyze ? Field.Index.ANALYZED : Field.Index.NOT_ANALYZED));
}
private void addIntIndexField( Document document, String name, Object value )
{
Long longValue;
if (value instanceof BigInteger) {
longValue = ((BigInteger)value).longValue();
} else if (value instanceof NodeInfo) {
longValue = Long.parseLong(((NodeInfo)value).getStringValue());
} else {
longValue = Long.parseLong(value.toString());
logger.warn("Not sure if I handle long value of [{}] for the field [{}] correctly, relying on Object.toString()", value.getClass().getName(), name);
}
if (null != longValue) {
document.add(new NumericField(name).setLongValue(longValue));
} else {
logger.warn("Long value of the field [{}] was null", name);
}
}
private void addIndexDocument( IndexWriter iwriter, Document document )
{
try {
iwriter.addDocument(document);
} catch (Throwable x) {
logger.error("Caught an exception:", x);
}
}
private void commitIndex( IndexWriter iwriter )
{
try {
iwriter.optimize();
iwriter.commit();
iwriter.close();
} catch (Throwable x) {
logger.error("Caught an exception:", x);
}
}
}
| true | true | public List<NodeInfo> index( DocumentInfo document )
{
List<NodeInfo> indexedNodes = null;
try {
XPath xp = new XPathEvaluator(document.getConfiguration());
XPathExpression xpe = xp.compile(this.env.indexDocumentPath);
List documentNodes = (List)xpe.evaluate(document, XPathConstants.NODESET);
indexedNodes = new ArrayList<NodeInfo>(documentNodes.size());
for (IndexEnvironment.FieldInfo field : this.env.fields.values()) {
fieldXpe.put( field.name, xp.compile(field.path));
}
IndexWriter w = createIndex(this.env.indexDirectory, this.env.indexAnalyzer);
for (Object node : documentNodes) {
Document d = new Document();
// get all the fields taken care of
for (IndexEnvironment.FieldInfo field : this.env.fields.values()) {
try {
List values = (List)fieldXpe.get(field.name).evaluate(node, XPathConstants.NODESET);
for (Object v : values) {
if ("integer".equals(field.type)) {
addIntIndexField(d, field.name, v);
} else {
addIndexField(d, field.name, v, field.shouldAnalyze, field.shouldStore);
}
}
} catch (XPathExpressionException x) {
logger.error("Caught an exception [" + x.getMessage() + "] while indexing expression [{}] for document [{}...]", field.path, ((NodeInfo)node).getStringValue().substring(0, 20));
}
}
addIndexDocument(w, d);
// append node to the list
indexedNodes.add((NodeInfo)node);
}
commitIndex(w);
} catch (Throwable x) {
logger.error("Caught an exception:", x);
}
return indexedNodes;
}
| public List<NodeInfo> index( DocumentInfo document )
{
List<NodeInfo> indexedNodes = null;
try {
XPath xp = new XPathEvaluator(document.getConfiguration());
XPathExpression xpe = xp.compile(this.env.indexDocumentPath);
List documentNodes = (List)xpe.evaluate(document, XPathConstants.NODESET);
indexedNodes = new ArrayList<NodeInfo>(documentNodes.size());
for (IndexEnvironment.FieldInfo field : this.env.fields.values()) {
fieldXpe.put( field.name, xp.compile(field.path));
}
IndexWriter w = createIndex(this.env.indexDirectory, this.env.indexAnalyzer);
for (Object node : documentNodes) {
Document d = new Document();
// get all the fields taken care of
for (IndexEnvironment.FieldInfo field : this.env.fields.values()) {
try {
List values = (List)fieldXpe.get(field.name).evaluate(node, XPathConstants.NODESET);
for (Object v : values) {
if ("integer".equals(field.type)) {
addIntIndexField(d, field.name, v);
} else {
addIndexField(d, field.name, v, field.shouldAnalyze, field.shouldStore);
}
}
} catch (XPathExpressionException x) {
logger.error("Caught an exception while indexing expression [" + field.path + "] for document [" + ((NodeInfo)node).getStringValue().substring(0, 20) + "...]", x);
}
}
addIndexDocument(w, d);
// append node to the list
indexedNodes.add((NodeInfo)node);
}
commitIndex(w);
} catch (Throwable x) {
logger.error("Caught an exception:", x);
}
return indexedNodes;
}
|
diff --git a/TFC_Shared/src/TFC/TFCItems.java b/TFC_Shared/src/TFC/TFCItems.java
index db01aceb6..478ef73dd 100644
--- a/TFC_Shared/src/TFC/TFCItems.java
+++ b/TFC_Shared/src/TFC/TFCItems.java
@@ -1,2020 +1,2020 @@
package TFC;
import java.io.File;
import net.minecraft.block.Block;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraft.item.Item;
import net.minecraft.item.ItemColored;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.EnumHelper;
import TFC.Core.Recipes;
import TFC.Core.TFCTabs;
import TFC.Core.TFC_Settings;
import TFC.Enums.EnumMetalType;
import TFC.Enums.EnumSize;
import TFC.Food.ItemMeal;
import TFC.Food.ItemTerraFood;
import TFC.Items.ItemBellows;
import TFC.Items.ItemBlueprint;
import TFC.Items.ItemCustomArmor;
import TFC.Items.ItemCustomMinecart;
import TFC.Items.ItemCustomPotion;
import TFC.Items.ItemCustomSeeds;
import TFC.Items.ItemDyeCustom;
import TFC.Items.ItemFlatLeather;
import TFC.Items.ItemFlatRock;
import TFC.Items.ItemFruitTreeSapling;
import TFC.Items.ItemGem;
import TFC.Items.ItemIngot;
import TFC.Items.ItemLogs;
import TFC.Items.ItemLooseRock;
import TFC.Items.ItemMeltedMetal;
import TFC.Items.ItemMetalSheet;
import TFC.Items.ItemMetalSheet2x;
import TFC.Items.ItemOre;
import TFC.Items.ItemOreSmall;
import TFC.Items.ItemPlank;
import TFC.Items.ItemSluice;
import TFC.Items.ItemStick;
import TFC.Items.ItemStoneBrick;
import TFC.Items.ItemTerra;
import TFC.Items.ItemUnfinishedArmor;
import TFC.Items.ItemBlocks.ItemWoodDoor;
import TFC.Items.Pottery.ItemPotteryBase;
import TFC.Items.Pottery.ItemPotteryJug;
import TFC.Items.Pottery.ItemPotteryLargeVessel;
import TFC.Items.Pottery.ItemPotteryPot;
import TFC.Items.Pottery.ItemPotterySmallVessel;
import TFC.Items.Tools.ItemChisel;
import TFC.Items.Tools.ItemCustomAxe;
import TFC.Items.Tools.ItemCustomBlueSteelBucket;
import TFC.Items.Tools.ItemCustomBow;
import TFC.Items.Tools.ItemCustomBucket;
import TFC.Items.Tools.ItemCustomBucketMilk;
import TFC.Items.Tools.ItemCustomHoe;
import TFC.Items.Tools.ItemCustomKnife;
import TFC.Items.Tools.ItemCustomPickaxe;
import TFC.Items.Tools.ItemCustomRedSteelBucket;
import TFC.Items.Tools.ItemCustomSaw;
import TFC.Items.Tools.ItemCustomScythe;
import TFC.Items.Tools.ItemCustomShovel;
import TFC.Items.Tools.ItemCustomSword;
import TFC.Items.Tools.ItemFirestarter;
import TFC.Items.Tools.ItemFlintSteel;
import TFC.Items.Tools.ItemGoldPan;
import TFC.Items.Tools.ItemHammer;
import TFC.Items.Tools.ItemJavelin;
import TFC.Items.Tools.ItemMiscToolHead;
import TFC.Items.Tools.ItemPlan;
import TFC.Items.Tools.ItemProPick;
import TFC.Items.Tools.ItemSpindle;
import TFC.Items.Tools.ItemWritableBookTFC;
public class TFCItems
{
public static Item GemRuby;
public static Item GemSapphire;
public static Item GemEmerald;
public static Item GemTopaz;
public static Item GemGarnet;
public static Item GemOpal;
public static Item GemAmethyst;
public static Item GemJasper;
public static Item GemBeryl;
public static Item GemTourmaline;
public static Item GemJade;
public static Item GemAgate;
public static Item GemDiamond;
public static Item SulfurPowder;
public static Item SaltpeterPowder;
public static Item BismuthIngot;
public static Item BismuthBronzeIngot;
public static Item BlackBronzeIngot;
public static Item BlackSteelIngot;
public static Item HCBlackSteelIngot;
public static Item BlueSteelIngot;
public static Item WeakBlueSteelIngot;
public static Item HCBlueSteelIngot;
public static Item BrassIngot;
public static Item BronzeIngot;
public static Item CopperIngot;
public static Item GoldIngot;
public static Item WroughtIronIngot;
public static Item LeadIngot;
public static Item NickelIngot;
public static Item PigIronIngot;
public static Item PlatinumIngot;
public static Item RedSteelIngot;
public static Item WeakRedSteelIngot;
public static Item HCRedSteelIngot;
public static Item RoseGoldIngot;
public static Item SilverIngot;
public static Item SteelIngot;
public static Item WeakSteelIngot;
public static Item HCSteelIngot;
public static Item SterlingSilverIngot;
public static Item TinIngot;
public static Item ZincIngot;
public static Item BismuthIngot2x;
public static Item BismuthBronzeIngot2x;
public static Item BlackBronzeIngot2x;
public static Item BlackSteelIngot2x;
public static Item BlueSteelIngot2x;
public static Item BrassIngot2x;
public static Item BronzeIngot2x;
public static Item CopperIngot2x;
public static Item GoldIngot2x;
public static Item WroughtIronIngot2x;
public static Item LeadIngot2x;
public static Item NickelIngot2x;
public static Item PigIronIngot2x;
public static Item PlatinumIngot2x;
public static Item RedSteelIngot2x;
public static Item RoseGoldIngot2x;
public static Item SilverIngot2x;
public static Item SteelIngot2x;
public static Item SterlingSilverIngot2x;
public static Item TinIngot2x;
public static Item ZincIngot2x;
public static Item IgInShovel;
public static Item IgInAxe;
public static Item IgInHoe;
public static Item SedShovel;
public static Item SedAxe;
public static Item SedHoe;
public static Item IgExShovel;
public static Item IgExAxe;
public static Item IgExHoe;
public static Item MMShovel;
public static Item MMAxe;
public static Item MMHoe;
public static Item BismuthPick;
public static Item BismuthShovel;
public static Item BismuthAxe;
public static Item BismuthHoe;
public static Item BismuthBronzePick;
public static Item BismuthBronzeShovel;
public static Item BismuthBronzeAxe;
public static Item BismuthBronzeHoe;
public static Item BlackBronzePick;
public static Item BlackBronzeShovel;
public static Item BlackBronzeAxe;
public static Item BlackBronzeHoe;
public static Item BlackSteelPick;
public static Item BlackSteelShovel;
public static Item BlackSteelAxe;
public static Item BlackSteelHoe;
public static Item BlueSteelPick;
public static Item BlueSteelShovel;
public static Item BlueSteelAxe;
public static Item BlueSteelHoe;
public static Item BronzePick;
public static Item BronzeShovel;
public static Item BronzeAxe;
public static Item BronzeHoe;
public static Item CopperPick;
public static Item CopperShovel;
public static Item CopperAxe;
public static Item CopperHoe;
public static Item WroughtIronPick;
public static Item WroughtIronShovel;
public static Item WroughtIronAxe;
public static Item WroughtIronHoe;
public static Item RedSteelPick;
public static Item RedSteelShovel;
public static Item RedSteelAxe;
public static Item RedSteelHoe;
public static Item RoseGoldPick;
public static Item RoseGoldShovel;
public static Item RoseGoldAxe;
public static Item RoseGoldHoe;
public static Item SteelPick;
public static Item SteelShovel;
public static Item SteelAxe;
public static Item SteelHoe;
public static Item TinPick;
public static Item TinShovel;
public static Item TinAxe;
public static Item TinHoe;
public static Item ZincPick;
public static Item ZincShovel;
public static Item ZincAxe;
public static Item ZincHoe;
public static Item StoneChisel;
public static Item BismuthChisel;
public static Item BismuthBronzeChisel;
public static Item BlackBronzeChisel;
public static Item BlackSteelChisel;
public static Item BlueSteelChisel;
public static Item BronzeChisel;
public static Item CopperChisel;
public static Item WroughtIronChisel;
public static Item RedSteelChisel;
public static Item RoseGoldChisel;
public static Item SteelChisel;
public static Item TinChisel;
public static Item ZincChisel;
public static Item IgInStoneSword;
public static Item IgExStoneSword;
public static Item SedStoneSword;
public static Item MMStoneSword;
public static Item BismuthSword;
public static Item BismuthBronzeSword;
public static Item BlackBronzeSword;
public static Item BlackSteelSword;
public static Item BlueSteelSword;
public static Item BronzeSword;
public static Item CopperSword;
public static Item WroughtIronSword;
public static Item RedSteelSword;
public static Item RoseGoldSword;
public static Item SteelSword;
public static Item TinSword;
public static Item ZincSword;
public static Item IgInStoneMace;
public static Item IgExStoneMace;
public static Item SedStoneMace;
public static Item MMStoneMace;
public static Item BismuthMace;
public static Item BismuthBronzeMace;
public static Item BlackBronzeMace;
public static Item BlackSteelMace;
public static Item BlueSteelMace;
public static Item BronzeMace;
public static Item CopperMace;
public static Item WroughtIronMace;
public static Item RedSteelMace;
public static Item RoseGoldMace;
public static Item SteelMace;
public static Item TinMace;
public static Item ZincMace;
public static Item BismuthSaw;
public static Item BismuthBronzeSaw;
public static Item BlackBronzeSaw;
public static Item BlackSteelSaw;
public static Item BlueSteelSaw;
public static Item BronzeSaw;
public static Item CopperSaw;
public static Item WroughtIronSaw;
public static Item RedSteelSaw;
public static Item RoseGoldSaw;
public static Item SteelSaw;
public static Item TinSaw;
public static Item ZincSaw;
public static Item OreChunk;
public static Item Logs;
public static Item Barrel;
public static Item Javelin;
public static Item BismuthScythe;
public static Item BismuthBronzeScythe;
public static Item BlackBronzeScythe;
public static Item BlackSteelScythe;
public static Item BlueSteelScythe;
public static Item BronzeScythe;
public static Item CopperScythe;
public static Item WroughtIronScythe;
public static Item RedSteelScythe;
public static Item RoseGoldScythe;
public static Item SteelScythe;
public static Item TinScythe;
public static Item ZincScythe;
public static Item BismuthKnife;
public static Item BismuthBronzeKnife;
public static Item BlackBronzeKnife;
public static Item BlackSteelKnife;
public static Item BlueSteelKnife;
public static Item BronzeKnife;
public static Item CopperKnife;
public static Item WroughtIronKnife;
public static Item RedSteelKnife;
public static Item RoseGoldKnife;
public static Item SteelKnife;
public static Item TinKnife;
public static Item ZincKnife;
public static Item FireStarter;
public static Item BellowsItem;
public static Item StoneHammer;
public static Item BismuthHammer;
public static Item BismuthBronzeHammer;
public static Item BlackBronzeHammer;
public static Item BlackSteelHammer;
public static Item BlueSteelHammer;
public static Item BronzeHammer;
public static Item CopperHammer;
public static Item WroughtIronHammer;
public static Item RedSteelHammer;
public static Item RoseGoldHammer;
public static Item SteelHammer;
public static Item TinHammer;
public static Item ZincHammer;
public static Item BismuthUnshaped;
public static Item BismuthBronzeUnshaped;
public static Item BlackBronzeUnshaped;
public static Item BlackSteelUnshaped;
public static Item HCBlackSteelUnshaped;
public static Item BlueSteelUnshaped;
public static Item WeakBlueSteelUnshaped;
public static Item HCBlueSteelUnshaped;
public static Item BrassUnshaped;
public static Item BronzeUnshaped;
public static Item CopperUnshaped;
public static Item GoldUnshaped;
public static Item WroughtIronUnshaped;
public static Item LeadUnshaped;
public static Item NickelUnshaped;
public static Item PigIronUnshaped;
public static Item PlatinumUnshaped;
public static Item RedSteelUnshaped;
public static Item WeakRedSteelUnshaped;
public static Item HCRedSteelUnshaped;
public static Item RoseGoldUnshaped;
public static Item SilverUnshaped;
public static Item SteelUnshaped;
public static Item WeakSteelUnshaped;
public static Item HCSteelUnshaped;
public static Item SterlingSilverUnshaped;
public static Item TinUnshaped;
public static Item ZincUnshaped;
public static Item CeramicMold;
public static Item Ink;
//Plans
public static Item PickaxeHeadPlan;
public static Item ShovelHeadPlan;
public static Item HoeHeadPlan;
public static Item AxeHeadPlan;
public static Item HammerHeadPlan;
public static Item ChiselHeadPlan;
public static Item SwordBladePlan;
public static Item MaceHeadPlan;
public static Item SawBladePlan;
public static Item ProPickHeadPlan;
public static Item HelmetPlan;
public static Item ChestplatePlan;
public static Item GreavesPlan;
public static Item BootsPlan;
public static Item ScythePlan;
public static Item KnifePlan;
public static Item BucketPlan;
//Tool Heads
public static Item BismuthPickaxeHead;
public static Item BismuthBronzePickaxeHead;
public static Item BlackBronzePickaxeHead;
public static Item BlackSteelPickaxeHead;
public static Item BlueSteelPickaxeHead;
public static Item BronzePickaxeHead;
public static Item CopperPickaxeHead;
public static Item WroughtIronPickaxeHead;
public static Item RedSteelPickaxeHead;
public static Item RoseGoldPickaxeHead;
public static Item SteelPickaxeHead;
public static Item TinPickaxeHead;
public static Item ZincPickaxeHead;
public static Item BismuthShovelHead;
public static Item BismuthBronzeShovelHead;
public static Item BlackBronzeShovelHead;
public static Item BlackSteelShovelHead;
public static Item BlueSteelShovelHead;
public static Item BronzeShovelHead;
public static Item CopperShovelHead;
public static Item WroughtIronShovelHead;
public static Item RedSteelShovelHead;
public static Item RoseGoldShovelHead;
public static Item SilverShovelHead;
public static Item SteelShovelHead;
public static Item TinShovelHead;
public static Item ZincShovelHead;
public static Item BismuthHoeHead;
public static Item BismuthBronzeHoeHead;
public static Item BlackBronzeHoeHead;
public static Item BlackSteelHoeHead;
public static Item BlueSteelHoeHead;
public static Item BronzeHoeHead;
public static Item CopperHoeHead;
public static Item WroughtIronHoeHead;
public static Item RedSteelHoeHead;
public static Item RoseGoldHoeHead;
public static Item SteelHoeHead;
public static Item TinHoeHead;
public static Item ZincHoeHead;
public static Item BismuthAxeHead;
public static Item BismuthBronzeAxeHead;
public static Item BlackBronzeAxeHead;
public static Item BlackSteelAxeHead;
public static Item BlueSteelAxeHead;
public static Item BronzeAxeHead;
public static Item CopperAxeHead;
public static Item WroughtIronAxeHead;
public static Item RedSteelAxeHead;
public static Item RoseGoldAxeHead;
public static Item SteelAxeHead;
public static Item TinAxeHead;
public static Item ZincAxeHead;
public static Item BismuthHammerHead;
public static Item BismuthBronzeHammerHead;
public static Item BlackBronzeHammerHead;
public static Item BlackSteelHammerHead;
public static Item BlueSteelHammerHead;
public static Item BronzeHammerHead;
public static Item CopperHammerHead;
public static Item WroughtIronHammerHead;
public static Item RedSteelHammerHead;
public static Item RoseGoldHammerHead;
public static Item SteelHammerHead;
public static Item TinHammerHead;
public static Item ZincHammerHead;
public static Item BismuthChiselHead;
public static Item BismuthBronzeChiselHead;
public static Item BlackBronzeChiselHead;
public static Item BlackSteelChiselHead;
public static Item BlueSteelChiselHead;
public static Item BronzeChiselHead;
public static Item CopperChiselHead;
public static Item WroughtIronChiselHead;
public static Item RedSteelChiselHead;
public static Item RoseGoldChiselHead;
public static Item SteelChiselHead;
public static Item TinChiselHead;
public static Item ZincChiselHead;
public static Item BismuthSwordHead;
public static Item BismuthBronzeSwordHead;
public static Item BlackBronzeSwordHead;
public static Item BlackSteelSwordHead;
public static Item BlueSteelSwordHead;
public static Item BronzeSwordHead;
public static Item CopperSwordHead;
public static Item WroughtIronSwordHead;
public static Item RedSteelSwordHead;
public static Item RoseGoldSwordHead;
public static Item SteelSwordHead;
public static Item TinSwordHead;
public static Item ZincSwordHead;
public static Item BismuthMaceHead;
public static Item BismuthBronzeMaceHead;
public static Item BlackBronzeMaceHead;
public static Item BlackSteelMaceHead;
public static Item BlueSteelMaceHead;
public static Item BronzeMaceHead;
public static Item CopperMaceHead;
public static Item WroughtIronMaceHead;
public static Item RedSteelMaceHead;
public static Item RoseGoldMaceHead;
public static Item SteelMaceHead;
public static Item TinMaceHead;
public static Item ZincMaceHead;
public static Item BismuthSawHead;
public static Item BismuthBronzeSawHead;
public static Item BlackBronzeSawHead;
public static Item BlackSteelSawHead;
public static Item BlueSteelSawHead;
public static Item BronzeSawHead;
public static Item CopperSawHead;
public static Item WroughtIronSawHead;
public static Item RedSteelSawHead;
public static Item RoseGoldSawHead;
public static Item SteelSawHead;
public static Item TinSawHead;
public static Item ZincSawHead;
public static Item BismuthProPickHead;
public static Item BismuthBronzeProPickHead;
public static Item BlackBronzeProPickHead;
public static Item BlackSteelProPickHead;
public static Item BlueSteelProPickHead;
public static Item BronzeProPickHead;
public static Item CopperProPickHead;
public static Item WroughtIronProPickHead;
public static Item RedSteelProPickHead;
public static Item RoseGoldProPickHead;
public static Item SteelProPickHead;
public static Item TinProPickHead;
public static Item ZincProPickHead;
public static Item BismuthScytheHead;
public static Item BismuthBronzeScytheHead;
public static Item BlackBronzeScytheHead;
public static Item BlackSteelScytheHead;
public static Item BlueSteelScytheHead;
public static Item BronzeScytheHead;
public static Item CopperScytheHead;
public static Item WroughtIronScytheHead;
public static Item RedSteelScytheHead;
public static Item RoseGoldScytheHead;
public static Item SteelScytheHead;
public static Item TinScytheHead;
public static Item ZincScytheHead;
public static Item BismuthKnifeHead;
public static Item BismuthBronzeKnifeHead;
public static Item BlackBronzeKnifeHead;
public static Item BlackSteelKnifeHead;
public static Item BlueSteelKnifeHead;
public static Item BronzeKnifeHead;
public static Item CopperKnifeHead;
public static Item WroughtIronKnifeHead;
public static Item RedSteelKnifeHead;
public static Item RoseGoldKnifeHead;
public static Item SteelKnifeHead;
public static Item TinKnifeHead;
public static Item ZincKnifeHead;
public static Item Coke;
public static Item Flux;
//Formerly TFC_Mining
public static Item GoldPan;
public static Item SluiceItem;
public static Item ProPickStone;
public static Item ProPickBismuth;
public static Item ProPickBismuthBronze;
public static Item ProPickBlackBronze;
public static Item ProPickBlackSteel;
public static Item ProPickBlueSteel;
public static Item ProPickBronze;
public static Item ProPickCopper;
public static Item ProPickIron;
public static Item ProPickRedSteel;
public static Item ProPickRoseGold;
public static Item ProPickSteel;
public static Item ProPickTin;
public static Item ProPickZinc;
/**Armor Crafting related items*/
public static Item BismuthSheet;
public static Item BismuthBronzeSheet;
public static Item BlackBronzeSheet;
public static Item BlackSteelSheet;
public static Item BlueSteelSheet;
public static Item BronzeSheet;
public static Item CopperSheet;
public static Item WroughtIronSheet;
public static Item RedSteelSheet;
public static Item RoseGoldSheet;
public static Item SteelSheet;
public static Item TinSheet;
public static Item ZincSheet;
public static Item BrassSheet;
public static Item GoldSheet;
public static Item LeadSheet;
public static Item NickelSheet;
public static Item PigIronSheet;
public static Item PlatinumSheet;
public static Item SilverSheet;
public static Item SterlingSilverSheet;
public static Item BismuthSheet2x;
public static Item BismuthBronzeSheet2x;
public static Item BlackBronzeSheet2x;
public static Item BlackSteelSheet2x;
public static Item BlueSteelSheet2x;
public static Item BronzeSheet2x;
public static Item CopperSheet2x;
public static Item WroughtIronSheet2x;
public static Item RedSteelSheet2x;
public static Item RoseGoldSheet2x;
public static Item SteelSheet2x;
public static Item TinSheet2x;
public static Item ZincSheet2x;
public static Item BrassSheet2x;
public static Item GoldSheet2x;
public static Item LeadSheet2x;
public static Item NickelSheet2x;
public static Item PigIronSheet2x;
public static Item PlatinumSheet2x;
public static Item SilverSheet2x;
public static Item SterlingSilverSheet2x;
public static Item BismuthUnfinishedChestplate;
public static Item BismuthBronzeUnfinishedChestplate;
public static Item BlackBronzeUnfinishedChestplate;
public static Item BlackSteelUnfinishedChestplate;
public static Item BlueSteelUnfinishedChestplate;
public static Item BronzeUnfinishedChestplate;
public static Item CopperUnfinishedChestplate;
public static Item WroughtIronUnfinishedChestplate;
public static Item RedSteelUnfinishedChestplate;
public static Item RoseGoldUnfinishedChestplate;
public static Item SteelUnfinishedChestplate;
public static Item TinUnfinishedChestplate;
public static Item ZincUnfinishedChestplate;
public static Item BismuthUnfinishedGreaves;
public static Item BismuthBronzeUnfinishedGreaves;
public static Item BlackBronzeUnfinishedGreaves;
public static Item BlackSteelUnfinishedGreaves;
public static Item BlueSteelUnfinishedGreaves;
public static Item BronzeUnfinishedGreaves;
public static Item CopperUnfinishedGreaves;
public static Item WroughtIronUnfinishedGreaves;
public static Item RedSteelUnfinishedGreaves;
public static Item RoseGoldUnfinishedGreaves;
public static Item SteelUnfinishedGreaves;
public static Item TinUnfinishedGreaves;
public static Item ZincUnfinishedGreaves;
public static Item BismuthUnfinishedBoots;
public static Item BismuthBronzeUnfinishedBoots;
public static Item BlackBronzeUnfinishedBoots;
public static Item BlackSteelUnfinishedBoots;
public static Item BlueSteelUnfinishedBoots;
public static Item BronzeUnfinishedBoots;
public static Item CopperUnfinishedBoots;
public static Item WroughtIronUnfinishedBoots;
public static Item RedSteelUnfinishedBoots;
public static Item RoseGoldUnfinishedBoots;
public static Item SteelUnfinishedBoots;
public static Item TinUnfinishedBoots;
public static Item ZincUnfinishedBoots;
public static Item BismuthUnfinishedHelmet;
public static Item BismuthBronzeUnfinishedHelmet;
public static Item BlackBronzeUnfinishedHelmet;
public static Item BlackSteelUnfinishedHelmet;
public static Item BlueSteelUnfinishedHelmet;
public static Item BronzeUnfinishedHelmet;
public static Item CopperUnfinishedHelmet;
public static Item WroughtIronUnfinishedHelmet;
public static Item RedSteelUnfinishedHelmet;
public static Item RoseGoldUnfinishedHelmet;
public static Item SteelUnfinishedHelmet;
public static Item TinUnfinishedHelmet;
public static Item ZincUnfinishedHelmet;
public static Item BismuthChestplate;
public static Item BismuthBronzeChestplate;
public static Item BlackBronzeChestplate;
public static Item BlackSteelChestplate;
public static Item BlueSteelChestplate;
public static Item BronzeChestplate;
public static Item CopperChestplate;
public static Item WroughtIronChestplate;
public static Item RedSteelChestplate;
public static Item RoseGoldChestplate;
public static Item SteelChestplate;
public static Item TinChestplate;
public static Item ZincChestplate;
public static Item BismuthGreaves;
public static Item BismuthBronzeGreaves;
public static Item BlackBronzeGreaves;
public static Item BlackSteelGreaves;
public static Item BlueSteelGreaves;
public static Item BronzeGreaves;
public static Item CopperGreaves;
public static Item WroughtIronGreaves;
public static Item RedSteelGreaves;
public static Item RoseGoldGreaves;
public static Item SteelGreaves;
public static Item TinGreaves;
public static Item ZincGreaves;
public static Item BismuthBoots;
public static Item BismuthBronzeBoots;
public static Item BlackBronzeBoots;
public static Item BlackSteelBoots;
public static Item BlueSteelBoots;
public static Item BronzeBoots;
public static Item CopperBoots;
public static Item WroughtIronBoots;
public static Item RedSteelBoots;
public static Item RoseGoldBoots;
public static Item SteelBoots;
public static Item TinBoots;
public static Item ZincBoots;
public static Item BismuthHelmet;
public static Item BismuthBronzeHelmet;
public static Item BlackBronzeHelmet;
public static Item BlackSteelHelmet;
public static Item BlueSteelHelmet;
public static Item BronzeHelmet;
public static Item CopperHelmet;
public static Item WroughtIronHelmet;
public static Item RedSteelHelmet;
public static Item RoseGoldHelmet;
public static Item SteelHelmet;
public static Item TinHelmet;
public static Item ZincHelmet;
public static Item WoodenBucketEmpty;
public static Item WoodenBucketWater;
public static Item WoodenBucketMilk;
/**Food Related Items and Blocks*/
public static Item SeedsWheat;
public static Item SeedsMelon;
public static Item SeedsPumpkin;
public static Item SeedsMaize;
public static Item SeedsTomato;
public static Item SeedsBarley;
public static Item SeedsRye;
public static Item SeedsOat;
public static Item SeedsRice;
public static Item SeedsPotato;
public static Item SeedsOnion;
public static Item SeedsCabbage;
public static Item SeedsGarlic;
public static Item SeedsCarrot;
public static Item SeedsSugarcane;
public static Item SeedsHemp;
public static Item SeedsYellowBellPepper;
public static Item SeedsRedBellPepper;
public static Item SeedsSoybean;
public static Item SeedsGreenbean;
public static Item SeedsSquash;
public static Item FruitTreeSapling1;
public static Item FruitTreeSapling2;
public static Item RedApple;
public static Item GreenApple;
public static Item Banana;
public static Item Orange;
public static Item Lemon;
public static Item Olive;
public static Item Cherry;
public static Item Peach;
public static Item Plum;
public static Item Egg;
public static Item EggCooked;
public static Item WheatGrain;
public static Item BarleyGrain;
public static Item OatGrain;
public static Item RyeGrain;
public static Item RiceGrain;
public static Item MaizeEar;
public static Item Tomato;
public static Item Potato;
public static Item Onion;
public static Item Cabbage;
public static Item Garlic;
public static Item Carrot;
public static Item Sugarcane;
public static Item Hemp;
public static Item Soybean;
public static Item Greenbeans;
public static Item GreenBellPepper;
public static Item YellowBellPepper;
public static Item RedBellPepper;
public static Item Squash;
public static Item WheatGround;
public static Item BarleyGround;
public static Item OatGround;
public static Item RyeGround;
public static Item RiceGround;
public static Item CornmealGround;
public static Item WheatDough;
public static Item BarleyDough;
public static Item OatDough;
public static Item RyeDough;
public static Item RiceDough;
public static Item CornmealDough;
public static Item BarleyBread;
public static Item OatBread;
public static Item RyeBread;
public static Item RiceBread;
public static Item CornBread;
public static Item WheatWhole;
public static Item BarleyWhole;
public static Item OatWhole;
public static Item RyeWhole;
public static Item RiceWhole;
public static Item LooseRock;
public static Item FlatRock;
public static Item IgInStoneShovelHead;
public static Item SedStoneShovelHead;
public static Item IgExStoneShovelHead;
public static Item MMStoneShovelHead;
public static Item IgInStoneAxeHead;
public static Item SedStoneAxeHead;
public static Item IgExStoneAxeHead;
public static Item MMStoneAxeHead;
public static Item IgInStoneHoeHead;
public static Item SedStoneHoeHead;
public static Item IgExStoneHoeHead;
public static Item MMStoneHoeHead;
public static Item StoneKnife;
public static Item StoneKnifeHead;
public static Item StoneHammerHead;
public static Item SmallOreChunk;
public static Item SinglePlank;
public static Item minecartEmpty;
public static Item minecartCrate;
public static Item RedSteelBucketEmpty;
public static Item RedSteelBucketWater;
public static Item BlueSteelBucketEmpty;
public static Item BlueSteelBucketLava;
public static Item MealGeneric;
public static Item MealMoveSpeed;
public static Item MealDigSpeed;
public static Item MealDamageBoost;
public static Item MealJump;
public static Item MealDamageResist;
public static Item MealFireResist;
public static Item MealWaterBreathing;
public static Item MealNightVision;
public static Item Quern;
public static Item FlintSteel;
public static Item DoorOak;
public static Item DoorAspen;
public static Item DoorBirch;
public static Item DoorChestnut;
public static Item DoorDouglasFir;
public static Item DoorHickory;
public static Item DoorMaple;
public static Item DoorAsh;
public static Item DoorPine;
public static Item DoorSequoia;
public static Item DoorSpruce;
public static Item DoorSycamore;
public static Item DoorWhiteCedar;
public static Item DoorWhiteElm;
public static Item DoorWillow;
public static Item DoorKapok;
public static Item Blueprint;
public static Item writabeBookTFC;
public static Item WoolYarn;
public static Item Wool;
public static Item WoolCloth;
public static Item Spindle;
public static Item ClaySpindle;
public static Item SpindleHead;
public static Item StoneBrick;
public static Item Mortar;
public static Item Limewater;
public static Item Hide;
public static Item SoakedHide;
public static Item ScrapedHide;
public static Item PrepHide;
public static Item SheepSkin;
public static Item TerraLeather;
public static Item muttonRaw;
public static Item muttonCooked;
public static Item FlatLeather;
public static Item Beer;
public static Item PotteryJug;
public static Item PotteryPot;
public static Item PotteryAmphora;
public static Item PotterySmallVessel;
public static Item PotteryLargeVessel;
public static Item KilnRack;
public static Item Straw;
/**
* Item Uses Setup
* */
public static int IgInStoneUses = 60;
public static int IgExStoneUses = 70;
public static int SedStoneUses = 50;
public static int MMStoneUses = 55;
//Tier 0
public static int BismuthUses = 300;
public static int TinUses = 290;
public static int ZincUses = 250;
//Tier 1
public static int CopperUses = 600;
//Tier 2
public static int BronzeUses = 1300;
public static int RoseGoldUses = 1140;
public static int BismuthBronzeUses = 1200;
public static int BlackBronzeUses = 1460;
//Tier 3
public static int WroughtIronUses = 2200;
//Tier 4
public static int SteelUses = 3300;
//Tier 5
public static int BlackSteelUses = 4200;
//Tier 6
public static int BlueSteelUses = 6500;
public static int RedSteelUses = 6500;
//Tier 0
public static float BismuthEff = 11;
public static float TinEff = 10.5f;
public static float ZincEff = 10;
//Tier 1
public static float CopperEff = 12;
//Tier 2
public static float BronzeEff = 15;
public static float RoseGoldEff = 13;
public static float BismuthBronzeEff = 14;
public static float BlackBronzeEff = 16;
//Tier 3
public static float WroughtIronEff = 16;
//Tier 4
public static float SteelEff = 17;
//Tier 5
public static float BlackSteelEff = 18;
//Tier 6
public static float BlueSteelEff = 21;
public static float RedSteelEff = 21;
public static EnumToolMaterial IgInToolMaterial;
public static EnumToolMaterial SedToolMaterial;
public static EnumToolMaterial IgExToolMaterial;
public static EnumToolMaterial MMToolMaterial;
public static EnumToolMaterial BismuthToolMaterial;
public static EnumToolMaterial BismuthBronzeToolMaterial;
public static EnumToolMaterial BlackBronzeToolMaterial;
public static EnumToolMaterial BlackSteelToolMaterial;
public static EnumToolMaterial BlueSteelToolMaterial;
public static EnumToolMaterial BronzeToolMaterial;
public static EnumToolMaterial CopperToolMaterial;
public static EnumToolMaterial IronToolMaterial;
public static EnumToolMaterial RedSteelToolMaterial;
public static EnumToolMaterial RoseGoldToolMaterial;
public static EnumToolMaterial SteelToolMaterial;
public static EnumToolMaterial TinToolMaterial;
public static EnumToolMaterial ZincToolMaterial;
static Configuration config;
public static void Setup()
{
try
{
config = new net.minecraftforge.common.Configuration(
new File(TerraFirmaCraft.proxy.getMinecraftDir(), "/config/TFC.cfg"));
config.load();
} catch (Exception e) {
System.out.println(new StringBuilder().append("[TFC] Error while trying to access item configuration!").toString());
config = null;
}
IgInToolMaterial = EnumHelper.addToolMaterial("IgIn", 1, IgInStoneUses, 7F, 10, 5);
SedToolMaterial = EnumHelper.addToolMaterial("Sed", 1, SedStoneUses, 6F, 10, 5);
IgExToolMaterial = EnumHelper.addToolMaterial("IgEx", 1, IgExStoneUses, 7F, 10, 5);
MMToolMaterial = EnumHelper.addToolMaterial("MM", 1, MMStoneUses, 6.5F, 10, 5);
BismuthToolMaterial = EnumHelper.addToolMaterial("Bismuth", 2, BismuthUses, BismuthEff, 65, 10);
BismuthBronzeToolMaterial = EnumHelper.addToolMaterial("BismuthBronze", 2, BismuthBronzeUses, BismuthBronzeEff, 85, 10);
BlackBronzeToolMaterial = EnumHelper.addToolMaterial("BlackBronze", 2, BlackBronzeUses, BlackBronzeEff, 100, 10);
BlackSteelToolMaterial = EnumHelper.addToolMaterial("BlackSteel", 2, BlackSteelUses, BlackSteelEff, 165, 12);
BlueSteelToolMaterial = EnumHelper.addToolMaterial("BlueSteel", 3, BlueSteelUses, BlueSteelEff, 185, 22);
BronzeToolMaterial = EnumHelper.addToolMaterial("Bronze", 2, BronzeUses, BronzeEff, 100, 13);
CopperToolMaterial = EnumHelper.addToolMaterial("Copper", 2, CopperUses, CopperEff, 85, 8);
IronToolMaterial = EnumHelper.addToolMaterial("Iron", 2, WroughtIronUses, WroughtIronEff, 135, 10);
RedSteelToolMaterial = EnumHelper.addToolMaterial("RedSteel", 3, RedSteelUses, RedSteelEff, 185, 22);
RoseGoldToolMaterial = EnumHelper.addToolMaterial("RoseGold", 2, RoseGoldUses, RoseGoldEff, 100, 20);
SteelToolMaterial = EnumHelper.addToolMaterial("Steel", 2, SteelUses, SteelEff, 150, 10);
TinToolMaterial = EnumHelper.addToolMaterial("Tin", 2, TinUses, TinEff, 65, 8);
ZincToolMaterial = EnumHelper.addToolMaterial("Zinc", 2, ZincUses, ZincEff, 65, 8);
System.out.println(new StringBuilder().append("[TFC] Loading Items").toString());
//Replace any vanilla Items here
Item.itemsList[Item.coal.itemID] = null; Item.itemsList[Item.coal.itemID] = (new TFC.Items.ItemCoal(7)).setUnlocalizedName("coal");
Item.itemsList[Item.stick.itemID] = null; Item.itemsList[Item.stick.itemID] = new ItemStick(24).setFull3D().setUnlocalizedName("stick");
Item.itemsList[Item.leather.itemID] = null; Item.itemsList[Item.leather.itemID] = new ItemTerra(Item.leather.itemID).setFull3D().setUnlocalizedName("leather");
Item.itemsList[Block.vine.blockID] = new ItemColored(Block.vine.blockID - 256, false);
minecartCrate = (new ItemCustomMinecart(TFC_Settings.getIntFor(config,"item","minecartCrate",16000), 1)).setUnlocalizedName("minecartChest");
Item.itemsList[5+256] = null; Item.itemsList[5+256] = (new ItemCustomBow(5)).setUnlocalizedName("bow");
Item.itemsList[63+256] = null; Item.itemsList[63+256] = new ItemTerra(63).setUnlocalizedName("porkchopRaw");
Item.itemsList[64+256] = null; Item.itemsList[64+256] = new ItemTerraFood(64, 35, 0.8F, true, 38).setFolder("").setUnlocalizedName("porkchopCooked");
Item.itemsList[93+256] = null; Item.itemsList[93+256] = new ItemTerra(93).setUnlocalizedName("fishRaw");
Item.itemsList[94+256] = null; Item.itemsList[94+256] = new ItemTerraFood(94, 30, 0.6F, true, 39).setFolder("").setUnlocalizedName("fishCooked");
Item.itemsList[107+256] = null; Item.itemsList[107+256] = new ItemTerra(107).setUnlocalizedName("beefRaw");
Item.itemsList[108+256] = null; Item.itemsList[108+256] = new ItemTerraFood(108, 40, 0.8F, true, 40).setFolder("").setUnlocalizedName("beefCooked");
Item.itemsList[109+256] = null; Item.itemsList[109+256] = new ItemTerra(109).setUnlocalizedName("chickenRaw");
Item.itemsList[110+256] = null; Item.itemsList[110+256] = new ItemTerraFood(110, 35, 0.6F, true, 41).setFolder("").setUnlocalizedName("chickenCooked");
Item.itemsList[41+256] = null; Item.itemsList[41+256] = (new ItemTerraFood(41, 25, 0.6F, false, 42)).setFolder("").setUnlocalizedName("bread");
Item.itemsList[88+256] = null; Item.itemsList[88+256] = (new ItemTerra(88)).setUnlocalizedName("egg");
Item.itemsList[Item.dyePowder.itemID] = null; Item.itemsList[Item.dyePowder.itemID] = new ItemDyeCustom(95).setUnlocalizedName("dyePowder");
Item.itemsList[Item.potion.itemID] = null; Item.itemsList[Item.potion.itemID] = (new ItemCustomPotion(117)).setUnlocalizedName("potion");
Item.itemsList[Block.tallGrass.blockID] = null; Item.itemsList[Block.tallGrass.blockID] = (new ItemColored(Block.tallGrass.blockID - 256, true)).setBlockNames(new String[] {"shrub", "grass", "fern"});
GoldPan = new ItemGoldPan(TFC_Settings.getIntFor(config,"item","GoldPan",16001)).setUnlocalizedName("GoldPan");
SluiceItem = new ItemSluice(TFC_Settings.getIntFor(config,"item","SluiceItem",16002)).setFolder("devices/").setUnlocalizedName("SluiceItem");
ProPickBismuth = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuth",16004)).setUnlocalizedName("Bismuth ProPick").setMaxDamage(BismuthUses);
ProPickBismuthBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuthBronze",16005)).setUnlocalizedName("Bismuth Bronze ProPick").setMaxDamage(BismuthBronzeUses);
ProPickBlackBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackBronze",16006)).setUnlocalizedName("Black Bronze ProPick").setMaxDamage(BlackBronzeUses);
ProPickBlackSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackSteel",16007)).setUnlocalizedName("Black Steel ProPick").setMaxDamage(BlackSteelUses);
ProPickBlueSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlueSteel",16008)).setUnlocalizedName("Blue Steel ProPick").setMaxDamage(BlueSteelUses);
ProPickBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBronze",16009)).setUnlocalizedName("Bronze ProPick").setMaxDamage(BronzeUses);
ProPickCopper = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickCopper",16010)).setUnlocalizedName("Copper ProPick").setMaxDamage(CopperUses);
ProPickIron = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickWroughtIron",16012)).setUnlocalizedName("Wrought Iron ProPick").setMaxDamage(WroughtIronUses);
ProPickRedSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRedSteel",16016)).setUnlocalizedName("Red Steel ProPick").setMaxDamage(RedSteelUses);
ProPickRoseGold = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRoseGold",16017)).setUnlocalizedName("Rose Gold ProPick").setMaxDamage(RoseGoldUses);
ProPickSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickSteel",16019)).setUnlocalizedName("Steel ProPick").setMaxDamage(SteelUses);
ProPickTin = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickTin",16021)).setUnlocalizedName("Tin ProPick").setMaxDamage(TinUses);
ProPickZinc = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickZinc",16022)).setUnlocalizedName("Zinc ProPick").setMaxDamage(ZincUses);
BismuthIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot",16028), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Ingot");
BismuthBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot",16029), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Ingot");
BlackBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot",16030), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Ingot");
BlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot",16031), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Ingot");
BlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot",16032), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Ingot");
BrassIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot",16033), EnumMetalType.BRASS).setUnlocalizedName("Brass Ingot");
BronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot",16034), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Ingot");
CopperIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot",16035), EnumMetalType.COPPER).setUnlocalizedName("Copper Ingot");
GoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot",16036), EnumMetalType.GOLD).setUnlocalizedName("Gold Ingot");
WroughtIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot",16037), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Ingot");
LeadIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot",16038), EnumMetalType.LEAD).setUnlocalizedName("Lead Ingot");
NickelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot",16039), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Ingot");
PigIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot",16040), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Ingot");
PlatinumIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot",16041), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Ingot");
RedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot",16042), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Ingot");
RoseGoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot",16043), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Ingot");
SilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot",16044), EnumMetalType.SILVER).setUnlocalizedName("Silver Ingot");
SteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot",16045), EnumMetalType.STEEL).setUnlocalizedName("Steel Ingot");
SterlingSilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot",16046), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Ingot");
TinIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot",16047), EnumMetalType.TIN).setUnlocalizedName("Tin Ingot");
ZincIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot",16048), EnumMetalType.ZINC).setUnlocalizedName("Zinc Ingot");
BismuthIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot2x",16049), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Double Ingot")).setSize(EnumSize.LARGE);
BismuthBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot2x",16050), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot2x",16051), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot2x",16052), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Double Ingot")).setSize(EnumSize.LARGE);
BlueSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot2x",16053), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Double Ingot")).setSize(EnumSize.LARGE);
BrassIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot2x",16054), EnumMetalType.BRASS).setUnlocalizedName("Brass Double Ingot")).setSize(EnumSize.LARGE);
BronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot2x",16055), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Double Ingot")).setSize(EnumSize.LARGE);
CopperIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot2x",16056), EnumMetalType.COPPER).setUnlocalizedName("Copper Double Ingot")).setSize(EnumSize.LARGE);
GoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot2x",16057), EnumMetalType.GOLD).setUnlocalizedName("Gold Double Ingot")).setSize(EnumSize.LARGE);
WroughtIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot2x",16058), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Double Ingot")).setSize(EnumSize.LARGE);
LeadIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot2x",16059), EnumMetalType.LEAD).setUnlocalizedName("Lead Double Ingot")).setSize(EnumSize.LARGE);
NickelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot2x",16060), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Double Ingot")).setSize(EnumSize.LARGE);
PigIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot2x",16061), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Double Ingot")).setSize(EnumSize.LARGE);
PlatinumIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot2x",16062), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Double Ingot")).setSize(EnumSize.LARGE);
RedSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot2x",16063), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Double Ingot")).setSize(EnumSize.LARGE);
RoseGoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot2x",16064), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Double Ingot")).setSize(EnumSize.LARGE);
SilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot2x",16065), EnumMetalType.SILVER).setUnlocalizedName("Silver Double Ingot")).setSize(EnumSize.LARGE);
SteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot2x",16066), EnumMetalType.STEEL).setUnlocalizedName("Steel Double Ingot")).setSize(EnumSize.LARGE);
SterlingSilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot2x",16067), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Double Ingot")).setSize(EnumSize.LARGE);
TinIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot2x",16068), EnumMetalType.TIN).setUnlocalizedName("Tin Double Ingot")).setSize(EnumSize.LARGE);
ZincIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot2x",16069), EnumMetalType.ZINC).setUnlocalizedName("Zinc Double Ingot")).setSize(EnumSize.LARGE);
SulfurPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SulfurPowder",16070)).setUnlocalizedName("Sulfur Powder");
SaltpeterPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SaltpeterPowder",16071)).setUnlocalizedName("Saltpeter Powder");
GemRuby = new ItemGem(TFC_Settings.getIntFor(config,"item","GemRuby",16080)).setUnlocalizedName("Ruby");
GemSapphire = new ItemGem(TFC_Settings.getIntFor(config,"item","GemSapphire",16081)).setUnlocalizedName("Sapphire");
GemEmerald = new ItemGem(TFC_Settings.getIntFor(config,"item","GemEmerald",16082)).setUnlocalizedName("Emerald");
GemTopaz = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTopaz",16083)).setUnlocalizedName("Topaz");
GemTourmaline = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTourmaline",16084)).setUnlocalizedName("Tourmaline");
GemJade = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJade",16085)).setUnlocalizedName("Jade");
GemBeryl = new ItemGem(TFC_Settings.getIntFor(config,"item","GemBeryl",16086)).setUnlocalizedName("Beryl");
GemAgate = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAgate",16087)).setUnlocalizedName("Agate");
GemOpal = new ItemGem(TFC_Settings.getIntFor(config,"item","GemOpal",16088)).setUnlocalizedName("Opal");
GemGarnet = new ItemGem(TFC_Settings.getIntFor(config,"item","GemGarnet",16089)).setUnlocalizedName("Garnet");
GemJasper = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJasper",16090)).setUnlocalizedName("Jasper");
GemAmethyst = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAmethyst",16091)).setUnlocalizedName("Amethyst");
GemDiamond = new ItemGem(TFC_Settings.getIntFor(config,"item","GemDiamond",16092)).setUnlocalizedName("Diamond");
//Tools
IgInShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgInShovel",16101),IgInToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgInStoneUses);
IgInAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgInAxe",16102),IgInToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgInStoneUses);
IgInHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgInHoe",16103),IgInToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgInStoneUses);
SedShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SedShovel",16105),SedToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(SedStoneUses);
SedAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SedAxe",16106),SedToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(SedStoneUses);
SedHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SedHoe",16107),SedToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(SedStoneUses);
IgExShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgExShovel",16109),IgExToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgExStoneUses);
IgExAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgExAxe",16110),IgExToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgExStoneUses);
IgExHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgExHoe",16111),IgExToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgExStoneUses);
MMShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","MMShovel",16113),MMToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(MMStoneUses);
MMAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","MMAxe",16114),MMToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(MMStoneUses);
MMHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","MMHoe",16115),MMToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(MMStoneUses);
BismuthPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthPick",16116),BismuthToolMaterial).setUnlocalizedName("Bismuth Pick").setMaxDamage(BismuthUses);
BismuthShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthShovel",16117),BismuthToolMaterial).setUnlocalizedName("Bismuth Shovel").setMaxDamage(BismuthUses);
BismuthAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthAxe",16118),BismuthToolMaterial).setUnlocalizedName("Bismuth Axe").setMaxDamage(BismuthUses);
BismuthHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthHoe",16119),BismuthToolMaterial).setUnlocalizedName("Bismuth Hoe").setMaxDamage(BismuthUses);
BismuthBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthBronzePick",16120),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Pick").setMaxDamage(BismuthBronzeUses);
BismuthBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovel",16121),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Shovel").setMaxDamage(BismuthBronzeUses);
BismuthBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxe",16122),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Axe").setMaxDamage(BismuthBronzeUses);
BismuthBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoe",16123),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hoe").setMaxDamage(BismuthBronzeUses);
BlackBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackBronzePick",16124),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Pick").setMaxDamage(BlackBronzeUses);
BlackBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackBronzeShovel",16125),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Shovel").setMaxDamage(BlackBronzeUses);
BlackBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackBronzeAxe",16126),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Axe").setMaxDamage(BlackBronzeUses);
BlackBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackBronzeHoe",16127),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hoe").setMaxDamage(BlackBronzeUses);
BlackSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackSteelPick",16128),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Pick").setMaxDamage(BlackSteelUses);
BlackSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackSteelShovel",16129),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Shovel").setMaxDamage(BlackSteelUses);
BlackSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackSteelAxe",16130),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Axe").setMaxDamage(BlackSteelUses);
BlackSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackSteelHoe",16131),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hoe").setMaxDamage(BlackSteelUses);
BlueSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlueSteelPick",16132),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Pick").setMaxDamage(BlueSteelUses);
BlueSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlueSteelShovel",16133),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Shovel").setMaxDamage(BlueSteelUses);
BlueSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlueSteelAxe",16134),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Axe").setMaxDamage(BlueSteelUses);
BlueSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlueSteelHoe",16135),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hoe").setMaxDamage(BlueSteelUses);
BronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BronzePick",16136),BronzeToolMaterial).setUnlocalizedName("Bronze Pick").setMaxDamage(BronzeUses);
BronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BronzeShovel",16137),BronzeToolMaterial).setUnlocalizedName("Bronze Shovel").setMaxDamage(BronzeUses);
BronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BronzeAxe",16138),BronzeToolMaterial).setUnlocalizedName("Bronze Axe").setMaxDamage(BronzeUses);
BronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BronzeHoe",16139),BronzeToolMaterial).setUnlocalizedName("Bronze Hoe").setMaxDamage(BronzeUses);
CopperPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","CopperPick",16140),CopperToolMaterial).setUnlocalizedName("Copper Pick").setMaxDamage(CopperUses);
CopperShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","CopperShovel",16141),CopperToolMaterial).setUnlocalizedName("Copper Shovel").setMaxDamage(CopperUses);
CopperAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","CopperAxe",16142),CopperToolMaterial).setUnlocalizedName("Copper Axe").setMaxDamage(CopperUses);
CopperHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","CopperHoe",16143),CopperToolMaterial).setUnlocalizedName("Copper Hoe").setMaxDamage(CopperUses);
WroughtIronPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","WroughtIronPick",16148),IronToolMaterial).setUnlocalizedName("Wrought Iron Pick").setMaxDamage(WroughtIronUses);
WroughtIronShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","WroughtIronShovel",16149),IronToolMaterial).setUnlocalizedName("Wrought Iron Shovel").setMaxDamage(WroughtIronUses);
WroughtIronAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","WroughtIronAxe",16150),IronToolMaterial).setUnlocalizedName("Wrought Iron Axe").setMaxDamage(WroughtIronUses);
WroughtIronHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","WroughtIronHoe",16151),IronToolMaterial).setUnlocalizedName("Wrought Iron Hoe").setMaxDamage(WroughtIronUses);;
RedSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RedSteelPick",16168),RedSteelToolMaterial).setUnlocalizedName("Red Steel Pick").setMaxDamage(RedSteelUses);
RedSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RedSteelShovel",16169),RedSteelToolMaterial).setUnlocalizedName("Red Steel Shovel").setMaxDamage(RedSteelUses);
RedSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RedSteelAxe",16170),RedSteelToolMaterial).setUnlocalizedName("Red Steel Axe").setMaxDamage(RedSteelUses);
RedSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RedSteelHoe",16171),RedSteelToolMaterial).setUnlocalizedName("Red Steel Hoe").setMaxDamage(RedSteelUses);
RoseGoldPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RoseGoldPick",16172),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Pick").setMaxDamage(RoseGoldUses);
RoseGoldShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RoseGoldShovel",16173),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Shovel").setMaxDamage(RoseGoldUses);
RoseGoldAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RoseGoldAxe",16174),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Axe").setMaxDamage(RoseGoldUses);
RoseGoldHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RoseGoldHoe",16175),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hoe").setMaxDamage(RoseGoldUses);
SteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","SteelPick",16180),SteelToolMaterial).setUnlocalizedName("Steel Pick").setMaxDamage(SteelUses);
SteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SteelShovel",16181),SteelToolMaterial).setUnlocalizedName("Steel Shovel").setMaxDamage(SteelUses);
SteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SteelAxe",16182),SteelToolMaterial).setUnlocalizedName("Steel Axe").setMaxDamage(SteelUses);
SteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SteelHoe",16183),SteelToolMaterial).setUnlocalizedName("Steel Hoe").setMaxDamage(SteelUses);
TinPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","TinPick",16188),TinToolMaterial).setUnlocalizedName("Tin Pick").setMaxDamage(TinUses);
TinShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","TinShovel",16189),TinToolMaterial).setUnlocalizedName("Tin Shovel").setMaxDamage(TinUses);
TinAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","TinAxe",16190),TinToolMaterial).setUnlocalizedName("Tin Axe").setMaxDamage(TinUses);
TinHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","TinHoe",16191),TinToolMaterial).setUnlocalizedName("Tin Hoe").setMaxDamage(TinUses);
ZincPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","ZincPick",16192),ZincToolMaterial).setUnlocalizedName("Zinc Pick").setMaxDamage(ZincUses);
ZincShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","ZincShovel",16193),ZincToolMaterial).setUnlocalizedName("Zinc Shovel").setMaxDamage(ZincUses);
ZincAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","ZincAxe",16194),ZincToolMaterial).setUnlocalizedName("Zinc Axe").setMaxDamage(ZincUses);
ZincHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","ZincHoe",16195),ZincToolMaterial).setUnlocalizedName("Zinc Hoe").setMaxDamage(ZincUses);
//chisels
BismuthChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthChisel",16226),BismuthToolMaterial).setUnlocalizedName("Bismuth Chisel").setMaxDamage(BismuthUses);
BismuthBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthBronzeChisel",16227),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Chisel").setMaxDamage(BismuthBronzeUses);
BlackBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackBronzeChisel",16228),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Chisel").setMaxDamage(BlackBronzeUses);
BlackSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackSteelChisel",16230),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Chisel").setMaxDamage(BlackSteelUses);
BlueSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlueSteelChisel",16231),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Chisel").setMaxDamage(BlueSteelUses);
BronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BronzeChisel",16232),BronzeToolMaterial).setUnlocalizedName("Bronze Chisel").setMaxDamage(BronzeUses);
CopperChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","CopperChisel",16233),CopperToolMaterial).setUnlocalizedName("Copper Chisel").setMaxDamage(CopperUses);
WroughtIronChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","WroughtIronChisel",16234),IronToolMaterial).setUnlocalizedName("Wrought Iron Chisel").setMaxDamage(WroughtIronUses);
RedSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RedSteelChisel",16235),RedSteelToolMaterial).setUnlocalizedName("Red Steel Chisel").setMaxDamage(RedSteelUses);
RoseGoldChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RoseGoldChisel",16236),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Chisel").setMaxDamage(RoseGoldUses);
SteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","SteelChisel",16237),SteelToolMaterial).setUnlocalizedName("Steel Chisel").setMaxDamage(SteelUses);
TinChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","TinChisel",16238),TinToolMaterial).setUnlocalizedName("Tin Chisel").setMaxDamage(TinUses);
ZincChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","ZincChisel",16239),ZincToolMaterial).setUnlocalizedName("Zinc Chisel").setMaxDamage(ZincUses);
StoneChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","StoneChisel",16240),IgInToolMaterial).setUnlocalizedName("Stone Chisel").setMaxDamage(IgInStoneUses);
BismuthSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthSword",16245),BismuthToolMaterial).setUnlocalizedName("Bismuth Sword").setMaxDamage(BismuthUses);
BismuthBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeSword",16246),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Sword").setMaxDamage(BismuthBronzeUses);
BlackBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeSword",16247),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Sword").setMaxDamage(BlackBronzeUses);
BlackSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelSword",16248),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Sword").setMaxDamage(BlackSteelUses);
BlueSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelSword",16249),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Sword").setMaxDamage(BlueSteelUses);
BronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeSword",16250),BronzeToolMaterial).setUnlocalizedName("Bronze Sword").setMaxDamage(BronzeUses);
CopperSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperSword",16251),CopperToolMaterial).setUnlocalizedName("Copper Sword").setMaxDamage(CopperUses);
WroughtIronSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronSword",16252),IronToolMaterial).setUnlocalizedName("Wrought Iron Sword").setMaxDamage(WroughtIronUses);
RedSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelSword",16253),RedSteelToolMaterial).setUnlocalizedName("Red Steel Sword").setMaxDamage(RedSteelUses);
RoseGoldSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldSword",16254),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Sword").setMaxDamage(RoseGoldUses);
SteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelSword",16255),SteelToolMaterial).setUnlocalizedName("Steel Sword").setMaxDamage(SteelUses);
TinSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinSword",16256),TinToolMaterial).setUnlocalizedName("Tin Sword").setMaxDamage(TinUses);
ZincSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincSword",16257),ZincToolMaterial).setUnlocalizedName("Zinc Sword").setMaxDamage(ZincUses);
BismuthMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthMace",16262),BismuthToolMaterial).setUnlocalizedName("Bismuth Mace").setMaxDamage(BismuthUses);
BismuthBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeMace",16263),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Mace").setMaxDamage(BismuthBronzeUses);
BlackBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeMace",16264),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Mace").setMaxDamage(BlackBronzeUses);
BlackSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelMace",16265),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Mace").setMaxDamage(BlackSteelUses);
BlueSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelMace",16266),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Mace").setMaxDamage(BlueSteelUses);
BronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeMace",16267),BronzeToolMaterial).setUnlocalizedName("Bronze Mace").setMaxDamage(BronzeUses);
CopperMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperMace",16268),CopperToolMaterial).setUnlocalizedName("Copper Mace").setMaxDamage(CopperUses);
WroughtIronMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronMace",16269),IronToolMaterial).setUnlocalizedName("Wrought Iron Mace").setMaxDamage(WroughtIronUses);
RedSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelMace",16270),RedSteelToolMaterial).setUnlocalizedName("Red Steel Mace").setMaxDamage(RedSteelUses);
RoseGoldMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldMace",16271),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Mace").setMaxDamage(RoseGoldUses);
SteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelMace",16272),SteelToolMaterial).setUnlocalizedName("Steel Mace").setMaxDamage(SteelUses);
TinMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinMace",16273),TinToolMaterial).setUnlocalizedName("Tin Mace").setMaxDamage(TinUses);
ZincMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincMace",16274),ZincToolMaterial).setUnlocalizedName("Zinc Mace").setMaxDamage(ZincUses);
BismuthSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthSaw",16275),BismuthToolMaterial).setUnlocalizedName("Bismuth Saw").setMaxDamage(BismuthUses);
BismuthBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthBronzeSaw",16276),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Saw").setMaxDamage(BismuthBronzeUses);
BlackBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackBronzeSaw",16277),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Saw").setMaxDamage(BlackBronzeUses);
BlackSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackSteelSaw",16278),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Saw").setMaxDamage(BlackSteelUses);
BlueSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlueSteelSaw",16279),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Saw").setMaxDamage(BlueSteelUses);
BronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BronzeSaw",16280),BronzeToolMaterial).setUnlocalizedName("Bronze Saw").setMaxDamage(BronzeUses);
CopperSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","CopperSaw",16281),CopperToolMaterial).setUnlocalizedName("Copper Saw").setMaxDamage(CopperUses);
WroughtIronSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","WroughtIronSaw",16282),IronToolMaterial).setUnlocalizedName("Wrought Iron Saw").setMaxDamage(WroughtIronUses);
RedSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RedSteelSaw",16283),RedSteelToolMaterial).setUnlocalizedName("Red Steel Saw").setMaxDamage(RedSteelUses);
RoseGoldSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RoseGoldSaw",16284),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Saw").setMaxDamage(RoseGoldUses);
SteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","SteelSaw",16285),SteelToolMaterial).setUnlocalizedName("Steel Saw").setMaxDamage(SteelUses);
TinSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","TinSaw",16286),TinToolMaterial).setUnlocalizedName("Tin Saw").setMaxDamage(TinUses);
ZincSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","ZincSaw",16287),ZincToolMaterial).setUnlocalizedName("Zinc Saw").setMaxDamage(ZincUses);
HCBlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlackSteelIngot",16290), EnumMetalType.BLACKSTEEL).setUnlocalizedName("HC Black Steel Ingot");
WeakBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakBlueSteelIngot",16291),EnumMetalType.BLUESTEEL).setUnlocalizedName("Weak Blue Steel Ingot");
WeakRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakRedSteelIngot",16292),EnumMetalType.REDSTEEL).setUnlocalizedName("Weak Red Steel Ingot");
WeakSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakSteelIngot",16293),EnumMetalType.STEEL).setUnlocalizedName("Weak Steel Ingot");
HCBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlueSteelIngot",16294), EnumMetalType.BLUESTEEL).setUnlocalizedName("HC Blue Steel Ingot");
HCRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCRedSteelIngot",16295), EnumMetalType.REDSTEEL).setUnlocalizedName("HC Red Steel Ingot");
HCSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCSteelIngot",16296), EnumMetalType.STEEL).setUnlocalizedName("HC Steel Ingot");
OreChunk = new ItemOre(TFC_Settings.getIntFor(config,"item","OreChunk",16297)).setFolder("ore/").setUnlocalizedName("Ore");
Logs = new ItemLogs(TFC_Settings.getIntFor(config,"item","Logs",16298)).setUnlocalizedName("Log");
Javelin = new ItemJavelin(TFC_Settings.getIntFor(config,"item","javelin",16318)).setUnlocalizedName("javelin");
BismuthUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuth",16350)).setUnlocalizedName("Bismuth Unshaped");
BismuthBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuthBronze",16351)).setUnlocalizedName("Bismuth Bronze Unshaped");
BlackBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackBronze",16352)).setUnlocalizedName("Black Bronze Unshaped");
BlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackSteel",16353)).setUnlocalizedName("Black Steel Unshaped");
BlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlueSteel",16354)).setUnlocalizedName("Blue Steel Unshaped");
BrassUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBrass",16355)).setUnlocalizedName("Brass Unshaped");
BronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBronze",16356)).setUnlocalizedName("Bronze Unshaped");
CopperUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedCopper",16357)).setUnlocalizedName("Copper Unshaped");
GoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedGold",16358)).setUnlocalizedName("Gold Unshaped");
WroughtIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedIron",16359)).setUnlocalizedName("Wrought Iron Unshaped");
LeadUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedLead",16360)).setUnlocalizedName("Lead Unshaped");
NickelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedNickel",16361)).setUnlocalizedName("Nickel Unshaped");
PigIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPigIron",16362)).setUnlocalizedName("Pig Iron Unshaped");
PlatinumUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPlatinum",16363)).setUnlocalizedName("Platinum Unshaped");
RedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRedSteel",16364)).setUnlocalizedName("Red Steel Unshaped");
RoseGoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRoseGold",16365)).setUnlocalizedName("Rose Gold Unshaped");
SilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSilver",16366)).setUnlocalizedName("Silver Unshaped");
SteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSteel",16367)).setUnlocalizedName("Steel Unshaped");
SterlingSilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSterlingSilver",16368)).setUnlocalizedName("Sterling Silver Unshaped");
TinUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedTin",16369)).setUnlocalizedName("Tin Unshaped");
ZincUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedZinc",16370)).setUnlocalizedName("Zinc Unshaped");
//Hammers
StoneHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","StoneHammer",16371),TFCItems.IgInToolMaterial).setUnlocalizedName("Stone Hammer").setMaxDamage(TFCItems.IgInStoneUses);
BismuthHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BismuthHammer",16372),TFCItems.BismuthToolMaterial).setUnlocalizedName("Bismuth Hammer").setMaxDamage(TFCItems.BismuthUses);
BismuthBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammer",16373),TFCItems.BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hammer").setMaxDamage(TFCItems.BismuthBronzeUses);
BlackBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlackBronzeHammer",16374),TFCItems.BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hammer").setMaxDamage(TFCItems.BlackBronzeUses);
BlackSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlackSteelHammer",16375),TFCItems.BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hammer").setMaxDamage(TFCItems.BlackSteelUses);
BlueSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlueSteelHammer",16376),TFCItems.BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hammer").setMaxDamage(TFCItems.BlueSteelUses);
BronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BronzeHammer",16377),TFCItems.BronzeToolMaterial).setUnlocalizedName("Bronze Hammer").setMaxDamage(TFCItems.BronzeUses);
CopperHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","CopperHammer",16378),TFCItems.CopperToolMaterial).setUnlocalizedName("Copper Hammer").setMaxDamage(TFCItems.CopperUses);
WroughtIronHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","WroughtIronHammer",16379),TFCItems.IronToolMaterial).setUnlocalizedName("Wrought Iron Hammer").setMaxDamage(TFCItems.WroughtIronUses);
RedSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","RedSteelHammer",16380),TFCItems.RedSteelToolMaterial).setUnlocalizedName("Red Steel Hammer").setMaxDamage(TFCItems.RedSteelUses);
RoseGoldHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","RoseGoldHammer",16381),TFCItems.RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hammer").setMaxDamage(TFCItems.RoseGoldUses);
SteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","SteelHammer",16382),TFCItems.SteelToolMaterial).setUnlocalizedName("Steel Hammer").setMaxDamage(TFCItems.SteelUses);
TinHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","TinHammer",16383),TFCItems.TinToolMaterial).setUnlocalizedName("Tin Hammer").setMaxDamage(TFCItems.TinUses);
ZincHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","ZincHammer",16384),TFCItems.ZincToolMaterial).setUnlocalizedName("Zinc Hammer").setMaxDamage(TFCItems.ZincUses);
Ink = new ItemTerra(TFC_Settings.getIntFor(config,"item","Ink",16391)).setUnlocalizedName("Ink");
BellowsItem = new ItemBellows(TFC_Settings.getIntFor(config,"item","BellowsItem",16406)).setUnlocalizedName("Bellows");
FireStarter = new ItemFirestarter(TFC_Settings.getIntFor(config,"item","FireStarter",16407)).setFolder("tools/").setUnlocalizedName("Firestarter");
//Tool heads
BismuthPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthPickaxeHead",16500)).setUnlocalizedName("Bismuth Pick Head");
BismuthBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzePickaxeHead",16501)).setUnlocalizedName("Bismuth Bronze Pick Head");
BlackBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzePickaxeHead",16502)).setUnlocalizedName("Black Bronze Pick Head");
BlackSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelPickaxeHead",16503)).setUnlocalizedName("Black Steel Pick Head");
BlueSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelPickaxeHead",16504)).setUnlocalizedName("Blue Steel Pick Head");
BronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzePickaxeHead",16505)).setUnlocalizedName("Bronze Pick Head");
CopperPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperPickaxeHead",16506)).setUnlocalizedName("Copper Pick Head");
WroughtIronPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronPickaxeHead",16507)).setUnlocalizedName("Wrought Iron Pick Head");
RedSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelPickaxeHead",16508)).setUnlocalizedName("Red Steel Pick Head");
RoseGoldPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldPickaxeHead",16509)).setUnlocalizedName("Rose Gold Pick Head");
SteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelPickaxeHead",16510)).setUnlocalizedName("Steel Pick Head");
TinPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinPickaxeHead",16511)).setUnlocalizedName("Tin Pick Head");
ZincPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincPickaxeHead",16512)).setUnlocalizedName("Zinc Pick Head");
BismuthShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthShovelHead",16513)).setUnlocalizedName("Bismuth Shovel Head");
BismuthBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovelHead",16514)).setUnlocalizedName("Bismuth Bronze Shovel Head");
BlackBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeShovelHead",16515)).setUnlocalizedName("Black Bronze Shovel Head");
BlackSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelShovelHead",16516)).setUnlocalizedName("Black Steel Shovel Head");
BlueSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelShovelHead",16517)).setUnlocalizedName("Blue Steel Shovel Head");
BronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeShovelHead",16518)).setUnlocalizedName("Bronze Shovel Head");
CopperShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperShovelHead",16519)).setUnlocalizedName("Copper Shovel Head");
WroughtIronShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronShovelHead",16520)).setUnlocalizedName("Wrought Iron Shovel Head");
RedSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelShovelHead",16521)).setUnlocalizedName("Red Steel Shovel Head");
RoseGoldShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldShovelHead",16522)).setUnlocalizedName("Rose Gold Shovel Head");
SteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelShovelHead",16523)).setUnlocalizedName("Steel Shovel Head");
TinShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinShovelHead",16524)).setUnlocalizedName("Tin Shovel Head");
ZincShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincShovelHead",16525)).setUnlocalizedName("Zinc Shovel Head");
BismuthHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHoeHead",16526)).setUnlocalizedName("Bismuth Hoe Head");
BismuthBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoeHead",16527)).setUnlocalizedName("Bismuth Bronze Hoe Head");
BlackBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHoeHead",16528)).setUnlocalizedName("Black Bronze Hoe Head");
BlackSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHoeHead",16529)).setUnlocalizedName("Black Steel Hoe Head");
BlueSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHoeHead",16530)).setUnlocalizedName("Blue Steel Hoe Head");
BronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHoeHead",16531)).setUnlocalizedName("Bronze Hoe Head");
CopperHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHoeHead",16532)).setUnlocalizedName("Copper Hoe Head");
WroughtIronHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHoeHead",16533)).setUnlocalizedName("Wrought Iron Hoe Head");
RedSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHoeHead",16534)).setUnlocalizedName("Red Steel Hoe Head");
RoseGoldHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHoeHead",16535)).setUnlocalizedName("Rose Gold Hoe Head");
SteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHoeHead",16536)).setUnlocalizedName("Steel Hoe Head");
TinHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHoeHead",16537)).setUnlocalizedName("Tin Hoe Head");
ZincHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHoeHead",16538)).setUnlocalizedName("Zinc Hoe Head");
BismuthAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthAxeHead",16539)).setUnlocalizedName("Bismuth Axe Head");
BismuthBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxeHead",16540)).setUnlocalizedName("Bismuth Bronze Axe Head");
BlackBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeAxeHead",16541)).setUnlocalizedName("Black Bronze Axe Head");
BlackSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelAxeHead",16542)).setUnlocalizedName("Black Steel Axe Head");
BlueSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelAxeHead",16543)).setUnlocalizedName("Blue Steel Axe Head");
BronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeAxeHead",16544)).setUnlocalizedName("Bronze Axe Head");
CopperAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperAxeHead",16545)).setUnlocalizedName("Copper Axe Head");
WroughtIronAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronAxeHead",16546)).setUnlocalizedName("Wrought Iron Axe Head");
RedSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelAxeHead",16547)).setUnlocalizedName("Red Steel Axe Head");
RoseGoldAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldAxeHead",16548)).setUnlocalizedName("Rose Gold Axe Head");
SteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelAxeHead",16549)).setUnlocalizedName("Steel Axe Head");
TinAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinAxeHead",16550)).setUnlocalizedName("Tin Axe Head");
ZincAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincAxeHead",16551)).setUnlocalizedName("Zinc Axe Head");
BismuthHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHammerHead",16552)).setUnlocalizedName("Bismuth Hammer Head");
BismuthBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammerHead",16553)).setUnlocalizedName("Bismuth Bronze Hammer Head");
BlackBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHammerHead",16554)).setUnlocalizedName("Black Bronze Hammer Head");
BlackSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHammerHead",16555)).setUnlocalizedName("Black Steel Hammer Head");
BlueSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHammerHead",16556)).setUnlocalizedName("Blue Steel Hammer Head");
BronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHammerHead",16557)).setUnlocalizedName("Bronze Hammer Head");
CopperHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHammerHead",16558)).setUnlocalizedName("Copper Hammer Head");
WroughtIronHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHammerHead",16559)).setUnlocalizedName("Wrought Iron Hammer Head");
RedSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHammerHead",16560)).setUnlocalizedName("Red Steel Hammer Head");
RoseGoldHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHammerHead",16561)).setUnlocalizedName("Rose Gold Hammer Head");
SteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHammerHead",16562)).setUnlocalizedName("Steel Hammer Head");
TinHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHammerHead",16563)).setUnlocalizedName("Tin Hammer Head");
ZincHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHammerHead",16564)).setUnlocalizedName("Zinc Hammer Head");
//chisel heads
BismuthChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthChiselHead",16565)).setUnlocalizedName("Bismuth Chisel Head");
BismuthBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeChiselHead",16566)).setUnlocalizedName("Bismuth Bronze Chisel Head");
BlackBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeChiselHead",16567)).setUnlocalizedName("Black Bronze Chisel Head");
BlackSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelChiselHead",16568)).setUnlocalizedName("Black Steel Chisel Head");
BlueSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelChiselHead",16569)).setUnlocalizedName("Blue Steel Chisel Head");
BronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeChiselHead",16570)).setUnlocalizedName("Bronze Chisel Head");
CopperChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperChiselHead",16571)).setUnlocalizedName("Copper Chisel Head");
WroughtIronChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronChiselHead",16572)).setUnlocalizedName("Wrought Iron Chisel Head");
RedSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelChiselHead",16573)).setUnlocalizedName("Red Steel Chisel Head");
RoseGoldChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldChiselHead",16574)).setUnlocalizedName("Rose Gold Chisel Head");
SteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelChiselHead",16575)).setUnlocalizedName("Steel Chisel Head");
TinChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinChiselHead",16576)).setUnlocalizedName("Tin Chisel Head");
ZincChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincChiselHead",16577)).setUnlocalizedName("Zinc Chisel Head");
BismuthSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSwordHead",16578)).setUnlocalizedName("Bismuth Sword Blade");
BismuthBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSwordHead",16579)).setUnlocalizedName("Bismuth Bronze Sword Blade");
BlackBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSwordHead",16580)).setUnlocalizedName("Black Bronze Sword Blade");
BlackSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSwordHead",16581)).setUnlocalizedName("Black Steel Sword Blade");
BlueSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSwordHead",16582)).setUnlocalizedName("Blue Steel Sword Blade");
BronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSwordHead",16583)).setUnlocalizedName("Bronze Sword Blade");
CopperSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSwordHead",16584)).setUnlocalizedName("Copper Sword Blade");
WroughtIronSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSwordHead",16585)).setUnlocalizedName("Wrought Iron Sword Blade");
RedSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSwordHead",16586)).setUnlocalizedName("Red Steel Sword Blade");
RoseGoldSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSwordHead",16587)).setUnlocalizedName("Rose Gold Sword Blade");
SteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSwordHead",16588)).setUnlocalizedName("Steel Sword Blade");
TinSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSwordHead",16589)).setUnlocalizedName("Tin Sword Blade");
ZincSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSwordHead",16590)).setUnlocalizedName("Zinc Sword Blade");
BismuthMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthMaceHead",16591)).setUnlocalizedName("Bismuth Mace Head");
BismuthBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeMaceHead",16592)).setUnlocalizedName("Bismuth Bronze Mace Head");
BlackBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeMaceHead",16593)).setUnlocalizedName("Black Bronze Mace Head");
BlackSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelMaceHead",16594)).setUnlocalizedName("Black Steel Mace Head");
BlueSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelMaceHead",16595)).setUnlocalizedName("Blue Steel Mace Head");
BronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeMaceHead",16596)).setUnlocalizedName("Bronze Mace Head");
CopperMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperMaceHead",16597)).setUnlocalizedName("Copper Mace Head");
WroughtIronMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronMaceHead",16598)).setUnlocalizedName("Wrought Iron Mace Head");
RedSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelMaceHead",16599)).setUnlocalizedName("Red Steel Mace Head");
RoseGoldMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldMaceHead",16600)).setUnlocalizedName("Rose Gold Mace Head");
SteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelMaceHead",16601)).setUnlocalizedName("Steel Mace Head");
TinMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinMaceHead",16602)).setUnlocalizedName("Tin Mace Head");
ZincMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincMaceHead",16603)).setUnlocalizedName("Zinc Mace Head");
BismuthSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSawHead",16604)).setUnlocalizedName("Bismuth Saw Blade");
BismuthBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSawHead",16605)).setUnlocalizedName("Bismuth Bronze Saw Blade");
BlackBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSawHead",16606)).setUnlocalizedName("Black Bronze Saw Blade");
BlackSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSawHead",16607)).setUnlocalizedName("Black Steel Saw Blade");
BlueSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSawHead",16608)).setUnlocalizedName("Blue Steel Saw Blade");
BronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSawHead",16609)).setUnlocalizedName("Bronze Saw Blade");
CopperSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSawHead",16610)).setUnlocalizedName("Copper Saw Blade");
WroughtIronSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSawHead",16611)).setUnlocalizedName("Wrought Iron Saw Blade");
RedSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSawHead",16612)).setUnlocalizedName("Red Steel Saw Blade");
RoseGoldSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSawHead",16613)).setUnlocalizedName("Rose Gold Saw Blade");
SteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSawHead",16614)).setUnlocalizedName("Steel Saw Blade");
TinSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSawHead",16615)).setUnlocalizedName("Tin Saw Blade");
ZincSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSawHead",16616)).setUnlocalizedName("Zinc Saw Blade");
HCBlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlackSteel",16617)).setUnlocalizedName("HC Black Steel Unshaped");
WeakBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakBlueSteel",16618)).setUnlocalizedName("Weak Blue Steel Unshaped");
HCBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlueSteel",16619)).setUnlocalizedName("HC Blue Steel Unshaped");
WeakRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakRedSteel",16621)).setUnlocalizedName("Weak Red Steel Unshaped");
HCRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCRedSteel",16622)).setUnlocalizedName("HC Red Steel Unshaped");
WeakSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakSteel",16623)).setUnlocalizedName("Weak Steel Unshaped");
HCSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCSteel",16624)).setUnlocalizedName("HC Steel Unshaped");
Coke = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Coke",16625)).setUnlocalizedName("Coke"));
BismuthProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthProPickHead",16626)).setUnlocalizedName("Bismuth ProPick Head");
BismuthBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeProPickHead",16627)).setUnlocalizedName("Bismuth Bronze ProPick Head");
BlackBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeProPickHead",16628)).setUnlocalizedName("Black Bronze ProPick Head");
BlackSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelProPickHead",16629)).setUnlocalizedName("Black Steel ProPick Head");
BlueSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelProPickHead",16630)).setUnlocalizedName("Blue Steel ProPick Head");
BronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeProPickHead",16631)).setUnlocalizedName("Bronze ProPick Head");
CopperProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperProPickHead",16632)).setUnlocalizedName("Copper ProPick Head");
WroughtIronProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronProPickHead",16633)).setUnlocalizedName("Wrought Iron ProPick Head");
RedSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelProPickHead",16634)).setUnlocalizedName("Red Steel ProPick Head");
RoseGoldProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldProPickHead",16635)).setUnlocalizedName("Rose Gold ProPick Head");
SteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelProPickHead",16636)).setUnlocalizedName("Steel ProPick Head");
TinProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinProPickHead",16637)).setUnlocalizedName("Tin ProPick Head");
ZincProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincProPickHead",16638)).setUnlocalizedName("Zinc ProPick Head");
Flux = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Flux",16639)).setUnlocalizedName("Flux"));
/**
* Scythe
* */
int num = 16643;
BismuthScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthScythe",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Scythe").setMaxDamage(BismuthUses);num++;
BismuthBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthBronzeScythe",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Scythe").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackBronzeScythe",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Scythe").setMaxDamage(BlackBronzeUses);num++;
BlackSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackSteelScythe",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Scythe").setMaxDamage(BlackSteelUses);num++;
BlueSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlueSteelScythe",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Scythe").setMaxDamage(BlueSteelUses);num++;
BronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BronzeScythe",num),BronzeToolMaterial).setUnlocalizedName("Bronze Scythe").setMaxDamage(BronzeUses);num++;
CopperScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","CopperScythe",num),CopperToolMaterial).setUnlocalizedName("Copper Scythe").setMaxDamage(CopperUses);num++;
WroughtIronScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","WroughtIronScythe",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Scythe").setMaxDamage(WroughtIronUses);num++;
RedSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RedSteelScythe",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Scythe").setMaxDamage(RedSteelUses);num++;
RoseGoldScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RoseGoldScythe",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Scythe").setMaxDamage(RoseGoldUses);num++;
SteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","SteelScythe",num),SteelToolMaterial).setUnlocalizedName("Steel Scythe").setMaxDamage(SteelUses);num++;
TinScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","TinScythe",num),TinToolMaterial).setUnlocalizedName("Tin Scythe").setMaxDamage(TinUses);num++;
ZincScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","ZincScythe",num),ZincToolMaterial).setUnlocalizedName("Zinc Scythe").setMaxDamage(ZincUses);num++;
BismuthScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthScytheHead",num)).setUnlocalizedName("Bismuth Scythe Blade");num++;
BismuthBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeScytheHead",num)).setUnlocalizedName("Bismuth Bronze Scythe Blade");num++;
BlackBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeScytheHead",num)).setUnlocalizedName("Black Bronze Scythe Blade");num++;
BlackSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelScytheHead",num)).setUnlocalizedName("Black Steel Scythe Blade");num++;
BlueSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelScytheHead",num)).setUnlocalizedName("Blue Steel Scythe Blade");num++;
BronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeScytheHead",num)).setUnlocalizedName("Bronze Scythe Blade");num++;
CopperScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperScytheHead",num)).setUnlocalizedName("Copper Scythe Blade");num++;
WroughtIronScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronScytheHead",num)).setUnlocalizedName("Wrought Iron Scythe Blade");num++;
RedSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelScytheHead",num)).setUnlocalizedName("Red Steel Scythe Blade");num++;
RoseGoldScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldScytheHead",num)).setUnlocalizedName("Rose Gold Scythe Blade");num++;
SteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelScytheHead",num)).setUnlocalizedName("Steel Scythe Blade");num++;
TinScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinScytheHead",num)).setUnlocalizedName("Tin Scythe Blade");num++;
ZincScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincScytheHead",num)).setUnlocalizedName("Zinc Scythe Blade");num++;
WoodenBucketEmpty = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketEmpty",num), 0)).setUnlocalizedName("Wooden Bucket Empty");num++;
WoodenBucketWater = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketWater",num), TFCBlocks.finiteWater.blockID)).setUnlocalizedName("Wooden Bucket Water").setContainerItem(WoodenBucketEmpty);num++;
WoodenBucketMilk = (new ItemCustomBucketMilk(TFC_Settings.getIntFor(config,"item","WoodenBucketMilk",num))).setUnlocalizedName("Wooden Bucket Milk").setContainerItem(WoodenBucketEmpty);num++;
BismuthKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthKnifeHead",num)).setUnlocalizedName("Bismuth Knife Blade");num++;
BismuthBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnifeHead",num)).setUnlocalizedName("Bismuth Bronze Knife Blade");num++;
BlackBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeKnifeHead",num)).setUnlocalizedName("Black Bronze Knife Blade");num++;
BlackSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelKnifeHead",num)).setUnlocalizedName("Black Steel Knife Blade");num++;
BlueSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelKnifeHead",num)).setUnlocalizedName("Blue Steel Knife Blade");num++;
BronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeKnifeHead",num)).setUnlocalizedName("Bronze Knife Blade");num++;
CopperKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperKnifeHead",num)).setUnlocalizedName("Copper Knife Blade");num++;
WroughtIronKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronKnifeHead",num)).setUnlocalizedName("Wrought Iron Knife Blade");num++;
RedSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelKnifeHead",num)).setUnlocalizedName("Red Steel Knife Blade");num++;
RoseGoldKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldKnifeHead",num)).setUnlocalizedName("Rose Gold Knife Blade");num++;
SteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelKnifeHead",num)).setUnlocalizedName("Steel Knife Blade");num++;
TinKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinKnifeHead",num)).setUnlocalizedName("Tin Knife Blade");num++;
ZincKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincKnifeHead",num)).setUnlocalizedName("Zinc Knife Blade");num++;
BismuthKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthKnife",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Knife").setMaxDamage(BismuthUses);num++;
BismuthBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnife",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Knife").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackBronzeKnife",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Knife").setMaxDamage(BlackBronzeUses);num++;
BlackSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackSteelKnife",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Knife").setMaxDamage(BlackSteelUses);num++;
BlueSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlueSteelKnife",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Knife").setMaxDamage(BlueSteelUses);num++;
BronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BronzeKnife",num),BronzeToolMaterial).setUnlocalizedName("Bronze Knife").setMaxDamage(BronzeUses);num++;
CopperKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","CopperKnife",num),CopperToolMaterial).setUnlocalizedName("Copper Knife").setMaxDamage(CopperUses);num++;
WroughtIronKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","WroughtIronKnife",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Knife").setMaxDamage(WroughtIronUses);num++;
RedSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RedSteelKnife",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Knife").setMaxDamage(RedSteelUses);num++;
RoseGoldKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RoseGoldKnife",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Knife").setMaxDamage(RoseGoldUses);num++;
SteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","SteelKnife",num),SteelToolMaterial).setUnlocalizedName("Steel Knife").setMaxDamage(SteelUses);num++;
TinKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","TinKnife",num),TinToolMaterial).setUnlocalizedName("Tin Knife").setMaxDamage(TinUses);num++;
ZincKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","ZincKnife",num),ZincToolMaterial).setUnlocalizedName("Zinc Knife").setMaxDamage(ZincUses);num++;
LooseRock = (new ItemLooseRock(TFC_Settings.getIntFor(config,"item","LooseRock",num)).setUnlocalizedName("LooseRock"));num++;
FlatRock = (new ItemFlatRock(TFC_Settings.getIntFor(config,"item","FlatRock",num)).setUnlocalizedName("FlatRock"));num++;
IgInStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
SedStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgExStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
MMStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgInStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
SedStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgExStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
MMStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgInStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
SedStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
IgExStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
MMStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
StoneKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneKnifeHead",num)).setUnlocalizedName("Stone Knife Blade");num++;
StoneHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneHammerHead",num)).setUnlocalizedName("Stone Hammer Head");num++;
StoneKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","StoneKnife",num),IgExToolMaterial).setUnlocalizedName("Stone Knife").setMaxDamage(IgExStoneUses);num++;
SmallOreChunk = new ItemOreSmall(TFC_Settings.getIntFor(config,"item","SmallOreChunk",num++)).setUnlocalizedName("Small Ore");
SinglePlank = new ItemPlank(TFC_Settings.getIntFor(config,"item","SinglePlank",num++)).setUnlocalizedName("SinglePlank");
RedSteelBucketEmpty = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketEmpty",num++), 0)).setUnlocalizedName("Red Steel Bucket Empty");
- RedSteelBucketWater = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketWater",num++), Block.waterMoving.blockID)).setUnlocalizedName("Red Steel Bucket Water");
+ RedSteelBucketWater = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketWater",num++), Block.waterMoving.blockID)).setUnlocalizedName("Red Steel Bucket Water").setContainerItem(RedSteelBucketEmpty);
BlueSteelBucketEmpty = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketEmpty",num++), 0)).setUnlocalizedName("Blue Steel Bucket Empty");
- BlueSteelBucketLava = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketLava",num++), Block.lavaMoving.blockID)).setUnlocalizedName("Blue Steel Bucket Lava");
+ BlueSteelBucketLava = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketLava",num++), Block.lavaMoving.blockID)).setUnlocalizedName("Blue Steel Bucket Lava").setContainerItem(BlueSteelBucketEmpty);
Quern = new ItemTerra(TFC_Settings.getIntFor(config,"item","Quern",num++)).setUnlocalizedName("Quern").setMaxDamage(250);
FlintSteel = new ItemFlintSteel(TFC_Settings.getIntFor(config,"item","FlintSteel",num++)).setUnlocalizedName("flintAndSteel").setMaxDamage(200);
DoorOak = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorOak", num++), 0).setUnlocalizedName("Oak Door");
DoorAspen = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAspen", num++), 1).setUnlocalizedName("Aspen Door");
DoorBirch = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorBirch", num++), 2).setUnlocalizedName("Birch Door");
DoorChestnut = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorChestnut", num++), 3).setUnlocalizedName("Chestnut Door");
DoorDouglasFir = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorDouglasFir", num++), 4).setUnlocalizedName("Douglas Fir Door");
DoorHickory = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorHickory", num++), 5).setUnlocalizedName("Hickory Door");
DoorMaple = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorMaple", num++), 6).setUnlocalizedName("Maple Door");
DoorAsh = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAsh", num++), 7).setUnlocalizedName("Ash Door");
DoorPine = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorPine", num++), 8).setUnlocalizedName("Pine Door");
DoorSequoia = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSequoia", num++), 9).setUnlocalizedName("Sequoia Door");
DoorSpruce = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSpruce", num++), 10).setUnlocalizedName("Spruce Door");
DoorSycamore = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSycamore", num++), 11).setUnlocalizedName("Sycamore Door");
DoorWhiteCedar = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteCedar", num++), 12).setUnlocalizedName("White Cedar Door");
DoorWhiteElm = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteElm", num++), 13).setUnlocalizedName("White Elm Door");
DoorWillow = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWillow", num++), 14).setUnlocalizedName("Willow Door");
DoorKapok = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorKapok", num++), 15).setUnlocalizedName("Kapok Door");
Blueprint = new ItemBlueprint(TFC_Settings.getIntFor(config,"item","Blueprint", num++));
writabeBookTFC = new ItemWritableBookTFC(TFC_Settings.getIntFor(config,"item","WritableBookTFC", num++),"Fix Me I'm Broken").setUnlocalizedName("book");
WoolYarn = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolYarn", num++)).setUnlocalizedName("WoolYarn").setCreativeTab(TFCTabs.TFCMaterials);
Wool = new ItemTerra(TFC_Settings.getIntFor(config,"item","Wool",num++)).setUnlocalizedName("Wool").setCreativeTab(TFCTabs.TFCMaterials);
WoolCloth = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolCloth", num++)).setUnlocalizedName("WoolCloth").setCreativeTab(TFCTabs.TFCMaterials);
Spindle = new ItemSpindle(TFC_Settings.getIntFor(config,"item","Spindle",num++),SedToolMaterial).setUnlocalizedName("Spindle").setCreativeTab(TFCTabs.TFCMaterials);
ClaySpindle = new ItemTerra(TFC_Settings.getIntFor(config, "item", "ClaySpindle", num++)).setFolder("tools/").setUnlocalizedName("Clay Spindle").setCreativeTab(TFCTabs.TFCMaterials);
SpindleHead = new ItemTerra(TFC_Settings.getIntFor(config, "item", "SpindleHead", num++)).setFolder("toolheads/").setUnlocalizedName("Spindle Head").setCreativeTab(TFCTabs.TFCMaterials);
StoneBrick = (new ItemStoneBrick(TFC_Settings.getIntFor(config,"item","ItemStoneBrick2",num++)).setFolder("tools/").setUnlocalizedName("ItemStoneBrick"));
Mortar = new ItemTerra(TFC_Settings.getIntFor(config,"item","Mortar",num++)).setFolder("tools/").setUnlocalizedName("Mortar").setCreativeTab(TFCTabs.TFCMaterials);
Limewater = new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","Limewater",num++),0).setFolder("tools/").setUnlocalizedName("Lime Water").setContainerItem(WoodenBucketEmpty).setCreativeTab(TFCTabs.TFCMaterials);
Hide = new ItemTerra(TFC_Settings.getIntFor(config,"item","Hide",num++)).setFolder("tools/").setUnlocalizedName("Hide").setCreativeTab(TFCTabs.TFCMaterials);
SoakedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","SoakedHide",num++)).setFolder("tools/").setUnlocalizedName("Soaked Hide").setCreativeTab(TFCTabs.TFCMaterials);
ScrapedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","ScrapedHide",num++)).setFolder("tools/").setUnlocalizedName("Scraped Hide").setCreativeTab(TFCTabs.TFCMaterials);
PrepHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","PrepHide",num++)).setFolder("tools/").setFolder("tools/").setUnlocalizedName("Prep Hide").setCreativeTab(TFCTabs.TFCMaterials);
TerraLeather = new ItemTerra(TFC_Settings.getIntFor(config,"item","TFCLeather",num++)).setFolder("tools/").setUnlocalizedName("TFC Leather").setCreativeTab(TFCTabs.TFCMaterials);
SheepSkin = new ItemTerra(TFC_Settings.getIntFor(config,"item","SheepSkin",num++)).setFolder("tools/").setUnlocalizedName("Sheep Skin").setCreativeTab(TFCTabs.TFCMaterials);
muttonRaw = new ItemTerra(TFC_Settings.getIntFor(config,"item","muttonRaw",num++)).setFolder("food/").setUnlocalizedName("Mutton Raw");
muttonCooked = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","muttonCooked",num++), 40, 0.8F, true, 48).setUnlocalizedName("Mutton Cooked");
FlatLeather = (new ItemFlatLeather(TFC_Settings.getIntFor(config,"items","FlatLeather2",num++)).setFolder("tools/").setUnlocalizedName("Flat Leather"));
PotteryJug = new ItemPotteryJug(TFC_Settings.getIntFor(config,"items","PotteryJug",num++)).setUnlocalizedName("Jug");
PotterySmallVessel = new ItemPotterySmallVessel(TFC_Settings.getIntFor(config,"items","PotterySmallVessel",num++)).setUnlocalizedName("Small Vessel");
PotteryLargeVessel = new ItemPotteryLargeVessel(TFC_Settings.getIntFor(config,"items","PotteryLargeVessel",num++)).setUnlocalizedName("Large Vessel");
PotteryPot = new ItemPotteryPot(TFC_Settings.getIntFor(config,"items","PotteryPot",num++)).setUnlocalizedName("Pot");
CeramicMold = new ItemPotteryBase(TFC_Settings.getIntFor(config,"item","CeramicMold",16409)).setMetaNames(new String[]{"Clay Mold","Ceramic Mold"}).setUnlocalizedName("Mold");
Straw = new ItemTerra(TFC_Settings.getIntFor(config,"items","Straw",num++)).setFolder("plants/").setUnlocalizedName("Straw");
/**Plans*/
num = 20000;
SetupPlans(num);
/**Food related items*/
num = 18000;
SetupFood(num);
/**Armor Crafting related items*/
num = 19000;
SetupArmor(num);
Recipes.Doors = new Item[]{DoorOak, DoorAspen, DoorBirch, DoorChestnut, DoorDouglasFir,
DoorHickory, DoorMaple, DoorAsh, DoorPine, DoorSequoia, DoorSpruce, DoorSycamore,
DoorWhiteCedar, DoorWhiteElm, DoorWillow, DoorKapok};
Recipes.Axes = new Item[]{SedAxe,IgInAxe,IgExAxe,MMAxe,
BismuthAxe,BismuthBronzeAxe,BlackBronzeAxe,
BlackSteelAxe,BlueSteelAxe,BronzeAxe,CopperAxe,
WroughtIronAxe,RedSteelAxe,RoseGoldAxe,SteelAxe,
TinAxe,ZincAxe};
Recipes.Chisels = new Item[]{BismuthChisel,BismuthBronzeChisel,BlackBronzeChisel,
BlackSteelChisel,BlueSteelChisel,BronzeChisel,CopperChisel,
WroughtIronChisel,RedSteelChisel,RoseGoldChisel,SteelChisel,
TinChisel,ZincChisel};
Recipes.Saws = new Item[]{BismuthSaw,BismuthBronzeSaw,BlackBronzeSaw,
BlackSteelSaw,BlueSteelSaw,BronzeSaw,CopperSaw,
WroughtIronSaw,RedSteelSaw,RoseGoldSaw,SteelSaw,
TinSaw,ZincSaw};
Recipes.Knives = new Item[]{StoneKnife,BismuthKnife,BismuthBronzeKnife,BlackBronzeKnife,
BlackSteelKnife,BlueSteelKnife,BronzeKnife,CopperKnife,
WroughtIronKnife,RedSteelKnife,RoseGoldKnife,SteelKnife,
TinKnife,ZincKnife};
Recipes.MeltedMetal = new Item[]{BismuthUnshaped, BismuthBronzeUnshaped,BlackBronzeUnshaped,
TFCItems.BlackSteelUnshaped,TFCItems.BlueSteelUnshaped,TFCItems.BrassUnshaped,TFCItems.BronzeUnshaped,
TFCItems.CopperUnshaped,TFCItems.GoldUnshaped,
TFCItems.WroughtIronUnshaped,TFCItems.LeadUnshaped,TFCItems.NickelUnshaped,TFCItems.PigIronUnshaped,
TFCItems.PlatinumUnshaped,TFCItems.RedSteelUnshaped,TFCItems.RoseGoldUnshaped,TFCItems.SilverUnshaped,
TFCItems.SteelUnshaped,TFCItems.SterlingSilverUnshaped,
TFCItems.TinUnshaped,TFCItems.ZincUnshaped, TFCItems.HCSteelUnshaped, TFCItems.WeakSteelUnshaped,
TFCItems.HCBlackSteelUnshaped, TFCItems.HCBlueSteelUnshaped, TFCItems.HCRedSteelUnshaped,
TFCItems.WeakBlueSteelUnshaped, TFCItems.WeakRedSteelUnshaped};
Recipes.Hammers = new Item[]{TFCItems.StoneHammer,TFCItems.BismuthHammer,TFCItems.BismuthBronzeHammer,TFCItems.BlackBronzeHammer,
TFCItems.BlackSteelHammer,TFCItems.BlueSteelHammer,TFCItems.BronzeHammer,TFCItems.CopperHammer,
TFCItems.WroughtIronHammer,TFCItems.RedSteelHammer,TFCItems.RoseGoldHammer,TFCItems.SteelHammer,
TFCItems.TinHammer,TFCItems.ZincHammer};
Recipes.Spindle = new Item[]{TFCItems.Spindle};
Recipes.Gems = new Item[]{TFCItems.GemAgate, TFCItems.GemAmethyst, TFCItems.GemBeryl, TFCItems.GemDiamond, TFCItems.GemEmerald, TFCItems.GemGarnet,
TFCItems.GemJade, TFCItems.GemJasper, TFCItems.GemOpal,TFCItems.GemRuby,TFCItems.GemSapphire,TFCItems.GemTopaz,TFCItems.GemTourmaline};
Meals = new Item[]{MealMoveSpeed, MealDigSpeed, MealDamageBoost, MealJump, MealDamageResist,
MealFireResist, MealWaterBreathing, MealNightVision};
((TFCTabs)TFCTabs.TFCTools).setTabIconItemIndex(TFCItems.RoseGoldHammer.itemID);
((TFCTabs)TFCTabs.TFCMaterials).setTabIconItemIndex(TFCItems.Spindle.itemID);
((TFCTabs)TFCTabs.TFCUnfinished).setTabIconItemIndex(TFCItems.RoseGoldHammerHead.itemID);
((TFCTabs)TFCTabs.TFCArmor).setTabIconItemIndex(TFCItems.SteelHelmet.itemID);
System.out.println(new StringBuilder().append("[TFC] Done Loading Items").toString());
if (config != null) {
config.save();
}
}
public static void SetupPlans(int num)
{
PickaxeHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","PickaxeHeadPlan",num)).setUnlocalizedName("PickaxeHeadPlan");num++;
ShovelHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ShovelHeadPlan",num)).setUnlocalizedName("ShovelHeadPlan");num++;
HoeHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","HoeHeadPlan",num)).setUnlocalizedName("HoeHeadPlan");num++;
AxeHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","AxeHeadPlan",num)).setUnlocalizedName("AxeHeadPlan");num++;
HammerHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","HammerHeadPlan",num)).setUnlocalizedName("HammerHeadPlan");num++;
ChiselHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ChiselHeadPlan",num)).setUnlocalizedName("ChiselHeadPlan");num++;
SwordBladePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","SwordBladePlan",num)).setUnlocalizedName("SwordBladePlan");num++;
MaceHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","MaceHeadPlan",num)).setUnlocalizedName("MaceHeadPlan");num++;
SawBladePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","SawBladePlan",num)).setUnlocalizedName("SawBladePlan");num++;
ProPickHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ProPickHeadPlan",num)).setUnlocalizedName("ProPickHeadPlan");num++;
HelmetPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","HelmetPlan",num)).setUnlocalizedName("HelmetPlan");num++;
ChestplatePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ChestplatePlan",num)).setUnlocalizedName("ChestplatePlan");num++;
GreavesPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","GreavesPlan",num)).setUnlocalizedName("GreavesPlan");num++;
BootsPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","BootsPlan",num)).setUnlocalizedName("BootsPlan");num++;
ScythePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ScythePlan",num)).setUnlocalizedName("ScythePlan");num++;
KnifePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","KnifePlan",num)).setUnlocalizedName("KnifePlan");num++;
BucketPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","BucketPlan",num)).setUnlocalizedName("BucketPlan");num++;
}
public static void SetupFood(int num)
{
FruitTreeSapling1 = new ItemFruitTreeSapling(TFC_Settings.getIntFor(config,"item","FruitSapling1", num), 0).setUnlocalizedName("FruitSapling1");num++;
FruitTreeSapling2 = new ItemFruitTreeSapling(TFC_Settings.getIntFor(config,"item","FruitSapling2", num), 8).setUnlocalizedName("FruitSapling2");num++;
RedApple = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Red Apple",num), 15, 0.1F, false, 2).setUnlocalizedName("Red Apple");num++;
Banana = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Banana",num), 10, 0.1F, false, 3).setUnlocalizedName("Banana");num++;
Orange = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Orange",num), 10, 0.1F, false, 4).setUnlocalizedName("Orange");num++;
GreenApple = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Green Apple",num), 15, 0.1F, false, 5).setUnlocalizedName("Green Apple");num++;
Lemon = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Lemon",num), 10, 0.03F, false, 6).setUnlocalizedName("Lemon");num++;
Olive = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Olive",num), 10, 0.05F, false, 7).setUnlocalizedName("Olive");num++;
Cherry = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Cherry",num), 10, 0.03F, false, 8).setUnlocalizedName("Cherry");num++;
Peach = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Peach",num), 12, 0.1F, false, 9).setUnlocalizedName("Peach");num++;
Plum = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Plum",num), 10, 0.1F, false, 10).setUnlocalizedName("Plum");num++;
EggCooked = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Meat.EggCooked",num), 25, 0.4F, false, 11).setUnlocalizedName("Egg Cooked");num++;
WheatGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","WheatGrain",num++), 1, 0.4F, false, 12).setUnlocalizedName("Wheat Grain");
BarleyGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","BarleyGrain",num++), 1, 0.4F, false, 14).setUnlocalizedName("Barley Grain");
OatGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","OatGrain",num++), 1, 0.4F, false, 16).setUnlocalizedName("Oat Grain");
RyeGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RyeGrain",num++), 1, 0.4F, false, 18).setUnlocalizedName("Rye Grain");
RiceGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RiceGrain",num++), 1, 0.4F, false, 20).setUnlocalizedName("Rice Grain");
MaizeEar = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","MaizeEar",num++), 10, 0.4F, false, 22).setUnlocalizedName("Maize Ear");
Tomato = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Tomato",num++), 15, 0.4F, false, 24).setUnlocalizedName("Tomato");
Potato = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Potato",num++), 22, 0.4F, false, 25).setUnlocalizedName("Potato");
Onion = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Onion",num++), 10, 0.4F, false, 27).setUnlocalizedName("Onion");
Cabbage = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Cabbage",num++), 20, 0.4F, false, 28).setUnlocalizedName("Cabbage");
Garlic = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Garlic",num++), 10, 0.4F, false, 29).setUnlocalizedName("Garlic");
Carrot = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Carrot",num++), 5, 0.4F, false, 30).setUnlocalizedName("Carrot");
Sugarcane = new ItemTerra(TFC_Settings.getIntFor(config,"item","Sugarcane",num++)).setFolder("plants/").setUnlocalizedName("Sugarcane");
Hemp = new ItemTerra(TFC_Settings.getIntFor(config,"item","Hemp",num++)).setFolder("plants/").setUnlocalizedName("Hemp");
Soybean = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Soybeans",num++), 10, 0.4F, false, 31).setUnlocalizedName("Soybeans");
Greenbeans = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Greenbeans",num++), 10, 0.4F, false, 32).setUnlocalizedName("Greenbeans");
GreenBellPepper = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","GreenBellPepper",num++), 10, 0.4F, false, 34).setUnlocalizedName("Green Bell Pepper");
YellowBellPepper = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","YellowBellPepper",num++), 10, 0.4F, false, 35).setUnlocalizedName("Yellow Bell Pepper");
RedBellPepper = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RedBellPepper",num++), 10, 0.4F, false, 36).setUnlocalizedName("Red Bell Pepper");
Squash = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Squash",num++), 12, 0.4F, false, 37).setUnlocalizedName("Squash");
WheatWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","WheatWhole",num++)).setFolder("food/").setUnlocalizedName("Wheat Whole");
BarleyWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","BarleyWhole",num++)).setFolder("food/").setUnlocalizedName("Barley Whole");
OatWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","OatWhole",num++)).setFolder("food/").setUnlocalizedName("Oat Whole");
RyeWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","RyeWhole",num++)).setFolder("food/").setUnlocalizedName("Rye Whole");
RiceWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","RiceWhole",num++)).setFolder("food/").setUnlocalizedName("Rice Whole");
MealGeneric = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealGeneric",num++)).setUnlocalizedName("MealGeneric");
MealMoveSpeed = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealMoveSpeed",num++)).setPotionEffect(new PotionEffect(Potion.moveSpeed.id,8000,4)).setUnlocalizedName("MealGeneric");
MealDigSpeed = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealDigSpeed",num++)).setPotionEffect(new PotionEffect(Potion.digSpeed.id,8000,4)).setUnlocalizedName("MealGeneric");
MealDamageBoost = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealDamageBoost",num++)).setPotionEffect(new PotionEffect(Potion.damageBoost.id,4000,4)).setUnlocalizedName("MealGeneric");
MealJump = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealJump",num++)).setPotionEffect(new PotionEffect(Potion.jump.id,8000,4)).setUnlocalizedName("MealGeneric");
MealDamageResist = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealDamageResist",num++)).setPotionEffect(new PotionEffect(Potion.resistance.id,8000,4)).setUnlocalizedName("MealGeneric");
MealFireResist = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealFireResist",num++)).setPotionEffect(new PotionEffect(Potion.fireResistance.id,8000,4)).setUnlocalizedName("MealGeneric");
MealWaterBreathing = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealWaterBreathing",num++)).setPotionEffect(new PotionEffect(Potion.waterBreathing.id,8000,4)).setUnlocalizedName("MealGeneric");
MealNightVision = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealNightVision",num++)).setPotionEffect(new PotionEffect(Potion.nightVision.id,4000,4)).setUnlocalizedName("MealGeneric");
WheatGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","WheatGround",num++)).setFolder("food/").setUnlocalizedName("Wheat Ground");
BarleyGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","BarleyGround",num++)).setFolder("food/").setUnlocalizedName("Barley Ground");
OatGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","OatGround",num++)).setFolder("food/").setUnlocalizedName("Oat Ground");
RyeGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","RyeGround",num++)).setFolder("food/").setUnlocalizedName("Rye Ground");
RiceGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","RiceGround",num++)).setFolder("food/").setUnlocalizedName("Rice Ground");
CornmealGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","CornmealGround",num++)).setFolder("food/").setUnlocalizedName("Cornmeal Ground");
WheatDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","WheatDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Wheat Dough");
BarleyDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","BarleyDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Barley Dough");
OatDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","OatDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Oat Dough");
RyeDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RyeDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Rye Dough");
RiceDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RiceDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Rice Dough");
CornmealDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","CornmealDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Cornmeal Dough");
BarleyBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","BarleyBread",num++), 25, 0.6F, false, 43).setUnlocalizedName("Barley Bread");
OatBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","OatBread",num++), 25, 0.6F, false, 44).setUnlocalizedName("Oat Bread");
RyeBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RyeBread",num++), 25, 0.6F, false, 45).setUnlocalizedName("Rye Bread");
RiceBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RiceBread",num++), 25, 0.6F, false, 46).setUnlocalizedName("Rice Bread");
CornBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","CornBread",num++), 25, 0.6F, false, 47).setUnlocalizedName("Corn Bread");
num = 18900;
SeedsWheat = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsWheat",num++),0).setUnlocalizedName("Seeds Wheat");
SeedsBarley = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsBarley",num++),5).setUnlocalizedName("Seeds Barley");
SeedsRye = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsRye",num++),7).setUnlocalizedName("Seeds Rye");
SeedsOat = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsOat",num++),9).setUnlocalizedName("Seeds Oat");
SeedsRice = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsRice",num++),11).setUnlocalizedName("Seeds Rice");
SeedsMaize = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsMaize",num++),2).setUnlocalizedName("Seeds Maize");
SeedsPotato = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsPotato",num++),13).setUnlocalizedName("Seeds Potato");
SeedsOnion = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsOnion",num++),15).setUnlocalizedName("Seeds Onion");
SeedsCabbage = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsCabbage",num++),16).setUnlocalizedName("Seeds Cabbage");
SeedsGarlic = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsGarlic",num++),17).setUnlocalizedName("Seeds Garlic");
SeedsCarrot = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsCarrot",num++),18).setUnlocalizedName("Seeds Carrot");
SeedsSugarcane = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsSugarcane",num++),21).setUnlocalizedName("Seeds Sugarcane");
SeedsHemp = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsHemp",num++),22).setUnlocalizedName("Seeds Hemp");
SeedsTomato = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsTomato",num++),4).setUnlocalizedName("Seeds Tomato");
SeedsYellowBellPepper = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsYellowBellPepper",num++),19).setUnlocalizedName("Seeds Yellow Bell Pepper");
SeedsRedBellPepper = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsRedBellPepper",num++),20).setUnlocalizedName("Seeds Red Bell Pepper");
SeedsSoybean = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsSoybean",num++),21).setUnlocalizedName("Seeds Soybean");
SeedsGreenbean = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsGreenbean",num++),22).setUnlocalizedName("Seeds Greenbean");
SeedsSquash = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsSquash",num++),23).setUnlocalizedName("Seeds Squash");
}
public static void SetupArmor(int num)
{
BismuthArmorMaterial = EnumHelper.addArmorMaterial("Bismuth", 200, new int[] {2,4,3,2}, 1);
BismuthBronzeArmorMaterial = EnumHelper.addArmorMaterial("BismuthBronze", 400, new int[] {4,6,5,4}, 1);
BlackBronzeArmorMaterial = EnumHelper.addArmorMaterial("BlackBronze", 400, new int[] {4,6,5,4}, 1);
BlackSteelArmorMaterial = EnumHelper.addArmorMaterial("BlackSteel", 700, new int[] {6,8,7,6}, 1);
BlueSteelArmorMaterial = EnumHelper.addArmorMaterial("BlueSteel", 800, new int[] {7,8,8,7}, 1);
BronzeArmorMaterial = EnumHelper.addArmorMaterial("Bronze", 420, new int[] {4,6,5,4}, 1);
CopperArmorMaterial = EnumHelper.addArmorMaterial("Copper", 300, new int[] {3,5,4,3}, 1);
IronArmorMaterial = EnumHelper.addArmorMaterial("Iron", 500, new int[] {5,7,6,5}, 1);
RedSteelArmorMaterial = EnumHelper.addArmorMaterial("RedSteel", 800, new int[] {7,8,8,7}, 1);
RoseGoldArmorMaterial = EnumHelper.addArmorMaterial("RoseGold", 400, new int[] {4,6,5,4}, 1);
SteelArmorMaterial = EnumHelper.addArmorMaterial("Steel", 600, new int[] {6,8,7,6}, 1);
TinArmorMaterial = EnumHelper.addArmorMaterial("Tin", 200, new int[] {2,4,3,2}, 1);
ZincArmorMaterial = EnumHelper.addArmorMaterial("Zinc", 200, new int[] {2,4,3,2}, 1);
String[] Names = {"Bismuth", "Bismuth Bronze", "Black Bronze", "Black Steel", "Blue Steel", "Bronze", "Copper", "Wrought Iron", "Red Steel", "Rose Gold", "Steel", "Tin", "Zinc"};
String[] NamesNS = {"Bismuth", "BismuthBronze", "BlackBronze", "BlackSteel", "BlueSteel", "Bronze", "Copper", "WroughtIron", "RedSteel", "RoseGold", "Steel", "Tin", "Zinc"};
String[] NamesNSO = {"Brass", "Gold", "Lead", "Nickel", "Pig Iron", "Platinum", "Silver", "Sterling Silver"};
CommonProxy proxy = TerraFirmaCraft.proxy;
EnumArmorMaterial[] mats = new EnumArmorMaterial[]{TFCItems.BismuthArmorMaterial,TFCItems.BismuthBronzeArmorMaterial,TFCItems.BlackBronzeArmorMaterial,TFCItems.BlackSteelArmorMaterial,TFCItems.BlueSteelArmorMaterial,
TFCItems.BronzeArmorMaterial,TFCItems.CopperArmorMaterial,TFCItems.IronArmorMaterial,TFCItems.RedSteelArmorMaterial,TFCItems.RoseGoldArmorMaterial,
TFCItems.SteelArmorMaterial,TFCItems.TinArmorMaterial,TFCItems.ZincArmorMaterial};
int i = 0;
TFCItems.BismuthSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Bismuth Sheet"));num++;
TFCItems.BismuthBronzeSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Bismuth Bronze Sheet"));num++;
TFCItems.BlackBronzeSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Black Bronze Sheet"));num++;
TFCItems.BlackSteelSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Black Steel Sheet"));num++;
TFCItems.BlueSteelSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Blue Steel Sheet"));num++;
TFCItems.BronzeSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Bronze Sheet"));num++;
TFCItems.CopperSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Copper Sheet"));num++;
TFCItems.WroughtIronSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Wrought Iron Sheet"));num++;
TFCItems.RedSteelSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Red Steel Sheet"));num++;
TFCItems.RoseGoldSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Rose Gold Sheet"));num++;
TFCItems.SteelSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Steel Sheet"));num++;
TFCItems.TinSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Tin Sheet"));num++;
TFCItems.ZincSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Zinc Sheet"));num++;
i = 0;
TFCItems.BismuthSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Bismuth Double Sheet"));num++;
TFCItems.BismuthBronzeSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Bismuth Bronze Double Sheet"));num++;
TFCItems.BlackBronzeSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Black Bronze Double Sheet"));num++;
TFCItems.BlackSteelSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Black Steel Double Sheet"));num++;
TFCItems.BlueSteelSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Blue Steel Double Sheet"));num++;
TFCItems.BronzeSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Bronze Double Sheet"));num++;
TFCItems.CopperSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Copper Double Sheet"));num++;
TFCItems.WroughtIronSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Wrought Iron Double Sheet"));num++;
TFCItems.RedSteelSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Red Steel Double Sheet"));num++;
TFCItems.RoseGoldSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Rose Gold Double Sheet"));num++;
TFCItems.SteelSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Steel Double Sheet"));num++;
TFCItems.TinSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Tin Double Sheet"));num++;
TFCItems.ZincSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Zinc Double Sheet"));num++;
i = 0;
TFCItems.BismuthUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BismuthBronzeUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BlackBronzeUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BlackSteelUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BlueSteelUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BronzeUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.CopperUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.WroughtIronUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.RedSteelUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.RoseGoldUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.SteelUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.TinUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.ZincUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
i = 0;
TFCItems.BismuthBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BismuthBronzeBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BlackBronzeBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BlackSteelBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BlueSteelBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BronzeBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.CopperBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.WroughtIronBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.RedSteelBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.RoseGoldBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.SteelBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.TinBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.ZincBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
i = 0;
TFCItems.BismuthUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BismuthBronzeUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BlackBronzeUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BlackSteelUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BlueSteelUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BronzeUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.CopperUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.WroughtIronUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.RedSteelUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.RoseGoldUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.SteelUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.TinUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.ZincUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
i = 0;
TFCItems.BismuthGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BismuthBronzeGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BlackBronzeGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BlackSteelGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BlueSteelGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BronzeGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.CopperGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.WroughtIronGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.RedSteelGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.RoseGoldGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.SteelGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.TinGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.ZincGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
i = 0;
TFCItems.BismuthUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BismuthBronzeUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BlackBronzeUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BlackSteelUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BlueSteelUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BronzeUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.CopperUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.WroughtIronUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.RedSteelUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.RoseGoldUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.SteelUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.TinUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.ZincUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
i = 0;
TFCItems.BismuthChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BismuthBronzeChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BlackBronzeChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BlackSteelChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BlueSteelChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BronzeChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.CopperChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.WroughtIronChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.RedSteelChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.RoseGoldChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.SteelChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.TinChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.ZincChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
i = 0;
TFCItems.BismuthUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BismuthBronzeUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BlackBronzeUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BlackSteelUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BlueSteelUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BronzeUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.CopperUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.WroughtIronUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.RedSteelUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.RoseGoldUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.SteelUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.TinUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.ZincUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
i = 0;
TFCItems.BismuthHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BismuthBronzeHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BlackBronzeHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BlackSteelHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BlueSteelHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BronzeHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.CopperHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.WroughtIronHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.RedSteelHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.RoseGoldHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.SteelHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.TinHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.ZincHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
i = 0;
TFCItems.BrassSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.GoldSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.LeadSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.NickelSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.PigIronSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.PlatinumSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.SilverSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.SterlingSilverSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
i = 0;
TFCItems.BrassSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.GoldSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.LeadSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.NickelSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.PigIronSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.PlatinumSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.SilverSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.SterlingSilverSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
}
public static Item[] Meals;
public static EnumArmorMaterial BismuthArmorMaterial;
public static EnumArmorMaterial BismuthBronzeArmorMaterial;
public static EnumArmorMaterial BlackBronzeArmorMaterial;
public static EnumArmorMaterial BlackSteelArmorMaterial;
public static EnumArmorMaterial BlueSteelArmorMaterial;
public static EnumArmorMaterial BronzeArmorMaterial;
public static EnumArmorMaterial CopperArmorMaterial;
public static EnumArmorMaterial IronArmorMaterial;
public static EnumArmorMaterial RedSteelArmorMaterial;
public static EnumArmorMaterial RoseGoldArmorMaterial;
public static EnumArmorMaterial SteelArmorMaterial;
public static EnumArmorMaterial TinArmorMaterial;
public static EnumArmorMaterial ZincArmorMaterial;
}
| false | true | public static void Setup()
{
try
{
config = new net.minecraftforge.common.Configuration(
new File(TerraFirmaCraft.proxy.getMinecraftDir(), "/config/TFC.cfg"));
config.load();
} catch (Exception e) {
System.out.println(new StringBuilder().append("[TFC] Error while trying to access item configuration!").toString());
config = null;
}
IgInToolMaterial = EnumHelper.addToolMaterial("IgIn", 1, IgInStoneUses, 7F, 10, 5);
SedToolMaterial = EnumHelper.addToolMaterial("Sed", 1, SedStoneUses, 6F, 10, 5);
IgExToolMaterial = EnumHelper.addToolMaterial("IgEx", 1, IgExStoneUses, 7F, 10, 5);
MMToolMaterial = EnumHelper.addToolMaterial("MM", 1, MMStoneUses, 6.5F, 10, 5);
BismuthToolMaterial = EnumHelper.addToolMaterial("Bismuth", 2, BismuthUses, BismuthEff, 65, 10);
BismuthBronzeToolMaterial = EnumHelper.addToolMaterial("BismuthBronze", 2, BismuthBronzeUses, BismuthBronzeEff, 85, 10);
BlackBronzeToolMaterial = EnumHelper.addToolMaterial("BlackBronze", 2, BlackBronzeUses, BlackBronzeEff, 100, 10);
BlackSteelToolMaterial = EnumHelper.addToolMaterial("BlackSteel", 2, BlackSteelUses, BlackSteelEff, 165, 12);
BlueSteelToolMaterial = EnumHelper.addToolMaterial("BlueSteel", 3, BlueSteelUses, BlueSteelEff, 185, 22);
BronzeToolMaterial = EnumHelper.addToolMaterial("Bronze", 2, BronzeUses, BronzeEff, 100, 13);
CopperToolMaterial = EnumHelper.addToolMaterial("Copper", 2, CopperUses, CopperEff, 85, 8);
IronToolMaterial = EnumHelper.addToolMaterial("Iron", 2, WroughtIronUses, WroughtIronEff, 135, 10);
RedSteelToolMaterial = EnumHelper.addToolMaterial("RedSteel", 3, RedSteelUses, RedSteelEff, 185, 22);
RoseGoldToolMaterial = EnumHelper.addToolMaterial("RoseGold", 2, RoseGoldUses, RoseGoldEff, 100, 20);
SteelToolMaterial = EnumHelper.addToolMaterial("Steel", 2, SteelUses, SteelEff, 150, 10);
TinToolMaterial = EnumHelper.addToolMaterial("Tin", 2, TinUses, TinEff, 65, 8);
ZincToolMaterial = EnumHelper.addToolMaterial("Zinc", 2, ZincUses, ZincEff, 65, 8);
System.out.println(new StringBuilder().append("[TFC] Loading Items").toString());
//Replace any vanilla Items here
Item.itemsList[Item.coal.itemID] = null; Item.itemsList[Item.coal.itemID] = (new TFC.Items.ItemCoal(7)).setUnlocalizedName("coal");
Item.itemsList[Item.stick.itemID] = null; Item.itemsList[Item.stick.itemID] = new ItemStick(24).setFull3D().setUnlocalizedName("stick");
Item.itemsList[Item.leather.itemID] = null; Item.itemsList[Item.leather.itemID] = new ItemTerra(Item.leather.itemID).setFull3D().setUnlocalizedName("leather");
Item.itemsList[Block.vine.blockID] = new ItemColored(Block.vine.blockID - 256, false);
minecartCrate = (new ItemCustomMinecart(TFC_Settings.getIntFor(config,"item","minecartCrate",16000), 1)).setUnlocalizedName("minecartChest");
Item.itemsList[5+256] = null; Item.itemsList[5+256] = (new ItemCustomBow(5)).setUnlocalizedName("bow");
Item.itemsList[63+256] = null; Item.itemsList[63+256] = new ItemTerra(63).setUnlocalizedName("porkchopRaw");
Item.itemsList[64+256] = null; Item.itemsList[64+256] = new ItemTerraFood(64, 35, 0.8F, true, 38).setFolder("").setUnlocalizedName("porkchopCooked");
Item.itemsList[93+256] = null; Item.itemsList[93+256] = new ItemTerra(93).setUnlocalizedName("fishRaw");
Item.itemsList[94+256] = null; Item.itemsList[94+256] = new ItemTerraFood(94, 30, 0.6F, true, 39).setFolder("").setUnlocalizedName("fishCooked");
Item.itemsList[107+256] = null; Item.itemsList[107+256] = new ItemTerra(107).setUnlocalizedName("beefRaw");
Item.itemsList[108+256] = null; Item.itemsList[108+256] = new ItemTerraFood(108, 40, 0.8F, true, 40).setFolder("").setUnlocalizedName("beefCooked");
Item.itemsList[109+256] = null; Item.itemsList[109+256] = new ItemTerra(109).setUnlocalizedName("chickenRaw");
Item.itemsList[110+256] = null; Item.itemsList[110+256] = new ItemTerraFood(110, 35, 0.6F, true, 41).setFolder("").setUnlocalizedName("chickenCooked");
Item.itemsList[41+256] = null; Item.itemsList[41+256] = (new ItemTerraFood(41, 25, 0.6F, false, 42)).setFolder("").setUnlocalizedName("bread");
Item.itemsList[88+256] = null; Item.itemsList[88+256] = (new ItemTerra(88)).setUnlocalizedName("egg");
Item.itemsList[Item.dyePowder.itemID] = null; Item.itemsList[Item.dyePowder.itemID] = new ItemDyeCustom(95).setUnlocalizedName("dyePowder");
Item.itemsList[Item.potion.itemID] = null; Item.itemsList[Item.potion.itemID] = (new ItemCustomPotion(117)).setUnlocalizedName("potion");
Item.itemsList[Block.tallGrass.blockID] = null; Item.itemsList[Block.tallGrass.blockID] = (new ItemColored(Block.tallGrass.blockID - 256, true)).setBlockNames(new String[] {"shrub", "grass", "fern"});
GoldPan = new ItemGoldPan(TFC_Settings.getIntFor(config,"item","GoldPan",16001)).setUnlocalizedName("GoldPan");
SluiceItem = new ItemSluice(TFC_Settings.getIntFor(config,"item","SluiceItem",16002)).setFolder("devices/").setUnlocalizedName("SluiceItem");
ProPickBismuth = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuth",16004)).setUnlocalizedName("Bismuth ProPick").setMaxDamage(BismuthUses);
ProPickBismuthBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuthBronze",16005)).setUnlocalizedName("Bismuth Bronze ProPick").setMaxDamage(BismuthBronzeUses);
ProPickBlackBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackBronze",16006)).setUnlocalizedName("Black Bronze ProPick").setMaxDamage(BlackBronzeUses);
ProPickBlackSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackSteel",16007)).setUnlocalizedName("Black Steel ProPick").setMaxDamage(BlackSteelUses);
ProPickBlueSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlueSteel",16008)).setUnlocalizedName("Blue Steel ProPick").setMaxDamage(BlueSteelUses);
ProPickBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBronze",16009)).setUnlocalizedName("Bronze ProPick").setMaxDamage(BronzeUses);
ProPickCopper = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickCopper",16010)).setUnlocalizedName("Copper ProPick").setMaxDamage(CopperUses);
ProPickIron = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickWroughtIron",16012)).setUnlocalizedName("Wrought Iron ProPick").setMaxDamage(WroughtIronUses);
ProPickRedSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRedSteel",16016)).setUnlocalizedName("Red Steel ProPick").setMaxDamage(RedSteelUses);
ProPickRoseGold = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRoseGold",16017)).setUnlocalizedName("Rose Gold ProPick").setMaxDamage(RoseGoldUses);
ProPickSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickSteel",16019)).setUnlocalizedName("Steel ProPick").setMaxDamage(SteelUses);
ProPickTin = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickTin",16021)).setUnlocalizedName("Tin ProPick").setMaxDamage(TinUses);
ProPickZinc = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickZinc",16022)).setUnlocalizedName("Zinc ProPick").setMaxDamage(ZincUses);
BismuthIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot",16028), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Ingot");
BismuthBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot",16029), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Ingot");
BlackBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot",16030), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Ingot");
BlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot",16031), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Ingot");
BlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot",16032), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Ingot");
BrassIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot",16033), EnumMetalType.BRASS).setUnlocalizedName("Brass Ingot");
BronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot",16034), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Ingot");
CopperIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot",16035), EnumMetalType.COPPER).setUnlocalizedName("Copper Ingot");
GoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot",16036), EnumMetalType.GOLD).setUnlocalizedName("Gold Ingot");
WroughtIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot",16037), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Ingot");
LeadIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot",16038), EnumMetalType.LEAD).setUnlocalizedName("Lead Ingot");
NickelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot",16039), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Ingot");
PigIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot",16040), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Ingot");
PlatinumIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot",16041), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Ingot");
RedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot",16042), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Ingot");
RoseGoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot",16043), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Ingot");
SilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot",16044), EnumMetalType.SILVER).setUnlocalizedName("Silver Ingot");
SteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot",16045), EnumMetalType.STEEL).setUnlocalizedName("Steel Ingot");
SterlingSilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot",16046), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Ingot");
TinIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot",16047), EnumMetalType.TIN).setUnlocalizedName("Tin Ingot");
ZincIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot",16048), EnumMetalType.ZINC).setUnlocalizedName("Zinc Ingot");
BismuthIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot2x",16049), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Double Ingot")).setSize(EnumSize.LARGE);
BismuthBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot2x",16050), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot2x",16051), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot2x",16052), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Double Ingot")).setSize(EnumSize.LARGE);
BlueSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot2x",16053), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Double Ingot")).setSize(EnumSize.LARGE);
BrassIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot2x",16054), EnumMetalType.BRASS).setUnlocalizedName("Brass Double Ingot")).setSize(EnumSize.LARGE);
BronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot2x",16055), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Double Ingot")).setSize(EnumSize.LARGE);
CopperIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot2x",16056), EnumMetalType.COPPER).setUnlocalizedName("Copper Double Ingot")).setSize(EnumSize.LARGE);
GoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot2x",16057), EnumMetalType.GOLD).setUnlocalizedName("Gold Double Ingot")).setSize(EnumSize.LARGE);
WroughtIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot2x",16058), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Double Ingot")).setSize(EnumSize.LARGE);
LeadIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot2x",16059), EnumMetalType.LEAD).setUnlocalizedName("Lead Double Ingot")).setSize(EnumSize.LARGE);
NickelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot2x",16060), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Double Ingot")).setSize(EnumSize.LARGE);
PigIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot2x",16061), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Double Ingot")).setSize(EnumSize.LARGE);
PlatinumIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot2x",16062), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Double Ingot")).setSize(EnumSize.LARGE);
RedSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot2x",16063), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Double Ingot")).setSize(EnumSize.LARGE);
RoseGoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot2x",16064), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Double Ingot")).setSize(EnumSize.LARGE);
SilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot2x",16065), EnumMetalType.SILVER).setUnlocalizedName("Silver Double Ingot")).setSize(EnumSize.LARGE);
SteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot2x",16066), EnumMetalType.STEEL).setUnlocalizedName("Steel Double Ingot")).setSize(EnumSize.LARGE);
SterlingSilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot2x",16067), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Double Ingot")).setSize(EnumSize.LARGE);
TinIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot2x",16068), EnumMetalType.TIN).setUnlocalizedName("Tin Double Ingot")).setSize(EnumSize.LARGE);
ZincIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot2x",16069), EnumMetalType.ZINC).setUnlocalizedName("Zinc Double Ingot")).setSize(EnumSize.LARGE);
SulfurPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SulfurPowder",16070)).setUnlocalizedName("Sulfur Powder");
SaltpeterPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SaltpeterPowder",16071)).setUnlocalizedName("Saltpeter Powder");
GemRuby = new ItemGem(TFC_Settings.getIntFor(config,"item","GemRuby",16080)).setUnlocalizedName("Ruby");
GemSapphire = new ItemGem(TFC_Settings.getIntFor(config,"item","GemSapphire",16081)).setUnlocalizedName("Sapphire");
GemEmerald = new ItemGem(TFC_Settings.getIntFor(config,"item","GemEmerald",16082)).setUnlocalizedName("Emerald");
GemTopaz = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTopaz",16083)).setUnlocalizedName("Topaz");
GemTourmaline = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTourmaline",16084)).setUnlocalizedName("Tourmaline");
GemJade = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJade",16085)).setUnlocalizedName("Jade");
GemBeryl = new ItemGem(TFC_Settings.getIntFor(config,"item","GemBeryl",16086)).setUnlocalizedName("Beryl");
GemAgate = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAgate",16087)).setUnlocalizedName("Agate");
GemOpal = new ItemGem(TFC_Settings.getIntFor(config,"item","GemOpal",16088)).setUnlocalizedName("Opal");
GemGarnet = new ItemGem(TFC_Settings.getIntFor(config,"item","GemGarnet",16089)).setUnlocalizedName("Garnet");
GemJasper = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJasper",16090)).setUnlocalizedName("Jasper");
GemAmethyst = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAmethyst",16091)).setUnlocalizedName("Amethyst");
GemDiamond = new ItemGem(TFC_Settings.getIntFor(config,"item","GemDiamond",16092)).setUnlocalizedName("Diamond");
//Tools
IgInShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgInShovel",16101),IgInToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgInStoneUses);
IgInAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgInAxe",16102),IgInToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgInStoneUses);
IgInHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgInHoe",16103),IgInToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgInStoneUses);
SedShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SedShovel",16105),SedToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(SedStoneUses);
SedAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SedAxe",16106),SedToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(SedStoneUses);
SedHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SedHoe",16107),SedToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(SedStoneUses);
IgExShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgExShovel",16109),IgExToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgExStoneUses);
IgExAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgExAxe",16110),IgExToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgExStoneUses);
IgExHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgExHoe",16111),IgExToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgExStoneUses);
MMShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","MMShovel",16113),MMToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(MMStoneUses);
MMAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","MMAxe",16114),MMToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(MMStoneUses);
MMHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","MMHoe",16115),MMToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(MMStoneUses);
BismuthPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthPick",16116),BismuthToolMaterial).setUnlocalizedName("Bismuth Pick").setMaxDamage(BismuthUses);
BismuthShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthShovel",16117),BismuthToolMaterial).setUnlocalizedName("Bismuth Shovel").setMaxDamage(BismuthUses);
BismuthAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthAxe",16118),BismuthToolMaterial).setUnlocalizedName("Bismuth Axe").setMaxDamage(BismuthUses);
BismuthHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthHoe",16119),BismuthToolMaterial).setUnlocalizedName("Bismuth Hoe").setMaxDamage(BismuthUses);
BismuthBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthBronzePick",16120),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Pick").setMaxDamage(BismuthBronzeUses);
BismuthBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovel",16121),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Shovel").setMaxDamage(BismuthBronzeUses);
BismuthBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxe",16122),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Axe").setMaxDamage(BismuthBronzeUses);
BismuthBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoe",16123),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hoe").setMaxDamage(BismuthBronzeUses);
BlackBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackBronzePick",16124),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Pick").setMaxDamage(BlackBronzeUses);
BlackBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackBronzeShovel",16125),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Shovel").setMaxDamage(BlackBronzeUses);
BlackBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackBronzeAxe",16126),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Axe").setMaxDamage(BlackBronzeUses);
BlackBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackBronzeHoe",16127),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hoe").setMaxDamage(BlackBronzeUses);
BlackSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackSteelPick",16128),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Pick").setMaxDamage(BlackSteelUses);
BlackSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackSteelShovel",16129),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Shovel").setMaxDamage(BlackSteelUses);
BlackSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackSteelAxe",16130),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Axe").setMaxDamage(BlackSteelUses);
BlackSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackSteelHoe",16131),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hoe").setMaxDamage(BlackSteelUses);
BlueSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlueSteelPick",16132),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Pick").setMaxDamage(BlueSteelUses);
BlueSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlueSteelShovel",16133),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Shovel").setMaxDamage(BlueSteelUses);
BlueSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlueSteelAxe",16134),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Axe").setMaxDamage(BlueSteelUses);
BlueSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlueSteelHoe",16135),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hoe").setMaxDamage(BlueSteelUses);
BronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BronzePick",16136),BronzeToolMaterial).setUnlocalizedName("Bronze Pick").setMaxDamage(BronzeUses);
BronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BronzeShovel",16137),BronzeToolMaterial).setUnlocalizedName("Bronze Shovel").setMaxDamage(BronzeUses);
BronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BronzeAxe",16138),BronzeToolMaterial).setUnlocalizedName("Bronze Axe").setMaxDamage(BronzeUses);
BronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BronzeHoe",16139),BronzeToolMaterial).setUnlocalizedName("Bronze Hoe").setMaxDamage(BronzeUses);
CopperPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","CopperPick",16140),CopperToolMaterial).setUnlocalizedName("Copper Pick").setMaxDamage(CopperUses);
CopperShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","CopperShovel",16141),CopperToolMaterial).setUnlocalizedName("Copper Shovel").setMaxDamage(CopperUses);
CopperAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","CopperAxe",16142),CopperToolMaterial).setUnlocalizedName("Copper Axe").setMaxDamage(CopperUses);
CopperHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","CopperHoe",16143),CopperToolMaterial).setUnlocalizedName("Copper Hoe").setMaxDamage(CopperUses);
WroughtIronPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","WroughtIronPick",16148),IronToolMaterial).setUnlocalizedName("Wrought Iron Pick").setMaxDamage(WroughtIronUses);
WroughtIronShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","WroughtIronShovel",16149),IronToolMaterial).setUnlocalizedName("Wrought Iron Shovel").setMaxDamage(WroughtIronUses);
WroughtIronAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","WroughtIronAxe",16150),IronToolMaterial).setUnlocalizedName("Wrought Iron Axe").setMaxDamage(WroughtIronUses);
WroughtIronHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","WroughtIronHoe",16151),IronToolMaterial).setUnlocalizedName("Wrought Iron Hoe").setMaxDamage(WroughtIronUses);;
RedSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RedSteelPick",16168),RedSteelToolMaterial).setUnlocalizedName("Red Steel Pick").setMaxDamage(RedSteelUses);
RedSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RedSteelShovel",16169),RedSteelToolMaterial).setUnlocalizedName("Red Steel Shovel").setMaxDamage(RedSteelUses);
RedSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RedSteelAxe",16170),RedSteelToolMaterial).setUnlocalizedName("Red Steel Axe").setMaxDamage(RedSteelUses);
RedSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RedSteelHoe",16171),RedSteelToolMaterial).setUnlocalizedName("Red Steel Hoe").setMaxDamage(RedSteelUses);
RoseGoldPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RoseGoldPick",16172),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Pick").setMaxDamage(RoseGoldUses);
RoseGoldShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RoseGoldShovel",16173),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Shovel").setMaxDamage(RoseGoldUses);
RoseGoldAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RoseGoldAxe",16174),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Axe").setMaxDamage(RoseGoldUses);
RoseGoldHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RoseGoldHoe",16175),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hoe").setMaxDamage(RoseGoldUses);
SteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","SteelPick",16180),SteelToolMaterial).setUnlocalizedName("Steel Pick").setMaxDamage(SteelUses);
SteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SteelShovel",16181),SteelToolMaterial).setUnlocalizedName("Steel Shovel").setMaxDamage(SteelUses);
SteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SteelAxe",16182),SteelToolMaterial).setUnlocalizedName("Steel Axe").setMaxDamage(SteelUses);
SteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SteelHoe",16183),SteelToolMaterial).setUnlocalizedName("Steel Hoe").setMaxDamage(SteelUses);
TinPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","TinPick",16188),TinToolMaterial).setUnlocalizedName("Tin Pick").setMaxDamage(TinUses);
TinShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","TinShovel",16189),TinToolMaterial).setUnlocalizedName("Tin Shovel").setMaxDamage(TinUses);
TinAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","TinAxe",16190),TinToolMaterial).setUnlocalizedName("Tin Axe").setMaxDamage(TinUses);
TinHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","TinHoe",16191),TinToolMaterial).setUnlocalizedName("Tin Hoe").setMaxDamage(TinUses);
ZincPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","ZincPick",16192),ZincToolMaterial).setUnlocalizedName("Zinc Pick").setMaxDamage(ZincUses);
ZincShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","ZincShovel",16193),ZincToolMaterial).setUnlocalizedName("Zinc Shovel").setMaxDamage(ZincUses);
ZincAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","ZincAxe",16194),ZincToolMaterial).setUnlocalizedName("Zinc Axe").setMaxDamage(ZincUses);
ZincHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","ZincHoe",16195),ZincToolMaterial).setUnlocalizedName("Zinc Hoe").setMaxDamage(ZincUses);
//chisels
BismuthChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthChisel",16226),BismuthToolMaterial).setUnlocalizedName("Bismuth Chisel").setMaxDamage(BismuthUses);
BismuthBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthBronzeChisel",16227),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Chisel").setMaxDamage(BismuthBronzeUses);
BlackBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackBronzeChisel",16228),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Chisel").setMaxDamage(BlackBronzeUses);
BlackSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackSteelChisel",16230),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Chisel").setMaxDamage(BlackSteelUses);
BlueSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlueSteelChisel",16231),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Chisel").setMaxDamage(BlueSteelUses);
BronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BronzeChisel",16232),BronzeToolMaterial).setUnlocalizedName("Bronze Chisel").setMaxDamage(BronzeUses);
CopperChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","CopperChisel",16233),CopperToolMaterial).setUnlocalizedName("Copper Chisel").setMaxDamage(CopperUses);
WroughtIronChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","WroughtIronChisel",16234),IronToolMaterial).setUnlocalizedName("Wrought Iron Chisel").setMaxDamage(WroughtIronUses);
RedSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RedSteelChisel",16235),RedSteelToolMaterial).setUnlocalizedName("Red Steel Chisel").setMaxDamage(RedSteelUses);
RoseGoldChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RoseGoldChisel",16236),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Chisel").setMaxDamage(RoseGoldUses);
SteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","SteelChisel",16237),SteelToolMaterial).setUnlocalizedName("Steel Chisel").setMaxDamage(SteelUses);
TinChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","TinChisel",16238),TinToolMaterial).setUnlocalizedName("Tin Chisel").setMaxDamage(TinUses);
ZincChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","ZincChisel",16239),ZincToolMaterial).setUnlocalizedName("Zinc Chisel").setMaxDamage(ZincUses);
StoneChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","StoneChisel",16240),IgInToolMaterial).setUnlocalizedName("Stone Chisel").setMaxDamage(IgInStoneUses);
BismuthSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthSword",16245),BismuthToolMaterial).setUnlocalizedName("Bismuth Sword").setMaxDamage(BismuthUses);
BismuthBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeSword",16246),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Sword").setMaxDamage(BismuthBronzeUses);
BlackBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeSword",16247),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Sword").setMaxDamage(BlackBronzeUses);
BlackSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelSword",16248),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Sword").setMaxDamage(BlackSteelUses);
BlueSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelSword",16249),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Sword").setMaxDamage(BlueSteelUses);
BronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeSword",16250),BronzeToolMaterial).setUnlocalizedName("Bronze Sword").setMaxDamage(BronzeUses);
CopperSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperSword",16251),CopperToolMaterial).setUnlocalizedName("Copper Sword").setMaxDamage(CopperUses);
WroughtIronSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronSword",16252),IronToolMaterial).setUnlocalizedName("Wrought Iron Sword").setMaxDamage(WroughtIronUses);
RedSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelSword",16253),RedSteelToolMaterial).setUnlocalizedName("Red Steel Sword").setMaxDamage(RedSteelUses);
RoseGoldSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldSword",16254),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Sword").setMaxDamage(RoseGoldUses);
SteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelSword",16255),SteelToolMaterial).setUnlocalizedName("Steel Sword").setMaxDamage(SteelUses);
TinSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinSword",16256),TinToolMaterial).setUnlocalizedName("Tin Sword").setMaxDamage(TinUses);
ZincSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincSword",16257),ZincToolMaterial).setUnlocalizedName("Zinc Sword").setMaxDamage(ZincUses);
BismuthMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthMace",16262),BismuthToolMaterial).setUnlocalizedName("Bismuth Mace").setMaxDamage(BismuthUses);
BismuthBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeMace",16263),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Mace").setMaxDamage(BismuthBronzeUses);
BlackBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeMace",16264),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Mace").setMaxDamage(BlackBronzeUses);
BlackSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelMace",16265),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Mace").setMaxDamage(BlackSteelUses);
BlueSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelMace",16266),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Mace").setMaxDamage(BlueSteelUses);
BronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeMace",16267),BronzeToolMaterial).setUnlocalizedName("Bronze Mace").setMaxDamage(BronzeUses);
CopperMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperMace",16268),CopperToolMaterial).setUnlocalizedName("Copper Mace").setMaxDamage(CopperUses);
WroughtIronMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronMace",16269),IronToolMaterial).setUnlocalizedName("Wrought Iron Mace").setMaxDamage(WroughtIronUses);
RedSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelMace",16270),RedSteelToolMaterial).setUnlocalizedName("Red Steel Mace").setMaxDamage(RedSteelUses);
RoseGoldMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldMace",16271),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Mace").setMaxDamage(RoseGoldUses);
SteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelMace",16272),SteelToolMaterial).setUnlocalizedName("Steel Mace").setMaxDamage(SteelUses);
TinMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinMace",16273),TinToolMaterial).setUnlocalizedName("Tin Mace").setMaxDamage(TinUses);
ZincMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincMace",16274),ZincToolMaterial).setUnlocalizedName("Zinc Mace").setMaxDamage(ZincUses);
BismuthSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthSaw",16275),BismuthToolMaterial).setUnlocalizedName("Bismuth Saw").setMaxDamage(BismuthUses);
BismuthBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthBronzeSaw",16276),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Saw").setMaxDamage(BismuthBronzeUses);
BlackBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackBronzeSaw",16277),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Saw").setMaxDamage(BlackBronzeUses);
BlackSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackSteelSaw",16278),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Saw").setMaxDamage(BlackSteelUses);
BlueSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlueSteelSaw",16279),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Saw").setMaxDamage(BlueSteelUses);
BronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BronzeSaw",16280),BronzeToolMaterial).setUnlocalizedName("Bronze Saw").setMaxDamage(BronzeUses);
CopperSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","CopperSaw",16281),CopperToolMaterial).setUnlocalizedName("Copper Saw").setMaxDamage(CopperUses);
WroughtIronSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","WroughtIronSaw",16282),IronToolMaterial).setUnlocalizedName("Wrought Iron Saw").setMaxDamage(WroughtIronUses);
RedSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RedSteelSaw",16283),RedSteelToolMaterial).setUnlocalizedName("Red Steel Saw").setMaxDamage(RedSteelUses);
RoseGoldSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RoseGoldSaw",16284),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Saw").setMaxDamage(RoseGoldUses);
SteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","SteelSaw",16285),SteelToolMaterial).setUnlocalizedName("Steel Saw").setMaxDamage(SteelUses);
TinSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","TinSaw",16286),TinToolMaterial).setUnlocalizedName("Tin Saw").setMaxDamage(TinUses);
ZincSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","ZincSaw",16287),ZincToolMaterial).setUnlocalizedName("Zinc Saw").setMaxDamage(ZincUses);
HCBlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlackSteelIngot",16290), EnumMetalType.BLACKSTEEL).setUnlocalizedName("HC Black Steel Ingot");
WeakBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakBlueSteelIngot",16291),EnumMetalType.BLUESTEEL).setUnlocalizedName("Weak Blue Steel Ingot");
WeakRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakRedSteelIngot",16292),EnumMetalType.REDSTEEL).setUnlocalizedName("Weak Red Steel Ingot");
WeakSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakSteelIngot",16293),EnumMetalType.STEEL).setUnlocalizedName("Weak Steel Ingot");
HCBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlueSteelIngot",16294), EnumMetalType.BLUESTEEL).setUnlocalizedName("HC Blue Steel Ingot");
HCRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCRedSteelIngot",16295), EnumMetalType.REDSTEEL).setUnlocalizedName("HC Red Steel Ingot");
HCSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCSteelIngot",16296), EnumMetalType.STEEL).setUnlocalizedName("HC Steel Ingot");
OreChunk = new ItemOre(TFC_Settings.getIntFor(config,"item","OreChunk",16297)).setFolder("ore/").setUnlocalizedName("Ore");
Logs = new ItemLogs(TFC_Settings.getIntFor(config,"item","Logs",16298)).setUnlocalizedName("Log");
Javelin = new ItemJavelin(TFC_Settings.getIntFor(config,"item","javelin",16318)).setUnlocalizedName("javelin");
BismuthUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuth",16350)).setUnlocalizedName("Bismuth Unshaped");
BismuthBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuthBronze",16351)).setUnlocalizedName("Bismuth Bronze Unshaped");
BlackBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackBronze",16352)).setUnlocalizedName("Black Bronze Unshaped");
BlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackSteel",16353)).setUnlocalizedName("Black Steel Unshaped");
BlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlueSteel",16354)).setUnlocalizedName("Blue Steel Unshaped");
BrassUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBrass",16355)).setUnlocalizedName("Brass Unshaped");
BronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBronze",16356)).setUnlocalizedName("Bronze Unshaped");
CopperUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedCopper",16357)).setUnlocalizedName("Copper Unshaped");
GoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedGold",16358)).setUnlocalizedName("Gold Unshaped");
WroughtIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedIron",16359)).setUnlocalizedName("Wrought Iron Unshaped");
LeadUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedLead",16360)).setUnlocalizedName("Lead Unshaped");
NickelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedNickel",16361)).setUnlocalizedName("Nickel Unshaped");
PigIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPigIron",16362)).setUnlocalizedName("Pig Iron Unshaped");
PlatinumUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPlatinum",16363)).setUnlocalizedName("Platinum Unshaped");
RedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRedSteel",16364)).setUnlocalizedName("Red Steel Unshaped");
RoseGoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRoseGold",16365)).setUnlocalizedName("Rose Gold Unshaped");
SilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSilver",16366)).setUnlocalizedName("Silver Unshaped");
SteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSteel",16367)).setUnlocalizedName("Steel Unshaped");
SterlingSilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSterlingSilver",16368)).setUnlocalizedName("Sterling Silver Unshaped");
TinUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedTin",16369)).setUnlocalizedName("Tin Unshaped");
ZincUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedZinc",16370)).setUnlocalizedName("Zinc Unshaped");
//Hammers
StoneHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","StoneHammer",16371),TFCItems.IgInToolMaterial).setUnlocalizedName("Stone Hammer").setMaxDamage(TFCItems.IgInStoneUses);
BismuthHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BismuthHammer",16372),TFCItems.BismuthToolMaterial).setUnlocalizedName("Bismuth Hammer").setMaxDamage(TFCItems.BismuthUses);
BismuthBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammer",16373),TFCItems.BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hammer").setMaxDamage(TFCItems.BismuthBronzeUses);
BlackBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlackBronzeHammer",16374),TFCItems.BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hammer").setMaxDamage(TFCItems.BlackBronzeUses);
BlackSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlackSteelHammer",16375),TFCItems.BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hammer").setMaxDamage(TFCItems.BlackSteelUses);
BlueSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlueSteelHammer",16376),TFCItems.BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hammer").setMaxDamage(TFCItems.BlueSteelUses);
BronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BronzeHammer",16377),TFCItems.BronzeToolMaterial).setUnlocalizedName("Bronze Hammer").setMaxDamage(TFCItems.BronzeUses);
CopperHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","CopperHammer",16378),TFCItems.CopperToolMaterial).setUnlocalizedName("Copper Hammer").setMaxDamage(TFCItems.CopperUses);
WroughtIronHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","WroughtIronHammer",16379),TFCItems.IronToolMaterial).setUnlocalizedName("Wrought Iron Hammer").setMaxDamage(TFCItems.WroughtIronUses);
RedSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","RedSteelHammer",16380),TFCItems.RedSteelToolMaterial).setUnlocalizedName("Red Steel Hammer").setMaxDamage(TFCItems.RedSteelUses);
RoseGoldHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","RoseGoldHammer",16381),TFCItems.RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hammer").setMaxDamage(TFCItems.RoseGoldUses);
SteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","SteelHammer",16382),TFCItems.SteelToolMaterial).setUnlocalizedName("Steel Hammer").setMaxDamage(TFCItems.SteelUses);
TinHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","TinHammer",16383),TFCItems.TinToolMaterial).setUnlocalizedName("Tin Hammer").setMaxDamage(TFCItems.TinUses);
ZincHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","ZincHammer",16384),TFCItems.ZincToolMaterial).setUnlocalizedName("Zinc Hammer").setMaxDamage(TFCItems.ZincUses);
Ink = new ItemTerra(TFC_Settings.getIntFor(config,"item","Ink",16391)).setUnlocalizedName("Ink");
BellowsItem = new ItemBellows(TFC_Settings.getIntFor(config,"item","BellowsItem",16406)).setUnlocalizedName("Bellows");
FireStarter = new ItemFirestarter(TFC_Settings.getIntFor(config,"item","FireStarter",16407)).setFolder("tools/").setUnlocalizedName("Firestarter");
//Tool heads
BismuthPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthPickaxeHead",16500)).setUnlocalizedName("Bismuth Pick Head");
BismuthBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzePickaxeHead",16501)).setUnlocalizedName("Bismuth Bronze Pick Head");
BlackBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzePickaxeHead",16502)).setUnlocalizedName("Black Bronze Pick Head");
BlackSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelPickaxeHead",16503)).setUnlocalizedName("Black Steel Pick Head");
BlueSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelPickaxeHead",16504)).setUnlocalizedName("Blue Steel Pick Head");
BronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzePickaxeHead",16505)).setUnlocalizedName("Bronze Pick Head");
CopperPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperPickaxeHead",16506)).setUnlocalizedName("Copper Pick Head");
WroughtIronPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronPickaxeHead",16507)).setUnlocalizedName("Wrought Iron Pick Head");
RedSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelPickaxeHead",16508)).setUnlocalizedName("Red Steel Pick Head");
RoseGoldPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldPickaxeHead",16509)).setUnlocalizedName("Rose Gold Pick Head");
SteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelPickaxeHead",16510)).setUnlocalizedName("Steel Pick Head");
TinPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinPickaxeHead",16511)).setUnlocalizedName("Tin Pick Head");
ZincPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincPickaxeHead",16512)).setUnlocalizedName("Zinc Pick Head");
BismuthShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthShovelHead",16513)).setUnlocalizedName("Bismuth Shovel Head");
BismuthBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovelHead",16514)).setUnlocalizedName("Bismuth Bronze Shovel Head");
BlackBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeShovelHead",16515)).setUnlocalizedName("Black Bronze Shovel Head");
BlackSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelShovelHead",16516)).setUnlocalizedName("Black Steel Shovel Head");
BlueSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelShovelHead",16517)).setUnlocalizedName("Blue Steel Shovel Head");
BronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeShovelHead",16518)).setUnlocalizedName("Bronze Shovel Head");
CopperShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperShovelHead",16519)).setUnlocalizedName("Copper Shovel Head");
WroughtIronShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronShovelHead",16520)).setUnlocalizedName("Wrought Iron Shovel Head");
RedSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelShovelHead",16521)).setUnlocalizedName("Red Steel Shovel Head");
RoseGoldShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldShovelHead",16522)).setUnlocalizedName("Rose Gold Shovel Head");
SteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelShovelHead",16523)).setUnlocalizedName("Steel Shovel Head");
TinShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinShovelHead",16524)).setUnlocalizedName("Tin Shovel Head");
ZincShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincShovelHead",16525)).setUnlocalizedName("Zinc Shovel Head");
BismuthHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHoeHead",16526)).setUnlocalizedName("Bismuth Hoe Head");
BismuthBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoeHead",16527)).setUnlocalizedName("Bismuth Bronze Hoe Head");
BlackBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHoeHead",16528)).setUnlocalizedName("Black Bronze Hoe Head");
BlackSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHoeHead",16529)).setUnlocalizedName("Black Steel Hoe Head");
BlueSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHoeHead",16530)).setUnlocalizedName("Blue Steel Hoe Head");
BronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHoeHead",16531)).setUnlocalizedName("Bronze Hoe Head");
CopperHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHoeHead",16532)).setUnlocalizedName("Copper Hoe Head");
WroughtIronHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHoeHead",16533)).setUnlocalizedName("Wrought Iron Hoe Head");
RedSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHoeHead",16534)).setUnlocalizedName("Red Steel Hoe Head");
RoseGoldHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHoeHead",16535)).setUnlocalizedName("Rose Gold Hoe Head");
SteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHoeHead",16536)).setUnlocalizedName("Steel Hoe Head");
TinHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHoeHead",16537)).setUnlocalizedName("Tin Hoe Head");
ZincHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHoeHead",16538)).setUnlocalizedName("Zinc Hoe Head");
BismuthAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthAxeHead",16539)).setUnlocalizedName("Bismuth Axe Head");
BismuthBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxeHead",16540)).setUnlocalizedName("Bismuth Bronze Axe Head");
BlackBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeAxeHead",16541)).setUnlocalizedName("Black Bronze Axe Head");
BlackSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelAxeHead",16542)).setUnlocalizedName("Black Steel Axe Head");
BlueSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelAxeHead",16543)).setUnlocalizedName("Blue Steel Axe Head");
BronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeAxeHead",16544)).setUnlocalizedName("Bronze Axe Head");
CopperAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperAxeHead",16545)).setUnlocalizedName("Copper Axe Head");
WroughtIronAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronAxeHead",16546)).setUnlocalizedName("Wrought Iron Axe Head");
RedSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelAxeHead",16547)).setUnlocalizedName("Red Steel Axe Head");
RoseGoldAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldAxeHead",16548)).setUnlocalizedName("Rose Gold Axe Head");
SteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelAxeHead",16549)).setUnlocalizedName("Steel Axe Head");
TinAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinAxeHead",16550)).setUnlocalizedName("Tin Axe Head");
ZincAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincAxeHead",16551)).setUnlocalizedName("Zinc Axe Head");
BismuthHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHammerHead",16552)).setUnlocalizedName("Bismuth Hammer Head");
BismuthBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammerHead",16553)).setUnlocalizedName("Bismuth Bronze Hammer Head");
BlackBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHammerHead",16554)).setUnlocalizedName("Black Bronze Hammer Head");
BlackSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHammerHead",16555)).setUnlocalizedName("Black Steel Hammer Head");
BlueSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHammerHead",16556)).setUnlocalizedName("Blue Steel Hammer Head");
BronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHammerHead",16557)).setUnlocalizedName("Bronze Hammer Head");
CopperHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHammerHead",16558)).setUnlocalizedName("Copper Hammer Head");
WroughtIronHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHammerHead",16559)).setUnlocalizedName("Wrought Iron Hammer Head");
RedSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHammerHead",16560)).setUnlocalizedName("Red Steel Hammer Head");
RoseGoldHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHammerHead",16561)).setUnlocalizedName("Rose Gold Hammer Head");
SteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHammerHead",16562)).setUnlocalizedName("Steel Hammer Head");
TinHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHammerHead",16563)).setUnlocalizedName("Tin Hammer Head");
ZincHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHammerHead",16564)).setUnlocalizedName("Zinc Hammer Head");
//chisel heads
BismuthChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthChiselHead",16565)).setUnlocalizedName("Bismuth Chisel Head");
BismuthBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeChiselHead",16566)).setUnlocalizedName("Bismuth Bronze Chisel Head");
BlackBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeChiselHead",16567)).setUnlocalizedName("Black Bronze Chisel Head");
BlackSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelChiselHead",16568)).setUnlocalizedName("Black Steel Chisel Head");
BlueSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelChiselHead",16569)).setUnlocalizedName("Blue Steel Chisel Head");
BronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeChiselHead",16570)).setUnlocalizedName("Bronze Chisel Head");
CopperChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperChiselHead",16571)).setUnlocalizedName("Copper Chisel Head");
WroughtIronChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronChiselHead",16572)).setUnlocalizedName("Wrought Iron Chisel Head");
RedSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelChiselHead",16573)).setUnlocalizedName("Red Steel Chisel Head");
RoseGoldChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldChiselHead",16574)).setUnlocalizedName("Rose Gold Chisel Head");
SteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelChiselHead",16575)).setUnlocalizedName("Steel Chisel Head");
TinChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinChiselHead",16576)).setUnlocalizedName("Tin Chisel Head");
ZincChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincChiselHead",16577)).setUnlocalizedName("Zinc Chisel Head");
BismuthSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSwordHead",16578)).setUnlocalizedName("Bismuth Sword Blade");
BismuthBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSwordHead",16579)).setUnlocalizedName("Bismuth Bronze Sword Blade");
BlackBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSwordHead",16580)).setUnlocalizedName("Black Bronze Sword Blade");
BlackSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSwordHead",16581)).setUnlocalizedName("Black Steel Sword Blade");
BlueSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSwordHead",16582)).setUnlocalizedName("Blue Steel Sword Blade");
BronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSwordHead",16583)).setUnlocalizedName("Bronze Sword Blade");
CopperSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSwordHead",16584)).setUnlocalizedName("Copper Sword Blade");
WroughtIronSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSwordHead",16585)).setUnlocalizedName("Wrought Iron Sword Blade");
RedSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSwordHead",16586)).setUnlocalizedName("Red Steel Sword Blade");
RoseGoldSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSwordHead",16587)).setUnlocalizedName("Rose Gold Sword Blade");
SteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSwordHead",16588)).setUnlocalizedName("Steel Sword Blade");
TinSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSwordHead",16589)).setUnlocalizedName("Tin Sword Blade");
ZincSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSwordHead",16590)).setUnlocalizedName("Zinc Sword Blade");
BismuthMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthMaceHead",16591)).setUnlocalizedName("Bismuth Mace Head");
BismuthBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeMaceHead",16592)).setUnlocalizedName("Bismuth Bronze Mace Head");
BlackBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeMaceHead",16593)).setUnlocalizedName("Black Bronze Mace Head");
BlackSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelMaceHead",16594)).setUnlocalizedName("Black Steel Mace Head");
BlueSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelMaceHead",16595)).setUnlocalizedName("Blue Steel Mace Head");
BronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeMaceHead",16596)).setUnlocalizedName("Bronze Mace Head");
CopperMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperMaceHead",16597)).setUnlocalizedName("Copper Mace Head");
WroughtIronMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronMaceHead",16598)).setUnlocalizedName("Wrought Iron Mace Head");
RedSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelMaceHead",16599)).setUnlocalizedName("Red Steel Mace Head");
RoseGoldMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldMaceHead",16600)).setUnlocalizedName("Rose Gold Mace Head");
SteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelMaceHead",16601)).setUnlocalizedName("Steel Mace Head");
TinMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinMaceHead",16602)).setUnlocalizedName("Tin Mace Head");
ZincMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincMaceHead",16603)).setUnlocalizedName("Zinc Mace Head");
BismuthSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSawHead",16604)).setUnlocalizedName("Bismuth Saw Blade");
BismuthBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSawHead",16605)).setUnlocalizedName("Bismuth Bronze Saw Blade");
BlackBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSawHead",16606)).setUnlocalizedName("Black Bronze Saw Blade");
BlackSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSawHead",16607)).setUnlocalizedName("Black Steel Saw Blade");
BlueSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSawHead",16608)).setUnlocalizedName("Blue Steel Saw Blade");
BronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSawHead",16609)).setUnlocalizedName("Bronze Saw Blade");
CopperSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSawHead",16610)).setUnlocalizedName("Copper Saw Blade");
WroughtIronSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSawHead",16611)).setUnlocalizedName("Wrought Iron Saw Blade");
RedSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSawHead",16612)).setUnlocalizedName("Red Steel Saw Blade");
RoseGoldSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSawHead",16613)).setUnlocalizedName("Rose Gold Saw Blade");
SteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSawHead",16614)).setUnlocalizedName("Steel Saw Blade");
TinSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSawHead",16615)).setUnlocalizedName("Tin Saw Blade");
ZincSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSawHead",16616)).setUnlocalizedName("Zinc Saw Blade");
HCBlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlackSteel",16617)).setUnlocalizedName("HC Black Steel Unshaped");
WeakBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakBlueSteel",16618)).setUnlocalizedName("Weak Blue Steel Unshaped");
HCBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlueSteel",16619)).setUnlocalizedName("HC Blue Steel Unshaped");
WeakRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakRedSteel",16621)).setUnlocalizedName("Weak Red Steel Unshaped");
HCRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCRedSteel",16622)).setUnlocalizedName("HC Red Steel Unshaped");
WeakSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakSteel",16623)).setUnlocalizedName("Weak Steel Unshaped");
HCSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCSteel",16624)).setUnlocalizedName("HC Steel Unshaped");
Coke = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Coke",16625)).setUnlocalizedName("Coke"));
BismuthProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthProPickHead",16626)).setUnlocalizedName("Bismuth ProPick Head");
BismuthBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeProPickHead",16627)).setUnlocalizedName("Bismuth Bronze ProPick Head");
BlackBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeProPickHead",16628)).setUnlocalizedName("Black Bronze ProPick Head");
BlackSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelProPickHead",16629)).setUnlocalizedName("Black Steel ProPick Head");
BlueSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelProPickHead",16630)).setUnlocalizedName("Blue Steel ProPick Head");
BronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeProPickHead",16631)).setUnlocalizedName("Bronze ProPick Head");
CopperProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperProPickHead",16632)).setUnlocalizedName("Copper ProPick Head");
WroughtIronProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronProPickHead",16633)).setUnlocalizedName("Wrought Iron ProPick Head");
RedSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelProPickHead",16634)).setUnlocalizedName("Red Steel ProPick Head");
RoseGoldProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldProPickHead",16635)).setUnlocalizedName("Rose Gold ProPick Head");
SteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelProPickHead",16636)).setUnlocalizedName("Steel ProPick Head");
TinProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinProPickHead",16637)).setUnlocalizedName("Tin ProPick Head");
ZincProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincProPickHead",16638)).setUnlocalizedName("Zinc ProPick Head");
Flux = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Flux",16639)).setUnlocalizedName("Flux"));
/**
* Scythe
* */
int num = 16643;
BismuthScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthScythe",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Scythe").setMaxDamage(BismuthUses);num++;
BismuthBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthBronzeScythe",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Scythe").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackBronzeScythe",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Scythe").setMaxDamage(BlackBronzeUses);num++;
BlackSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackSteelScythe",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Scythe").setMaxDamage(BlackSteelUses);num++;
BlueSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlueSteelScythe",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Scythe").setMaxDamage(BlueSteelUses);num++;
BronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BronzeScythe",num),BronzeToolMaterial).setUnlocalizedName("Bronze Scythe").setMaxDamage(BronzeUses);num++;
CopperScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","CopperScythe",num),CopperToolMaterial).setUnlocalizedName("Copper Scythe").setMaxDamage(CopperUses);num++;
WroughtIronScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","WroughtIronScythe",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Scythe").setMaxDamage(WroughtIronUses);num++;
RedSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RedSteelScythe",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Scythe").setMaxDamage(RedSteelUses);num++;
RoseGoldScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RoseGoldScythe",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Scythe").setMaxDamage(RoseGoldUses);num++;
SteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","SteelScythe",num),SteelToolMaterial).setUnlocalizedName("Steel Scythe").setMaxDamage(SteelUses);num++;
TinScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","TinScythe",num),TinToolMaterial).setUnlocalizedName("Tin Scythe").setMaxDamage(TinUses);num++;
ZincScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","ZincScythe",num),ZincToolMaterial).setUnlocalizedName("Zinc Scythe").setMaxDamage(ZincUses);num++;
BismuthScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthScytheHead",num)).setUnlocalizedName("Bismuth Scythe Blade");num++;
BismuthBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeScytheHead",num)).setUnlocalizedName("Bismuth Bronze Scythe Blade");num++;
BlackBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeScytheHead",num)).setUnlocalizedName("Black Bronze Scythe Blade");num++;
BlackSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelScytheHead",num)).setUnlocalizedName("Black Steel Scythe Blade");num++;
BlueSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelScytheHead",num)).setUnlocalizedName("Blue Steel Scythe Blade");num++;
BronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeScytheHead",num)).setUnlocalizedName("Bronze Scythe Blade");num++;
CopperScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperScytheHead",num)).setUnlocalizedName("Copper Scythe Blade");num++;
WroughtIronScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronScytheHead",num)).setUnlocalizedName("Wrought Iron Scythe Blade");num++;
RedSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelScytheHead",num)).setUnlocalizedName("Red Steel Scythe Blade");num++;
RoseGoldScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldScytheHead",num)).setUnlocalizedName("Rose Gold Scythe Blade");num++;
SteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelScytheHead",num)).setUnlocalizedName("Steel Scythe Blade");num++;
TinScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinScytheHead",num)).setUnlocalizedName("Tin Scythe Blade");num++;
ZincScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincScytheHead",num)).setUnlocalizedName("Zinc Scythe Blade");num++;
WoodenBucketEmpty = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketEmpty",num), 0)).setUnlocalizedName("Wooden Bucket Empty");num++;
WoodenBucketWater = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketWater",num), TFCBlocks.finiteWater.blockID)).setUnlocalizedName("Wooden Bucket Water").setContainerItem(WoodenBucketEmpty);num++;
WoodenBucketMilk = (new ItemCustomBucketMilk(TFC_Settings.getIntFor(config,"item","WoodenBucketMilk",num))).setUnlocalizedName("Wooden Bucket Milk").setContainerItem(WoodenBucketEmpty);num++;
BismuthKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthKnifeHead",num)).setUnlocalizedName("Bismuth Knife Blade");num++;
BismuthBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnifeHead",num)).setUnlocalizedName("Bismuth Bronze Knife Blade");num++;
BlackBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeKnifeHead",num)).setUnlocalizedName("Black Bronze Knife Blade");num++;
BlackSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelKnifeHead",num)).setUnlocalizedName("Black Steel Knife Blade");num++;
BlueSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelKnifeHead",num)).setUnlocalizedName("Blue Steel Knife Blade");num++;
BronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeKnifeHead",num)).setUnlocalizedName("Bronze Knife Blade");num++;
CopperKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperKnifeHead",num)).setUnlocalizedName("Copper Knife Blade");num++;
WroughtIronKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronKnifeHead",num)).setUnlocalizedName("Wrought Iron Knife Blade");num++;
RedSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelKnifeHead",num)).setUnlocalizedName("Red Steel Knife Blade");num++;
RoseGoldKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldKnifeHead",num)).setUnlocalizedName("Rose Gold Knife Blade");num++;
SteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelKnifeHead",num)).setUnlocalizedName("Steel Knife Blade");num++;
TinKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinKnifeHead",num)).setUnlocalizedName("Tin Knife Blade");num++;
ZincKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincKnifeHead",num)).setUnlocalizedName("Zinc Knife Blade");num++;
BismuthKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthKnife",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Knife").setMaxDamage(BismuthUses);num++;
BismuthBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnife",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Knife").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackBronzeKnife",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Knife").setMaxDamage(BlackBronzeUses);num++;
BlackSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackSteelKnife",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Knife").setMaxDamage(BlackSteelUses);num++;
BlueSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlueSteelKnife",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Knife").setMaxDamage(BlueSteelUses);num++;
BronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BronzeKnife",num),BronzeToolMaterial).setUnlocalizedName("Bronze Knife").setMaxDamage(BronzeUses);num++;
CopperKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","CopperKnife",num),CopperToolMaterial).setUnlocalizedName("Copper Knife").setMaxDamage(CopperUses);num++;
WroughtIronKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","WroughtIronKnife",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Knife").setMaxDamage(WroughtIronUses);num++;
RedSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RedSteelKnife",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Knife").setMaxDamage(RedSteelUses);num++;
RoseGoldKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RoseGoldKnife",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Knife").setMaxDamage(RoseGoldUses);num++;
SteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","SteelKnife",num),SteelToolMaterial).setUnlocalizedName("Steel Knife").setMaxDamage(SteelUses);num++;
TinKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","TinKnife",num),TinToolMaterial).setUnlocalizedName("Tin Knife").setMaxDamage(TinUses);num++;
ZincKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","ZincKnife",num),ZincToolMaterial).setUnlocalizedName("Zinc Knife").setMaxDamage(ZincUses);num++;
LooseRock = (new ItemLooseRock(TFC_Settings.getIntFor(config,"item","LooseRock",num)).setUnlocalizedName("LooseRock"));num++;
FlatRock = (new ItemFlatRock(TFC_Settings.getIntFor(config,"item","FlatRock",num)).setUnlocalizedName("FlatRock"));num++;
IgInStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
SedStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgExStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
MMStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgInStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
SedStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgExStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
MMStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgInStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
SedStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
IgExStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
MMStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
StoneKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneKnifeHead",num)).setUnlocalizedName("Stone Knife Blade");num++;
StoneHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneHammerHead",num)).setUnlocalizedName("Stone Hammer Head");num++;
StoneKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","StoneKnife",num),IgExToolMaterial).setUnlocalizedName("Stone Knife").setMaxDamage(IgExStoneUses);num++;
SmallOreChunk = new ItemOreSmall(TFC_Settings.getIntFor(config,"item","SmallOreChunk",num++)).setUnlocalizedName("Small Ore");
SinglePlank = new ItemPlank(TFC_Settings.getIntFor(config,"item","SinglePlank",num++)).setUnlocalizedName("SinglePlank");
RedSteelBucketEmpty = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketEmpty",num++), 0)).setUnlocalizedName("Red Steel Bucket Empty");
RedSteelBucketWater = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketWater",num++), Block.waterMoving.blockID)).setUnlocalizedName("Red Steel Bucket Water");
BlueSteelBucketEmpty = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketEmpty",num++), 0)).setUnlocalizedName("Blue Steel Bucket Empty");
BlueSteelBucketLava = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketLava",num++), Block.lavaMoving.blockID)).setUnlocalizedName("Blue Steel Bucket Lava");
Quern = new ItemTerra(TFC_Settings.getIntFor(config,"item","Quern",num++)).setUnlocalizedName("Quern").setMaxDamage(250);
FlintSteel = new ItemFlintSteel(TFC_Settings.getIntFor(config,"item","FlintSteel",num++)).setUnlocalizedName("flintAndSteel").setMaxDamage(200);
DoorOak = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorOak", num++), 0).setUnlocalizedName("Oak Door");
DoorAspen = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAspen", num++), 1).setUnlocalizedName("Aspen Door");
DoorBirch = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorBirch", num++), 2).setUnlocalizedName("Birch Door");
DoorChestnut = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorChestnut", num++), 3).setUnlocalizedName("Chestnut Door");
DoorDouglasFir = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorDouglasFir", num++), 4).setUnlocalizedName("Douglas Fir Door");
DoorHickory = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorHickory", num++), 5).setUnlocalizedName("Hickory Door");
DoorMaple = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorMaple", num++), 6).setUnlocalizedName("Maple Door");
DoorAsh = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAsh", num++), 7).setUnlocalizedName("Ash Door");
DoorPine = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorPine", num++), 8).setUnlocalizedName("Pine Door");
DoorSequoia = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSequoia", num++), 9).setUnlocalizedName("Sequoia Door");
DoorSpruce = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSpruce", num++), 10).setUnlocalizedName("Spruce Door");
DoorSycamore = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSycamore", num++), 11).setUnlocalizedName("Sycamore Door");
DoorWhiteCedar = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteCedar", num++), 12).setUnlocalizedName("White Cedar Door");
DoorWhiteElm = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteElm", num++), 13).setUnlocalizedName("White Elm Door");
DoorWillow = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWillow", num++), 14).setUnlocalizedName("Willow Door");
DoorKapok = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorKapok", num++), 15).setUnlocalizedName("Kapok Door");
Blueprint = new ItemBlueprint(TFC_Settings.getIntFor(config,"item","Blueprint", num++));
writabeBookTFC = new ItemWritableBookTFC(TFC_Settings.getIntFor(config,"item","WritableBookTFC", num++),"Fix Me I'm Broken").setUnlocalizedName("book");
WoolYarn = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolYarn", num++)).setUnlocalizedName("WoolYarn").setCreativeTab(TFCTabs.TFCMaterials);
Wool = new ItemTerra(TFC_Settings.getIntFor(config,"item","Wool",num++)).setUnlocalizedName("Wool").setCreativeTab(TFCTabs.TFCMaterials);
WoolCloth = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolCloth", num++)).setUnlocalizedName("WoolCloth").setCreativeTab(TFCTabs.TFCMaterials);
Spindle = new ItemSpindle(TFC_Settings.getIntFor(config,"item","Spindle",num++),SedToolMaterial).setUnlocalizedName("Spindle").setCreativeTab(TFCTabs.TFCMaterials);
ClaySpindle = new ItemTerra(TFC_Settings.getIntFor(config, "item", "ClaySpindle", num++)).setFolder("tools/").setUnlocalizedName("Clay Spindle").setCreativeTab(TFCTabs.TFCMaterials);
SpindleHead = new ItemTerra(TFC_Settings.getIntFor(config, "item", "SpindleHead", num++)).setFolder("toolheads/").setUnlocalizedName("Spindle Head").setCreativeTab(TFCTabs.TFCMaterials);
StoneBrick = (new ItemStoneBrick(TFC_Settings.getIntFor(config,"item","ItemStoneBrick2",num++)).setFolder("tools/").setUnlocalizedName("ItemStoneBrick"));
Mortar = new ItemTerra(TFC_Settings.getIntFor(config,"item","Mortar",num++)).setFolder("tools/").setUnlocalizedName("Mortar").setCreativeTab(TFCTabs.TFCMaterials);
Limewater = new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","Limewater",num++),0).setFolder("tools/").setUnlocalizedName("Lime Water").setContainerItem(WoodenBucketEmpty).setCreativeTab(TFCTabs.TFCMaterials);
Hide = new ItemTerra(TFC_Settings.getIntFor(config,"item","Hide",num++)).setFolder("tools/").setUnlocalizedName("Hide").setCreativeTab(TFCTabs.TFCMaterials);
SoakedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","SoakedHide",num++)).setFolder("tools/").setUnlocalizedName("Soaked Hide").setCreativeTab(TFCTabs.TFCMaterials);
ScrapedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","ScrapedHide",num++)).setFolder("tools/").setUnlocalizedName("Scraped Hide").setCreativeTab(TFCTabs.TFCMaterials);
PrepHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","PrepHide",num++)).setFolder("tools/").setFolder("tools/").setUnlocalizedName("Prep Hide").setCreativeTab(TFCTabs.TFCMaterials);
TerraLeather = new ItemTerra(TFC_Settings.getIntFor(config,"item","TFCLeather",num++)).setFolder("tools/").setUnlocalizedName("TFC Leather").setCreativeTab(TFCTabs.TFCMaterials);
SheepSkin = new ItemTerra(TFC_Settings.getIntFor(config,"item","SheepSkin",num++)).setFolder("tools/").setUnlocalizedName("Sheep Skin").setCreativeTab(TFCTabs.TFCMaterials);
muttonRaw = new ItemTerra(TFC_Settings.getIntFor(config,"item","muttonRaw",num++)).setFolder("food/").setUnlocalizedName("Mutton Raw");
muttonCooked = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","muttonCooked",num++), 40, 0.8F, true, 48).setUnlocalizedName("Mutton Cooked");
FlatLeather = (new ItemFlatLeather(TFC_Settings.getIntFor(config,"items","FlatLeather2",num++)).setFolder("tools/").setUnlocalizedName("Flat Leather"));
PotteryJug = new ItemPotteryJug(TFC_Settings.getIntFor(config,"items","PotteryJug",num++)).setUnlocalizedName("Jug");
PotterySmallVessel = new ItemPotterySmallVessel(TFC_Settings.getIntFor(config,"items","PotterySmallVessel",num++)).setUnlocalizedName("Small Vessel");
PotteryLargeVessel = new ItemPotteryLargeVessel(TFC_Settings.getIntFor(config,"items","PotteryLargeVessel",num++)).setUnlocalizedName("Large Vessel");
PotteryPot = new ItemPotteryPot(TFC_Settings.getIntFor(config,"items","PotteryPot",num++)).setUnlocalizedName("Pot");
CeramicMold = new ItemPotteryBase(TFC_Settings.getIntFor(config,"item","CeramicMold",16409)).setMetaNames(new String[]{"Clay Mold","Ceramic Mold"}).setUnlocalizedName("Mold");
Straw = new ItemTerra(TFC_Settings.getIntFor(config,"items","Straw",num++)).setFolder("plants/").setUnlocalizedName("Straw");
/**Plans*/
num = 20000;
SetupPlans(num);
/**Food related items*/
num = 18000;
SetupFood(num);
/**Armor Crafting related items*/
num = 19000;
SetupArmor(num);
Recipes.Doors = new Item[]{DoorOak, DoorAspen, DoorBirch, DoorChestnut, DoorDouglasFir,
DoorHickory, DoorMaple, DoorAsh, DoorPine, DoorSequoia, DoorSpruce, DoorSycamore,
DoorWhiteCedar, DoorWhiteElm, DoorWillow, DoorKapok};
Recipes.Axes = new Item[]{SedAxe,IgInAxe,IgExAxe,MMAxe,
BismuthAxe,BismuthBronzeAxe,BlackBronzeAxe,
BlackSteelAxe,BlueSteelAxe,BronzeAxe,CopperAxe,
WroughtIronAxe,RedSteelAxe,RoseGoldAxe,SteelAxe,
TinAxe,ZincAxe};
Recipes.Chisels = new Item[]{BismuthChisel,BismuthBronzeChisel,BlackBronzeChisel,
BlackSteelChisel,BlueSteelChisel,BronzeChisel,CopperChisel,
WroughtIronChisel,RedSteelChisel,RoseGoldChisel,SteelChisel,
TinChisel,ZincChisel};
Recipes.Saws = new Item[]{BismuthSaw,BismuthBronzeSaw,BlackBronzeSaw,
BlackSteelSaw,BlueSteelSaw,BronzeSaw,CopperSaw,
WroughtIronSaw,RedSteelSaw,RoseGoldSaw,SteelSaw,
TinSaw,ZincSaw};
Recipes.Knives = new Item[]{StoneKnife,BismuthKnife,BismuthBronzeKnife,BlackBronzeKnife,
BlackSteelKnife,BlueSteelKnife,BronzeKnife,CopperKnife,
WroughtIronKnife,RedSteelKnife,RoseGoldKnife,SteelKnife,
TinKnife,ZincKnife};
Recipes.MeltedMetal = new Item[]{BismuthUnshaped, BismuthBronzeUnshaped,BlackBronzeUnshaped,
TFCItems.BlackSteelUnshaped,TFCItems.BlueSteelUnshaped,TFCItems.BrassUnshaped,TFCItems.BronzeUnshaped,
TFCItems.CopperUnshaped,TFCItems.GoldUnshaped,
TFCItems.WroughtIronUnshaped,TFCItems.LeadUnshaped,TFCItems.NickelUnshaped,TFCItems.PigIronUnshaped,
TFCItems.PlatinumUnshaped,TFCItems.RedSteelUnshaped,TFCItems.RoseGoldUnshaped,TFCItems.SilverUnshaped,
TFCItems.SteelUnshaped,TFCItems.SterlingSilverUnshaped,
TFCItems.TinUnshaped,TFCItems.ZincUnshaped, TFCItems.HCSteelUnshaped, TFCItems.WeakSteelUnshaped,
TFCItems.HCBlackSteelUnshaped, TFCItems.HCBlueSteelUnshaped, TFCItems.HCRedSteelUnshaped,
TFCItems.WeakBlueSteelUnshaped, TFCItems.WeakRedSteelUnshaped};
Recipes.Hammers = new Item[]{TFCItems.StoneHammer,TFCItems.BismuthHammer,TFCItems.BismuthBronzeHammer,TFCItems.BlackBronzeHammer,
TFCItems.BlackSteelHammer,TFCItems.BlueSteelHammer,TFCItems.BronzeHammer,TFCItems.CopperHammer,
TFCItems.WroughtIronHammer,TFCItems.RedSteelHammer,TFCItems.RoseGoldHammer,TFCItems.SteelHammer,
TFCItems.TinHammer,TFCItems.ZincHammer};
Recipes.Spindle = new Item[]{TFCItems.Spindle};
Recipes.Gems = new Item[]{TFCItems.GemAgate, TFCItems.GemAmethyst, TFCItems.GemBeryl, TFCItems.GemDiamond, TFCItems.GemEmerald, TFCItems.GemGarnet,
TFCItems.GemJade, TFCItems.GemJasper, TFCItems.GemOpal,TFCItems.GemRuby,TFCItems.GemSapphire,TFCItems.GemTopaz,TFCItems.GemTourmaline};
Meals = new Item[]{MealMoveSpeed, MealDigSpeed, MealDamageBoost, MealJump, MealDamageResist,
MealFireResist, MealWaterBreathing, MealNightVision};
((TFCTabs)TFCTabs.TFCTools).setTabIconItemIndex(TFCItems.RoseGoldHammer.itemID);
((TFCTabs)TFCTabs.TFCMaterials).setTabIconItemIndex(TFCItems.Spindle.itemID);
((TFCTabs)TFCTabs.TFCUnfinished).setTabIconItemIndex(TFCItems.RoseGoldHammerHead.itemID);
((TFCTabs)TFCTabs.TFCArmor).setTabIconItemIndex(TFCItems.SteelHelmet.itemID);
System.out.println(new StringBuilder().append("[TFC] Done Loading Items").toString());
if (config != null) {
config.save();
}
}
| public static void Setup()
{
try
{
config = new net.minecraftforge.common.Configuration(
new File(TerraFirmaCraft.proxy.getMinecraftDir(), "/config/TFC.cfg"));
config.load();
} catch (Exception e) {
System.out.println(new StringBuilder().append("[TFC] Error while trying to access item configuration!").toString());
config = null;
}
IgInToolMaterial = EnumHelper.addToolMaterial("IgIn", 1, IgInStoneUses, 7F, 10, 5);
SedToolMaterial = EnumHelper.addToolMaterial("Sed", 1, SedStoneUses, 6F, 10, 5);
IgExToolMaterial = EnumHelper.addToolMaterial("IgEx", 1, IgExStoneUses, 7F, 10, 5);
MMToolMaterial = EnumHelper.addToolMaterial("MM", 1, MMStoneUses, 6.5F, 10, 5);
BismuthToolMaterial = EnumHelper.addToolMaterial("Bismuth", 2, BismuthUses, BismuthEff, 65, 10);
BismuthBronzeToolMaterial = EnumHelper.addToolMaterial("BismuthBronze", 2, BismuthBronzeUses, BismuthBronzeEff, 85, 10);
BlackBronzeToolMaterial = EnumHelper.addToolMaterial("BlackBronze", 2, BlackBronzeUses, BlackBronzeEff, 100, 10);
BlackSteelToolMaterial = EnumHelper.addToolMaterial("BlackSteel", 2, BlackSteelUses, BlackSteelEff, 165, 12);
BlueSteelToolMaterial = EnumHelper.addToolMaterial("BlueSteel", 3, BlueSteelUses, BlueSteelEff, 185, 22);
BronzeToolMaterial = EnumHelper.addToolMaterial("Bronze", 2, BronzeUses, BronzeEff, 100, 13);
CopperToolMaterial = EnumHelper.addToolMaterial("Copper", 2, CopperUses, CopperEff, 85, 8);
IronToolMaterial = EnumHelper.addToolMaterial("Iron", 2, WroughtIronUses, WroughtIronEff, 135, 10);
RedSteelToolMaterial = EnumHelper.addToolMaterial("RedSteel", 3, RedSteelUses, RedSteelEff, 185, 22);
RoseGoldToolMaterial = EnumHelper.addToolMaterial("RoseGold", 2, RoseGoldUses, RoseGoldEff, 100, 20);
SteelToolMaterial = EnumHelper.addToolMaterial("Steel", 2, SteelUses, SteelEff, 150, 10);
TinToolMaterial = EnumHelper.addToolMaterial("Tin", 2, TinUses, TinEff, 65, 8);
ZincToolMaterial = EnumHelper.addToolMaterial("Zinc", 2, ZincUses, ZincEff, 65, 8);
System.out.println(new StringBuilder().append("[TFC] Loading Items").toString());
//Replace any vanilla Items here
Item.itemsList[Item.coal.itemID] = null; Item.itemsList[Item.coal.itemID] = (new TFC.Items.ItemCoal(7)).setUnlocalizedName("coal");
Item.itemsList[Item.stick.itemID] = null; Item.itemsList[Item.stick.itemID] = new ItemStick(24).setFull3D().setUnlocalizedName("stick");
Item.itemsList[Item.leather.itemID] = null; Item.itemsList[Item.leather.itemID] = new ItemTerra(Item.leather.itemID).setFull3D().setUnlocalizedName("leather");
Item.itemsList[Block.vine.blockID] = new ItemColored(Block.vine.blockID - 256, false);
minecartCrate = (new ItemCustomMinecart(TFC_Settings.getIntFor(config,"item","minecartCrate",16000), 1)).setUnlocalizedName("minecartChest");
Item.itemsList[5+256] = null; Item.itemsList[5+256] = (new ItemCustomBow(5)).setUnlocalizedName("bow");
Item.itemsList[63+256] = null; Item.itemsList[63+256] = new ItemTerra(63).setUnlocalizedName("porkchopRaw");
Item.itemsList[64+256] = null; Item.itemsList[64+256] = new ItemTerraFood(64, 35, 0.8F, true, 38).setFolder("").setUnlocalizedName("porkchopCooked");
Item.itemsList[93+256] = null; Item.itemsList[93+256] = new ItemTerra(93).setUnlocalizedName("fishRaw");
Item.itemsList[94+256] = null; Item.itemsList[94+256] = new ItemTerraFood(94, 30, 0.6F, true, 39).setFolder("").setUnlocalizedName("fishCooked");
Item.itemsList[107+256] = null; Item.itemsList[107+256] = new ItemTerra(107).setUnlocalizedName("beefRaw");
Item.itemsList[108+256] = null; Item.itemsList[108+256] = new ItemTerraFood(108, 40, 0.8F, true, 40).setFolder("").setUnlocalizedName("beefCooked");
Item.itemsList[109+256] = null; Item.itemsList[109+256] = new ItemTerra(109).setUnlocalizedName("chickenRaw");
Item.itemsList[110+256] = null; Item.itemsList[110+256] = new ItemTerraFood(110, 35, 0.6F, true, 41).setFolder("").setUnlocalizedName("chickenCooked");
Item.itemsList[41+256] = null; Item.itemsList[41+256] = (new ItemTerraFood(41, 25, 0.6F, false, 42)).setFolder("").setUnlocalizedName("bread");
Item.itemsList[88+256] = null; Item.itemsList[88+256] = (new ItemTerra(88)).setUnlocalizedName("egg");
Item.itemsList[Item.dyePowder.itemID] = null; Item.itemsList[Item.dyePowder.itemID] = new ItemDyeCustom(95).setUnlocalizedName("dyePowder");
Item.itemsList[Item.potion.itemID] = null; Item.itemsList[Item.potion.itemID] = (new ItemCustomPotion(117)).setUnlocalizedName("potion");
Item.itemsList[Block.tallGrass.blockID] = null; Item.itemsList[Block.tallGrass.blockID] = (new ItemColored(Block.tallGrass.blockID - 256, true)).setBlockNames(new String[] {"shrub", "grass", "fern"});
GoldPan = new ItemGoldPan(TFC_Settings.getIntFor(config,"item","GoldPan",16001)).setUnlocalizedName("GoldPan");
SluiceItem = new ItemSluice(TFC_Settings.getIntFor(config,"item","SluiceItem",16002)).setFolder("devices/").setUnlocalizedName("SluiceItem");
ProPickBismuth = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuth",16004)).setUnlocalizedName("Bismuth ProPick").setMaxDamage(BismuthUses);
ProPickBismuthBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuthBronze",16005)).setUnlocalizedName("Bismuth Bronze ProPick").setMaxDamage(BismuthBronzeUses);
ProPickBlackBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackBronze",16006)).setUnlocalizedName("Black Bronze ProPick").setMaxDamage(BlackBronzeUses);
ProPickBlackSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackSteel",16007)).setUnlocalizedName("Black Steel ProPick").setMaxDamage(BlackSteelUses);
ProPickBlueSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlueSteel",16008)).setUnlocalizedName("Blue Steel ProPick").setMaxDamage(BlueSteelUses);
ProPickBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBronze",16009)).setUnlocalizedName("Bronze ProPick").setMaxDamage(BronzeUses);
ProPickCopper = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickCopper",16010)).setUnlocalizedName("Copper ProPick").setMaxDamage(CopperUses);
ProPickIron = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickWroughtIron",16012)).setUnlocalizedName("Wrought Iron ProPick").setMaxDamage(WroughtIronUses);
ProPickRedSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRedSteel",16016)).setUnlocalizedName("Red Steel ProPick").setMaxDamage(RedSteelUses);
ProPickRoseGold = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRoseGold",16017)).setUnlocalizedName("Rose Gold ProPick").setMaxDamage(RoseGoldUses);
ProPickSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickSteel",16019)).setUnlocalizedName("Steel ProPick").setMaxDamage(SteelUses);
ProPickTin = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickTin",16021)).setUnlocalizedName("Tin ProPick").setMaxDamage(TinUses);
ProPickZinc = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickZinc",16022)).setUnlocalizedName("Zinc ProPick").setMaxDamage(ZincUses);
BismuthIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot",16028), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Ingot");
BismuthBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot",16029), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Ingot");
BlackBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot",16030), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Ingot");
BlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot",16031), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Ingot");
BlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot",16032), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Ingot");
BrassIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot",16033), EnumMetalType.BRASS).setUnlocalizedName("Brass Ingot");
BronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot",16034), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Ingot");
CopperIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot",16035), EnumMetalType.COPPER).setUnlocalizedName("Copper Ingot");
GoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot",16036), EnumMetalType.GOLD).setUnlocalizedName("Gold Ingot");
WroughtIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot",16037), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Ingot");
LeadIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot",16038), EnumMetalType.LEAD).setUnlocalizedName("Lead Ingot");
NickelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot",16039), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Ingot");
PigIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot",16040), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Ingot");
PlatinumIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot",16041), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Ingot");
RedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot",16042), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Ingot");
RoseGoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot",16043), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Ingot");
SilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot",16044), EnumMetalType.SILVER).setUnlocalizedName("Silver Ingot");
SteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot",16045), EnumMetalType.STEEL).setUnlocalizedName("Steel Ingot");
SterlingSilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot",16046), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Ingot");
TinIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot",16047), EnumMetalType.TIN).setUnlocalizedName("Tin Ingot");
ZincIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot",16048), EnumMetalType.ZINC).setUnlocalizedName("Zinc Ingot");
BismuthIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot2x",16049), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Double Ingot")).setSize(EnumSize.LARGE);
BismuthBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot2x",16050), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot2x",16051), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot2x",16052), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Double Ingot")).setSize(EnumSize.LARGE);
BlueSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot2x",16053), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Double Ingot")).setSize(EnumSize.LARGE);
BrassIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot2x",16054), EnumMetalType.BRASS).setUnlocalizedName("Brass Double Ingot")).setSize(EnumSize.LARGE);
BronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot2x",16055), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Double Ingot")).setSize(EnumSize.LARGE);
CopperIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot2x",16056), EnumMetalType.COPPER).setUnlocalizedName("Copper Double Ingot")).setSize(EnumSize.LARGE);
GoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot2x",16057), EnumMetalType.GOLD).setUnlocalizedName("Gold Double Ingot")).setSize(EnumSize.LARGE);
WroughtIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot2x",16058), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Double Ingot")).setSize(EnumSize.LARGE);
LeadIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot2x",16059), EnumMetalType.LEAD).setUnlocalizedName("Lead Double Ingot")).setSize(EnumSize.LARGE);
NickelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot2x",16060), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Double Ingot")).setSize(EnumSize.LARGE);
PigIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot2x",16061), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Double Ingot")).setSize(EnumSize.LARGE);
PlatinumIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot2x",16062), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Double Ingot")).setSize(EnumSize.LARGE);
RedSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot2x",16063), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Double Ingot")).setSize(EnumSize.LARGE);
RoseGoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot2x",16064), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Double Ingot")).setSize(EnumSize.LARGE);
SilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot2x",16065), EnumMetalType.SILVER).setUnlocalizedName("Silver Double Ingot")).setSize(EnumSize.LARGE);
SteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot2x",16066), EnumMetalType.STEEL).setUnlocalizedName("Steel Double Ingot")).setSize(EnumSize.LARGE);
SterlingSilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot2x",16067), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Double Ingot")).setSize(EnumSize.LARGE);
TinIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot2x",16068), EnumMetalType.TIN).setUnlocalizedName("Tin Double Ingot")).setSize(EnumSize.LARGE);
ZincIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot2x",16069), EnumMetalType.ZINC).setUnlocalizedName("Zinc Double Ingot")).setSize(EnumSize.LARGE);
SulfurPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SulfurPowder",16070)).setUnlocalizedName("Sulfur Powder");
SaltpeterPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SaltpeterPowder",16071)).setUnlocalizedName("Saltpeter Powder");
GemRuby = new ItemGem(TFC_Settings.getIntFor(config,"item","GemRuby",16080)).setUnlocalizedName("Ruby");
GemSapphire = new ItemGem(TFC_Settings.getIntFor(config,"item","GemSapphire",16081)).setUnlocalizedName("Sapphire");
GemEmerald = new ItemGem(TFC_Settings.getIntFor(config,"item","GemEmerald",16082)).setUnlocalizedName("Emerald");
GemTopaz = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTopaz",16083)).setUnlocalizedName("Topaz");
GemTourmaline = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTourmaline",16084)).setUnlocalizedName("Tourmaline");
GemJade = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJade",16085)).setUnlocalizedName("Jade");
GemBeryl = new ItemGem(TFC_Settings.getIntFor(config,"item","GemBeryl",16086)).setUnlocalizedName("Beryl");
GemAgate = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAgate",16087)).setUnlocalizedName("Agate");
GemOpal = new ItemGem(TFC_Settings.getIntFor(config,"item","GemOpal",16088)).setUnlocalizedName("Opal");
GemGarnet = new ItemGem(TFC_Settings.getIntFor(config,"item","GemGarnet",16089)).setUnlocalizedName("Garnet");
GemJasper = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJasper",16090)).setUnlocalizedName("Jasper");
GemAmethyst = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAmethyst",16091)).setUnlocalizedName("Amethyst");
GemDiamond = new ItemGem(TFC_Settings.getIntFor(config,"item","GemDiamond",16092)).setUnlocalizedName("Diamond");
//Tools
IgInShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgInShovel",16101),IgInToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgInStoneUses);
IgInAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgInAxe",16102),IgInToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgInStoneUses);
IgInHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgInHoe",16103),IgInToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgInStoneUses);
SedShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SedShovel",16105),SedToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(SedStoneUses);
SedAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SedAxe",16106),SedToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(SedStoneUses);
SedHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SedHoe",16107),SedToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(SedStoneUses);
IgExShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgExShovel",16109),IgExToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgExStoneUses);
IgExAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgExAxe",16110),IgExToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgExStoneUses);
IgExHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgExHoe",16111),IgExToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgExStoneUses);
MMShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","MMShovel",16113),MMToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(MMStoneUses);
MMAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","MMAxe",16114),MMToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(MMStoneUses);
MMHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","MMHoe",16115),MMToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(MMStoneUses);
BismuthPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthPick",16116),BismuthToolMaterial).setUnlocalizedName("Bismuth Pick").setMaxDamage(BismuthUses);
BismuthShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthShovel",16117),BismuthToolMaterial).setUnlocalizedName("Bismuth Shovel").setMaxDamage(BismuthUses);
BismuthAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthAxe",16118),BismuthToolMaterial).setUnlocalizedName("Bismuth Axe").setMaxDamage(BismuthUses);
BismuthHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthHoe",16119),BismuthToolMaterial).setUnlocalizedName("Bismuth Hoe").setMaxDamage(BismuthUses);
BismuthBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthBronzePick",16120),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Pick").setMaxDamage(BismuthBronzeUses);
BismuthBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovel",16121),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Shovel").setMaxDamage(BismuthBronzeUses);
BismuthBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxe",16122),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Axe").setMaxDamage(BismuthBronzeUses);
BismuthBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoe",16123),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hoe").setMaxDamage(BismuthBronzeUses);
BlackBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackBronzePick",16124),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Pick").setMaxDamage(BlackBronzeUses);
BlackBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackBronzeShovel",16125),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Shovel").setMaxDamage(BlackBronzeUses);
BlackBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackBronzeAxe",16126),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Axe").setMaxDamage(BlackBronzeUses);
BlackBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackBronzeHoe",16127),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hoe").setMaxDamage(BlackBronzeUses);
BlackSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackSteelPick",16128),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Pick").setMaxDamage(BlackSteelUses);
BlackSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackSteelShovel",16129),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Shovel").setMaxDamage(BlackSteelUses);
BlackSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackSteelAxe",16130),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Axe").setMaxDamage(BlackSteelUses);
BlackSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackSteelHoe",16131),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hoe").setMaxDamage(BlackSteelUses);
BlueSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlueSteelPick",16132),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Pick").setMaxDamage(BlueSteelUses);
BlueSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlueSteelShovel",16133),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Shovel").setMaxDamage(BlueSteelUses);
BlueSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlueSteelAxe",16134),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Axe").setMaxDamage(BlueSteelUses);
BlueSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlueSteelHoe",16135),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hoe").setMaxDamage(BlueSteelUses);
BronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BronzePick",16136),BronzeToolMaterial).setUnlocalizedName("Bronze Pick").setMaxDamage(BronzeUses);
BronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BronzeShovel",16137),BronzeToolMaterial).setUnlocalizedName("Bronze Shovel").setMaxDamage(BronzeUses);
BronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BronzeAxe",16138),BronzeToolMaterial).setUnlocalizedName("Bronze Axe").setMaxDamage(BronzeUses);
BronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BronzeHoe",16139),BronzeToolMaterial).setUnlocalizedName("Bronze Hoe").setMaxDamage(BronzeUses);
CopperPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","CopperPick",16140),CopperToolMaterial).setUnlocalizedName("Copper Pick").setMaxDamage(CopperUses);
CopperShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","CopperShovel",16141),CopperToolMaterial).setUnlocalizedName("Copper Shovel").setMaxDamage(CopperUses);
CopperAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","CopperAxe",16142),CopperToolMaterial).setUnlocalizedName("Copper Axe").setMaxDamage(CopperUses);
CopperHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","CopperHoe",16143),CopperToolMaterial).setUnlocalizedName("Copper Hoe").setMaxDamage(CopperUses);
WroughtIronPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","WroughtIronPick",16148),IronToolMaterial).setUnlocalizedName("Wrought Iron Pick").setMaxDamage(WroughtIronUses);
WroughtIronShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","WroughtIronShovel",16149),IronToolMaterial).setUnlocalizedName("Wrought Iron Shovel").setMaxDamage(WroughtIronUses);
WroughtIronAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","WroughtIronAxe",16150),IronToolMaterial).setUnlocalizedName("Wrought Iron Axe").setMaxDamage(WroughtIronUses);
WroughtIronHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","WroughtIronHoe",16151),IronToolMaterial).setUnlocalizedName("Wrought Iron Hoe").setMaxDamage(WroughtIronUses);;
RedSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RedSteelPick",16168),RedSteelToolMaterial).setUnlocalizedName("Red Steel Pick").setMaxDamage(RedSteelUses);
RedSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RedSteelShovel",16169),RedSteelToolMaterial).setUnlocalizedName("Red Steel Shovel").setMaxDamage(RedSteelUses);
RedSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RedSteelAxe",16170),RedSteelToolMaterial).setUnlocalizedName("Red Steel Axe").setMaxDamage(RedSteelUses);
RedSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RedSteelHoe",16171),RedSteelToolMaterial).setUnlocalizedName("Red Steel Hoe").setMaxDamage(RedSteelUses);
RoseGoldPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RoseGoldPick",16172),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Pick").setMaxDamage(RoseGoldUses);
RoseGoldShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RoseGoldShovel",16173),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Shovel").setMaxDamage(RoseGoldUses);
RoseGoldAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RoseGoldAxe",16174),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Axe").setMaxDamage(RoseGoldUses);
RoseGoldHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RoseGoldHoe",16175),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hoe").setMaxDamage(RoseGoldUses);
SteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","SteelPick",16180),SteelToolMaterial).setUnlocalizedName("Steel Pick").setMaxDamage(SteelUses);
SteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SteelShovel",16181),SteelToolMaterial).setUnlocalizedName("Steel Shovel").setMaxDamage(SteelUses);
SteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SteelAxe",16182),SteelToolMaterial).setUnlocalizedName("Steel Axe").setMaxDamage(SteelUses);
SteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SteelHoe",16183),SteelToolMaterial).setUnlocalizedName("Steel Hoe").setMaxDamage(SteelUses);
TinPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","TinPick",16188),TinToolMaterial).setUnlocalizedName("Tin Pick").setMaxDamage(TinUses);
TinShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","TinShovel",16189),TinToolMaterial).setUnlocalizedName("Tin Shovel").setMaxDamage(TinUses);
TinAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","TinAxe",16190),TinToolMaterial).setUnlocalizedName("Tin Axe").setMaxDamage(TinUses);
TinHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","TinHoe",16191),TinToolMaterial).setUnlocalizedName("Tin Hoe").setMaxDamage(TinUses);
ZincPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","ZincPick",16192),ZincToolMaterial).setUnlocalizedName("Zinc Pick").setMaxDamage(ZincUses);
ZincShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","ZincShovel",16193),ZincToolMaterial).setUnlocalizedName("Zinc Shovel").setMaxDamage(ZincUses);
ZincAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","ZincAxe",16194),ZincToolMaterial).setUnlocalizedName("Zinc Axe").setMaxDamage(ZincUses);
ZincHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","ZincHoe",16195),ZincToolMaterial).setUnlocalizedName("Zinc Hoe").setMaxDamage(ZincUses);
//chisels
BismuthChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthChisel",16226),BismuthToolMaterial).setUnlocalizedName("Bismuth Chisel").setMaxDamage(BismuthUses);
BismuthBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthBronzeChisel",16227),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Chisel").setMaxDamage(BismuthBronzeUses);
BlackBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackBronzeChisel",16228),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Chisel").setMaxDamage(BlackBronzeUses);
BlackSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackSteelChisel",16230),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Chisel").setMaxDamage(BlackSteelUses);
BlueSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlueSteelChisel",16231),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Chisel").setMaxDamage(BlueSteelUses);
BronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BronzeChisel",16232),BronzeToolMaterial).setUnlocalizedName("Bronze Chisel").setMaxDamage(BronzeUses);
CopperChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","CopperChisel",16233),CopperToolMaterial).setUnlocalizedName("Copper Chisel").setMaxDamage(CopperUses);
WroughtIronChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","WroughtIronChisel",16234),IronToolMaterial).setUnlocalizedName("Wrought Iron Chisel").setMaxDamage(WroughtIronUses);
RedSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RedSteelChisel",16235),RedSteelToolMaterial).setUnlocalizedName("Red Steel Chisel").setMaxDamage(RedSteelUses);
RoseGoldChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RoseGoldChisel",16236),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Chisel").setMaxDamage(RoseGoldUses);
SteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","SteelChisel",16237),SteelToolMaterial).setUnlocalizedName("Steel Chisel").setMaxDamage(SteelUses);
TinChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","TinChisel",16238),TinToolMaterial).setUnlocalizedName("Tin Chisel").setMaxDamage(TinUses);
ZincChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","ZincChisel",16239),ZincToolMaterial).setUnlocalizedName("Zinc Chisel").setMaxDamage(ZincUses);
StoneChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","StoneChisel",16240),IgInToolMaterial).setUnlocalizedName("Stone Chisel").setMaxDamage(IgInStoneUses);
BismuthSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthSword",16245),BismuthToolMaterial).setUnlocalizedName("Bismuth Sword").setMaxDamage(BismuthUses);
BismuthBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeSword",16246),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Sword").setMaxDamage(BismuthBronzeUses);
BlackBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeSword",16247),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Sword").setMaxDamage(BlackBronzeUses);
BlackSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelSword",16248),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Sword").setMaxDamage(BlackSteelUses);
BlueSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelSword",16249),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Sword").setMaxDamage(BlueSteelUses);
BronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeSword",16250),BronzeToolMaterial).setUnlocalizedName("Bronze Sword").setMaxDamage(BronzeUses);
CopperSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperSword",16251),CopperToolMaterial).setUnlocalizedName("Copper Sword").setMaxDamage(CopperUses);
WroughtIronSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronSword",16252),IronToolMaterial).setUnlocalizedName("Wrought Iron Sword").setMaxDamage(WroughtIronUses);
RedSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelSword",16253),RedSteelToolMaterial).setUnlocalizedName("Red Steel Sword").setMaxDamage(RedSteelUses);
RoseGoldSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldSword",16254),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Sword").setMaxDamage(RoseGoldUses);
SteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelSword",16255),SteelToolMaterial).setUnlocalizedName("Steel Sword").setMaxDamage(SteelUses);
TinSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinSword",16256),TinToolMaterial).setUnlocalizedName("Tin Sword").setMaxDamage(TinUses);
ZincSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincSword",16257),ZincToolMaterial).setUnlocalizedName("Zinc Sword").setMaxDamage(ZincUses);
BismuthMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthMace",16262),BismuthToolMaterial).setUnlocalizedName("Bismuth Mace").setMaxDamage(BismuthUses);
BismuthBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeMace",16263),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Mace").setMaxDamage(BismuthBronzeUses);
BlackBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeMace",16264),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Mace").setMaxDamage(BlackBronzeUses);
BlackSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelMace",16265),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Mace").setMaxDamage(BlackSteelUses);
BlueSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelMace",16266),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Mace").setMaxDamage(BlueSteelUses);
BronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeMace",16267),BronzeToolMaterial).setUnlocalizedName("Bronze Mace").setMaxDamage(BronzeUses);
CopperMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperMace",16268),CopperToolMaterial).setUnlocalizedName("Copper Mace").setMaxDamage(CopperUses);
WroughtIronMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronMace",16269),IronToolMaterial).setUnlocalizedName("Wrought Iron Mace").setMaxDamage(WroughtIronUses);
RedSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelMace",16270),RedSteelToolMaterial).setUnlocalizedName("Red Steel Mace").setMaxDamage(RedSteelUses);
RoseGoldMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldMace",16271),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Mace").setMaxDamage(RoseGoldUses);
SteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelMace",16272),SteelToolMaterial).setUnlocalizedName("Steel Mace").setMaxDamage(SteelUses);
TinMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinMace",16273),TinToolMaterial).setUnlocalizedName("Tin Mace").setMaxDamage(TinUses);
ZincMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincMace",16274),ZincToolMaterial).setUnlocalizedName("Zinc Mace").setMaxDamage(ZincUses);
BismuthSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthSaw",16275),BismuthToolMaterial).setUnlocalizedName("Bismuth Saw").setMaxDamage(BismuthUses);
BismuthBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthBronzeSaw",16276),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Saw").setMaxDamage(BismuthBronzeUses);
BlackBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackBronzeSaw",16277),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Saw").setMaxDamage(BlackBronzeUses);
BlackSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackSteelSaw",16278),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Saw").setMaxDamage(BlackSteelUses);
BlueSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlueSteelSaw",16279),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Saw").setMaxDamage(BlueSteelUses);
BronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BronzeSaw",16280),BronzeToolMaterial).setUnlocalizedName("Bronze Saw").setMaxDamage(BronzeUses);
CopperSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","CopperSaw",16281),CopperToolMaterial).setUnlocalizedName("Copper Saw").setMaxDamage(CopperUses);
WroughtIronSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","WroughtIronSaw",16282),IronToolMaterial).setUnlocalizedName("Wrought Iron Saw").setMaxDamage(WroughtIronUses);
RedSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RedSteelSaw",16283),RedSteelToolMaterial).setUnlocalizedName("Red Steel Saw").setMaxDamage(RedSteelUses);
RoseGoldSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RoseGoldSaw",16284),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Saw").setMaxDamage(RoseGoldUses);
SteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","SteelSaw",16285),SteelToolMaterial).setUnlocalizedName("Steel Saw").setMaxDamage(SteelUses);
TinSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","TinSaw",16286),TinToolMaterial).setUnlocalizedName("Tin Saw").setMaxDamage(TinUses);
ZincSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","ZincSaw",16287),ZincToolMaterial).setUnlocalizedName("Zinc Saw").setMaxDamage(ZincUses);
HCBlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlackSteelIngot",16290), EnumMetalType.BLACKSTEEL).setUnlocalizedName("HC Black Steel Ingot");
WeakBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakBlueSteelIngot",16291),EnumMetalType.BLUESTEEL).setUnlocalizedName("Weak Blue Steel Ingot");
WeakRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakRedSteelIngot",16292),EnumMetalType.REDSTEEL).setUnlocalizedName("Weak Red Steel Ingot");
WeakSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakSteelIngot",16293),EnumMetalType.STEEL).setUnlocalizedName("Weak Steel Ingot");
HCBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlueSteelIngot",16294), EnumMetalType.BLUESTEEL).setUnlocalizedName("HC Blue Steel Ingot");
HCRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCRedSteelIngot",16295), EnumMetalType.REDSTEEL).setUnlocalizedName("HC Red Steel Ingot");
HCSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCSteelIngot",16296), EnumMetalType.STEEL).setUnlocalizedName("HC Steel Ingot");
OreChunk = new ItemOre(TFC_Settings.getIntFor(config,"item","OreChunk",16297)).setFolder("ore/").setUnlocalizedName("Ore");
Logs = new ItemLogs(TFC_Settings.getIntFor(config,"item","Logs",16298)).setUnlocalizedName("Log");
Javelin = new ItemJavelin(TFC_Settings.getIntFor(config,"item","javelin",16318)).setUnlocalizedName("javelin");
BismuthUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuth",16350)).setUnlocalizedName("Bismuth Unshaped");
BismuthBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuthBronze",16351)).setUnlocalizedName("Bismuth Bronze Unshaped");
BlackBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackBronze",16352)).setUnlocalizedName("Black Bronze Unshaped");
BlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackSteel",16353)).setUnlocalizedName("Black Steel Unshaped");
BlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlueSteel",16354)).setUnlocalizedName("Blue Steel Unshaped");
BrassUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBrass",16355)).setUnlocalizedName("Brass Unshaped");
BronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBronze",16356)).setUnlocalizedName("Bronze Unshaped");
CopperUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedCopper",16357)).setUnlocalizedName("Copper Unshaped");
GoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedGold",16358)).setUnlocalizedName("Gold Unshaped");
WroughtIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedIron",16359)).setUnlocalizedName("Wrought Iron Unshaped");
LeadUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedLead",16360)).setUnlocalizedName("Lead Unshaped");
NickelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedNickel",16361)).setUnlocalizedName("Nickel Unshaped");
PigIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPigIron",16362)).setUnlocalizedName("Pig Iron Unshaped");
PlatinumUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPlatinum",16363)).setUnlocalizedName("Platinum Unshaped");
RedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRedSteel",16364)).setUnlocalizedName("Red Steel Unshaped");
RoseGoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRoseGold",16365)).setUnlocalizedName("Rose Gold Unshaped");
SilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSilver",16366)).setUnlocalizedName("Silver Unshaped");
SteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSteel",16367)).setUnlocalizedName("Steel Unshaped");
SterlingSilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSterlingSilver",16368)).setUnlocalizedName("Sterling Silver Unshaped");
TinUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedTin",16369)).setUnlocalizedName("Tin Unshaped");
ZincUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedZinc",16370)).setUnlocalizedName("Zinc Unshaped");
//Hammers
StoneHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","StoneHammer",16371),TFCItems.IgInToolMaterial).setUnlocalizedName("Stone Hammer").setMaxDamage(TFCItems.IgInStoneUses);
BismuthHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BismuthHammer",16372),TFCItems.BismuthToolMaterial).setUnlocalizedName("Bismuth Hammer").setMaxDamage(TFCItems.BismuthUses);
BismuthBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammer",16373),TFCItems.BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hammer").setMaxDamage(TFCItems.BismuthBronzeUses);
BlackBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlackBronzeHammer",16374),TFCItems.BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hammer").setMaxDamage(TFCItems.BlackBronzeUses);
BlackSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlackSteelHammer",16375),TFCItems.BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hammer").setMaxDamage(TFCItems.BlackSteelUses);
BlueSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BlueSteelHammer",16376),TFCItems.BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hammer").setMaxDamage(TFCItems.BlueSteelUses);
BronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","BronzeHammer",16377),TFCItems.BronzeToolMaterial).setUnlocalizedName("Bronze Hammer").setMaxDamage(TFCItems.BronzeUses);
CopperHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","CopperHammer",16378),TFCItems.CopperToolMaterial).setUnlocalizedName("Copper Hammer").setMaxDamage(TFCItems.CopperUses);
WroughtIronHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","WroughtIronHammer",16379),TFCItems.IronToolMaterial).setUnlocalizedName("Wrought Iron Hammer").setMaxDamage(TFCItems.WroughtIronUses);
RedSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","RedSteelHammer",16380),TFCItems.RedSteelToolMaterial).setUnlocalizedName("Red Steel Hammer").setMaxDamage(TFCItems.RedSteelUses);
RoseGoldHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","RoseGoldHammer",16381),TFCItems.RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hammer").setMaxDamage(TFCItems.RoseGoldUses);
SteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","SteelHammer",16382),TFCItems.SteelToolMaterial).setUnlocalizedName("Steel Hammer").setMaxDamage(TFCItems.SteelUses);
TinHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","TinHammer",16383),TFCItems.TinToolMaterial).setUnlocalizedName("Tin Hammer").setMaxDamage(TFCItems.TinUses);
ZincHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","ZincHammer",16384),TFCItems.ZincToolMaterial).setUnlocalizedName("Zinc Hammer").setMaxDamage(TFCItems.ZincUses);
Ink = new ItemTerra(TFC_Settings.getIntFor(config,"item","Ink",16391)).setUnlocalizedName("Ink");
BellowsItem = new ItemBellows(TFC_Settings.getIntFor(config,"item","BellowsItem",16406)).setUnlocalizedName("Bellows");
FireStarter = new ItemFirestarter(TFC_Settings.getIntFor(config,"item","FireStarter",16407)).setFolder("tools/").setUnlocalizedName("Firestarter");
//Tool heads
BismuthPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthPickaxeHead",16500)).setUnlocalizedName("Bismuth Pick Head");
BismuthBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzePickaxeHead",16501)).setUnlocalizedName("Bismuth Bronze Pick Head");
BlackBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzePickaxeHead",16502)).setUnlocalizedName("Black Bronze Pick Head");
BlackSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelPickaxeHead",16503)).setUnlocalizedName("Black Steel Pick Head");
BlueSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelPickaxeHead",16504)).setUnlocalizedName("Blue Steel Pick Head");
BronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzePickaxeHead",16505)).setUnlocalizedName("Bronze Pick Head");
CopperPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperPickaxeHead",16506)).setUnlocalizedName("Copper Pick Head");
WroughtIronPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronPickaxeHead",16507)).setUnlocalizedName("Wrought Iron Pick Head");
RedSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelPickaxeHead",16508)).setUnlocalizedName("Red Steel Pick Head");
RoseGoldPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldPickaxeHead",16509)).setUnlocalizedName("Rose Gold Pick Head");
SteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelPickaxeHead",16510)).setUnlocalizedName("Steel Pick Head");
TinPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinPickaxeHead",16511)).setUnlocalizedName("Tin Pick Head");
ZincPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincPickaxeHead",16512)).setUnlocalizedName("Zinc Pick Head");
BismuthShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthShovelHead",16513)).setUnlocalizedName("Bismuth Shovel Head");
BismuthBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovelHead",16514)).setUnlocalizedName("Bismuth Bronze Shovel Head");
BlackBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeShovelHead",16515)).setUnlocalizedName("Black Bronze Shovel Head");
BlackSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelShovelHead",16516)).setUnlocalizedName("Black Steel Shovel Head");
BlueSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelShovelHead",16517)).setUnlocalizedName("Blue Steel Shovel Head");
BronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeShovelHead",16518)).setUnlocalizedName("Bronze Shovel Head");
CopperShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperShovelHead",16519)).setUnlocalizedName("Copper Shovel Head");
WroughtIronShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronShovelHead",16520)).setUnlocalizedName("Wrought Iron Shovel Head");
RedSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelShovelHead",16521)).setUnlocalizedName("Red Steel Shovel Head");
RoseGoldShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldShovelHead",16522)).setUnlocalizedName("Rose Gold Shovel Head");
SteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelShovelHead",16523)).setUnlocalizedName("Steel Shovel Head");
TinShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinShovelHead",16524)).setUnlocalizedName("Tin Shovel Head");
ZincShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincShovelHead",16525)).setUnlocalizedName("Zinc Shovel Head");
BismuthHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHoeHead",16526)).setUnlocalizedName("Bismuth Hoe Head");
BismuthBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoeHead",16527)).setUnlocalizedName("Bismuth Bronze Hoe Head");
BlackBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHoeHead",16528)).setUnlocalizedName("Black Bronze Hoe Head");
BlackSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHoeHead",16529)).setUnlocalizedName("Black Steel Hoe Head");
BlueSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHoeHead",16530)).setUnlocalizedName("Blue Steel Hoe Head");
BronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHoeHead",16531)).setUnlocalizedName("Bronze Hoe Head");
CopperHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHoeHead",16532)).setUnlocalizedName("Copper Hoe Head");
WroughtIronHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHoeHead",16533)).setUnlocalizedName("Wrought Iron Hoe Head");
RedSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHoeHead",16534)).setUnlocalizedName("Red Steel Hoe Head");
RoseGoldHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHoeHead",16535)).setUnlocalizedName("Rose Gold Hoe Head");
SteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHoeHead",16536)).setUnlocalizedName("Steel Hoe Head");
TinHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHoeHead",16537)).setUnlocalizedName("Tin Hoe Head");
ZincHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHoeHead",16538)).setUnlocalizedName("Zinc Hoe Head");
BismuthAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthAxeHead",16539)).setUnlocalizedName("Bismuth Axe Head");
BismuthBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxeHead",16540)).setUnlocalizedName("Bismuth Bronze Axe Head");
BlackBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeAxeHead",16541)).setUnlocalizedName("Black Bronze Axe Head");
BlackSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelAxeHead",16542)).setUnlocalizedName("Black Steel Axe Head");
BlueSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelAxeHead",16543)).setUnlocalizedName("Blue Steel Axe Head");
BronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeAxeHead",16544)).setUnlocalizedName("Bronze Axe Head");
CopperAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperAxeHead",16545)).setUnlocalizedName("Copper Axe Head");
WroughtIronAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronAxeHead",16546)).setUnlocalizedName("Wrought Iron Axe Head");
RedSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelAxeHead",16547)).setUnlocalizedName("Red Steel Axe Head");
RoseGoldAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldAxeHead",16548)).setUnlocalizedName("Rose Gold Axe Head");
SteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelAxeHead",16549)).setUnlocalizedName("Steel Axe Head");
TinAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinAxeHead",16550)).setUnlocalizedName("Tin Axe Head");
ZincAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincAxeHead",16551)).setUnlocalizedName("Zinc Axe Head");
BismuthHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHammerHead",16552)).setUnlocalizedName("Bismuth Hammer Head");
BismuthBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammerHead",16553)).setUnlocalizedName("Bismuth Bronze Hammer Head");
BlackBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHammerHead",16554)).setUnlocalizedName("Black Bronze Hammer Head");
BlackSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHammerHead",16555)).setUnlocalizedName("Black Steel Hammer Head");
BlueSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHammerHead",16556)).setUnlocalizedName("Blue Steel Hammer Head");
BronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHammerHead",16557)).setUnlocalizedName("Bronze Hammer Head");
CopperHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHammerHead",16558)).setUnlocalizedName("Copper Hammer Head");
WroughtIronHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHammerHead",16559)).setUnlocalizedName("Wrought Iron Hammer Head");
RedSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHammerHead",16560)).setUnlocalizedName("Red Steel Hammer Head");
RoseGoldHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHammerHead",16561)).setUnlocalizedName("Rose Gold Hammer Head");
SteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHammerHead",16562)).setUnlocalizedName("Steel Hammer Head");
TinHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHammerHead",16563)).setUnlocalizedName("Tin Hammer Head");
ZincHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHammerHead",16564)).setUnlocalizedName("Zinc Hammer Head");
//chisel heads
BismuthChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthChiselHead",16565)).setUnlocalizedName("Bismuth Chisel Head");
BismuthBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeChiselHead",16566)).setUnlocalizedName("Bismuth Bronze Chisel Head");
BlackBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeChiselHead",16567)).setUnlocalizedName("Black Bronze Chisel Head");
BlackSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelChiselHead",16568)).setUnlocalizedName("Black Steel Chisel Head");
BlueSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelChiselHead",16569)).setUnlocalizedName("Blue Steel Chisel Head");
BronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeChiselHead",16570)).setUnlocalizedName("Bronze Chisel Head");
CopperChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperChiselHead",16571)).setUnlocalizedName("Copper Chisel Head");
WroughtIronChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronChiselHead",16572)).setUnlocalizedName("Wrought Iron Chisel Head");
RedSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelChiselHead",16573)).setUnlocalizedName("Red Steel Chisel Head");
RoseGoldChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldChiselHead",16574)).setUnlocalizedName("Rose Gold Chisel Head");
SteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelChiselHead",16575)).setUnlocalizedName("Steel Chisel Head");
TinChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinChiselHead",16576)).setUnlocalizedName("Tin Chisel Head");
ZincChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincChiselHead",16577)).setUnlocalizedName("Zinc Chisel Head");
BismuthSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSwordHead",16578)).setUnlocalizedName("Bismuth Sword Blade");
BismuthBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSwordHead",16579)).setUnlocalizedName("Bismuth Bronze Sword Blade");
BlackBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSwordHead",16580)).setUnlocalizedName("Black Bronze Sword Blade");
BlackSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSwordHead",16581)).setUnlocalizedName("Black Steel Sword Blade");
BlueSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSwordHead",16582)).setUnlocalizedName("Blue Steel Sword Blade");
BronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSwordHead",16583)).setUnlocalizedName("Bronze Sword Blade");
CopperSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSwordHead",16584)).setUnlocalizedName("Copper Sword Blade");
WroughtIronSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSwordHead",16585)).setUnlocalizedName("Wrought Iron Sword Blade");
RedSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSwordHead",16586)).setUnlocalizedName("Red Steel Sword Blade");
RoseGoldSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSwordHead",16587)).setUnlocalizedName("Rose Gold Sword Blade");
SteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSwordHead",16588)).setUnlocalizedName("Steel Sword Blade");
TinSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSwordHead",16589)).setUnlocalizedName("Tin Sword Blade");
ZincSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSwordHead",16590)).setUnlocalizedName("Zinc Sword Blade");
BismuthMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthMaceHead",16591)).setUnlocalizedName("Bismuth Mace Head");
BismuthBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeMaceHead",16592)).setUnlocalizedName("Bismuth Bronze Mace Head");
BlackBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeMaceHead",16593)).setUnlocalizedName("Black Bronze Mace Head");
BlackSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelMaceHead",16594)).setUnlocalizedName("Black Steel Mace Head");
BlueSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelMaceHead",16595)).setUnlocalizedName("Blue Steel Mace Head");
BronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeMaceHead",16596)).setUnlocalizedName("Bronze Mace Head");
CopperMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperMaceHead",16597)).setUnlocalizedName("Copper Mace Head");
WroughtIronMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronMaceHead",16598)).setUnlocalizedName("Wrought Iron Mace Head");
RedSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelMaceHead",16599)).setUnlocalizedName("Red Steel Mace Head");
RoseGoldMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldMaceHead",16600)).setUnlocalizedName("Rose Gold Mace Head");
SteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelMaceHead",16601)).setUnlocalizedName("Steel Mace Head");
TinMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinMaceHead",16602)).setUnlocalizedName("Tin Mace Head");
ZincMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincMaceHead",16603)).setUnlocalizedName("Zinc Mace Head");
BismuthSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSawHead",16604)).setUnlocalizedName("Bismuth Saw Blade");
BismuthBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSawHead",16605)).setUnlocalizedName("Bismuth Bronze Saw Blade");
BlackBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSawHead",16606)).setUnlocalizedName("Black Bronze Saw Blade");
BlackSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSawHead",16607)).setUnlocalizedName("Black Steel Saw Blade");
BlueSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSawHead",16608)).setUnlocalizedName("Blue Steel Saw Blade");
BronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSawHead",16609)).setUnlocalizedName("Bronze Saw Blade");
CopperSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSawHead",16610)).setUnlocalizedName("Copper Saw Blade");
WroughtIronSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSawHead",16611)).setUnlocalizedName("Wrought Iron Saw Blade");
RedSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSawHead",16612)).setUnlocalizedName("Red Steel Saw Blade");
RoseGoldSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSawHead",16613)).setUnlocalizedName("Rose Gold Saw Blade");
SteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSawHead",16614)).setUnlocalizedName("Steel Saw Blade");
TinSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSawHead",16615)).setUnlocalizedName("Tin Saw Blade");
ZincSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSawHead",16616)).setUnlocalizedName("Zinc Saw Blade");
HCBlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlackSteel",16617)).setUnlocalizedName("HC Black Steel Unshaped");
WeakBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakBlueSteel",16618)).setUnlocalizedName("Weak Blue Steel Unshaped");
HCBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlueSteel",16619)).setUnlocalizedName("HC Blue Steel Unshaped");
WeakRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakRedSteel",16621)).setUnlocalizedName("Weak Red Steel Unshaped");
HCRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCRedSteel",16622)).setUnlocalizedName("HC Red Steel Unshaped");
WeakSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakSteel",16623)).setUnlocalizedName("Weak Steel Unshaped");
HCSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCSteel",16624)).setUnlocalizedName("HC Steel Unshaped");
Coke = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Coke",16625)).setUnlocalizedName("Coke"));
BismuthProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthProPickHead",16626)).setUnlocalizedName("Bismuth ProPick Head");
BismuthBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeProPickHead",16627)).setUnlocalizedName("Bismuth Bronze ProPick Head");
BlackBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeProPickHead",16628)).setUnlocalizedName("Black Bronze ProPick Head");
BlackSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelProPickHead",16629)).setUnlocalizedName("Black Steel ProPick Head");
BlueSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelProPickHead",16630)).setUnlocalizedName("Blue Steel ProPick Head");
BronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeProPickHead",16631)).setUnlocalizedName("Bronze ProPick Head");
CopperProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperProPickHead",16632)).setUnlocalizedName("Copper ProPick Head");
WroughtIronProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronProPickHead",16633)).setUnlocalizedName("Wrought Iron ProPick Head");
RedSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelProPickHead",16634)).setUnlocalizedName("Red Steel ProPick Head");
RoseGoldProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldProPickHead",16635)).setUnlocalizedName("Rose Gold ProPick Head");
SteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelProPickHead",16636)).setUnlocalizedName("Steel ProPick Head");
TinProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinProPickHead",16637)).setUnlocalizedName("Tin ProPick Head");
ZincProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincProPickHead",16638)).setUnlocalizedName("Zinc ProPick Head");
Flux = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Flux",16639)).setUnlocalizedName("Flux"));
/**
* Scythe
* */
int num = 16643;
BismuthScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthScythe",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Scythe").setMaxDamage(BismuthUses);num++;
BismuthBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthBronzeScythe",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Scythe").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackBronzeScythe",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Scythe").setMaxDamage(BlackBronzeUses);num++;
BlackSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackSteelScythe",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Scythe").setMaxDamage(BlackSteelUses);num++;
BlueSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlueSteelScythe",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Scythe").setMaxDamage(BlueSteelUses);num++;
BronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BronzeScythe",num),BronzeToolMaterial).setUnlocalizedName("Bronze Scythe").setMaxDamage(BronzeUses);num++;
CopperScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","CopperScythe",num),CopperToolMaterial).setUnlocalizedName("Copper Scythe").setMaxDamage(CopperUses);num++;
WroughtIronScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","WroughtIronScythe",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Scythe").setMaxDamage(WroughtIronUses);num++;
RedSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RedSteelScythe",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Scythe").setMaxDamage(RedSteelUses);num++;
RoseGoldScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RoseGoldScythe",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Scythe").setMaxDamage(RoseGoldUses);num++;
SteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","SteelScythe",num),SteelToolMaterial).setUnlocalizedName("Steel Scythe").setMaxDamage(SteelUses);num++;
TinScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","TinScythe",num),TinToolMaterial).setUnlocalizedName("Tin Scythe").setMaxDamage(TinUses);num++;
ZincScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","ZincScythe",num),ZincToolMaterial).setUnlocalizedName("Zinc Scythe").setMaxDamage(ZincUses);num++;
BismuthScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthScytheHead",num)).setUnlocalizedName("Bismuth Scythe Blade");num++;
BismuthBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeScytheHead",num)).setUnlocalizedName("Bismuth Bronze Scythe Blade");num++;
BlackBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeScytheHead",num)).setUnlocalizedName("Black Bronze Scythe Blade");num++;
BlackSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelScytheHead",num)).setUnlocalizedName("Black Steel Scythe Blade");num++;
BlueSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelScytheHead",num)).setUnlocalizedName("Blue Steel Scythe Blade");num++;
BronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeScytheHead",num)).setUnlocalizedName("Bronze Scythe Blade");num++;
CopperScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperScytheHead",num)).setUnlocalizedName("Copper Scythe Blade");num++;
WroughtIronScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronScytheHead",num)).setUnlocalizedName("Wrought Iron Scythe Blade");num++;
RedSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelScytheHead",num)).setUnlocalizedName("Red Steel Scythe Blade");num++;
RoseGoldScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldScytheHead",num)).setUnlocalizedName("Rose Gold Scythe Blade");num++;
SteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelScytheHead",num)).setUnlocalizedName("Steel Scythe Blade");num++;
TinScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinScytheHead",num)).setUnlocalizedName("Tin Scythe Blade");num++;
ZincScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincScytheHead",num)).setUnlocalizedName("Zinc Scythe Blade");num++;
WoodenBucketEmpty = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketEmpty",num), 0)).setUnlocalizedName("Wooden Bucket Empty");num++;
WoodenBucketWater = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketWater",num), TFCBlocks.finiteWater.blockID)).setUnlocalizedName("Wooden Bucket Water").setContainerItem(WoodenBucketEmpty);num++;
WoodenBucketMilk = (new ItemCustomBucketMilk(TFC_Settings.getIntFor(config,"item","WoodenBucketMilk",num))).setUnlocalizedName("Wooden Bucket Milk").setContainerItem(WoodenBucketEmpty);num++;
BismuthKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthKnifeHead",num)).setUnlocalizedName("Bismuth Knife Blade");num++;
BismuthBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnifeHead",num)).setUnlocalizedName("Bismuth Bronze Knife Blade");num++;
BlackBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeKnifeHead",num)).setUnlocalizedName("Black Bronze Knife Blade");num++;
BlackSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelKnifeHead",num)).setUnlocalizedName("Black Steel Knife Blade");num++;
BlueSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelKnifeHead",num)).setUnlocalizedName("Blue Steel Knife Blade");num++;
BronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeKnifeHead",num)).setUnlocalizedName("Bronze Knife Blade");num++;
CopperKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperKnifeHead",num)).setUnlocalizedName("Copper Knife Blade");num++;
WroughtIronKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronKnifeHead",num)).setUnlocalizedName("Wrought Iron Knife Blade");num++;
RedSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelKnifeHead",num)).setUnlocalizedName("Red Steel Knife Blade");num++;
RoseGoldKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldKnifeHead",num)).setUnlocalizedName("Rose Gold Knife Blade");num++;
SteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelKnifeHead",num)).setUnlocalizedName("Steel Knife Blade");num++;
TinKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinKnifeHead",num)).setUnlocalizedName("Tin Knife Blade");num++;
ZincKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincKnifeHead",num)).setUnlocalizedName("Zinc Knife Blade");num++;
BismuthKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthKnife",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Knife").setMaxDamage(BismuthUses);num++;
BismuthBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnife",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Knife").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackBronzeKnife",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Knife").setMaxDamage(BlackBronzeUses);num++;
BlackSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackSteelKnife",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Knife").setMaxDamage(BlackSteelUses);num++;
BlueSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlueSteelKnife",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Knife").setMaxDamage(BlueSteelUses);num++;
BronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BronzeKnife",num),BronzeToolMaterial).setUnlocalizedName("Bronze Knife").setMaxDamage(BronzeUses);num++;
CopperKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","CopperKnife",num),CopperToolMaterial).setUnlocalizedName("Copper Knife").setMaxDamage(CopperUses);num++;
WroughtIronKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","WroughtIronKnife",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Knife").setMaxDamage(WroughtIronUses);num++;
RedSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RedSteelKnife",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Knife").setMaxDamage(RedSteelUses);num++;
RoseGoldKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RoseGoldKnife",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Knife").setMaxDamage(RoseGoldUses);num++;
SteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","SteelKnife",num),SteelToolMaterial).setUnlocalizedName("Steel Knife").setMaxDamage(SteelUses);num++;
TinKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","TinKnife",num),TinToolMaterial).setUnlocalizedName("Tin Knife").setMaxDamage(TinUses);num++;
ZincKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","ZincKnife",num),ZincToolMaterial).setUnlocalizedName("Zinc Knife").setMaxDamage(ZincUses);num++;
LooseRock = (new ItemLooseRock(TFC_Settings.getIntFor(config,"item","LooseRock",num)).setUnlocalizedName("LooseRock"));num++;
FlatRock = (new ItemFlatRock(TFC_Settings.getIntFor(config,"item","FlatRock",num)).setUnlocalizedName("FlatRock"));num++;
IgInStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
SedStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgExStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
MMStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgInStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
SedStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgExStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
MMStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgInStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
SedStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
IgExStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
MMStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
StoneKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneKnifeHead",num)).setUnlocalizedName("Stone Knife Blade");num++;
StoneHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneHammerHead",num)).setUnlocalizedName("Stone Hammer Head");num++;
StoneKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","StoneKnife",num),IgExToolMaterial).setUnlocalizedName("Stone Knife").setMaxDamage(IgExStoneUses);num++;
SmallOreChunk = new ItemOreSmall(TFC_Settings.getIntFor(config,"item","SmallOreChunk",num++)).setUnlocalizedName("Small Ore");
SinglePlank = new ItemPlank(TFC_Settings.getIntFor(config,"item","SinglePlank",num++)).setUnlocalizedName("SinglePlank");
RedSteelBucketEmpty = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketEmpty",num++), 0)).setUnlocalizedName("Red Steel Bucket Empty");
RedSteelBucketWater = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketWater",num++), Block.waterMoving.blockID)).setUnlocalizedName("Red Steel Bucket Water").setContainerItem(RedSteelBucketEmpty);
BlueSteelBucketEmpty = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketEmpty",num++), 0)).setUnlocalizedName("Blue Steel Bucket Empty");
BlueSteelBucketLava = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketLava",num++), Block.lavaMoving.blockID)).setUnlocalizedName("Blue Steel Bucket Lava").setContainerItem(BlueSteelBucketEmpty);
Quern = new ItemTerra(TFC_Settings.getIntFor(config,"item","Quern",num++)).setUnlocalizedName("Quern").setMaxDamage(250);
FlintSteel = new ItemFlintSteel(TFC_Settings.getIntFor(config,"item","FlintSteel",num++)).setUnlocalizedName("flintAndSteel").setMaxDamage(200);
DoorOak = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorOak", num++), 0).setUnlocalizedName("Oak Door");
DoorAspen = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAspen", num++), 1).setUnlocalizedName("Aspen Door");
DoorBirch = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorBirch", num++), 2).setUnlocalizedName("Birch Door");
DoorChestnut = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorChestnut", num++), 3).setUnlocalizedName("Chestnut Door");
DoorDouglasFir = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorDouglasFir", num++), 4).setUnlocalizedName("Douglas Fir Door");
DoorHickory = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorHickory", num++), 5).setUnlocalizedName("Hickory Door");
DoorMaple = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorMaple", num++), 6).setUnlocalizedName("Maple Door");
DoorAsh = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAsh", num++), 7).setUnlocalizedName("Ash Door");
DoorPine = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorPine", num++), 8).setUnlocalizedName("Pine Door");
DoorSequoia = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSequoia", num++), 9).setUnlocalizedName("Sequoia Door");
DoorSpruce = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSpruce", num++), 10).setUnlocalizedName("Spruce Door");
DoorSycamore = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSycamore", num++), 11).setUnlocalizedName("Sycamore Door");
DoorWhiteCedar = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteCedar", num++), 12).setUnlocalizedName("White Cedar Door");
DoorWhiteElm = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteElm", num++), 13).setUnlocalizedName("White Elm Door");
DoorWillow = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWillow", num++), 14).setUnlocalizedName("Willow Door");
DoorKapok = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorKapok", num++), 15).setUnlocalizedName("Kapok Door");
Blueprint = new ItemBlueprint(TFC_Settings.getIntFor(config,"item","Blueprint", num++));
writabeBookTFC = new ItemWritableBookTFC(TFC_Settings.getIntFor(config,"item","WritableBookTFC", num++),"Fix Me I'm Broken").setUnlocalizedName("book");
WoolYarn = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolYarn", num++)).setUnlocalizedName("WoolYarn").setCreativeTab(TFCTabs.TFCMaterials);
Wool = new ItemTerra(TFC_Settings.getIntFor(config,"item","Wool",num++)).setUnlocalizedName("Wool").setCreativeTab(TFCTabs.TFCMaterials);
WoolCloth = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolCloth", num++)).setUnlocalizedName("WoolCloth").setCreativeTab(TFCTabs.TFCMaterials);
Spindle = new ItemSpindle(TFC_Settings.getIntFor(config,"item","Spindle",num++),SedToolMaterial).setUnlocalizedName("Spindle").setCreativeTab(TFCTabs.TFCMaterials);
ClaySpindle = new ItemTerra(TFC_Settings.getIntFor(config, "item", "ClaySpindle", num++)).setFolder("tools/").setUnlocalizedName("Clay Spindle").setCreativeTab(TFCTabs.TFCMaterials);
SpindleHead = new ItemTerra(TFC_Settings.getIntFor(config, "item", "SpindleHead", num++)).setFolder("toolheads/").setUnlocalizedName("Spindle Head").setCreativeTab(TFCTabs.TFCMaterials);
StoneBrick = (new ItemStoneBrick(TFC_Settings.getIntFor(config,"item","ItemStoneBrick2",num++)).setFolder("tools/").setUnlocalizedName("ItemStoneBrick"));
Mortar = new ItemTerra(TFC_Settings.getIntFor(config,"item","Mortar",num++)).setFolder("tools/").setUnlocalizedName("Mortar").setCreativeTab(TFCTabs.TFCMaterials);
Limewater = new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","Limewater",num++),0).setFolder("tools/").setUnlocalizedName("Lime Water").setContainerItem(WoodenBucketEmpty).setCreativeTab(TFCTabs.TFCMaterials);
Hide = new ItemTerra(TFC_Settings.getIntFor(config,"item","Hide",num++)).setFolder("tools/").setUnlocalizedName("Hide").setCreativeTab(TFCTabs.TFCMaterials);
SoakedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","SoakedHide",num++)).setFolder("tools/").setUnlocalizedName("Soaked Hide").setCreativeTab(TFCTabs.TFCMaterials);
ScrapedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","ScrapedHide",num++)).setFolder("tools/").setUnlocalizedName("Scraped Hide").setCreativeTab(TFCTabs.TFCMaterials);
PrepHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","PrepHide",num++)).setFolder("tools/").setFolder("tools/").setUnlocalizedName("Prep Hide").setCreativeTab(TFCTabs.TFCMaterials);
TerraLeather = new ItemTerra(TFC_Settings.getIntFor(config,"item","TFCLeather",num++)).setFolder("tools/").setUnlocalizedName("TFC Leather").setCreativeTab(TFCTabs.TFCMaterials);
SheepSkin = new ItemTerra(TFC_Settings.getIntFor(config,"item","SheepSkin",num++)).setFolder("tools/").setUnlocalizedName("Sheep Skin").setCreativeTab(TFCTabs.TFCMaterials);
muttonRaw = new ItemTerra(TFC_Settings.getIntFor(config,"item","muttonRaw",num++)).setFolder("food/").setUnlocalizedName("Mutton Raw");
muttonCooked = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","muttonCooked",num++), 40, 0.8F, true, 48).setUnlocalizedName("Mutton Cooked");
FlatLeather = (new ItemFlatLeather(TFC_Settings.getIntFor(config,"items","FlatLeather2",num++)).setFolder("tools/").setUnlocalizedName("Flat Leather"));
PotteryJug = new ItemPotteryJug(TFC_Settings.getIntFor(config,"items","PotteryJug",num++)).setUnlocalizedName("Jug");
PotterySmallVessel = new ItemPotterySmallVessel(TFC_Settings.getIntFor(config,"items","PotterySmallVessel",num++)).setUnlocalizedName("Small Vessel");
PotteryLargeVessel = new ItemPotteryLargeVessel(TFC_Settings.getIntFor(config,"items","PotteryLargeVessel",num++)).setUnlocalizedName("Large Vessel");
PotteryPot = new ItemPotteryPot(TFC_Settings.getIntFor(config,"items","PotteryPot",num++)).setUnlocalizedName("Pot");
CeramicMold = new ItemPotteryBase(TFC_Settings.getIntFor(config,"item","CeramicMold",16409)).setMetaNames(new String[]{"Clay Mold","Ceramic Mold"}).setUnlocalizedName("Mold");
Straw = new ItemTerra(TFC_Settings.getIntFor(config,"items","Straw",num++)).setFolder("plants/").setUnlocalizedName("Straw");
/**Plans*/
num = 20000;
SetupPlans(num);
/**Food related items*/
num = 18000;
SetupFood(num);
/**Armor Crafting related items*/
num = 19000;
SetupArmor(num);
Recipes.Doors = new Item[]{DoorOak, DoorAspen, DoorBirch, DoorChestnut, DoorDouglasFir,
DoorHickory, DoorMaple, DoorAsh, DoorPine, DoorSequoia, DoorSpruce, DoorSycamore,
DoorWhiteCedar, DoorWhiteElm, DoorWillow, DoorKapok};
Recipes.Axes = new Item[]{SedAxe,IgInAxe,IgExAxe,MMAxe,
BismuthAxe,BismuthBronzeAxe,BlackBronzeAxe,
BlackSteelAxe,BlueSteelAxe,BronzeAxe,CopperAxe,
WroughtIronAxe,RedSteelAxe,RoseGoldAxe,SteelAxe,
TinAxe,ZincAxe};
Recipes.Chisels = new Item[]{BismuthChisel,BismuthBronzeChisel,BlackBronzeChisel,
BlackSteelChisel,BlueSteelChisel,BronzeChisel,CopperChisel,
WroughtIronChisel,RedSteelChisel,RoseGoldChisel,SteelChisel,
TinChisel,ZincChisel};
Recipes.Saws = new Item[]{BismuthSaw,BismuthBronzeSaw,BlackBronzeSaw,
BlackSteelSaw,BlueSteelSaw,BronzeSaw,CopperSaw,
WroughtIronSaw,RedSteelSaw,RoseGoldSaw,SteelSaw,
TinSaw,ZincSaw};
Recipes.Knives = new Item[]{StoneKnife,BismuthKnife,BismuthBronzeKnife,BlackBronzeKnife,
BlackSteelKnife,BlueSteelKnife,BronzeKnife,CopperKnife,
WroughtIronKnife,RedSteelKnife,RoseGoldKnife,SteelKnife,
TinKnife,ZincKnife};
Recipes.MeltedMetal = new Item[]{BismuthUnshaped, BismuthBronzeUnshaped,BlackBronzeUnshaped,
TFCItems.BlackSteelUnshaped,TFCItems.BlueSteelUnshaped,TFCItems.BrassUnshaped,TFCItems.BronzeUnshaped,
TFCItems.CopperUnshaped,TFCItems.GoldUnshaped,
TFCItems.WroughtIronUnshaped,TFCItems.LeadUnshaped,TFCItems.NickelUnshaped,TFCItems.PigIronUnshaped,
TFCItems.PlatinumUnshaped,TFCItems.RedSteelUnshaped,TFCItems.RoseGoldUnshaped,TFCItems.SilverUnshaped,
TFCItems.SteelUnshaped,TFCItems.SterlingSilverUnshaped,
TFCItems.TinUnshaped,TFCItems.ZincUnshaped, TFCItems.HCSteelUnshaped, TFCItems.WeakSteelUnshaped,
TFCItems.HCBlackSteelUnshaped, TFCItems.HCBlueSteelUnshaped, TFCItems.HCRedSteelUnshaped,
TFCItems.WeakBlueSteelUnshaped, TFCItems.WeakRedSteelUnshaped};
Recipes.Hammers = new Item[]{TFCItems.StoneHammer,TFCItems.BismuthHammer,TFCItems.BismuthBronzeHammer,TFCItems.BlackBronzeHammer,
TFCItems.BlackSteelHammer,TFCItems.BlueSteelHammer,TFCItems.BronzeHammer,TFCItems.CopperHammer,
TFCItems.WroughtIronHammer,TFCItems.RedSteelHammer,TFCItems.RoseGoldHammer,TFCItems.SteelHammer,
TFCItems.TinHammer,TFCItems.ZincHammer};
Recipes.Spindle = new Item[]{TFCItems.Spindle};
Recipes.Gems = new Item[]{TFCItems.GemAgate, TFCItems.GemAmethyst, TFCItems.GemBeryl, TFCItems.GemDiamond, TFCItems.GemEmerald, TFCItems.GemGarnet,
TFCItems.GemJade, TFCItems.GemJasper, TFCItems.GemOpal,TFCItems.GemRuby,TFCItems.GemSapphire,TFCItems.GemTopaz,TFCItems.GemTourmaline};
Meals = new Item[]{MealMoveSpeed, MealDigSpeed, MealDamageBoost, MealJump, MealDamageResist,
MealFireResist, MealWaterBreathing, MealNightVision};
((TFCTabs)TFCTabs.TFCTools).setTabIconItemIndex(TFCItems.RoseGoldHammer.itemID);
((TFCTabs)TFCTabs.TFCMaterials).setTabIconItemIndex(TFCItems.Spindle.itemID);
((TFCTabs)TFCTabs.TFCUnfinished).setTabIconItemIndex(TFCItems.RoseGoldHammerHead.itemID);
((TFCTabs)TFCTabs.TFCArmor).setTabIconItemIndex(TFCItems.SteelHelmet.itemID);
System.out.println(new StringBuilder().append("[TFC] Done Loading Items").toString());
if (config != null) {
config.save();
}
}
|
diff --git a/src/main/java/com/celements/photo/plugin/cmd/ComputeImageCommand.java b/src/main/java/com/celements/photo/plugin/cmd/ComputeImageCommand.java
index eef3a34..51df50a 100644
--- a/src/main/java/com/celements/photo/plugin/cmd/ComputeImageCommand.java
+++ b/src/main/java/com/celements/photo/plugin/cmd/ComputeImageCommand.java
@@ -1,132 +1,132 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 com.celements.photo.plugin.cmd;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.celements.photo.container.ImageDimensions;
import com.celements.photo.image.GenerateThumbnail;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.doc.XWikiAttachment;
public class ComputeImageCommand {
private static final Log mLogger = LogFactory.getFactory().getInstance(
ComputeImageCommand.class);
private ImageCacheCommand imgCacheCmd;
public XWikiAttachment computeImage(XWikiAttachment attachment,
XWikiContext context, XWikiAttachment attachmentClone, String sheight,
String swidth, String copyright, String watermark, Color defaultBg,
String defaultBgString) {
if((defaultBgString != null) && defaultBgString.matches("[0-9A-Fa-f]{6}")) {
int r = Integer.parseInt(defaultBgString.substring(1, 3), 16);
int g = Integer.parseInt(defaultBgString.substring(3, 5), 16);
int b = Integer.parseInt(defaultBgString.substring(5), 16);
defaultBg = new Color(r, g, b);
}
int height = parseIntWithDefault(sheight, 0);
int width = parseIntWithDefault(swidth, 0);
if ((height > 0) || (width > 0)) {
try {
attachmentClone = (XWikiAttachment) attachment.clone();
- GenerateThumbnail thumbGen = new GenerateThumbnail();
- ByteArrayInputStream in = new ByteArrayInputStream(attachmentClone.getContent(
- context));
- BufferedImage img = thumbGen.decodeImage(in);
- in.close();
// mLogger.debug("dimension: target width=" + width + "; target height=" + height
// + "; resized width=" + dimension.getWidth() + "; resized height="
// + dimension.getHeight());
String key = getImageCacheCmd(context).getCacheKey(attachmentClone,
new ImageDimensions(width, height), copyright, watermark, context);
mLogger.debug("attachment key: '" + key + "'");
byte[] data = getImageCacheCmd(context).getImageForKey(key, context);
if (data != null) {
mLogger.info("Found image in Cache.");
attachmentClone.setContent(data);
} else {
+ GenerateThumbnail thumbGen = new GenerateThumbnail();
+ ByteArrayInputStream in = new ByteArrayInputStream(attachmentClone.getContent(
+ context));
+ BufferedImage img = thumbGen.decodeImage(in);
+ in.close();
ImageDimensions dimension = thumbGen.getThumbnailDimensions(img, width, height);
mLogger.info("No cached image.");
attachmentClone.setContent(getThumbAttachment(img, dimension, thumbGen,
attachmentClone.getMimeType(context), watermark, copyright, defaultBg));
getImageCacheCmd(context).addToCache(key, attachmentClone, context);
}
} catch (Exception exp) {
mLogger.error("Error, could not resize / cache image", exp);
attachmentClone = attachment;
}
}
return attachmentClone;
}
int parseIntWithDefault(String sheight, int defValue) {
int height = defValue;
if ((sheight != null) && (sheight.length() > 0)) {
if (sheight != null) {
try {
height = Integer.parseInt(sheight);
} catch (NumberFormatException numExp) {
mLogger.debug("Failed to parse height [" + sheight + "].", numExp);
}
}
}
return height;
}
void injectImageCacheCmd(ImageCacheCommand mockImgCacheCmd) {
imgCacheCmd = mockImgCacheCmd;
}
ImageCacheCommand getImageCacheCmd(XWikiContext context) {
if (imgCacheCmd == null) {
imgCacheCmd = new ImageCacheCommand();
}
return imgCacheCmd;
}
public void flushCache() {
if (imgCacheCmd != null) {
imgCacheCmd.flushCache();
imgCacheCmd = null;
}
}
private byte[] getThumbAttachment(BufferedImage img, ImageDimensions dim,
GenerateThumbnail thumbGen, String mimeType, String watermark, String copyright,
Color defaultBg) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
thumbGen.createThumbnail(img, out, dim, watermark, copyright,
mimeType, defaultBg);
return out.toByteArray();
}
}
| false | true | public XWikiAttachment computeImage(XWikiAttachment attachment,
XWikiContext context, XWikiAttachment attachmentClone, String sheight,
String swidth, String copyright, String watermark, Color defaultBg,
String defaultBgString) {
if((defaultBgString != null) && defaultBgString.matches("[0-9A-Fa-f]{6}")) {
int r = Integer.parseInt(defaultBgString.substring(1, 3), 16);
int g = Integer.parseInt(defaultBgString.substring(3, 5), 16);
int b = Integer.parseInt(defaultBgString.substring(5), 16);
defaultBg = new Color(r, g, b);
}
int height = parseIntWithDefault(sheight, 0);
int width = parseIntWithDefault(swidth, 0);
if ((height > 0) || (width > 0)) {
try {
attachmentClone = (XWikiAttachment) attachment.clone();
GenerateThumbnail thumbGen = new GenerateThumbnail();
ByteArrayInputStream in = new ByteArrayInputStream(attachmentClone.getContent(
context));
BufferedImage img = thumbGen.decodeImage(in);
in.close();
// mLogger.debug("dimension: target width=" + width + "; target height=" + height
// + "; resized width=" + dimension.getWidth() + "; resized height="
// + dimension.getHeight());
String key = getImageCacheCmd(context).getCacheKey(attachmentClone,
new ImageDimensions(width, height), copyright, watermark, context);
mLogger.debug("attachment key: '" + key + "'");
byte[] data = getImageCacheCmd(context).getImageForKey(key, context);
if (data != null) {
mLogger.info("Found image in Cache.");
attachmentClone.setContent(data);
} else {
ImageDimensions dimension = thumbGen.getThumbnailDimensions(img, width, height);
mLogger.info("No cached image.");
attachmentClone.setContent(getThumbAttachment(img, dimension, thumbGen,
attachmentClone.getMimeType(context), watermark, copyright, defaultBg));
getImageCacheCmd(context).addToCache(key, attachmentClone, context);
}
} catch (Exception exp) {
mLogger.error("Error, could not resize / cache image", exp);
attachmentClone = attachment;
}
}
return attachmentClone;
}
| public XWikiAttachment computeImage(XWikiAttachment attachment,
XWikiContext context, XWikiAttachment attachmentClone, String sheight,
String swidth, String copyright, String watermark, Color defaultBg,
String defaultBgString) {
if((defaultBgString != null) && defaultBgString.matches("[0-9A-Fa-f]{6}")) {
int r = Integer.parseInt(defaultBgString.substring(1, 3), 16);
int g = Integer.parseInt(defaultBgString.substring(3, 5), 16);
int b = Integer.parseInt(defaultBgString.substring(5), 16);
defaultBg = new Color(r, g, b);
}
int height = parseIntWithDefault(sheight, 0);
int width = parseIntWithDefault(swidth, 0);
if ((height > 0) || (width > 0)) {
try {
attachmentClone = (XWikiAttachment) attachment.clone();
// mLogger.debug("dimension: target width=" + width + "; target height=" + height
// + "; resized width=" + dimension.getWidth() + "; resized height="
// + dimension.getHeight());
String key = getImageCacheCmd(context).getCacheKey(attachmentClone,
new ImageDimensions(width, height), copyright, watermark, context);
mLogger.debug("attachment key: '" + key + "'");
byte[] data = getImageCacheCmd(context).getImageForKey(key, context);
if (data != null) {
mLogger.info("Found image in Cache.");
attachmentClone.setContent(data);
} else {
GenerateThumbnail thumbGen = new GenerateThumbnail();
ByteArrayInputStream in = new ByteArrayInputStream(attachmentClone.getContent(
context));
BufferedImage img = thumbGen.decodeImage(in);
in.close();
ImageDimensions dimension = thumbGen.getThumbnailDimensions(img, width, height);
mLogger.info("No cached image.");
attachmentClone.setContent(getThumbAttachment(img, dimension, thumbGen,
attachmentClone.getMimeType(context), watermark, copyright, defaultBg));
getImageCacheCmd(context).addToCache(key, attachmentClone, context);
}
} catch (Exception exp) {
mLogger.error("Error, could not resize / cache image", exp);
attachmentClone = attachment;
}
}
return attachmentClone;
}
|
diff --git a/examples/undocumented/java_modular/mkl_multiclass_modular.java b/examples/undocumented/java_modular/mkl_multiclass_modular.java
index 556f4fa4a..6ba64a273 100644
--- a/examples/undocumented/java_modular/mkl_multiclass_modular.java
+++ b/examples/undocumented/java_modular/mkl_multiclass_modular.java
@@ -1,70 +1,70 @@
import org.shogun.*;
import org.jblas.*;
public class mkl_multiclass_modular {
static {
System.loadLibrary("modshogun");
}
public static void main(String argv[]) {
modshogun.init_shogun_with_defaults();
double width = 2.1;
double epsilon = 1e-5;
double C = 1.0;
int mkl_norm = 2;
DoubleMatrix traindata_real = Load.load_numbers("../data/fm_train_real.dat");
DoubleMatrix testdata_real = Load.load_numbers("../data/fm_test_real.dat");
- DoubleMatrix trainlab = Load.load_labels("../data/label_train_twoclass.dat");
+ DoubleMatrix trainlab = Load.load_labels("../data/label_train_multiclass.dat");
CombinedKernel kernel = new CombinedKernel();
CombinedFeatures feats_train = new CombinedFeatures();
CombinedFeatures feats_test = new CombinedFeatures();
RealFeatures subkfeats1_train = new RealFeatures(traindata_real);
RealFeatures subkfeats1_test = new RealFeatures(testdata_real);
GaussianKernel subkernel = new GaussianKernel(10, width);
feats_train.append_feature_obj(subkfeats1_train);
feats_test.append_feature_obj(subkfeats1_test);
kernel.append_kernel(subkernel);
RealFeatures subkfeats2_train = new RealFeatures(traindata_real);
RealFeatures subkfeats2_test = new RealFeatures(testdata_real);
LinearKernel subkernel2 = new LinearKernel();
feats_train.append_feature_obj(subkfeats2_train);
feats_test.append_feature_obj(subkfeats2_test);
kernel.append_kernel(subkernel2);
RealFeatures subkfeats3_train = new RealFeatures(traindata_real);
RealFeatures subkfeats3_test = new RealFeatures(testdata_real);
PolyKernel subkernel3 = new PolyKernel(10, 2);
feats_train.append_feature_obj(subkfeats3_train);
feats_test.append_feature_obj(subkfeats3_test);
kernel.append_kernel(subkernel3);
kernel.init(feats_train, feats_train);
System.out.println(trainlab);
Labels labels = new Labels(trainlab);
System.out.println(labels.get_labels());
MKLMultiClass mkl = new MKLMultiClass(C, kernel, labels);
mkl.set_epsilon(epsilon);
mkl.set_mkl_epsilon(epsilon);
mkl.set_mkl_norm(mkl_norm);
mkl.train();
//kernel.init(feats_train, feats_test);
//DoubleMatrix out = mkl.apply().get_labels();
modshogun.exit_shogun();
}
}
| true | true | public static void main(String argv[]) {
modshogun.init_shogun_with_defaults();
double width = 2.1;
double epsilon = 1e-5;
double C = 1.0;
int mkl_norm = 2;
DoubleMatrix traindata_real = Load.load_numbers("../data/fm_train_real.dat");
DoubleMatrix testdata_real = Load.load_numbers("../data/fm_test_real.dat");
DoubleMatrix trainlab = Load.load_labels("../data/label_train_twoclass.dat");
CombinedKernel kernel = new CombinedKernel();
CombinedFeatures feats_train = new CombinedFeatures();
CombinedFeatures feats_test = new CombinedFeatures();
RealFeatures subkfeats1_train = new RealFeatures(traindata_real);
RealFeatures subkfeats1_test = new RealFeatures(testdata_real);
GaussianKernel subkernel = new GaussianKernel(10, width);
feats_train.append_feature_obj(subkfeats1_train);
feats_test.append_feature_obj(subkfeats1_test);
kernel.append_kernel(subkernel);
RealFeatures subkfeats2_train = new RealFeatures(traindata_real);
RealFeatures subkfeats2_test = new RealFeatures(testdata_real);
LinearKernel subkernel2 = new LinearKernel();
feats_train.append_feature_obj(subkfeats2_train);
feats_test.append_feature_obj(subkfeats2_test);
kernel.append_kernel(subkernel2);
RealFeatures subkfeats3_train = new RealFeatures(traindata_real);
RealFeatures subkfeats3_test = new RealFeatures(testdata_real);
PolyKernel subkernel3 = new PolyKernel(10, 2);
feats_train.append_feature_obj(subkfeats3_train);
feats_test.append_feature_obj(subkfeats3_test);
kernel.append_kernel(subkernel3);
kernel.init(feats_train, feats_train);
System.out.println(trainlab);
Labels labels = new Labels(trainlab);
System.out.println(labels.get_labels());
MKLMultiClass mkl = new MKLMultiClass(C, kernel, labels);
mkl.set_epsilon(epsilon);
mkl.set_mkl_epsilon(epsilon);
mkl.set_mkl_norm(mkl_norm);
mkl.train();
//kernel.init(feats_train, feats_test);
//DoubleMatrix out = mkl.apply().get_labels();
modshogun.exit_shogun();
}
| public static void main(String argv[]) {
modshogun.init_shogun_with_defaults();
double width = 2.1;
double epsilon = 1e-5;
double C = 1.0;
int mkl_norm = 2;
DoubleMatrix traindata_real = Load.load_numbers("../data/fm_train_real.dat");
DoubleMatrix testdata_real = Load.load_numbers("../data/fm_test_real.dat");
DoubleMatrix trainlab = Load.load_labels("../data/label_train_multiclass.dat");
CombinedKernel kernel = new CombinedKernel();
CombinedFeatures feats_train = new CombinedFeatures();
CombinedFeatures feats_test = new CombinedFeatures();
RealFeatures subkfeats1_train = new RealFeatures(traindata_real);
RealFeatures subkfeats1_test = new RealFeatures(testdata_real);
GaussianKernel subkernel = new GaussianKernel(10, width);
feats_train.append_feature_obj(subkfeats1_train);
feats_test.append_feature_obj(subkfeats1_test);
kernel.append_kernel(subkernel);
RealFeatures subkfeats2_train = new RealFeatures(traindata_real);
RealFeatures subkfeats2_test = new RealFeatures(testdata_real);
LinearKernel subkernel2 = new LinearKernel();
feats_train.append_feature_obj(subkfeats2_train);
feats_test.append_feature_obj(subkfeats2_test);
kernel.append_kernel(subkernel2);
RealFeatures subkfeats3_train = new RealFeatures(traindata_real);
RealFeatures subkfeats3_test = new RealFeatures(testdata_real);
PolyKernel subkernel3 = new PolyKernel(10, 2);
feats_train.append_feature_obj(subkfeats3_train);
feats_test.append_feature_obj(subkfeats3_test);
kernel.append_kernel(subkernel3);
kernel.init(feats_train, feats_train);
System.out.println(trainlab);
Labels labels = new Labels(trainlab);
System.out.println(labels.get_labels());
MKLMultiClass mkl = new MKLMultiClass(C, kernel, labels);
mkl.set_epsilon(epsilon);
mkl.set_mkl_epsilon(epsilon);
mkl.set_mkl_norm(mkl_norm);
mkl.train();
//kernel.init(feats_train, feats_test);
//DoubleMatrix out = mkl.apply().get_labels();
modshogun.exit_shogun();
}
|
diff --git a/tests/frontend/org/voltdb/benchmark/tpcc/procedures/InsertNewOrder.java b/tests/frontend/org/voltdb/benchmark/tpcc/procedures/InsertNewOrder.java
index 5ff30d4a8..ed896efc4 100644
--- a/tests/frontend/org/voltdb/benchmark/tpcc/procedures/InsertNewOrder.java
+++ b/tests/frontend/org/voltdb/benchmark/tpcc/procedures/InsertNewOrder.java
@@ -1,67 +1,67 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* 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 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.
*/
/* Copyright (C) 2008
* Michael McCanna
* Massachusetts Institute of Technology
*
* 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 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 org.voltdb.benchmark.tpcc.procedures;
import org.voltdb.*;
@ProcInfo (
partitionInfo = "NEW_ORDER.NO_W_ID: 2",
singlePartition = true
)
public class InsertNewOrder extends VoltProcedure {
public final SQLStmt insert = new SQLStmt("INSERT INTO NEW_ORDER VALUES (?, ?, ?);");
- public VoltTable[] run(long no_o_id, long no_d_id, short no_w_id) {
+ public VoltTable[] run(long no_o_id, byte no_d_id, short no_w_id) {
voltQueueSQL(insert, no_o_id, no_d_id, no_w_id);
return voltExecuteSQL();
}
}
| true | true | public VoltTable[] run(long no_o_id, long no_d_id, short no_w_id) {
voltQueueSQL(insert, no_o_id, no_d_id, no_w_id);
return voltExecuteSQL();
}
| public VoltTable[] run(long no_o_id, byte no_d_id, short no_w_id) {
voltQueueSQL(insert, no_o_id, no_d_id, no_w_id);
return voltExecuteSQL();
}
|
diff --git a/sqo-oss/prototype/src/eu/sqooss/plugin/cccc/CCCCExecutor.java b/sqo-oss/prototype/src/eu/sqooss/plugin/cccc/CCCCExecutor.java
index 3ff83ce1..e19ce9b9 100644
--- a/sqo-oss/prototype/src/eu/sqooss/plugin/cccc/CCCCExecutor.java
+++ b/sqo-oss/prototype/src/eu/sqooss/plugin/cccc/CCCCExecutor.java
@@ -1,80 +1,80 @@
/*
* Copyright (c) Members of the SQO-OSS Collaboration, 2007
* All rights reserved by respective owners.
* See http://www.sqo-oss.eu/ for details on the copyright holders.
*
* 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. Neither the name of the SQO-OSS project 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.
*/
package eu.sqooss.plugin.cccc;
import java.io.*;
import eu.sqooss.plugin.ExternalExecutor;
/**
* Implements the Executor that handles the CCCC tool execution.
*/
public class CCCCExecutor extends ExternalExecutor {
public CCCCExecutor(String cmd) {
super(cmd);
}
/* (non-Javadoc)
* @see eu.sqooss.plugin.ExternalExecutor#execute(java.io.File)
*/
@Override
public InputStream execute(File file) {
StringBuilder target = new StringBuilder();
- target.append(cmd);
+ //target.append(cmd);
String outputPath = System.getProperty("java.io.tmpdir");
if ( !outputPath.endsWith(System.getProperty("file.separator")) )
outputPath += System.getProperty("file.separator");
outputPath += "cccc";
outputPath += System.getProperty("file.separator");
target.append(" --outdir=");
target.append(outputPath);
// if(file.isDirectory()) {
// for(File f: file.listFiles()) {
// target.append(" " + f.toString());
// }
// }
// else
target.append(" " + file.toString());
try {
Process p = Runtime.getRuntime().exec(target.toString());
p.waitFor();
FileInputStream result = new FileInputStream(outputPath + "cccc.xml");
return result;
} catch(Exception e) {
return null;
}
}
}
| true | true | public InputStream execute(File file) {
StringBuilder target = new StringBuilder();
target.append(cmd);
String outputPath = System.getProperty("java.io.tmpdir");
if ( !outputPath.endsWith(System.getProperty("file.separator")) )
outputPath += System.getProperty("file.separator");
outputPath += "cccc";
outputPath += System.getProperty("file.separator");
target.append(" --outdir=");
target.append(outputPath);
// if(file.isDirectory()) {
// for(File f: file.listFiles()) {
// target.append(" " + f.toString());
// }
// }
// else
target.append(" " + file.toString());
try {
Process p = Runtime.getRuntime().exec(target.toString());
p.waitFor();
FileInputStream result = new FileInputStream(outputPath + "cccc.xml");
return result;
} catch(Exception e) {
return null;
}
}
| public InputStream execute(File file) {
StringBuilder target = new StringBuilder();
//target.append(cmd);
String outputPath = System.getProperty("java.io.tmpdir");
if ( !outputPath.endsWith(System.getProperty("file.separator")) )
outputPath += System.getProperty("file.separator");
outputPath += "cccc";
outputPath += System.getProperty("file.separator");
target.append(" --outdir=");
target.append(outputPath);
// if(file.isDirectory()) {
// for(File f: file.listFiles()) {
// target.append(" " + f.toString());
// }
// }
// else
target.append(" " + file.toString());
try {
Process p = Runtime.getRuntime().exec(target.toString());
p.waitFor();
FileInputStream result = new FileInputStream(outputPath + "cccc.xml");
return result;
} catch(Exception e) {
return null;
}
}
|
diff --git a/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/ShapefilePopulation.java b/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/ShapefilePopulation.java
index dd934e78f..257e94a50 100644
--- a/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/ShapefilePopulation.java
+++ b/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/ShapefilePopulation.java
@@ -1,102 +1,104 @@
/* This program 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 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.opentripplanner.analyst.batch;
import java.io.File;
import lombok.Setter;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Query;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.referencing.CRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
public class ShapefilePopulation extends BasicPopulation {
private static final Logger LOG = LoggerFactory.getLogger(ShapefilePopulation.class);
@Setter String labelAttribute;
@Setter String inputAttribute;
@Override
public void createIndividuals() {
String filename = this.sourceFilename;
LOG.debug("Loading population from shapefile {}", filename);
LOG.debug("Feature attributes: input data in {}, labeled with {}", inputAttribute, labelAttribute);
try {
File file = new File(filename);
+ if ( ! file.exists())
+ throw new RuntimeException("Shapefile does not exist.");
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
Query query = new Query();
query.setCoordinateSystem(sourceCRS);
query.setCoordinateSystemReproject(WGS84);
SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
SimpleFeatureIterator it = featureCollection.features();
int i = 0;
while (it.hasNext()) {
SimpleFeature feature = it.next();
Geometry geom = (Geometry) feature.getDefaultGeometry();
Point point = null;
if (geom instanceof Point) {
point = (Point) geom;
} else if (geom instanceof Polygon) {
point = ((Polygon) geom).getCentroid();
} else if (geom instanceof MultiPolygon) {
point = ((MultiPolygon) geom).getCentroid();
} else {
throw new RuntimeException("Shapefile must contain either points or polygons.");
}
String label;
if (labelAttribute == null) {
label = Integer.toString(i);
} else {
label = feature.getAttribute(labelAttribute).toString();
}
double input = 0.0;
if (inputAttribute != null) {
Number n = (Number) feature.getAttribute(inputAttribute);
input = n.doubleValue();
}
Individual individual = new Individual(label, point.getX(), point.getY(), input);
this.addIndividual(individual);
i += 1;
}
LOG.debug("loaded {} features", i);
it.close();
} catch (Exception ex) {
LOG.error("Error loading population from shapefile: {}", ex.getMessage());
throw new RuntimeException(ex);
}
LOG.debug("Done loading shapefile.");
}
}
| true | true | public void createIndividuals() {
String filename = this.sourceFilename;
LOG.debug("Loading population from shapefile {}", filename);
LOG.debug("Feature attributes: input data in {}, labeled with {}", inputAttribute, labelAttribute);
try {
File file = new File(filename);
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
Query query = new Query();
query.setCoordinateSystem(sourceCRS);
query.setCoordinateSystemReproject(WGS84);
SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
SimpleFeatureIterator it = featureCollection.features();
int i = 0;
while (it.hasNext()) {
SimpleFeature feature = it.next();
Geometry geom = (Geometry) feature.getDefaultGeometry();
Point point = null;
if (geom instanceof Point) {
point = (Point) geom;
} else if (geom instanceof Polygon) {
point = ((Polygon) geom).getCentroid();
} else if (geom instanceof MultiPolygon) {
point = ((MultiPolygon) geom).getCentroid();
} else {
throw new RuntimeException("Shapefile must contain either points or polygons.");
}
String label;
if (labelAttribute == null) {
label = Integer.toString(i);
} else {
label = feature.getAttribute(labelAttribute).toString();
}
double input = 0.0;
if (inputAttribute != null) {
Number n = (Number) feature.getAttribute(inputAttribute);
input = n.doubleValue();
}
Individual individual = new Individual(label, point.getX(), point.getY(), input);
this.addIndividual(individual);
i += 1;
}
LOG.debug("loaded {} features", i);
it.close();
} catch (Exception ex) {
LOG.error("Error loading population from shapefile: {}", ex.getMessage());
throw new RuntimeException(ex);
}
LOG.debug("Done loading shapefile.");
}
| public void createIndividuals() {
String filename = this.sourceFilename;
LOG.debug("Loading population from shapefile {}", filename);
LOG.debug("Feature attributes: input data in {}, labeled with {}", inputAttribute, labelAttribute);
try {
File file = new File(filename);
if ( ! file.exists())
throw new RuntimeException("Shapefile does not exist.");
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
Query query = new Query();
query.setCoordinateSystem(sourceCRS);
query.setCoordinateSystemReproject(WGS84);
SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
SimpleFeatureIterator it = featureCollection.features();
int i = 0;
while (it.hasNext()) {
SimpleFeature feature = it.next();
Geometry geom = (Geometry) feature.getDefaultGeometry();
Point point = null;
if (geom instanceof Point) {
point = (Point) geom;
} else if (geom instanceof Polygon) {
point = ((Polygon) geom).getCentroid();
} else if (geom instanceof MultiPolygon) {
point = ((MultiPolygon) geom).getCentroid();
} else {
throw new RuntimeException("Shapefile must contain either points or polygons.");
}
String label;
if (labelAttribute == null) {
label = Integer.toString(i);
} else {
label = feature.getAttribute(labelAttribute).toString();
}
double input = 0.0;
if (inputAttribute != null) {
Number n = (Number) feature.getAttribute(inputAttribute);
input = n.doubleValue();
}
Individual individual = new Individual(label, point.getX(), point.getY(), input);
this.addIndividual(individual);
i += 1;
}
LOG.debug("loaded {} features", i);
it.close();
} catch (Exception ex) {
LOG.error("Error loading population from shapefile: {}", ex.getMessage());
throw new RuntimeException(ex);
}
LOG.debug("Done loading shapefile.");
}
|
diff --git a/demos/webvie/src/main/java/org/apache/stanbol/commons/web/vie/fragment/EnhancerVieWebFragment.java b/demos/webvie/src/main/java/org/apache/stanbol/commons/web/vie/fragment/EnhancerVieWebFragment.java
index 63e2bdaf0..048e60b20 100644
--- a/demos/webvie/src/main/java/org/apache/stanbol/commons/web/vie/fragment/EnhancerVieWebFragment.java
+++ b/demos/webvie/src/main/java/org/apache/stanbol/commons/web/vie/fragment/EnhancerVieWebFragment.java
@@ -1,130 +1,130 @@
/*
* 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.stanbol.commons.web.vie.fragment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.apache.stanbol.commons.web.base.LinkResource;
import org.apache.stanbol.commons.web.base.NavigationLink;
import org.apache.stanbol.commons.web.base.ScriptResource;
import org.apache.stanbol.commons.web.base.WebFragment;
import org.apache.stanbol.commons.web.vie.resource.EnhancerVieRootResource;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
/**
* Statically define the list of available resources and providers to be contributed to the the Stanbol JAX-RS
* Endpoint.
*/
@Component(immediate = true, metatype = true)
@Service
public class EnhancerVieWebFragment implements WebFragment {
private static final String NAME = "enhancervie";
private static final String STATIC_RESOURCE_PATH = "/org/apache/stanbol/commons/web/vie/static";
private static final String TEMPLATE_PATH = "/org/apache/stanbol/commons/web/vie/templates";
private BundleContext bundleContext;
@Override
public String getName() {
return NAME;
}
@Activate
protected void activate(ComponentContext ctx) {
this.bundleContext = ctx.getBundleContext();
}
@Override
public Set<Class<?>> getJaxrsResourceClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(EnhancerVieRootResource.class);
return classes;
}
@Override
public Set<Object> getJaxrsResourceSingletons() {
return Collections.emptySet();
}
@Override
public String getStaticResourceClassPath() {
return STATIC_RESOURCE_PATH;
}
@Override
public TemplateLoader getTemplateLoader() {
return new ClassTemplateLoader(getClass(), TEMPLATE_PATH);
}
@Override
public List<LinkResource> getLinkResources() {
List<LinkResource> resources = new ArrayList<LinkResource>();
// resources.add(new LinkResource("stylesheet", "lib/Aristo/jquery-ui-1.8.7.custom.css", this, 10));
resources.add(new LinkResource("stylesheet", "lib/jquery/jquery-ui.min.css", this, 10));
resources.add(new LinkResource("stylesheet", "lib/Smoothness/jquery.ui.all.css", this, 10));
resources.add(new LinkResource("stylesheet", "annotate.css", this, 10));
// resources.add(new LinkResource("stylesheet", "lib/Aristo/jquery.ui.menu.css", this, 10));
return resources;
}
@Override
public List<ScriptResource> getScriptResources() {
List<ScriptResource> resources = new ArrayList<ScriptResource>();
- resources.add(new ScriptResource("text/javascript", "lib/jquery-1.5.1.js", this, 10));
+ resources.add(new ScriptResource("text/javascript", "lib/jquery-1.7.1.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/jquery-ui.1.9m5.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/underscore-min.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/backbone.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/jquery.rdfquery.debug.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/vie/vie-latest.debug.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/hallo/hallo.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/hallo/format.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/annotate.js", this, 10));
return resources;
}
@Override
public List<NavigationLink> getNavigationLinks() {
List<NavigationLink> links = new ArrayList<NavigationLink>();
links.add(new NavigationLink("enhancervie", "/enhancer VIE", "/imports/enhancervieDescription.ftl", 20));
return links;
}
@Override
public BundleContext getBundleContext() {
return bundleContext;
}
}
| true | true | public List<ScriptResource> getScriptResources() {
List<ScriptResource> resources = new ArrayList<ScriptResource>();
resources.add(new ScriptResource("text/javascript", "lib/jquery-1.5.1.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/jquery-ui.1.9m5.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/underscore-min.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/backbone.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/jquery.rdfquery.debug.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/vie/vie-latest.debug.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/hallo/hallo.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/hallo/format.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/annotate.js", this, 10));
return resources;
}
| public List<ScriptResource> getScriptResources() {
List<ScriptResource> resources = new ArrayList<ScriptResource>();
resources.add(new ScriptResource("text/javascript", "lib/jquery-1.7.1.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/jquery-ui.1.9m5.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/underscore-min.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/backbone.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/jquery.rdfquery.debug.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/vie/vie-latest.debug.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/hallo/hallo.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/hallo/format.js", this, 10));
resources.add(new ScriptResource("text/javascript", "lib/annotate.js", this, 10));
return resources;
}
|
diff --git a/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-integration-tests/src/test/java/org/xwiki/tool/xar/FixedResourceExtractor.java b/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-integration-tests/src/test/java/org/xwiki/tool/xar/FixedResourceExtractor.java
index 947f916e7..65151d52e 100644
--- a/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-integration-tests/src/test/java/org/xwiki/tool/xar/FixedResourceExtractor.java
+++ b/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-integration-tests/src/test/java/org/xwiki/tool/xar/FixedResourceExtractor.java
@@ -1,51 +1,51 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.tool.xar;
import java.io.File;
import java.io.IOException;
import org.apache.maven.it.util.FileUtils;
import org.apache.maven.it.util.ResourceExtractor;
/**
* Workaround bugs in {@link ResourceExtractor}.
*
* @version $Id$
* @since 5.0M2
*/
public class FixedResourceExtractor extends ResourceExtractor
{
/**
* Proper version of {@link ResourceExtractor}.
*/
- public static File simpleExtractResources(Class< ? > cl, String resourcePath) throws IOException
+ public static File simpleExtractResources(Class cl, String resourcePath) throws IOException
{
String tempDirPath = System.getProperty("maven.test.tmpdir", System.getProperty("java.io.tmpdir"));
File tempDir = new File(tempDirPath);
File testDir = new File(tempDir, resourcePath);
FileUtils.deleteDirectory(testDir);
testDir = ResourceExtractor.extractResourcePath(cl, resourcePath, tempDir, true);
return testDir;
}
}
| true | true | public static File simpleExtractResources(Class< ? > cl, String resourcePath) throws IOException
{
String tempDirPath = System.getProperty("maven.test.tmpdir", System.getProperty("java.io.tmpdir"));
File tempDir = new File(tempDirPath);
File testDir = new File(tempDir, resourcePath);
FileUtils.deleteDirectory(testDir);
testDir = ResourceExtractor.extractResourcePath(cl, resourcePath, tempDir, true);
return testDir;
}
| public static File simpleExtractResources(Class cl, String resourcePath) throws IOException
{
String tempDirPath = System.getProperty("maven.test.tmpdir", System.getProperty("java.io.tmpdir"));
File tempDir = new File(tempDirPath);
File testDir = new File(tempDir, resourcePath);
FileUtils.deleteDirectory(testDir);
testDir = ResourceExtractor.extractResourcePath(cl, resourcePath, tempDir, true);
return testDir;
}
|
diff --git a/asm/src/org/objectweb/asm/util/ASMifierAbstractVisitor.java b/asm/src/org/objectweb/asm/util/ASMifierAbstractVisitor.java
index 2a40dbe1..e32b6014 100644
--- a/asm/src/org/objectweb/asm/util/ASMifierAbstractVisitor.java
+++ b/asm/src/org/objectweb/asm/util/ASMifierAbstractVisitor.java
@@ -1,221 +1,220 @@
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000,2002,2003 INRIA, France Telecom
* 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. Neither the name of the copyright holders 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 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 org.objectweb.asm.util;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.attrs.ASMifiable;
/**
* An abstract ASMifier visitor.
*
* @author Eric Bruneton
*/
public class ASMifierAbstractVisitor extends AbstractVisitor {
/**
* The name of the variable for this visitor in the produced code.
*/
protected String name;
/**
* Constructs a new {@link ASMifierAbstractVisitor}.
*
* @param name the name of the variable for this visitor in the produced code.
*/
protected ASMifierAbstractVisitor (final String name) {
this.name = name;
}
/**
* Prints the ASM code that generates the given annotation.
*
* @param desc the class descriptor of the annotation class.
* @param visible <tt>true</tt> if the annotation is visible at runtime.
* @return a visitor to visit the annotation values.
*/
public AnnotationVisitor visitAnnotation (
final String desc,
final boolean visible)
{
buf.setLength(0);
buf.append("{\n").append("av0 = ").append(name).append(".visitAnnotation(");
appendConstant(desc);
buf.append(", ").append(visible).append(");\n");
text.add(buf.toString());
ASMifierAnnotationVisitor av = new ASMifierAnnotationVisitor(0);
text.add(av.getText());
text.add("}\n");
return av;
}
/**
* Prints the ASM code that generates the given attribute.
*
* @param attr an attribute.
*/
public void visitAttribute (final Attribute attr) {
buf.setLength(0);
if (attr instanceof ASMifiable) {
buf.append("{\n");
buf.append("// ATTRIBUTE\n");
((ASMifiable)attr).asmify(buf, "attr", null);
buf.append(name).append(".visitAttribute(attr);\n");
buf.append("}\n");
} else {
buf.append("// WARNING! skipped a non standard attribute of type \"");
buf.append(attr.type).append("\"\n");
}
text.add(buf.toString());
}
/**
* Prints the ASM code to end the visit.
*/
public void visitEnd () {
buf.setLength(0);
buf.append(name).append(".visitEnd();\n");
text.add(buf.toString());
}
/**
* Appends a string representation of the given constant to the given buffer.
*
* @param cst an {@link Integer}, {@link Float}, {@link Long}, {@link Double}
* or {@link String} object. May be <tt>null</tt>.
*/
void appendConstant (final Object cst) {
appendConstant(buf, cst);
}
/**
* Appends a string representation of the given constant to the given buffer.
*
* @param buf a string buffer.
* @param cst an {@link Integer}, {@link Float}, {@link Long}, {@link Double}
* or {@link String} object. May be <tt>null</tt>.
*/
static void appendConstant (final StringBuffer buf, final Object cst) {
if (cst == null) {
buf.append("null");
} else if (cst instanceof String) {
appendString(buf, (String)cst);
} else if (cst instanceof Type) {
buf.append("Type.getType(\"");
buf.append(((Type)cst).getDescriptor());
buf.append("\")");
+ } else if (cst instanceof Byte) {
+ buf.append("new Byte((byte)").append(cst).append(")");
+ } else if (cst instanceof Boolean) {
+ buf.append("new Boolean(").append(cst).append(")");
+ } else if (cst instanceof Short) {
+ buf.append("new Short((short)").append(cst).append(")");
+ } else if (cst instanceof Character) {
+ int c = (int)((Character)cst).charValue();
+ buf.append("new Character((char)").append(c).append(")");
} else if (cst instanceof Integer) {
buf.append("new Integer(").append(cst).append(")");
} else if (cst instanceof Float) {
- Float f = (Float)cst;
- if (f.isInfinite() || f.isNaN()) {
- buf.append("new Float(\"").append(cst).append("\")");
- } else {
- buf.append("new Float(").append(cst).append("F)");
- }
+ buf.append("new Float(\"").append(cst).append("\")");
} else if (cst instanceof Long) {
buf.append("new Long(").append(cst).append("L)");
} else if (cst instanceof Double) {
- Double d = (Double)cst;
- if (d.isInfinite() || d.isNaN()) {
- buf.append("new Double(\"").append(cst).append("\")");
- } else {
- buf.append("new Double(").append(cst).append(")");
- }
- // support for arrays: TODO should we keep this?
+ buf.append("new Double(\"").append(cst).append("\")");
+ // support for arrays: TODO should we keep this?
} else if (cst instanceof byte[]) {
byte[] v = (byte[])cst;
buf.append("new byte[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof boolean[]) {
boolean[] v = (boolean[])cst;
buf.append("new boolean[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof short[]) {
short[] v = (short[])cst;
buf.append("new short[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(short)").append(v[i]);
}
buf.append("}");
} else if (cst instanceof char[]) {
char[] v = (char[])cst;
buf.append("new char[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(char)").append((int)v[i]);
}
buf.append("}");
} else if (cst instanceof int[]) {
int[] v = (int[])cst;
buf.append("new int[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof long[]) {
long[] v = (long[])cst;
buf.append("new long[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("L");
}
buf.append("}");
} else if (cst instanceof float[]) {
float[] v = (float[])cst;
buf.append("new float[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("f");
}
buf.append("}");
} else if (cst instanceof double[]) {
double[] v = (double[])cst;
buf.append("new double[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("d");
}
buf.append("}");
}
}
}
| false | true | static void appendConstant (final StringBuffer buf, final Object cst) {
if (cst == null) {
buf.append("null");
} else if (cst instanceof String) {
appendString(buf, (String)cst);
} else if (cst instanceof Type) {
buf.append("Type.getType(\"");
buf.append(((Type)cst).getDescriptor());
buf.append("\")");
} else if (cst instanceof Integer) {
buf.append("new Integer(").append(cst).append(")");
} else if (cst instanceof Float) {
Float f = (Float)cst;
if (f.isInfinite() || f.isNaN()) {
buf.append("new Float(\"").append(cst).append("\")");
} else {
buf.append("new Float(").append(cst).append("F)");
}
} else if (cst instanceof Long) {
buf.append("new Long(").append(cst).append("L)");
} else if (cst instanceof Double) {
Double d = (Double)cst;
if (d.isInfinite() || d.isNaN()) {
buf.append("new Double(\"").append(cst).append("\")");
} else {
buf.append("new Double(").append(cst).append(")");
}
// support for arrays: TODO should we keep this?
} else if (cst instanceof byte[]) {
byte[] v = (byte[])cst;
buf.append("new byte[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof boolean[]) {
boolean[] v = (boolean[])cst;
buf.append("new boolean[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof short[]) {
short[] v = (short[])cst;
buf.append("new short[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(short)").append(v[i]);
}
buf.append("}");
} else if (cst instanceof char[]) {
char[] v = (char[])cst;
buf.append("new char[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(char)").append((int)v[i]);
}
buf.append("}");
} else if (cst instanceof int[]) {
int[] v = (int[])cst;
buf.append("new int[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof long[]) {
long[] v = (long[])cst;
buf.append("new long[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("L");
}
buf.append("}");
} else if (cst instanceof float[]) {
float[] v = (float[])cst;
buf.append("new float[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("f");
}
buf.append("}");
} else if (cst instanceof double[]) {
double[] v = (double[])cst;
buf.append("new double[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("d");
}
buf.append("}");
}
}
| static void appendConstant (final StringBuffer buf, final Object cst) {
if (cst == null) {
buf.append("null");
} else if (cst instanceof String) {
appendString(buf, (String)cst);
} else if (cst instanceof Type) {
buf.append("Type.getType(\"");
buf.append(((Type)cst).getDescriptor());
buf.append("\")");
} else if (cst instanceof Byte) {
buf.append("new Byte((byte)").append(cst).append(")");
} else if (cst instanceof Boolean) {
buf.append("new Boolean(").append(cst).append(")");
} else if (cst instanceof Short) {
buf.append("new Short((short)").append(cst).append(")");
} else if (cst instanceof Character) {
int c = (int)((Character)cst).charValue();
buf.append("new Character((char)").append(c).append(")");
} else if (cst instanceof Integer) {
buf.append("new Integer(").append(cst).append(")");
} else if (cst instanceof Float) {
buf.append("new Float(\"").append(cst).append("\")");
} else if (cst instanceof Long) {
buf.append("new Long(").append(cst).append("L)");
} else if (cst instanceof Double) {
buf.append("new Double(\"").append(cst).append("\")");
// support for arrays: TODO should we keep this?
} else if (cst instanceof byte[]) {
byte[] v = (byte[])cst;
buf.append("new byte[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof boolean[]) {
boolean[] v = (boolean[])cst;
buf.append("new boolean[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof short[]) {
short[] v = (short[])cst;
buf.append("new short[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(short)").append(v[i]);
}
buf.append("}");
} else if (cst instanceof char[]) {
char[] v = (char[])cst;
buf.append("new char[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(char)").append((int)v[i]);
}
buf.append("}");
} else if (cst instanceof int[]) {
int[] v = (int[])cst;
buf.append("new int[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append("}");
} else if (cst instanceof long[]) {
long[] v = (long[])cst;
buf.append("new long[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("L");
}
buf.append("}");
} else if (cst instanceof float[]) {
float[] v = (float[])cst;
buf.append("new float[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("f");
}
buf.append("}");
} else if (cst instanceof double[]) {
double[] v = (double[])cst;
buf.append("new double[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append("d");
}
buf.append("}");
}
}
|
diff --git a/src/graindcafe/tribu/Listeners/TribuPlayerListener.java b/src/graindcafe/tribu/Listeners/TribuPlayerListener.java
index 3ee4e23..9fcee98 100644
--- a/src/graindcafe/tribu/Listeners/TribuPlayerListener.java
+++ b/src/graindcafe/tribu/Listeners/TribuPlayerListener.java
@@ -1,125 +1,128 @@
/*******************************************************************************
* Copyright or � or Copr. Quentin Godron (2011)
*
* [email protected]
*
* This software is a computer program whose purpose is to create zombie
* survival games on Bukkit's server.
*
* This software is governed by the CeCILL-C license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-C
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C license and that you accept its terms.
******************************************************************************/
package graindcafe.tribu.Listeners;
import graindcafe.tribu.Tribu;
import graindcafe.tribu.Signs.TribuSign;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.plugin.PluginManager;
public class TribuPlayerListener implements Listener {
private final Tribu plugin;
public TribuPlayerListener(final Tribu instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerChangeWorld(final PlayerChangedWorldEvent event) {
// If he is playing, then he is inside the world...
if (plugin.config().PluginModeWorldExclusive) if (plugin.isInsideLevel(event.getPlayer().getLocation()))
// Timed out add player
// you need this orelse you will get kicked
// "Moving to fast Hacking?"
// its just a .5 of a second delay (it can be set to even less)
plugin.addPlayer(event.getPlayer(), 0.5);
else if (plugin.isPlaying(event.getPlayer())) plugin.removePlayer(event.getPlayer());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInteract(final PlayerInteractEvent event) {
if (!event.isCancelled()) {
final Block block = event.getClickedBlock();
- if (block != null && plugin.isPlaying(event.getPlayer())) if (Sign.class.isInstance(block.getState()) && plugin.getLevel() != null) {
- if (plugin.isRunning()) {
+ if (block != null && Sign.class.isInstance(block.getState()) && plugin.getLevel() != null) {
+ if (plugin.isRunning() && plugin.isPlaying(event.getPlayer())) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) plugin.getLevel().onSignClicked(event);
- } else if (event.getPlayer().hasPermission("tribu.signs.place")) if (plugin.getLevel().removeSign(block.getLocation()))
- Tribu.messagePlayer(event.getPlayer(), plugin.getLocale("Message.TribuSignRemoved"));
- else if (plugin.getLevel().addSign(TribuSign.getObject(plugin, block.getLocation()))) Tribu.messagePlayer(event.getPlayer(), plugin.getLocale("Message.TribuSignAdded"));
+ } else if (event.getPlayer().hasPermission("tribu.signs.place")) {
+ if (plugin.getLevel().removeSign(block.getLocation()))
+ Tribu.messagePlayer(event.getPlayer(), plugin.getLocale("Message.TribuSignRemoved"));
+ else if (plugin.getLevel().addSign(TribuSign.getObject(plugin, block.getLocation())))
+ Tribu.messagePlayer(event.getPlayer(), plugin.getLocale("Message.TribuSignAdded"));
+ }
} else if (plugin.isRunning()) plugin.getLevel().onClick(event);
}
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
if (plugin.config().PluginModeServerExclusive || plugin.config().PluginModeWorldExclusive && plugin.isInsideLevel(event.getPlayer().getLocation(), true)) plugin.addPlayer(event.getPlayer());
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerMove(final PlayerMoveEvent event) {
final Player player = event.getPlayer();
if (plugin.isRunning() && plugin.isPlaying(player)) {
plugin.getChunkMemory().add(player.getLocation().getChunk());
if (plugin.config().LevelJail && !plugin.isAlive(player) && plugin.getLevel().getDeathSpawn().distanceSquared(player.getLocation()) > plugin.config().LevelJailRadius) {
player.teleport(plugin.getLevel().getDeathSpawn());
Tribu.messagePlayer(player, plugin.getLocale("Message.PlayerDSpawnLeaveWarning"));
}
}
}
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event) {
plugin.restoreInventory(event.getPlayer());
plugin.removePlayer(event.getPlayer());
}
@EventHandler
public void onPlayerRespawn(final PlayerRespawnEvent event) {
if (plugin.getLevel() != null) {
plugin.setDead(event.getPlayer());
plugin.resetedSpawnAdd(event.getPlayer(), event.getRespawnLocation());
event.setRespawnLocation(plugin.getLevel().getDeathSpawn());
plugin.restoreTempInv(event.getPlayer());
if (!plugin.isPlaying(event.getPlayer())) plugin.restoreInventory(event.getPlayer());
}
}
public void registerEvents(final PluginManager pm) {
pm.registerEvents(this, plugin);
}
}
| false | true | public void onPlayerInteract(final PlayerInteractEvent event) {
if (!event.isCancelled()) {
final Block block = event.getClickedBlock();
if (block != null && plugin.isPlaying(event.getPlayer())) if (Sign.class.isInstance(block.getState()) && plugin.getLevel() != null) {
if (plugin.isRunning()) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) plugin.getLevel().onSignClicked(event);
} else if (event.getPlayer().hasPermission("tribu.signs.place")) if (plugin.getLevel().removeSign(block.getLocation()))
Tribu.messagePlayer(event.getPlayer(), plugin.getLocale("Message.TribuSignRemoved"));
else if (plugin.getLevel().addSign(TribuSign.getObject(plugin, block.getLocation()))) Tribu.messagePlayer(event.getPlayer(), plugin.getLocale("Message.TribuSignAdded"));
} else if (plugin.isRunning()) plugin.getLevel().onClick(event);
}
}
| public void onPlayerInteract(final PlayerInteractEvent event) {
if (!event.isCancelled()) {
final Block block = event.getClickedBlock();
if (block != null && Sign.class.isInstance(block.getState()) && plugin.getLevel() != null) {
if (plugin.isRunning() && plugin.isPlaying(event.getPlayer())) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) plugin.getLevel().onSignClicked(event);
} else if (event.getPlayer().hasPermission("tribu.signs.place")) {
if (plugin.getLevel().removeSign(block.getLocation()))
Tribu.messagePlayer(event.getPlayer(), plugin.getLocale("Message.TribuSignRemoved"));
else if (plugin.getLevel().addSign(TribuSign.getObject(plugin, block.getLocation())))
Tribu.messagePlayer(event.getPlayer(), plugin.getLocale("Message.TribuSignAdded"));
}
} else if (plugin.isRunning()) plugin.getLevel().onClick(event);
}
}
|
diff --git a/src/votemenu/VoteMenuGUIController2.java b/src/votemenu/VoteMenuGUIController2.java
index 6335e22..61246bd 100644
--- a/src/votemenu/VoteMenuGUIController2.java
+++ b/src/votemenu/VoteMenuGUIController2.java
@@ -1,87 +1,87 @@
package votemenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import database.QuestionDescription;
import database.User;
import questionmenu.QuestionListMenuGUI2;
import questionmenu.QuestionListMenuGUIController2;
import questionmenu.QuestionListMenuModel;
public class VoteMenuGUIController2 {
private VoteMenuGUI2 view;
private JButton backButton;
private List<JButton> buttonList;
private User user;
private QuestionDescription question;
private VoteMenuModel model;
private List<JButton> desList;
public VoteMenuGUIController2(VoteMenuGUI2 view , VoteMenuModel model , User user , QuestionDescription question) {
this.view = view;
this.model = model;
this.user = user;
this.question = question;
view.setTeamList();
view.setNBallot(model.getUserBallot(user , question));
view.create();
backButton = view.getbackButton();
buttonList = view.getButtonList();
desList = view.getDesList();
setAction();
}
private void setAction()
{
//Add ActionListener for Vote Button
for(int i=0;i<buttonList.size();i++)
{
final int num = i+1;
JButton button = buttonList.get(i);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(model.isTextExist(num))
{
if(model.vote(user, question, num))
{
- new messagebox.ShowPopup("Vote Completed","Completed",0);
+ new messagebox.ShowPopup("Vote Completed","Completed",1);
view.setBallotShow(model.getUserBallot(user, question));
}else new messagebox.ShowPopup("Inefficient Ballot","Error",0);
}else new messagebox.ShowPopup("Can't find team","Unexpected Error",0);
}
});
}
//Add ActionListener for Description Button
for(int i=0;i<desList.size();i++)
{
final int num = i+1;
JButton button = desList.get(i);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Description of team : "+num);
}
});
}
//Add ActionListener for Back Button
backButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new QuestionListMenuGUIController2(new QuestionListMenuGUI2(), new QuestionListMenuModel(), user);
view.close();
}
});
}
}
| true | true | private void setAction()
{
//Add ActionListener for Vote Button
for(int i=0;i<buttonList.size();i++)
{
final int num = i+1;
JButton button = buttonList.get(i);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(model.isTextExist(num))
{
if(model.vote(user, question, num))
{
new messagebox.ShowPopup("Vote Completed","Completed",0);
view.setBallotShow(model.getUserBallot(user, question));
}else new messagebox.ShowPopup("Inefficient Ballot","Error",0);
}else new messagebox.ShowPopup("Can't find team","Unexpected Error",0);
}
});
}
//Add ActionListener for Description Button
for(int i=0;i<desList.size();i++)
{
final int num = i+1;
JButton button = desList.get(i);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Description of team : "+num);
}
});
}
//Add ActionListener for Back Button
backButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new QuestionListMenuGUIController2(new QuestionListMenuGUI2(), new QuestionListMenuModel(), user);
view.close();
}
});
}
| private void setAction()
{
//Add ActionListener for Vote Button
for(int i=0;i<buttonList.size();i++)
{
final int num = i+1;
JButton button = buttonList.get(i);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(model.isTextExist(num))
{
if(model.vote(user, question, num))
{
new messagebox.ShowPopup("Vote Completed","Completed",1);
view.setBallotShow(model.getUserBallot(user, question));
}else new messagebox.ShowPopup("Inefficient Ballot","Error",0);
}else new messagebox.ShowPopup("Can't find team","Unexpected Error",0);
}
});
}
//Add ActionListener for Description Button
for(int i=0;i<desList.size();i++)
{
final int num = i+1;
JButton button = desList.get(i);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Description of team : "+num);
}
});
}
//Add ActionListener for Back Button
backButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new QuestionListMenuGUIController2(new QuestionListMenuGUI2(), new QuestionListMenuModel(), user);
view.close();
}
});
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java
index 9ef29c820..b37284edc 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java
@@ -1,938 +1,938 @@
/*
* 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.synapse.core.axis2;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMNode;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.*;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.AxisEvent;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.SynapseConfigUtils;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.mediators.base.SequenceMediator;
import org.apache.synapse.util.PolicyInfo;
import org.xml.sax.InputSource;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;
/**
* <proxy-service name="string" [transports="(http |https |jms )+|all"] [trace="enable|disable"]>
* <description>..</description>?
* <target [inSequence="name"] [outSequence="name"] [faultSequence="name"] [endpoint="name"]>
* <endpoint>...</endpoint>
* <inSequence>...</inSequence>
* <outSequence>...</outSequence>
* <faultSequence>...</faultSequence>
* </target>?
* <publishWSDL uri=".." key="string">
* <wsdl:definition>...</wsdl:definition>?
* <wsdl20:description>...</wsdl20:description>?
* <resource location="..." key="..."/>*
* </publishWSDL>?
* <enableSec/>?
* <enableRM/>?
* <policy key="string" [type=("in" |"out")] [operationName="string"]
* [operationNamespace="string"]>?
* // optional service parameters
* <parameter name="string">
* text | xml
* </parameter>?
* </proxy-service>
*/
public class ProxyService {
private static final Log log = LogFactory.getLog(ProxyService.class);
private static final Log trace = LogFactory.getLog(SynapseConstants.TRACE_LOGGER);
private final Log serviceLog;
/**
* The name of the proxy service
*/
private String name;
/**
* The proxy service description. This could be optional informative text about the service
*/
private String description;
/**
* The transport/s over which this service should be exposed, or defaults to all available
*/
private ArrayList transports;
/**
* Server names for which this service should be exposed
*/
private List pinnedServers = new ArrayList();
/**
* The target endpoint key
*/
private String targetEndpoint = null;
/**
* The target inSequence key
*/
private String targetInSequence = null;
/**
* The target outSequence key
*/
private String targetOutSequence = null;
/**
* The target faultSequence key
*/
private String targetFaultSequence = null;
/**
* The inlined definition of the target endpoint, if defined
*/
private Endpoint targetInLineEndpoint = null;
/**
* The inlined definition of the target in-sequence, if defined
*/
private SequenceMediator targetInLineInSequence = null;
/**
* The inlined definition of the target out-sequence, if defined
*/
private SequenceMediator targetInLineOutSequence = null;
/**
* The inlined definition of the target fault-sequence, if defined
*/
private SequenceMediator targetInLineFaultSequence = null;
/**
* A list of any service parameters (e.g. JMS parameters etc)
*/
private final Map<String, Object> parameters = new HashMap<String, Object>();
/**
* The key for the base WSDL
*/
private String wsdlKey;
/**
* The URI for the base WSDL, if defined as a URL
*/
private URI wsdlURI;
/**
* The inlined representation of the service WSDL, if defined inline
*/
private Object inLineWSDL;
/**
* A ResourceMap object allowing to locate artifacts (WSDL and XSD) imported
* by the service WSDL to be located in the registry.
*/
private ResourceMap resourceMap;
/**
* Policies to be set to the service, this can include service level, operation level,
* message level or hybrid level policies as well.
*/
private List<PolicyInfo> policies = new ArrayList<PolicyInfo>();
/**
* The keys for any supplied policies that would apply at the service level
*/
private final List<String> serviceLevelPolicies = new ArrayList<String>();
/**
* The keys for any supplied policies that would apply at the in message level
*/
private List<String> inMessagePolicies = new ArrayList<String>();
/**
* The keys for any supplied policies that would apply at the out message level
*/
private List<String> outMessagePolicies = new ArrayList<String>();
/**
* Should WS Addressing be engaged on this service
*/
private boolean wsAddrEnabled = false;
/**
* Should WS RM be engaged on this service
*/
private boolean wsRMEnabled = false;
/**
* Should WS Sec be engaged on this service
*/
private boolean wsSecEnabled = false;
/**
* Should this service be started by default on initialization?
*/
private boolean startOnLoad = true;
/**
* Is this service running now?
*/
private boolean running = false;
public static final String ALL_TRANSPORTS = "all";
/**
* The variable that indicate tracing on or off for the current mediator
*/
protected int traceState = SynapseConstants.TRACING_UNSET;
/**
* Constructor
*
* @param name the name of the Proxy service
*/
public ProxyService(String name) {
this.name = name;
serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
}
/**
* Build the underlying Axis2 service from the Proxy service definition
*
* @param synCfg the Synapse configuration
* @param axisCfg the Axis2 configuration
* @return the Axis2 service for the Proxy
*/
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
auditInfo("Building Axis service for Proxy service : " + name);
AxisService proxyService = null;
// get the wsdlElement as an OMElement
if (trace()) {
trace.info("Loading the WSDL : " +
(wsdlKey != null ? " key = " + wsdlKey :
(wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>")));
}
InputStream wsdlInputStream = null;
OMElement wsdlElement = null;
boolean wsdlFound = false;
String publishWSDL = null;
if (wsdlKey != null) {
synCfg.getEntryDefinition(wsdlKey);
Object keyObject = synCfg.getEntry(wsdlKey);
if (keyObject instanceof OMElement) {
wsdlElement = (OMElement) keyObject;
}
wsdlFound = true;
} else if (inLineWSDL != null) {
wsdlElement = (OMElement) inLineWSDL;
wsdlFound = true;
} else if (wsdlURI != null) {
try {
URL url = wsdlURI.toURL();
publishWSDL = url.toString();
OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL);
if (node instanceof OMElement) {
wsdlElement = (OMElement) node;
}
wsdlFound = true;
} catch (MalformedURLException e) {
handleException("Malformed URI for wsdl", e);
} catch (IOException e) {
//handleException("Error reading from wsdl URI", e);
boolean enablePublishWSDLSafeMode = false;
Map proxyParameters= this.getParameterMap();
if (!proxyParameters.isEmpty()) {
if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
enablePublishWSDLSafeMode =
Boolean.parseBoolean(
proxyParameters.get("enablePublishWSDLSafeMode").
toString().toLowerCase());
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" +
"</syn:parameter> to proxy service.");
}
handleException("Error reading from wsdl URI", e);
}
}
if (enablePublishWSDLSafeMode) {
// this is if the wsdl cannot be loaded... create a dummy service and an operation for which
// our SynapseDispatcher will properly dispatch to
//!!!Need to add a reload function... And display that the wsdl/service is offline!!!
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: true");
}
proxyService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate"));
proxyService.addOperation(mediateOperation);
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: false");
}
handleException("Error reading from wsdl URI", e);
}
}
} else {
// this is for POX... create a dummy service and an operation for which
// our SynapseDispatcher will properly dispatch to
if (trace()) trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
proxyService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(
SynapseConstants.SYNAPSE_OPERATION_NAME);
// Set the names of the two messages so that Axis2 is able to produce a WSDL (see SYNAPSE-366):
mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE).setName("in");
mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).setName("out");
proxyService.addOperation(mediateOperation);
}
// if a WSDL was found
if (wsdlElement != null) {
OMNamespace wsdlNamespace = wsdlElement.getNamespace();
// serialize and create an inputstream to read WSDL
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (trace()) trace.info("Serializing wsdlElement found to build an Axis2 service");
wsdlElement.serialize(baos);
wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
} catch (XMLStreamException e) {
handleException("Error converting to a StreamSource", e);
}
if (wsdlInputStream != null) {
try {
// detect version of the WSDL 1.1 or 2.0
if (trace()) trace.info("WSDL Namespace is : "
+ wsdlNamespace.getNamespaceURI());
if (wsdlNamespace != null) {
WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
if (WSDL2Constants.WSDL_NAMESPACE.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
} else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL11ToAxisServiceBuilder(wsdlInputStream);
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
if (wsdlToAxisServiceBuilder == null) {
throw new SynapseException(
"Could not get the WSDL to Axis Service Builder");
}
wsdlToAxisServiceBuilder.setBaseUri(
wsdlURI != null ? wsdlURI.toString() :
SynapseConfigUtils.getSynapseHome());
if (trace()) {
trace.info("Setting up custom resolvers");
}
// Set up the URIResolver
if (resourceMap != null) {
// if the resource map is available use it
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver(resourceMap, synCfg));
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
- wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
+ wsdlToAxisServiceBuilder).setCustomWSDLResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : "",
resourceMap, synCfg));
}
} else {
//if the resource map isn't available ,
//then each import URIs will be resolved using base URI
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver());
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
- wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
+ wsdlToAxisServiceBuilder).setCustomWSDLResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : ""));
}
}
if (trace()) {
trace.info("Populating Axis2 service using WSDL");
if (trace.isTraceEnabled()) {
trace.trace("WSDL : " + wsdlElement.toString());
}
}
proxyService = wsdlToAxisServiceBuilder.populateService();
// this is to clear the bindinigs and ports already in the WSDL so that the
// service will generate the bindings on calling the printWSDL otherwise
// the WSDL which will be shown is same as the original WSDL except for the
// service name
proxyService.getEndpoints().clear();
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
} catch (AxisFault af) {
handleException("Error building service from WSDL", af);
} catch (IOException ioe) {
handleException("Error reading WSDL", ioe);
}
}
} else if (wsdlFound) {
handleException("Couldn't build the proxy service : " + name
+ ". Unable to locate the specified WSDL to build the service");
}
// Set the name and description. Currently Axis2 uses the name as the
// default Service destination
if (proxyService == null) {
throw new SynapseException("Could not create a proxy service");
}
proxyService.setName(name);
if (description != null) {
proxyService.setDocumentation(description);
}
// process transports and expose over requested transports. If none
// is specified, default to all transports using service name as
// destination
if (transports == null || transports.size() == 0) {
// default to all transports using service name as destination
} else {
if (trace()) trace.info("Exposing transports : " + transports);
proxyService.setExposedTransports(transports);
}
// process parameters
if (trace() && parameters.size() > 0) {
trace.info("Setting service parameters : " + parameters);
}
for (Object o : parameters.keySet()) {
String name = (String) o;
Object value = parameters.get(name);
Parameter p = new Parameter();
p.setName(name);
p.setValue(value);
try {
proxyService.addParameter(p);
} catch (AxisFault af) {
handleException("Error setting parameter : " + name + "" +
"to proxy service as a Parameter", af);
}
}
if (!policies.isEmpty()) {
for (PolicyInfo pi : policies) {
if (pi.isServicePolicy()) {
proxyService.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else if (pi.isOperationPolicy()) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation specified " +
"by the QName : " + pi.getOperation());
}
} else if (pi.isMessagePolicy()) {
if (pi.getOperation() != null) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getMessage(pi.getMessageLable()).getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation " +
"specified by the QName : " + pi.getOperation());
}
} else {
// operation is not specified and hence apply to all the applicable messages
for (Iterator itr = proxyService.getOperations(); itr.hasNext();) {
Object obj = itr.next();
if (obj instanceof AxisOperation) {
// check whether the policy is applicable
if (!((obj instanceof OutOnlyAxisOperation && pi.getType()
== PolicyInfo.MESSAGE_TYPE_IN) ||
(obj instanceof InOnlyAxisOperation
&& pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
AxisMessage message = ((AxisOperation)
obj).getMessage(pi.getMessageLable());
message.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
}
}
}
}
} else {
handleException("Undefined Policy type");
}
}
}
// create a custom message receiver for this proxy service
ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
msgRcvr.setName(name);
msgRcvr.setProxy(this);
Iterator iter = proxyService.getOperations();
while (iter.hasNext()) {
AxisOperation op = (AxisOperation) iter.next();
op.setMessageReceiver(msgRcvr);
}
try {
proxyService.addParameter(
SynapseConstants.SERVICE_TYPE_PARAM_NAME, SynapseConstants.PROXY_SERVICE_TYPE);
auditInfo("Adding service " + name + " to the Axis2 configuration");
axisCfg.addService(proxyService);
this.setRunning(true);
} catch (AxisFault axisFault) {
try {
if (axisCfg.getService(proxyService.getName()) != null) {
if (trace()) trace.info("Removing service " + name + " due to error : "
+ axisFault.getMessage());
axisCfg.removeService(proxyService.getName());
}
} catch (AxisFault ignore) {}
handleException("Error adding Proxy service to the Axis2 engine", axisFault);
}
// should Addressing be engaged on this service?
if (wsAddrEnabled) {
auditInfo("WS-Addressing is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Addressing module on proxy service : " + name, axisFault);
}
}
// should RM be engaged on this service?
if (wsRMEnabled) {
auditInfo("WS-Reliable messaging is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.RM_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS RM module on proxy service : " + name, axisFault);
}
}
// should Security be engaged on this service?
if (wsSecEnabled) {
auditInfo("WS-Security is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.SECURITY_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Sec module on proxy service : "
+ name, axisFault);
}
}
auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
return proxyService;
}
private Policy getPolicyFromKey(String key, SynapseConfiguration synCfg) {
synCfg.getEntryDefinition(key);
return PolicyEngine.getPolicy(
SynapseConfigUtils.getStreamSource(synCfg.getEntry(key)).getInputStream());
}
/**
* Start the proxy service
* @param synCfg the synapse configuration
*/
public void start(SynapseConfiguration synCfg) {
AxisConfiguration axisConfig = synCfg.getAxisConfiguration();
if (axisConfig != null) {
Parameter param = axisConfig.getParameter(SynapseConstants.SYNAPSE_ENV);
if (param != null && param.getValue() instanceof SynapseEnvironment) {
SynapseEnvironment env = (SynapseEnvironment) param.getValue();
if (targetInLineInSequence != null) {
targetInLineInSequence.init(env);
}
if (targetInLineOutSequence != null) {
targetInLineOutSequence.init(env);
}
if (targetInLineFaultSequence != null) {
targetInLineFaultSequence.init(env);
}
} else {
auditWarn("Unable to find the SynapseEnvironment. " +
"Components of the proxy service may not be initialized");
}
AxisService as = axisConfig.getServiceForActivation(this.getName());
as.setActive(true);
axisConfig.notifyObservers(AxisEvent.SERVICE_START, as);
this.setRunning(true);
auditInfo("Started the proxy service : " + name);
} else {
auditWarn("Unable to start proxy service : " + name +
". Couldn't access Axis configuration");
}
}
/**
* Stop the proxy service
* @param synCfg the synapse configuration
*/
public void stop(SynapseConfiguration synCfg) {
AxisConfiguration axisConfig = synCfg.getAxisConfiguration();
if (axisConfig != null) {
if (targetInLineInSequence != null) {
targetInLineInSequence.destroy();
}
if (targetInLineOutSequence != null) {
targetInLineOutSequence.destroy();
}
if (targetInLineFaultSequence != null) {
targetInLineFaultSequence.destroy();
}
try {
AxisService as = axisConfig.getService(this.getName());
if (as != null) {
as.setActive(false);
axisConfig.notifyObservers(AxisEvent.SERVICE_STOP, as);
}
this.setRunning(false);
auditInfo("Stopped the proxy service : " + name);
} catch (AxisFault axisFault) {
handleException("Error stopping the proxy service : " + name, axisFault);
}
} else {
auditWarn("Unable to stop proxy service : " + name +
". Couldn't access Axis configuration");
}
}
private void handleException(String msg) {
serviceLog.error(msg);
log.error(msg);
if (trace()) trace.error(msg);
throw new SynapseException(msg);
}
private void handleException(String msg, Exception e) {
serviceLog.error(msg);
log.error(msg, e);
if (trace()) trace.error(msg + " :: " + e.getMessage());
throw new SynapseException(msg, e);
}
/**
* Write to the general log, as well as any service specific logs the audit message at INFO
* @param message the INFO level audit message
*/
private void auditInfo(String message) {
log.info(message);
serviceLog.info(message);
if (trace()) {
trace.info(message);
}
}
/**
* Write to the general log, as well as any service specific logs the audit message at WARN
* @param message the WARN level audit message
*/
private void auditWarn(String message) {
log.warn(message);
serviceLog.warn(message);
if (trace()) {
trace.warn(message);
}
}
/**
* Return true if tracing should be enabled
* @return true if tracing is enabled for this service
*/
private boolean trace() {
return traceState == SynapseConstants.TRACING_ON;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList getTransports() {
return transports;
}
public void addParameter(String name, Object value) {
parameters.put(name, value);
}
public Map<String, Object> getParameterMap() {
return this.parameters;
}
public void setTransports(ArrayList transports) {
this.transports = transports;
}
public String getTargetEndpoint() {
return targetEndpoint;
}
public void setTargetEndpoint(String targetEndpoint) {
this.targetEndpoint = targetEndpoint;
}
public String getTargetInSequence() {
return targetInSequence;
}
public void setTargetInSequence(String targetInSequence) {
this.targetInSequence = targetInSequence;
}
public String getTargetOutSequence() {
return targetOutSequence;
}
public void setTargetOutSequence(String targetOutSequence) {
this.targetOutSequence = targetOutSequence;
}
public String getWSDLKey() {
return wsdlKey;
}
public void setWSDLKey(String wsdlKey) {
this.wsdlKey = wsdlKey;
}
public List<String> getServiceLevelPolicies() {
return serviceLevelPolicies;
}
public void addServiceLevelPolicy(String serviceLevelPolicy) {
this.serviceLevelPolicies.add(serviceLevelPolicy);
}
public boolean isWsAddrEnabled() {
return wsAddrEnabled;
}
public void setWsAddrEnabled(boolean wsAddrEnabled) {
this.wsAddrEnabled = wsAddrEnabled;
}
public boolean isWsRMEnabled() {
return wsRMEnabled;
}
public void setWsRMEnabled(boolean wsRMEnabled) {
this.wsRMEnabled = wsRMEnabled;
}
public boolean isWsSecEnabled() {
return wsSecEnabled;
}
public void setWsSecEnabled(boolean wsSecEnabled) {
this.wsSecEnabled = wsSecEnabled;
}
public boolean isStartOnLoad() {
return startOnLoad;
}
public void setStartOnLoad(boolean startOnLoad) {
this.startOnLoad = startOnLoad;
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
/**
* Returns the int value that indicate the tracing state
*
* @return Returns the int value that indicate the tracing state
*/
public int getTraceState() {
return traceState;
}
/**
* Set the tracing State variable
*
* @param traceState tracing state
*/
public void setTraceState(int traceState) {
this.traceState = traceState;
}
public String getTargetFaultSequence() {
return targetFaultSequence;
}
public void setTargetFaultSequence(String targetFaultSequence) {
this.targetFaultSequence = targetFaultSequence;
}
public Object getInLineWSDL() {
return inLineWSDL;
}
public void setInLineWSDL(Object inLineWSDL) {
this.inLineWSDL = inLineWSDL;
}
public URI getWsdlURI() {
return wsdlURI;
}
public void setWsdlURI(URI wsdlURI) {
this.wsdlURI = wsdlURI;
}
public Endpoint getTargetInLineEndpoint() {
return targetInLineEndpoint;
}
public void setTargetInLineEndpoint(Endpoint targetInLineEndpoint) {
this.targetInLineEndpoint = targetInLineEndpoint;
}
public SequenceMediator getTargetInLineInSequence() {
return targetInLineInSequence;
}
public void setTargetInLineInSequence(SequenceMediator targetInLineInSequence) {
this.targetInLineInSequence = targetInLineInSequence;
}
public SequenceMediator getTargetInLineOutSequence() {
return targetInLineOutSequence;
}
public void setTargetInLineOutSequence(SequenceMediator targetInLineOutSequence) {
this.targetInLineOutSequence = targetInLineOutSequence;
}
public SequenceMediator getTargetInLineFaultSequence() {
return targetInLineFaultSequence;
}
public void setTargetInLineFaultSequence(SequenceMediator targetInLineFaultSequence) {
this.targetInLineFaultSequence = targetInLineFaultSequence;
}
public List getPinnedServers() {
return pinnedServers;
}
public void setPinnedServers(List pinnedServers) {
this.pinnedServers = pinnedServers;
}
public ResourceMap getResourceMap() {
return resourceMap;
}
public void setResourceMap(ResourceMap resourceMap) {
this.resourceMap = resourceMap;
}
public List<String> getInMessagePolicies() {
return inMessagePolicies;
}
public void setInMessagePolicies(List<String> inMessagePolicies) {
this.inMessagePolicies = inMessagePolicies;
}
public void addInMessagePolicy(String messagePolicy) {
this.inMessagePolicies.add(messagePolicy);
}
public List<String> getOutMessagePolicies() {
return outMessagePolicies;
}
public void setOutMessagePolicies(List<String> outMessagePolicies) {
this.outMessagePolicies = outMessagePolicies;
}
public void addOutMessagePolicy(String messagePolicy) {
this.outMessagePolicies.add(messagePolicy);
}
public List<PolicyInfo> getPolicies() {
return policies;
}
public void setPolicies(List<PolicyInfo> policies) {
this.policies = policies;
}
public void addPolicyInfo(PolicyInfo pi) {
this.policies.add(pi);
}
}
| false | true | public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
auditInfo("Building Axis service for Proxy service : " + name);
AxisService proxyService = null;
// get the wsdlElement as an OMElement
if (trace()) {
trace.info("Loading the WSDL : " +
(wsdlKey != null ? " key = " + wsdlKey :
(wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>")));
}
InputStream wsdlInputStream = null;
OMElement wsdlElement = null;
boolean wsdlFound = false;
String publishWSDL = null;
if (wsdlKey != null) {
synCfg.getEntryDefinition(wsdlKey);
Object keyObject = synCfg.getEntry(wsdlKey);
if (keyObject instanceof OMElement) {
wsdlElement = (OMElement) keyObject;
}
wsdlFound = true;
} else if (inLineWSDL != null) {
wsdlElement = (OMElement) inLineWSDL;
wsdlFound = true;
} else if (wsdlURI != null) {
try {
URL url = wsdlURI.toURL();
publishWSDL = url.toString();
OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL);
if (node instanceof OMElement) {
wsdlElement = (OMElement) node;
}
wsdlFound = true;
} catch (MalformedURLException e) {
handleException("Malformed URI for wsdl", e);
} catch (IOException e) {
//handleException("Error reading from wsdl URI", e);
boolean enablePublishWSDLSafeMode = false;
Map proxyParameters= this.getParameterMap();
if (!proxyParameters.isEmpty()) {
if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
enablePublishWSDLSafeMode =
Boolean.parseBoolean(
proxyParameters.get("enablePublishWSDLSafeMode").
toString().toLowerCase());
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" +
"</syn:parameter> to proxy service.");
}
handleException("Error reading from wsdl URI", e);
}
}
if (enablePublishWSDLSafeMode) {
// this is if the wsdl cannot be loaded... create a dummy service and an operation for which
// our SynapseDispatcher will properly dispatch to
//!!!Need to add a reload function... And display that the wsdl/service is offline!!!
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: true");
}
proxyService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate"));
proxyService.addOperation(mediateOperation);
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: false");
}
handleException("Error reading from wsdl URI", e);
}
}
} else {
// this is for POX... create a dummy service and an operation for which
// our SynapseDispatcher will properly dispatch to
if (trace()) trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
proxyService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(
SynapseConstants.SYNAPSE_OPERATION_NAME);
// Set the names of the two messages so that Axis2 is able to produce a WSDL (see SYNAPSE-366):
mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE).setName("in");
mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).setName("out");
proxyService.addOperation(mediateOperation);
}
// if a WSDL was found
if (wsdlElement != null) {
OMNamespace wsdlNamespace = wsdlElement.getNamespace();
// serialize and create an inputstream to read WSDL
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (trace()) trace.info("Serializing wsdlElement found to build an Axis2 service");
wsdlElement.serialize(baos);
wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
} catch (XMLStreamException e) {
handleException("Error converting to a StreamSource", e);
}
if (wsdlInputStream != null) {
try {
// detect version of the WSDL 1.1 or 2.0
if (trace()) trace.info("WSDL Namespace is : "
+ wsdlNamespace.getNamespaceURI());
if (wsdlNamespace != null) {
WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
if (WSDL2Constants.WSDL_NAMESPACE.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
} else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL11ToAxisServiceBuilder(wsdlInputStream);
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
if (wsdlToAxisServiceBuilder == null) {
throw new SynapseException(
"Could not get the WSDL to Axis Service Builder");
}
wsdlToAxisServiceBuilder.setBaseUri(
wsdlURI != null ? wsdlURI.toString() :
SynapseConfigUtils.getSynapseHome());
if (trace()) {
trace.info("Setting up custom resolvers");
}
// Set up the URIResolver
if (resourceMap != null) {
// if the resource map is available use it
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver(resourceMap, synCfg));
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : "",
resourceMap, synCfg));
}
} else {
//if the resource map isn't available ,
//then each import URIs will be resolved using base URI
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver());
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSLD4JResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : ""));
}
}
if (trace()) {
trace.info("Populating Axis2 service using WSDL");
if (trace.isTraceEnabled()) {
trace.trace("WSDL : " + wsdlElement.toString());
}
}
proxyService = wsdlToAxisServiceBuilder.populateService();
// this is to clear the bindinigs and ports already in the WSDL so that the
// service will generate the bindings on calling the printWSDL otherwise
// the WSDL which will be shown is same as the original WSDL except for the
// service name
proxyService.getEndpoints().clear();
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
} catch (AxisFault af) {
handleException("Error building service from WSDL", af);
} catch (IOException ioe) {
handleException("Error reading WSDL", ioe);
}
}
} else if (wsdlFound) {
handleException("Couldn't build the proxy service : " + name
+ ". Unable to locate the specified WSDL to build the service");
}
// Set the name and description. Currently Axis2 uses the name as the
// default Service destination
if (proxyService == null) {
throw new SynapseException("Could not create a proxy service");
}
proxyService.setName(name);
if (description != null) {
proxyService.setDocumentation(description);
}
// process transports and expose over requested transports. If none
// is specified, default to all transports using service name as
// destination
if (transports == null || transports.size() == 0) {
// default to all transports using service name as destination
} else {
if (trace()) trace.info("Exposing transports : " + transports);
proxyService.setExposedTransports(transports);
}
// process parameters
if (trace() && parameters.size() > 0) {
trace.info("Setting service parameters : " + parameters);
}
for (Object o : parameters.keySet()) {
String name = (String) o;
Object value = parameters.get(name);
Parameter p = new Parameter();
p.setName(name);
p.setValue(value);
try {
proxyService.addParameter(p);
} catch (AxisFault af) {
handleException("Error setting parameter : " + name + "" +
"to proxy service as a Parameter", af);
}
}
if (!policies.isEmpty()) {
for (PolicyInfo pi : policies) {
if (pi.isServicePolicy()) {
proxyService.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else if (pi.isOperationPolicy()) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation specified " +
"by the QName : " + pi.getOperation());
}
} else if (pi.isMessagePolicy()) {
if (pi.getOperation() != null) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getMessage(pi.getMessageLable()).getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation " +
"specified by the QName : " + pi.getOperation());
}
} else {
// operation is not specified and hence apply to all the applicable messages
for (Iterator itr = proxyService.getOperations(); itr.hasNext();) {
Object obj = itr.next();
if (obj instanceof AxisOperation) {
// check whether the policy is applicable
if (!((obj instanceof OutOnlyAxisOperation && pi.getType()
== PolicyInfo.MESSAGE_TYPE_IN) ||
(obj instanceof InOnlyAxisOperation
&& pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
AxisMessage message = ((AxisOperation)
obj).getMessage(pi.getMessageLable());
message.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
}
}
}
}
} else {
handleException("Undefined Policy type");
}
}
}
// create a custom message receiver for this proxy service
ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
msgRcvr.setName(name);
msgRcvr.setProxy(this);
Iterator iter = proxyService.getOperations();
while (iter.hasNext()) {
AxisOperation op = (AxisOperation) iter.next();
op.setMessageReceiver(msgRcvr);
}
try {
proxyService.addParameter(
SynapseConstants.SERVICE_TYPE_PARAM_NAME, SynapseConstants.PROXY_SERVICE_TYPE);
auditInfo("Adding service " + name + " to the Axis2 configuration");
axisCfg.addService(proxyService);
this.setRunning(true);
} catch (AxisFault axisFault) {
try {
if (axisCfg.getService(proxyService.getName()) != null) {
if (trace()) trace.info("Removing service " + name + " due to error : "
+ axisFault.getMessage());
axisCfg.removeService(proxyService.getName());
}
} catch (AxisFault ignore) {}
handleException("Error adding Proxy service to the Axis2 engine", axisFault);
}
// should Addressing be engaged on this service?
if (wsAddrEnabled) {
auditInfo("WS-Addressing is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Addressing module on proxy service : " + name, axisFault);
}
}
// should RM be engaged on this service?
if (wsRMEnabled) {
auditInfo("WS-Reliable messaging is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.RM_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS RM module on proxy service : " + name, axisFault);
}
}
// should Security be engaged on this service?
if (wsSecEnabled) {
auditInfo("WS-Security is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.SECURITY_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Sec module on proxy service : "
+ name, axisFault);
}
}
auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
return proxyService;
}
| public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
auditInfo("Building Axis service for Proxy service : " + name);
AxisService proxyService = null;
// get the wsdlElement as an OMElement
if (trace()) {
trace.info("Loading the WSDL : " +
(wsdlKey != null ? " key = " + wsdlKey :
(wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>")));
}
InputStream wsdlInputStream = null;
OMElement wsdlElement = null;
boolean wsdlFound = false;
String publishWSDL = null;
if (wsdlKey != null) {
synCfg.getEntryDefinition(wsdlKey);
Object keyObject = synCfg.getEntry(wsdlKey);
if (keyObject instanceof OMElement) {
wsdlElement = (OMElement) keyObject;
}
wsdlFound = true;
} else if (inLineWSDL != null) {
wsdlElement = (OMElement) inLineWSDL;
wsdlFound = true;
} else if (wsdlURI != null) {
try {
URL url = wsdlURI.toURL();
publishWSDL = url.toString();
OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL);
if (node instanceof OMElement) {
wsdlElement = (OMElement) node;
}
wsdlFound = true;
} catch (MalformedURLException e) {
handleException("Malformed URI for wsdl", e);
} catch (IOException e) {
//handleException("Error reading from wsdl URI", e);
boolean enablePublishWSDLSafeMode = false;
Map proxyParameters= this.getParameterMap();
if (!proxyParameters.isEmpty()) {
if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
enablePublishWSDLSafeMode =
Boolean.parseBoolean(
proxyParameters.get("enablePublishWSDLSafeMode").
toString().toLowerCase());
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" +
"</syn:parameter> to proxy service.");
}
handleException("Error reading from wsdl URI", e);
}
}
if (enablePublishWSDLSafeMode) {
// this is if the wsdl cannot be loaded... create a dummy service and an operation for which
// our SynapseDispatcher will properly dispatch to
//!!!Need to add a reload function... And display that the wsdl/service is offline!!!
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: true");
}
proxyService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate"));
proxyService.addOperation(mediateOperation);
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: false");
}
handleException("Error reading from wsdl URI", e);
}
}
} else {
// this is for POX... create a dummy service and an operation for which
// our SynapseDispatcher will properly dispatch to
if (trace()) trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
proxyService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(
SynapseConstants.SYNAPSE_OPERATION_NAME);
// Set the names of the two messages so that Axis2 is able to produce a WSDL (see SYNAPSE-366):
mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE).setName("in");
mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).setName("out");
proxyService.addOperation(mediateOperation);
}
// if a WSDL was found
if (wsdlElement != null) {
OMNamespace wsdlNamespace = wsdlElement.getNamespace();
// serialize and create an inputstream to read WSDL
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (trace()) trace.info("Serializing wsdlElement found to build an Axis2 service");
wsdlElement.serialize(baos);
wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
} catch (XMLStreamException e) {
handleException("Error converting to a StreamSource", e);
}
if (wsdlInputStream != null) {
try {
// detect version of the WSDL 1.1 or 2.0
if (trace()) trace.info("WSDL Namespace is : "
+ wsdlNamespace.getNamespaceURI());
if (wsdlNamespace != null) {
WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
if (WSDL2Constants.WSDL_NAMESPACE.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
} else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.
equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder =
new WSDL11ToAxisServiceBuilder(wsdlInputStream);
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
if (wsdlToAxisServiceBuilder == null) {
throw new SynapseException(
"Could not get the WSDL to Axis Service Builder");
}
wsdlToAxisServiceBuilder.setBaseUri(
wsdlURI != null ? wsdlURI.toString() :
SynapseConfigUtils.getSynapseHome());
if (trace()) {
trace.info("Setting up custom resolvers");
}
// Set up the URIResolver
if (resourceMap != null) {
// if the resource map is available use it
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver(resourceMap, synCfg));
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSDLResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : "",
resourceMap, synCfg));
}
} else {
//if the resource map isn't available ,
//then each import URIs will be resolved using base URI
wsdlToAxisServiceBuilder.setCustomResolver(
new CustomURIResolver());
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder)
wsdlToAxisServiceBuilder).setCustomWSDLResolver(
new CustomWSDLLocator(new InputSource(wsdlInputStream),
wsdlURI != null ? wsdlURI.toString() : ""));
}
}
if (trace()) {
trace.info("Populating Axis2 service using WSDL");
if (trace.isTraceEnabled()) {
trace.trace("WSDL : " + wsdlElement.toString());
}
}
proxyService = wsdlToAxisServiceBuilder.populateService();
// this is to clear the bindinigs and ports already in the WSDL so that the
// service will generate the bindings on calling the printWSDL otherwise
// the WSDL which will be shown is same as the original WSDL except for the
// service name
proxyService.getEndpoints().clear();
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
} catch (AxisFault af) {
handleException("Error building service from WSDL", af);
} catch (IOException ioe) {
handleException("Error reading WSDL", ioe);
}
}
} else if (wsdlFound) {
handleException("Couldn't build the proxy service : " + name
+ ". Unable to locate the specified WSDL to build the service");
}
// Set the name and description. Currently Axis2 uses the name as the
// default Service destination
if (proxyService == null) {
throw new SynapseException("Could not create a proxy service");
}
proxyService.setName(name);
if (description != null) {
proxyService.setDocumentation(description);
}
// process transports and expose over requested transports. If none
// is specified, default to all transports using service name as
// destination
if (transports == null || transports.size() == 0) {
// default to all transports using service name as destination
} else {
if (trace()) trace.info("Exposing transports : " + transports);
proxyService.setExposedTransports(transports);
}
// process parameters
if (trace() && parameters.size() > 0) {
trace.info("Setting service parameters : " + parameters);
}
for (Object o : parameters.keySet()) {
String name = (String) o;
Object value = parameters.get(name);
Parameter p = new Parameter();
p.setName(name);
p.setValue(value);
try {
proxyService.addParameter(p);
} catch (AxisFault af) {
handleException("Error setting parameter : " + name + "" +
"to proxy service as a Parameter", af);
}
}
if (!policies.isEmpty()) {
for (PolicyInfo pi : policies) {
if (pi.isServicePolicy()) {
proxyService.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else if (pi.isOperationPolicy()) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation specified " +
"by the QName : " + pi.getOperation());
}
} else if (pi.isMessagePolicy()) {
if (pi.getOperation() != null) {
AxisOperation op = proxyService.getOperation(pi.getOperation());
if (op != null) {
op.getMessage(pi.getMessageLable()).getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
} else {
handleException("Couldn't find the operation " +
"specified by the QName : " + pi.getOperation());
}
} else {
// operation is not specified and hence apply to all the applicable messages
for (Iterator itr = proxyService.getOperations(); itr.hasNext();) {
Object obj = itr.next();
if (obj instanceof AxisOperation) {
// check whether the policy is applicable
if (!((obj instanceof OutOnlyAxisOperation && pi.getType()
== PolicyInfo.MESSAGE_TYPE_IN) ||
(obj instanceof InOnlyAxisOperation
&& pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
AxisMessage message = ((AxisOperation)
obj).getMessage(pi.getMessageLable());
message.getPolicySubject().attachPolicy(
getPolicyFromKey(pi.getPolicyKey(), synCfg));
}
}
}
}
} else {
handleException("Undefined Policy type");
}
}
}
// create a custom message receiver for this proxy service
ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
msgRcvr.setName(name);
msgRcvr.setProxy(this);
Iterator iter = proxyService.getOperations();
while (iter.hasNext()) {
AxisOperation op = (AxisOperation) iter.next();
op.setMessageReceiver(msgRcvr);
}
try {
proxyService.addParameter(
SynapseConstants.SERVICE_TYPE_PARAM_NAME, SynapseConstants.PROXY_SERVICE_TYPE);
auditInfo("Adding service " + name + " to the Axis2 configuration");
axisCfg.addService(proxyService);
this.setRunning(true);
} catch (AxisFault axisFault) {
try {
if (axisCfg.getService(proxyService.getName()) != null) {
if (trace()) trace.info("Removing service " + name + " due to error : "
+ axisFault.getMessage());
axisCfg.removeService(proxyService.getName());
}
} catch (AxisFault ignore) {}
handleException("Error adding Proxy service to the Axis2 engine", axisFault);
}
// should Addressing be engaged on this service?
if (wsAddrEnabled) {
auditInfo("WS-Addressing is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Addressing module on proxy service : " + name, axisFault);
}
}
// should RM be engaged on this service?
if (wsRMEnabled) {
auditInfo("WS-Reliable messaging is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.RM_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS RM module on proxy service : " + name, axisFault);
}
}
// should Security be engaged on this service?
if (wsSecEnabled) {
auditInfo("WS-Security is enabled for service : " + name);
try {
proxyService.engageModule(axisCfg.getModule(
SynapseConstants.SECURITY_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Sec module on proxy service : "
+ name, axisFault);
}
}
auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
return proxyService;
}
|
diff --git a/src/quizsite/util/Activity.java b/src/quizsite/util/Activity.java
index 2f7653e..e61cdc7 100644
--- a/src/quizsite/util/Activity.java
+++ b/src/quizsite/util/Activity.java
@@ -1,75 +1,75 @@
package quizsite.util;
import java.util.ArrayList;
import java.util.List;
/**
* A class representing an activity that has taken place
*/
public class Activity {
/* Instance variables */
private int userId;
private String userName;
private String date;
private String verb;
private String subject;
public Activity(int userId, String userName, String date, String verb, String subject) {
System.err.println("(Activity Constructor: line 18) Making an activity with userId: " + userId);
this.userId = userId;
this.userName = userName;
this.date = date;
this.verb = verb;
this.subject = subject;
}
public int getUserId() {
return userId;
}
public String getUser() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDate() {
return date;
}
public String getVerb() {
return verb;
}
public String subject() {
return subject;
}
/**
* Takes in a list of persistent models and returns a list of equivalent activities
*/
public static <T extends PersistentModel> List<Activity> toActivityList(List<T>models) {
List<Activity> activities = new ArrayList<Activity>();
for(PersistentModel model : models) {
activities.add(model.getActivity());
}
return activities;
}
/**
* Returns a print string for the given activity
*/
public String getActivityPrintString() {
StringBuilder sb = new StringBuilder();
sb.append("<div class='activity'>\n");
sb.append("<p>\n");
- sb.append("<a href='/user?userId="+userId+"'>"+userName+"</a>");
+ sb.append("<a href='display_user.jsp?userId="+userId+"'>"+userName+"</a>");
sb.append(" " + verb + " " + subject + " on " + date + ".\n");
sb.append("</p>\n");
sb.append("</div>");
return sb.toString();
}
}
| true | true | public String getActivityPrintString() {
StringBuilder sb = new StringBuilder();
sb.append("<div class='activity'>\n");
sb.append("<p>\n");
sb.append("<a href='/user?userId="+userId+"'>"+userName+"</a>");
sb.append(" " + verb + " " + subject + " on " + date + ".\n");
sb.append("</p>\n");
sb.append("</div>");
return sb.toString();
}
| public String getActivityPrintString() {
StringBuilder sb = new StringBuilder();
sb.append("<div class='activity'>\n");
sb.append("<p>\n");
sb.append("<a href='display_user.jsp?userId="+userId+"'>"+userName+"</a>");
sb.append(" " + verb + " " + subject + " on " + date + ".\n");
sb.append("</p>\n");
sb.append("</div>");
return sb.toString();
}
|
diff --git a/src/com/ioabsoftware/gameraven/AllInOneV2.java b/src/com/ioabsoftware/gameraven/AllInOneV2.java
index 3436a10..8988a5f 100644
--- a/src/com/ioabsoftware/gameraven/AllInOneV2.java
+++ b/src/com/ioabsoftware/gameraven/AllInOneV2.java
@@ -1,3060 +1,3060 @@
package com.ioabsoftware.gameraven;
import java.io.File;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.MenuDrawer.OnDrawerStateChangeListener;
import net.simonvt.menudrawer.MenuDrawer.Type;
import org.acra.ACRA;
import org.acra.ACRAConfiguration;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.DefaultHeaderTransformer;
import uk.co.senab.actionbarpulltorefresh.library.Options;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;
import com.ioabsoftware.gameraven.db.HighlightListDBHelper;
import com.ioabsoftware.gameraven.db.HighlightedUser;
import com.ioabsoftware.gameraven.networking.HandlesNetworkResult.NetDesc;
import com.ioabsoftware.gameraven.networking.Session;
import com.ioabsoftware.gameraven.views.BaseRowData;
import com.ioabsoftware.gameraven.views.ViewAdapter;
import com.ioabsoftware.gameraven.views.rowdata.AMPRowData;
import com.ioabsoftware.gameraven.views.rowdata.AdRowData;
import com.ioabsoftware.gameraven.views.rowdata.BoardRowData;
import com.ioabsoftware.gameraven.views.rowdata.BoardRowData.BoardType;
import com.ioabsoftware.gameraven.views.rowdata.GameSearchRowData;
import com.ioabsoftware.gameraven.views.rowdata.HeaderRowData;
import com.ioabsoftware.gameraven.views.rowdata.MessageRowData;
import com.ioabsoftware.gameraven.views.rowdata.PMDetailRowData;
import com.ioabsoftware.gameraven.views.rowdata.PMRowData;
import com.ioabsoftware.gameraven.views.rowdata.TopicRowData;
import com.ioabsoftware.gameraven.views.rowdata.TopicRowData.ReadStatus;
import com.ioabsoftware.gameraven.views.rowdata.TopicRowData.TopicType;
import com.ioabsoftware.gameraven.views.rowdata.TrackedTopicRowData;
import com.ioabsoftware.gameraven.views.rowdata.UserDetailRowData;
import com.ioabsoftware.gameraven.views.rowview.MessageRowView;
import de.keyboardsurfer.android.widget.crouton.Configuration;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
public class AllInOneV2 extends Activity {
public static boolean isReleaseBuild = true;
public static final int SEND_PM_DIALOG = 102;
public static final int MESSAGE_ACTION_DIALOG = 103;
public static final int REPORT_MESSAGE_DIALOG = 104;
public static final int POLL_OPTIONS_DIALOG = 105;
public static final int CHANGE_LOGGED_IN_DIALOG = 106;
protected static final String ACCOUNTS_PREFNAME = "com.ioabsoftware.DroidFAQs.Accounts";
protected static String secureSalt;
public static final String EMPTY_STRING = "";
public static String defaultSig;
/** current session */
private Session session = null;
public Session getSession()
{return session;}
private String boardID;
public String getBoardID()
{return boardID;}
private String topicID;
public String getTopicID()
{return topicID;}
private String messageIDForEditing;
public String getMessageID()
{return messageIDForEditing;}
private String postPostUrl;
public String getPostPostUrl()
{return postPostUrl;}
private String savedPostBody;
public String getSavedPostBody() {
if (settings.getBoolean("autoCensorEnable", true))
return autoCensor(savedPostBody);
else
return savedPostBody;
}
private String savedPostTitle;
public String getSavedPostTitle() {
if (settings.getBoolean("autoCensorEnable", true))
return autoCensor(savedPostTitle);
else
return savedPostTitle;
}
/** preference object for global settings */
private static SharedPreferences settings = null;
public static SharedPreferences getSettingsPref()
{return settings;}
/** list of accounts (username, password) */
private static SecurePreferences accounts = null;
public static SecurePreferences getAccounts()
{return accounts;}
private LinearLayout titleWrapper;
private EditText postTitle;
private EditText postBody;
private TextView titleCounter;
private TextView bodyCounter;
private Button postButton;
private Button cancelButton;
private Button pollButton;
private View pollSep;
private boolean pollUse = false;
public boolean isUsingPoll() {return pollUse;}
private String pollTitle = EMPTY_STRING;
public String getPollTitle() {return pollTitle;}
private String[] pollOptions = new String[10];
public String[] getPollOptions() {return pollOptions;}
private int pollMinLevel = -1;
public String getPollMinLevel() {return Integer.toString(pollMinLevel);}
private LinearLayout postWrapper;
private PullToRefreshLayout ptrLayout;
private ListView contentList;
private ActionBar aBar;
private MenuItem refreshIcon;
private MenuItem postIcon;
private MenuItem addFavIcon;
private MenuItem remFavIcon;
private MenuItem searchIcon;
private MenuItem topicListIcon;
private String tlUrl;
private enum PostMode {ON_BOARD, ON_TOPIC, NEW_PM};
private PostMode pMode;
private enum FavMode {ON_BOARD, ON_TOPIC};
private FavMode fMode;
private TextView title;
private Button firstPage, prevPage, nextPage, lastPage;
private String firstPageUrl, prevPageUrl, nextPageUrl, lastPageUrl;
private NetDesc pageJumperDesc;
private TextView pageLabel;
private View pageJumperWrapper;
public int[] getScrollerVertLoc() {
try {
int firstVis = contentList.getFirstVisiblePosition();
return new int[] {firstVis, contentList.getChildAt(0).getTop()};
}
catch (NullPointerException npe) {
return new int[] {0, 0};
}
}
private static boolean usingLightTheme;
public static boolean getUsingLightTheme() {return usingLightTheme;}
private static int accentColor, accentTextColor;
public static int getAccentColor() {return accentColor;};
public static int getAccentTextColor() {return accentTextColor;}
private static float textScale = 1f;
public static float getTextScale() {return textScale;}
private static boolean isAccentLight;
public static boolean isAccentLight() {return isAccentLight;}
private static Style croutonStyle;
public static Style getCroutonStyle() {return croutonStyle;}
private static Configuration croutonShort = new Configuration.Builder()
.setDuration(2500).build();
private static HighlightListDBHelper hlDB;
public static HighlightListDBHelper getHLDB() {return hlDB;}
private MenuDrawer drawer;
private static AllInOneV2 me;
public static AllInOneV2 get() {return me;}
/**********************************************
* START METHODS
**********************************************/
@Override
protected void onCreate(Bundle savedInstanceState) {
me = this;
settings = PreferenceManager.getDefaultSharedPreferences(this);
accentColor = settings.getInt("accentColor", (getResources().getColor(R.color.holo_blue)));
usingLightTheme = settings.getBoolean("useLightTheme", false);
if (usingLightTheme) {
setTheme(R.style.MyThemes_LightTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.allinonev2);
colorOverscroll(this, accentColor);
aBar = getActionBar();
aBar.setDisplayHomeAsUpEnabled(true);
aBar.setDisplayShowTitleEnabled(false);
drawer = MenuDrawer.attach(this, Type.OVERLAY);
drawer.setContentView(R.layout.allinonev2);
drawer.setMenuView(R.layout.drawer);
drawer.setOnDrawerStateChangeListener(new OnDrawerStateChangeListener() {
@Override
public void onDrawerStateChange(int oldState, int newState) {
if (newState == MenuDrawer.STATE_CLOSED)
drawer.findViewById(R.id.dwrScroller).scrollTo(0, 0);
}
@Override
public void onDrawerSlide(float openRatio, int offsetPixels) {
// not needed
}
});
if (usingLightTheme)
drawer.findViewById(R.id.dwrScroller).setBackgroundResource(android.R.drawable.screen_background_light);
else
drawer.findViewById(R.id.dwrScroller).setBackgroundResource(android.R.drawable.screen_background_dark_transparent);
((Button) drawer.findViewById(R.id.dwrChangeAcc)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeMenu(true);
showDialog(CHANGE_LOGGED_IN_DIALOG);
}
});
((Button) drawer.findViewById(R.id.dwrBoardJumper)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeMenu(true);
session.get(NetDesc.BOARD_JUMPER, "/boards", null);
}
});
((Button) drawer.findViewById(R.id.dwrAMPList)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeMenu(true);
session.get(NetDesc.AMP_LIST, buildAMPLink(), null);
}
});
((Button) drawer.findViewById(R.id.dwrTrackedTopics)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeMenu(true);
session.get(NetDesc.TRACKED_TOPICS, "/boards/tracked", null);
}
});
((Button) drawer.findViewById(R.id.dwrPMInbox)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeMenu(true);
session.get(NetDesc.PM_INBOX, "/pm/", null);
}
});
((Button) drawer.findViewById(R.id.dwrCopyCurrURL)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
android.content.ClipboardManager clipboard =
(android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(android.content.ClipData.newPlainText("simple text", session.getLastPath()));
drawer.closeMenu(true);
Crouton.showText(AllInOneV2.this, "URL copied to clipboard.", croutonStyle);
}
});
((Button) drawer.findViewById(R.id.dwrHighlightList)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeMenu(false);
startActivity(new Intent(AllInOneV2.this, SettingsHighlightedUsers.class));
}
});
((Button) drawer.findViewById(R.id.dwrSettings)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeMenu(false);
startActivity(new Intent(AllInOneV2.this, SettingsMain.class));
}
});
((Button) drawer.findViewById(R.id.dwrExit)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AllInOneV2.this.finish();
}
});
// The drawable that replaces the up indicator in the action bar
if (usingLightTheme)
drawer.setSlideDrawable(R.drawable.ic_drawer_light);
else
drawer.setSlideDrawable(R.drawable.ic_drawer);
// Whether the previous drawable should be shown
drawer.setDrawerIndicatorEnabled(true);
if (!settings.contains("defaultAccount")) {
// settings need to be set to default
PreferenceManager.setDefaultValues(this, R.xml.settingsmain, false);
Editor sEditor = settings.edit();
sEditor.putString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT)
.putString("timezone", TimeZone.getDefault().getID())
.commit();
}
wtl("getting accounts");
if (settings.contains("secureSalt"))
secureSalt = settings.getString("secureSalt", null);
else {
secureSalt = UUID.randomUUID().toString();
settings.edit().putString("secureSalt", secureSalt).commit();
}
accounts = new SecurePreferences(getApplicationContext(), ACCOUNTS_PREFNAME, secureSalt, false);
ptrLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
// Now setup the PullToRefreshLayout
ActionBarPullToRefresh.from(this)
.options(Options.create()
.noMinimize()
.refreshOnUp(true)
.build())
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(new OnRefreshListener() {
@Override
public void onRefreshStarted(View view) {
refreshClicked(view);
}
})
// Finally commit the setup to our PullToRefreshLayout
.setup(ptrLayout);
contentList = (ListView) findViewById(R.id.aioMainList);
titleWrapper = (LinearLayout) findViewById(R.id.aioPostTitleWrapper);
postTitle = (EditText) findViewById(R.id.aioPostTitle);
postBody = (EditText) findViewById(R.id.aioPostBody);
titleCounter = (TextView) findViewById(R.id.aioPostTitleCounter);
bodyCounter = (TextView) findViewById(R.id.aioPostBodyCounter);
title = (TextView) findViewById(R.id.aioTitle);
title.setSelected(true);
pageJumperWrapper = findViewById(R.id.aioPageJumperWrapper);
firstPage = (Button) findViewById(R.id.aioFirstPage);
firstPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
session.get(pageJumperDesc, firstPageUrl, null);
}
});
prevPage = (Button) findViewById(R.id.aioPreviousPage);
prevPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
session.get(pageJumperDesc, prevPageUrl, null);
}
});
nextPage = (Button) findViewById(R.id.aioNextPage);
nextPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
session.get(pageJumperDesc, nextPageUrl, null);
}
});
lastPage = (Button) findViewById(R.id.aioLastPage);
lastPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
session.get(pageJumperDesc, lastPageUrl, null);
}
});
pageLabel = (TextView) findViewById(R.id.aioPageLabel);
htBase = ((TextView) drawer.findViewById(R.id.dwrChangeAccHeader)).getTextSize();
btBase = ((TextView) drawer.findViewById(R.id.dwrChangeAcc)).getTextSize();
ttBase = title.getTextSize();
pjbBase = firstPage.getTextSize();
pjlBase = pageLabel.getTextSize();
postTitle.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
String escapedTitle = StringEscapeUtils.escapeHtml4(postTitle.getText().toString());
titleCounter.setText(escapedTitle.length() + "/80");
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
postBody.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
String escapedBody = StringEscapeUtils.escapeHtml4(postBody.getText().toString());
// GFAQs adds 13(!) characters onto bodies when they have a sig, apparently.
int length = escapedBody.length() + getSig().length() + 13;
bodyCounter.setText(length + "/4096");
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
postButton = (Button) findViewById(R.id.aioPostDo);
cancelButton = (Button) findViewById(R.id.aioPostCancel);
pollButton = (Button) findViewById(R.id.aioPollOptions);
pollSep = findViewById(R.id.aioPollSep);
postWrapper = (LinearLayout) findViewById(R.id.aioPostWrapper);
wtl("creating default sig");
defaultSig = "Posted with GameRaven *grver*";
wtl("getting css directory");
File cssDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/gameraven");
if (!cssDirectory.exists()) {
wtl("css directory does not exist, creating");
cssDirectory.mkdir();
}
wtl("starting db creation");
hlDB = new HighlightListDBHelper(this);
wtl("onCreate finishing");
}
@Override
protected void onNewIntent(Intent intent) {
if (intent.getData() != null && intent.getData().getPath() != null) {
String url = intent.getData().getPath();
NetDesc desc = Session.determineNetDesc(url);
if (desc != NetDesc.UNSPECIFIED)
session.get(desc, url, null);
else
Crouton.showText(this, "Page not recognized: " + url, croutonStyle);
}
}
private boolean firstResume = true;
private float htBase, btBase, ttBase, pjbBase, pjlBase;
@Override
protected void onResume() {
wtl("onResume fired");
super.onResume();
ptrLayout.setEnabled(settings.getBoolean("enablePTR", false));
float oldScale = textScale;
textScale = settings.getInt("textScale", 100) / 100f;
if (textScale != oldScale) {
int px = TypedValue.COMPLEX_UNIT_PX;
title.setTextSize(px, ttBase * getTextScale());
firstPage.setTextSize(px, pjbBase * getTextScale());
prevPage.setTextSize(px, pjbBase * getTextScale());
nextPage.setTextSize(px, pjbBase * getTextScale());
lastPage.setTextSize(px, pjbBase * getTextScale());
pageLabel.setTextSize(px, pjlBase * getTextScale());
float htSize = htBase * getTextScale();
float btSize = btBase * getTextScale();
((TextView) drawer.findViewById(R.id.dwrChangeAccHeader)).setTextSize(px, htSize);
((TextView) drawer.findViewById(R.id.dwrChangeAcc)).setTextSize(px, btSize);
((TextView) drawer.findViewById(R.id.dwrNavHeader)).setTextSize(px, htSize);
((TextView) drawer.findViewById(R.id.dwrBoardJumper)).setTextSize(px, btSize);
((TextView) drawer.findViewById(R.id.dwrAMPList)).setTextSize(px, btSize);
((TextView) drawer.findViewById(R.id.dwrTrackedTopics)).setTextSize(px, btSize);
((TextView) drawer.findViewById(R.id.dwrPMInbox)).setTextSize(px, btSize);
((TextView) drawer.findViewById(R.id.dwrFuncHeader)).setTextSize(px, htSize);
((TextView) drawer.findViewById(R.id.dwrCopyCurrURL)).setTextSize(px, btSize);
((TextView) drawer.findViewById(R.id.dwrHighlightList)).setTextSize(px, btSize);
((TextView) drawer.findViewById(R.id.dwrSettings)).setTextSize(px, btSize);
((TextView) drawer.findViewById(R.id.dwrExit)).setTextSize(px, btSize);
}
int oldColor = accentColor;
accentColor = settings.getInt("accentColor", (getResources().getColor(R.color.holo_blue)));
if (accentColor != oldColor || firstResume) {
float[] hsv = new float[3];
Color.colorToHSV(accentColor, hsv);
if (settings.getBoolean("useWhiteAccentText", false)) {
// color is probably dark
if (hsv[2] > 0)
hsv[2] *= 1.2f;
else
hsv[2] = 0.2f;
accentTextColor = Color.WHITE;
isAccentLight = false;
}
else {
// color is probably bright
hsv[2] *= 0.8f;
accentTextColor = Color.BLACK;
isAccentLight = true;
}
Drawable aBarDrawable;
if (usingLightTheme)
aBarDrawable = getResources().getDrawable(R.drawable.ab_transparent_dark_holo);
else
aBarDrawable = getResources().getDrawable(R.drawable.ab_transparent_light_holo);
aBarDrawable.setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP);
aBar.setBackgroundDrawable(aBarDrawable);
((DefaultHeaderTransformer) ptrLayout.getHeaderTransformer()).setProgressBarColor(accentColor);
findViewById(R.id.aioPJTopSep).setBackgroundColor(accentColor);
findViewById(R.id.aioFirstPrevSep).setBackgroundColor(accentColor);
findViewById(R.id.aioNextLastSep).setBackgroundColor(accentColor);
findViewById(R.id.aioSep).setBackgroundColor(accentColor);
findViewById(R.id.aioPostWrapperSep).setBackgroundColor(accentColor);
findViewById(R.id.aioPostTitleSep).setBackgroundColor(accentColor);
findViewById(R.id.aioPostBodySep).setBackgroundColor(accentColor);
findViewById(R.id.aioBoldSep).setBackgroundColor(accentColor);
findViewById(R.id.aioItalicSep).setBackgroundColor(accentColor);
findViewById(R.id.aioCodeSep).setBackgroundColor(accentColor);
findViewById(R.id.aioSpoilerSep).setBackgroundColor(accentColor);
findViewById(R.id.aioCiteSep).setBackgroundColor(accentColor);
findViewById(R.id.aioHTMLSep).setBackgroundColor(accentColor);
findViewById(R.id.aioPostButtonSep).setBackgroundColor(accentColor);
findViewById(R.id.aioPollSep).setBackgroundColor(accentColor);
findViewById(R.id.aioPostSep).setBackgroundColor(accentColor);
drawer.findViewById(R.id.dwrCAHSep).setBackgroundColor(accentColor);
drawer.findViewById(R.id.dwrNavSep).setBackgroundColor(accentColor);
drawer.findViewById(R.id.dwrFuncSep).setBackgroundColor(accentColor);
croutonStyle = new Style.Builder()
.setBackgroundColorValue(accentColor)
.setTextColorValue(accentTextColor)
.setConfiguration(croutonShort)
.build();
}
if (session != null) {
if (settings.getBoolean("reloadOnResume", false)) {
wtl("session exists, reload on resume is true, refreshing page");
isRoR = true;
session.refresh();
}
}
else {
String initUrl = null;
NetDesc initDesc = null;
if (firstResume) {
Uri uri = getIntent().getData();
if (uri != null && uri.getScheme() != null && uri.getHost() != null) {
if (uri.getScheme().equals("http") && uri.getHost().contains("gamefaqs.com")) {
initUrl = uri.getPath();
initDesc = Session.determineNetDesc(initUrl);
}
}
}
String defaultAccount = settings.getString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT);
if (accounts.containsKey(defaultAccount)) {
wtl("starting new session from onResume, logged in");
session = new Session(this, defaultAccount, accounts.getString(defaultAccount), initUrl, initDesc);
}
else {
wtl("starting new session from onResume, no login");
session = new Session(this, null, null, initUrl, initDesc);
}
}
title.setSelected(true);
if (!settings.contains("beenWelcomed")) {
settings.edit().putBoolean("beenWelcomed", true).apply();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Welcome!");
b.setMessage("Would you like to view the quick start help files? This dialog won't be shown again.");
b.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/InsanityOnABun/GameRaven/wiki")));
}
});
b.setNegativeButton("No", null);
b.create().show();
}
firstResume = false;
wtl("onResume finishing");
}
@Override
protected void onDestroy() {
Crouton.clearCroutonsForActivity(this);
super.onDestroy();
}
static void colorOverscroll(Context context, int brandColor) {
//glow
int glowDrawableId = context.getResources().getIdentifier("overscroll_glow", "drawable", "android");
Drawable androidGlow = context.getResources().getDrawable(glowDrawableId);
androidGlow.setColorFilter(brandColor, PorterDuff.Mode.SRC_IN);
//edge
int edgeDrawableId = context.getResources().getIdentifier("overscroll_edge", "drawable", "android");
Drawable androidEdge = context.getResources().getDrawable(edgeDrawableId);
androidEdge.setColorFilter(brandColor, PorterDuff.Mode.SRC_IN);
}
private boolean needToSetNavList = true;
public void disableNavList() {
drawer.findViewById(R.id.dwrNavWrapper).setVisibility(View.GONE);
needToSetNavList = true;
}
public void setNavList(boolean isLoggedIn) {
drawer.findViewById(R.id.dwrNavWrapper).setVisibility(View.VISIBLE);
if (isLoggedIn)
drawer.findViewById(R.id.dwrLoggedInNav).setVisibility(View.VISIBLE);
else
drawer.findViewById(R.id.dwrLoggedInNav).setVisibility(View.GONE);
}
@Override
public boolean onSearchRequested() {
if (searchIcon != null && searchIcon.isVisible())
searchIcon.expandActionView();
return false;
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
drawer.toggleMenu();
return true;
} else {
return super.onKeyUp(keyCode, event);
}
}
/** Adds menu items */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
searchIcon = menu.getItem(0);
topicListIcon = menu.getItem(1);
addFavIcon = menu.getItem(2);
remFavIcon = menu.getItem(3);
postIcon = menu.getItem(4);
refreshIcon = menu.getItem(5);
SearchView searchView = (SearchView) searchIcon.getActionView();
if (searchView != null) {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener()
{
public boolean onQueryTextChange(String newText)
{
// just do default
return false;
}
public boolean onQueryTextSubmit(String query)
{
HashMap<String, String> data = new HashMap<String, String>();
if (session.getLastDesc() == NetDesc.BOARD) {
wtl("searching board for query");
data.put("search", query);
session.get(NetDesc.BOARD, session.getLastPathWithoutData(), data);
}
else if (session.getLastDesc() == NetDesc.BOARD_JUMPER || session.getLastDesc() == NetDesc.GAME_SEARCH) {
wtl("searching for games");
data.put("game", query);
session.get(NetDesc.GAME_SEARCH, "/search/index.html", data);
}
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
}
else {
// throw new NullPointerException("searchView is null");
}
return true;
}
/** fires when a menu option is selected */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
wtl("toggling drawer");
drawer.toggleMenu();
return true;
case R.id.search:
onSearchRequested();
// MenuItemCompat.expandActionView(searchIcon);
return true;
case R.id.addFav:
AlertDialog.Builder afb = new AlertDialog.Builder(this);
afb.setNegativeButton("No", null);
switch (fMode) {
case ON_BOARD:
afb.setTitle("Add Board to Favorites?");
afb.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String addFavUrl = session.getLastPath();
if (addFavUrl.contains("remfav"))
addFavUrl = addFavUrl.replace("remfav", "addfav");
else if (addFavUrl.indexOf('?') != -1)
addFavUrl += "&action=addfav";
else
addFavUrl += "?action=addfav";
session.get(NetDesc.BOARD, addFavUrl, null);
}
});
break;
case ON_TOPIC:
afb.setTitle("Track Topic?");
afb.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String addFavUrl = session.getLastPath();
int x = addFavUrl.indexOf('#');
if (x != -1)
addFavUrl = addFavUrl.substring(0, x);
if (addFavUrl.contains("stoptrack"))
addFavUrl = addFavUrl.replace("stoptrack", "tracktopic");
else if (addFavUrl.indexOf('?') != -1)
addFavUrl += "&action=tracktopic";
else
addFavUrl += "?action=tracktopic";
session.get(NetDesc.TOPIC, addFavUrl, null);
}
});
break;
}
afb.create().show();
return true;
case R.id.remFav:
AlertDialog.Builder rfb = new AlertDialog.Builder(this);
rfb.setNegativeButton("No", null);
switch (fMode) {
case ON_BOARD:
rfb.setTitle("Remove Board from Favorites?");
rfb.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String remFavUrl = session.getLastPath();
if (remFavUrl.contains("addfav"))
remFavUrl = remFavUrl.replace("addfav", "remfav");
else if (remFavUrl.indexOf('?') != -1)
remFavUrl += "&action=remfav";
else
remFavUrl += "?action=remfav";
session.get(NetDesc.BOARD, remFavUrl, null);
}
});
break;
case ON_TOPIC:
rfb.setTitle("Stop Tracking Topic?");
rfb.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String remFavUrl = session.getLastPath();
int x = remFavUrl.indexOf('#');
if (x != -1)
remFavUrl = remFavUrl.substring(0, x);
if (remFavUrl.contains("tracktopic"))
remFavUrl = remFavUrl.replace("tracktopic", "stoptrack");
else if (remFavUrl.indexOf('?') != -1)
remFavUrl += "&action=stoptrack";
else
remFavUrl += "?action=stoptrack";
session.get(NetDesc.TOPIC, remFavUrl, null);
}
});
break;
}
rfb.create().show();
return true;
case R.id.topiclist:
session.get(NetDesc.BOARD, tlUrl, null);
return true;
case R.id.post:
if (pMode == PostMode.ON_BOARD)
postSetup(false);
else if (pMode == PostMode.ON_TOPIC)
postSetup(true);
else if (pMode == PostMode.NEW_PM)
pmSetup(EMPTY_STRING, EMPTY_STRING, EMPTY_STRING);
return true;
case R.id.refresh:
if (session.getLastPath() == null) {
if (Session.isLoggedIn()) {
wtl("starting new session from case R.id.refresh, logged in");
session = new Session(this, Session.getUser(), accounts.getString(Session.getUser()));
}
else {
wtl("starting new session from R.id.refresh, no login");
session = new Session(this);
}
}
else
session.refresh();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setMenuItemVisible(MenuItem item, boolean visible) {
if (item != null)
item.setVisible(visible);
}
public void setLoginName(String name) {
((TextView) findViewById(R.id.dwrChangeAcc)).setText(name + " (Click to Change)");
}
public void postError(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg);
builder.setTitle("There was a problem with your post...");
builder.setPositiveButton("Ok", null);
builder.create().show();
uiCleanup();
}
public void genError(String errorTitle, String errorMsg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(errorMsg);
builder.setTitle(errorTitle);
builder.setPositiveButton("Ok", null);
builder.create().show();
uiCleanup();
}
public void noNetworkConnection() {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("No Network Connection");
b.setMessage("Couldn't establish network connection. Check your network settings, then try again.");
b.setNegativeButton("Dismiss", null);
b.show();
}
public void timeoutCleanup(NetDesc desc) {
String msg = "timeout msg unset";
String title = "timeout title unset";
String posButtonText = "pos button text not set";
boolean retrySub = false;
switch (desc) {
case LOGIN_S1:
case LOGIN_S2:
title = "Login Timeout";
msg = "Login timed out, press retry to try again.";
posButtonText = "Retry";
break;
case POSTMSG_S1:
case POSTMSG_S2:
case POSTMSG_S3:
case POSTTPC_S1:
case POSTTPC_S2:
case POSTTPC_S3:
case QPOSTMSG_S1:
case QPOSTMSG_S3:
case QPOSTTPC_S1:
case QPOSTTPC_S3:
title = "Post Timeout";
msg = "Post timed out. Press refresh to check if your post made it through.";
posButtonText = "Refresh";
break;
default:
retrySub = true;
title = "Timeout";
msg = "Connection timed out, press retry to try again.";
posButtonText = "Retry";
break;
}
final boolean retry = retrySub;
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(title);
b.setMessage(msg);
b.setPositiveButton(posButtonText, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (retry)
session.get(session.getLastAttemptedDesc(), session.getLastAttemptedPath(), null);
else
refreshClicked(new View(AllInOneV2.this));
}
});
b.setNegativeButton("Dismiss", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// switch ((session.getLastDoc() == null) ? 1 : 0) {
// case 0:
// processContent(session.getLastDesc(), session.getLastDoc(), session.getLastPath());
// case 1:
postExecuteCleanup(session.getLastDesc());
// break;
// }
}
});
b.create().show();
}
private void uiCleanup() {
ptrLayout.setRefreshing(false);
setMenuItemVisible(refreshIcon, true);
if (postWrapper.getVisibility() == View.VISIBLE) {
postButton.setEnabled(true);
cancelButton.setEnabled(true);
pollButton.setEnabled(true);
setMenuItemVisible(postIcon, true);
}
}
public void preExecuteSetup(NetDesc desc) {
wtl("GRAIO dPreES fired --NEL, desc: " + desc.name());
ptrLayout.setRefreshing(true);
setMenuItemVisible(refreshIcon, false);
setMenuItemVisible(searchIcon, false);
setMenuItemVisible(postIcon, false);
setMenuItemVisible(addFavIcon, false);
setMenuItemVisible(remFavIcon, false);
setMenuItemVisible(topicListIcon, false);
if (desc != NetDesc.POSTMSG_S1 && desc != NetDesc.POSTTPC_S1 &&
desc != NetDesc.QPOSTMSG_S1 && desc != NetDesc.QPOSTTPC_S1 &&
desc != NetDesc.QEDIT_MSG)
postCleanup();
}
private boolean isRoR = false;
private void postCleanup() {
if (!isRoR && postWrapper.getVisibility() == View.VISIBLE) {
pageJumperWrapper.setVisibility(View.VISIBLE);
wtl("postCleanup fired --NEL");
postWrapper.setVisibility(View.GONE);
pollButton.setVisibility(View.GONE);
pollSep.setVisibility(View.GONE);
postBody.setText(null);
postTitle.setText(null);
clearPoll();
messageIDForEditing = null;
postPostUrl = null;
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
hideSoftInputFromWindow(postBody.getWindowToken(), 0);
}
}
public void setAMPLinkVisible(boolean visible) {
if (visible)
findViewById(R.id.dwrAMPWrapper).setVisibility(View.VISIBLE);
else
findViewById(R.id.dwrAMPWrapper).setVisibility(View.GONE);
}
/********************************************
* START HNR
* ******************************************/
ArrayList<BaseRowData> adapterRows = new ArrayList<BaseRowData>();
ViewAdapter viewAdapter = new ViewAdapter(this, adapterRows);
boolean adapterSet = false;
WebView web;
String adBaseUrl;
StringBuilder adBuilder = new StringBuilder();
Runnable loadAds = new Runnable() {
@Override
public void run() {web.loadDataWithBaseURL(adBaseUrl, adBuilder.toString(), null, "iso-8859-1", null);}
};
@SuppressLint("SetJavaScriptEnabled")
public void processContent(NetDesc desc, Document doc, String resUrl) {
wtl("GRAIO hNR fired, desc: " + desc.name());
ptrLayout.setEnabled(false);
setMenuItemVisible(searchIcon, false);
if (searchIcon != null)
searchIcon.collapseActionView();
setMenuItemVisible(postIcon, false);
setMenuItemVisible(addFavIcon, false);
setMenuItemVisible(remFavIcon, false);
setMenuItemVisible(topicListIcon, false);
adapterRows.clear();
boolean isDefaultAcc;
if (Session.getUser() != null &&
Session.getUser().equals(settings.getString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT)))
isDefaultAcc = true;
else
isDefaultAcc = false;
wtl("setting board, topic, message id to null");
boardID = null;
topicID = null;
messageIDForEditing = null;
Element tbody;
Element pj = null;
String headerTitle;
String firstPage = null;
String prevPage = null;
String currPage = "1";
String pageCount = "1";
String nextPage = null;
String lastPage = null;
String bgcolor;
if (usingLightTheme)
bgcolor = "#ffffff";
else
bgcolor = "#000000";
adBuilder.setLength(0);
adBuilder.append("<html>");
adBuilder.append(doc.head().outerHtml());
adBuilder.append("<body bgcolor=\"" + bgcolor + "\">");
for (Element e : doc.getElementsByClass("ad")) {
adBuilder.append(e.outerHtml());
e.remove();
}
for (Element e : doc.getElementsByTag("script")) {
adBuilder.append(e.outerHtml());
}
adBuilder.append("</body></html>");
adBaseUrl = resUrl;
if (web == null)
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(AllInOneV2.getSettingsPref().getBoolean("enableJS", true));
switch (desc) {
case BOARD_JUMPER:
case LOGIN_S2:
updateHeaderNoJumper("Board Jumper", NetDesc.BOARD_JUMPER);
adapterRows.add(new HeaderRowData("Announcements"));
setMenuItemVisible(searchIcon, true);
processBoards(doc, true);
break;
case BOARD_LIST:
updateHeaderNoJumper(doc.getElementsByTag("th").get(4).text(), NetDesc.BOARD_LIST);
processBoards(doc, true);
break;
case PM_INBOX:
tbody = doc.getElementsByTag("tbody").first();
headerTitle = Session.getUser() + "'s PM Inbox";
if (tbody != null) {
pj = doc.select("ul.paginate").first();
if (pj != null) {
String pjText = pj.child(0).text();
if (pjText.contains("Previous"))
pjText = pj.child(1).text();
//Page 1 of 5
int currPageStart = 5;
int ofIndex = pjText.indexOf(" of ");
currPage = pjText.substring(currPageStart, ofIndex);
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4, pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "/pm/";
prevPage = "/pm/?page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = "/pm/?page=" + currPageNum;
lastPage = "/pm/?page=" + (pageCountNum - 1);
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.PM_INBOX);
if (isDefaultAcc)
NotifierService.dismissPMNotif(this);
for (Element row : tbody.getElementsByTag("tr")) {
Elements cells = row.children();
// [icon] [sender] [subject] [time] [check]
boolean isOld = true;
if (cells.get(0).children().first().hasClass("icon-circle"))
isOld = false;
String sender = cells.get(1).text();
Element subjectLinkElem = cells.get(2).children().first();
String subject = subjectLinkElem.text();
String link = subjectLinkElem.attr("href");
String time = cells.get(3).text();
adapterRows.add(new PMRowData(subject, sender, time, link, isOld));
}
}
else {
updateHeaderNoJumper(headerTitle, NetDesc.PM_INBOX);
adapterRows.add(new HeaderRowData("You have no private messages at this time."));
}
setMenuItemVisible(postIcon, true);
pMode = PostMode.NEW_PM;
break;
case PM_DETAIL:
headerTitle = doc.select("h2.title").first().text();
String pmTitle = headerTitle;
if (!pmTitle.startsWith("Re: "))
pmTitle = "Re: " + pmTitle;
String pmMessage = doc.select("div.body").first().outerHtml();
Element foot = doc.select("div.foot").first();
foot.child(1).remove();
String pmFoot = foot.outerHtml();
//Sent by: P4wn4g3 on 6/1/2013 2:15:55 PM
String footText = foot.text();
String sender = footText.substring(9, footText.indexOf(" on "));
- updateHeaderNoJumper(pmTitle, NetDesc.PM_DETAIL);
+ updateHeaderNoJumper(headerTitle, NetDesc.PM_DETAIL);
adapterRows.add(new PMDetailRowData(sender, pmTitle, pmMessage + pmFoot));
break;
case AMP_LIST:
wtl("GRAIO hNR determined this is an amp response");
tbody = doc.getElementsByTag("tbody").first();
headerTitle = Session.getUser() + "'s Active Messages";
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")
&& !pj.hasClass("tsort")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page 2 of 3
int currPageStart = 5;
int ofIndex = pjText.indexOf(" of ");
currPage = pjText.substring(currPageStart, ofIndex);
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
String amp = buildAMPLink();
if (currPageNum > 1) {
firstPage = amp;
prevPage = amp + "&page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = amp + "&page=" + currPageNum;
lastPage = amp + "&page=" + (pageCountNum - 1);
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.AMP_LIST);
if (isDefaultAcc)
NotifierService.dismissAMPNotif(this);
if (!tbody.children().isEmpty()) {
if (settings.getBoolean("notifsEnable", false) && isDefaultAcc) {
Element lPost = doc.select("td.lastpost").first();
if (lPost != null) {
try {
String lTime = lPost.text();
Date newDate;
lTime = lTime.replace("Last:", EMPTY_STRING);
if (lTime.contains("AM") || lTime.contains("PM"))
newDate = new SimpleDateFormat("MM'/'dd hh':'mmaa", Locale.US).parse(lTime);
else
newDate = new SimpleDateFormat("MM'/'dd'/'yyyy", Locale.US).parse(lTime);
long newTime = newDate.getTime();
long oldTime = settings.getLong("notifsLastPost", 0);
if (newTime > oldTime) {
wtl("time is newer");
settings.edit().putLong("notifsLastPost", newTime).apply();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
for (Element row : tbody.children()) {
// [board] [title] [msg] [last post] [your last post]
Elements cells = row.children();
String board = cells.get(0).text();
Element titleLinkElem = cells.get(1).child(0);
String title = titleLinkElem.text();
String link = titleLinkElem.attr("href");
String mCount = cells.get(2).textNodes().get(0).text().trim();
Element lPostLinkElem = cells.get(3).child(1);
String lPost = lPostLinkElem.text();
String lPostLink = lPostLinkElem.attr("href");
String ylpLink = cells.get(4).child(1).attr("href");
adapterRows.add(new AMPRowData(title, board, lPost, mCount, link,
lPostLink, ylpLink));
}
}
else {
adapterRows.add(new HeaderRowData("You have no active messages at this time."));
}
wtl("amp response block finished");
break;
case TRACKED_TOPICS:
headerTitle = Session.getUser() + "'s Tracked Topics";
updateHeaderNoJumper(headerTitle, desc);
if (isDefaultAcc)
NotifierService.dismissTTNotif(this);
tbody = doc.getElementsByTag("tbody").first();
if (tbody != null) {
for (Element row : tbody.children()) {
// [remove] [title] [board name] [msgs] [last [pst]
Elements cells = row.children();
String removeLink = cells.get(0).child(0)
.attr("href");
String topicLink = cells.get(1).child(0)
.attr("href");
String topicText = cells.get(1).text();
String board = cells.get(2).text();
String msgs = cells.get(3).text();
String lPostLink = cells.get(4).child(0)
.attr("href");
String lPostText = cells.get(4).text();
adapterRows.add(new TrackedTopicRowData(board, topicText, lPostText,
msgs, topicLink, removeLink, lPostLink));
}
}
else {
adapterRows.add(new HeaderRowData("You have no tracked topics at this time."));
}
break;
case BOARD:
wtl("GRAIO hNR determined this is a board response");
wtl("setting board id");
boardID = parseBoardID(resUrl);
boolean isSplitList = false;
if (doc.getElementsByTag("th").first() != null) {
if (doc.getElementsByTag("th").first().text().equals("Board Title")) {
wtl("is actually a split board list");
updateHeaderNoJumper(doc.select("h1.page-title").first().text(), NetDesc.BOARD);
processBoards(doc, false);
isSplitList = true;
}
}
if (!isSplitList) {
String url = resUrl;
String searchQuery = EMPTY_STRING;
String searchPJAddition = EMPTY_STRING;
if (url.contains("search=")) {
wtl("board search url: " + url);
searchQuery = url.substring(url.indexOf("search=") + 7);
int i = searchQuery.indexOf('&');
if (i != -1)
searchQuery.replace(searchQuery.substring(i), EMPTY_STRING);
searchPJAddition = "&search=" + searchQuery;
searchQuery = URLDecoder.decode(searchQuery);
}
Element headerElem = doc.getElementsByClass("page-title").first();
if (headerElem != null)
headerTitle = headerElem.text();
else
headerTitle = "GFAQs Cache Error, Board Title Not Found";
if (searchQuery.length() > 0)
headerTitle += " (search: " + searchQuery + ")";
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page [dropdown] of 3
// Page 1 of 3
int ofIndex = pjText.indexOf(" of ");
int currPageStart = 5;
if (pj.getElementsByTag("select").isEmpty())
currPage = pjText.substring(currPageStart,
ofIndex);
else
currPage = pj
.select("option[selected=selected]")
.first().text();
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "boards/" + boardID + "?page=0"
+ searchPJAddition;
prevPage = "boards/" + boardID + "?page="
+ (currPageNum - 2)
+ searchPJAddition;
}
if (currPageNum != pageCountNum) {
nextPage = "boards/" + boardID + "?page="
+ currPageNum + searchPJAddition;
lastPage = "boards/" + boardID + "?page="
+ (pageCountNum - 1)
+ searchPJAddition;
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.BOARD);
setMenuItemVisible(searchIcon, true);
if (Session.isLoggedIn()) {
String favtext = doc.getElementsByClass("user").first().text().toLowerCase(Locale.US);
if (favtext.contains("add to favorites")) {
setMenuItemVisible(addFavIcon, true);
fMode = FavMode.ON_BOARD;
}
else if (favtext.contains("remove favorite")) {
setMenuItemVisible(remFavIcon, true);
fMode = FavMode.ON_BOARD;
}
updatePostingRights(doc, false);
}
Element splitList = doc.select("p:contains(this is a split board)").first();
if (splitList != null) {
String splitListLink = splitList.child(0).attr("href");
adapterRows.add(new BoardRowData("This is a Split Board.", "Click here to return to the Split List.",
null, null, null, splitListLink, BoardType.SPLIT));
}
Element table = doc.select("table.board").first();
if (table != null) {
table.getElementsByTag("col").get(2).remove();
table.getElementsByTag("th").get(2).remove();
table.getElementsByTag("col").get(0).remove();
table.getElementsByTag("th").get(0).remove();
wtl("board row parsing start");
boolean skipFirst = true;
Set<String> hlUsers = hlDB.getHighlightedUsers().keySet();
for (Element row : table.getElementsByTag("tr")) {
if (!skipFirst) {
Elements cells = row.getElementsByTag("td");
// cells = [image] [title] [author] [post count] [last post]
String tImg = cells.get(0).child(0).className();
Element titleLinkElem = cells.get(1).child(0);
String title = titleLinkElem.text();
String tUrl = titleLinkElem.attr("href");
String tc = cells.get(2).text();
Element lPostLinkElem = cells.get(4).child(0);
String lastPost = lPostLinkElem.text();
String lpUrl = lPostLinkElem.attr("href");
String mCount = cells.get(3).text();
TopicType type = TopicType.NORMAL;
if (tImg.contains("poll"))
type = TopicType.POLL;
else if (tImg.contains("sticky"))
type = TopicType.PINNED;
else if (tImg.contains("closed"))
type = TopicType.LOCKED;
else if (tImg.contains("archived"))
type = TopicType.ARCHIVED;
wtl(tImg + ", " + type.name());
ReadStatus status = ReadStatus.UNREAD;
if (tImg.endsWith("_read"))
status = ReadStatus.READ;
else if (tImg.endsWith("_unread"))
status = ReadStatus.NEW_POST;
int hlColor = 0;
if (hlUsers.contains(tc.toLowerCase(Locale.US))) {
HighlightedUser hUser = hlDB.getHighlightedUsers().get(tc.toLowerCase(Locale.US));
hlColor = hUser.getColor();
tc += " (" + hUser.getLabel() + ")";
}
adapterRows.add(new TopicRowData(title, tc, lastPost, mCount, tUrl,
lpUrl, type, status, hlColor));
}
else
skipFirst = false;
}
wtl("board row parsing end");
}
else {
adapterRows.add(new HeaderRowData("There are no topics at this time."));
}
}
wtl("board response block finished");
break;
case TOPIC:
boardID = parseBoardID(resUrl);
topicID = parseTopicID(resUrl);
tlUrl = "boards/" + boardID;
wtl(tlUrl);
setMenuItemVisible(topicListIcon, true);
Element headerElem = doc.getElementsByClass("title").first();
if (headerElem != null)
headerTitle = headerElem.text();
else
headerTitle = "GFAQs Cache Error, Title Not Found";
if (headerTitle.equals("Log In to GameFAQs")) {
headerElem = doc.getElementsByClass("title").get(1);
if (headerElem != null)
headerTitle = headerElem.text();
}
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page [dropdown] of 3
// Page 1 of 3
int ofIndex = pjText.indexOf(" of ");
int currPageStart = 5;
if (pj.getElementsByTag("select").isEmpty())
currPage = pjText.substring(currPageStart,
ofIndex);
else
currPage = pj
.select("option[selected=selected]")
.first().text();
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "boards/" + boardID + "/" + topicID;
prevPage = "boards/" + boardID + "/" + topicID
+ "?page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = "boards/" + boardID + "/" + topicID
+ "?page=" + currPageNum;
lastPage = "boards/" + boardID + "/" + topicID
+ "?page=" + (pageCountNum - 1);
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.TOPIC);
if (Session.isLoggedIn()) {
String favtext = doc.getElementsByClass("user").first().text().toLowerCase(Locale.US);
if (favtext.contains("track topic")) {
setMenuItemVisible(addFavIcon, true);
fMode = FavMode.ON_TOPIC;
}
else if (favtext.contains("stop tracking")) {
setMenuItemVisible(remFavIcon, true);
fMode = FavMode.ON_TOPIC;
}
updatePostingRights(doc, true);
}
String goToThisPost = null;
if (goToUrlDefinedPost) {
String url = resUrl;
goToThisPost = url.substring(url.indexOf('#') + 1);
}
Elements rows = doc.select("table.board").first().getElementsByTag("tr");
int rowCount = rows.size();
int msgIndex = 0;
Set<String> hlUsers = hlDB.getHighlightedUsers().keySet();
for (int x = 0; x < rowCount; x++) {
Element row = rows.get(x);
String user = null;
String postNum = null;
String mID = null;
String userTitles = EMPTY_STRING;
String postTimeText = EMPTY_STRING;
String postTime = EMPTY_STRING;
Element msgBody = null;
if (row.hasClass("left")) {
// message poster display set to left of message
Elements authorData = row.getElementsByClass("author_data");
user = row.getElementsByTag("b").first().text();
postNum = row.getElementsByTag("a").first().attr("name");
for (int i = 1; i < authorData.size(); i++) {
Element e = authorData.get(i);
String t = e.text();
if (t.startsWith("("))
userTitles += " " + t;
else if (e.hasClass("tag"))
userTitles += " (tagged as " + t + ")";
else if (t.startsWith("Posted"))
postTime = t;
else if (t.equals("message detail"))
mID = parseMessageID(e.child(0).attr("href"));
}
msgBody = row.child(1).child(0);
}
else {
// message poster display set to above message
List<TextNode> textNodes = row.child(0).child(0).textNodes();
Elements elements = row.child(0).child(0).children();
int textNodesSize = textNodes.size();
for (int y = 0; y < textNodesSize; y++) {
String text = textNodes.get(y).text();
if (text.startsWith("Posted"))
postTimeText = text;
else if (text.contains("(")) {
userTitles += " " + text.substring(text.indexOf('('), text.lastIndexOf(')') + 1);
}
}
user = elements.get(0).text();
int anchorCount = row.getElementsByTag("a").size();
postNum = row.getElementsByTag("a").get((anchorCount > 1 ? 1 : 0)).attr("name");
int elementsSize = elements.size();
for (int y = 0; y < elementsSize; y++) {
Element e = elements.get(y);
if (e.hasClass("tag"))
userTitles += " (tagged as " + e.text() + ")";
else if (e.text().equals("message detail"))
mID = parseMessageID(e.attr("href"));
}
//Posted 11/15/2012 11:20:27 AM | (edited) [if archived]
if (postTimeText.contains("(edited)"))
userTitles += " (edited)";
int endPoint = postTimeText.indexOf('|') - 1;
if (endPoint < 0)
endPoint = postTimeText.length();
postTime = postTimeText.substring(0, endPoint);
x++;
msgBody = rows.get(x).child(0).child(0);
}
int hlColor = 0;
if (hlUsers.contains(user.toLowerCase(Locale.US))) {
HighlightedUser hUser = hlDB
.getHighlightedUsers().get(
user.toLowerCase(Locale.US));
hlColor = hUser.getColor();
userTitles += " (" + hUser.getLabel() + ")";
}
if (goToUrlDefinedPost) {
if (postNum.equals(goToThisPost))
goToThisIndex = msgIndex;
}
wtl("creating messagerowdata object");
adapterRows.add(new MessageRowData(user, userTitles, postNum,
postTime, msgBody, boardID, topicID, mID, hlColor));
msgIndex++;
}
break;
case MESSAGE_DETAIL:
updateHeaderNoJumper("Message Detail", NetDesc.MESSAGE_DETAIL);
boardID = parseBoardID(resUrl);
topicID = parseTopicID(resUrl);
Elements msgDRows = doc.getElementsByTag("tr");
String user = msgDRows.first().child(0).child(0).text();
adapterRows.add(new HeaderRowData("Current Version"));
Element currRow, body;
MessageRowData msg;
String postTime;
String mID = parseMessageID(resUrl);
for (int x = 0; x < msgDRows.size(); x++) {
if (x == 1)
adapterRows.add(new HeaderRowData("Previous Version(s)"));
else {
currRow = msgDRows.get(x);
if (currRow.child(0).textNodes().size() > 1)
postTime = currRow.child(0).textNodes().get(1).text();
else
postTime = currRow.child(0).textNodes().get(0).text();
body = currRow.child(1);
msg = new MessageRowData(user, null, null, postTime, body, boardID, topicID, mID, 0);
msg.disableTopClick();
adapterRows.add(msg);
}
}
break;
case USER_DETAIL:
wtl("starting user detail processing");
tbody = doc.select("table.board").first().getElementsByTag("tbody").first();
Log.d("udtb", tbody.outerHtml());
String name = null;
String ID = null;
String level = null;
String creation = null;
String lVisit = null;
String sig = null;
String karma = null;
String AMP = null;
for (Element row : tbody.children()) {
String label = row.child(0).text().toLowerCase(Locale.US);
wtl("user detail row label: " + label);
if (label.equals("user name"))
name = row.child(1).text();
else if (label.equals("user id"))
ID = row.child(1).text();
else if (label.equals("board user level")) {
level = row.child(1).html();
wtl("set level: " + level);
}
else if (label.equals("account created"))
creation = row.child(1).text();
else if (label.equals("last visit"))
lVisit = row.child(1).text();
else if (label.equals("signature"))
sig = row.child(1).html();
else if (label.equals("karma"))
karma = row.child(1).text();
else if (label.equals("active messages posted"))
AMP = row.child(1).text();
}
updateHeaderNoJumper(name + "'s Details", NetDesc.USER_DETAIL);
adapterRows.add(new UserDetailRowData(name, ID, level, creation, lVisit, sig, karma, AMP));
break;
case GAME_SEARCH:
wtl("GRAIO hNR determined this is a game search response");
String url = resUrl;
wtl("game search url: " + url);
String searchQuery = url.substring(url.indexOf("game=") + 5);
int i = searchQuery.indexOf("&");
if (i != -1)
searchQuery = searchQuery.replace(searchQuery.substring(i), EMPTY_STRING);
int pageIndex = url.indexOf("page=");
if (pageIndex != -1) {
currPage = url.substring(pageIndex + 5);
i = currPage.indexOf("&");
if (i != -1)
currPage = currPage.replace(currPage.substring(i), EMPTY_STRING);
}
else {
currPage = "0";
}
int currPageNum = Integer.parseInt(currPage);
Element nextPageElem = null;
if (!doc.getElementsContainingOwnText("Next Page").isEmpty())
nextPageElem = doc.getElementsContainingOwnText("Next Page").first();
pageCount = "???";
if (nextPageElem != null) {
nextPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum + 1);
}
if (currPageNum > 0) {
prevPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum - 1);
firstPage = "/search/index.html?game=" + searchQuery + "&page=0";
}
headerTitle = "Searching games: " + URLDecoder.decode(searchQuery) + EMPTY_STRING;
updateHeader(headerTitle, firstPage, prevPage, Integer.toString(currPageNum + 1),
pageCount, nextPage, lastPage, NetDesc.GAME_SEARCH);
setMenuItemVisible(searchIcon, true);
Elements gameSearchTables = doc.select("table.results");
int tCount = gameSearchTables.size();
int tCounter = 0;
if (!gameSearchTables.isEmpty()) {
for (Element table : gameSearchTables) {
tCounter++;
if (tCounter < tCount)
adapterRows.add(new HeaderRowData("Best Matches"));
else
adapterRows.add(new HeaderRowData("Good Matches"));
String prevPlatform = EMPTY_STRING;
wtl("board row parsing start");
for (Element row : table.getElementsByTag("tr")) {
Elements cells = row.getElementsByTag("td");
// cells = [platform] [title] [faqs] [codes] [saves] [revs] [mygames] [q&a] [pics] [vids] [board]
String platform = cells.get(0).text();
String bName = cells.get(1).text();
String bUrl = cells.get(9).child(0).attr("href");
if (platform.codePointAt(0) == ('\u00A0')) {
platform = prevPlatform;
}
else {
prevPlatform = platform;
}
adapterRows.add(new GameSearchRowData(bName, platform, bUrl));
}
wtl("board row parsing end");
}
}
else {
adapterRows.add(new HeaderRowData("No results."));
}
wtl("game search response block finished");
break;
default:
wtl("GRAIO hNR determined response type is unhandled");
title.setText("Page unhandled - " + resUrl);
break;
}
try {
((ViewGroup) web.getParent()).removeView(web);
} catch (Exception e1) {}
adapterRows.add(new AdRowData(web));
contentList.post(loadAds);
Element pmInboxLink = doc.select("div.masthead_user").first().select("a[href=/pm/]").first();
String pmButtonLabel = getResources().getString(R.string.pm_inbox);
if (pmInboxLink != null) {
String text = pmInboxLink.text();
int count = 0;
if (text.contains("(")) {
count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')')));
int prevCount = settings.getInt("unreadPMCount", 0);
if (count > prevCount) {
if (count > 1)
Crouton.showText(this, "You have " + count + " unread PMs", croutonStyle);
else
Crouton.showText(this, "You have 1 unread PM", croutonStyle);
}
pmButtonLabel += " (" + count + ")";
}
settings.edit().putInt("unreadPMCount", count).apply();
if (isDefaultAcc)
settings.edit().putInt("notifsUnreadPMCount", count).apply();
}
((Button) findViewById(R.id.dwrPMInbox)).setText(pmButtonLabel);
Element trackedLink = doc.select("div.masthead_user").first().select("a[href=/boards/tracked]").first();
String ttButtonLabel = getResources().getString(R.string.tracked_topics);
if (trackedLink != null) {
String text = trackedLink.text();
int count = 0;
if (text.contains("(")) {
count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')')));
int prevCount = settings.getInt("unreadTTCount", 0);
if (count > prevCount) {
if (count > 1)
Crouton.showText(this, "You have " + count + " unread tracked topics", croutonStyle);
else
Crouton.showText(this, "You have 1 unread tracked topic", croutonStyle);
}
ttButtonLabel += " (" + count + ")";
}
settings.edit().putInt("unreadTTCount", count).apply();
if (isDefaultAcc)
settings.edit().putInt("notifsUnreadTTCount", count).apply();
}
((Button) findViewById(R.id.dwrTrackedTopics)).setText(ttButtonLabel);
ptrLayout.setEnabled(settings.getBoolean("enablePTR", false));
if (!adapterSet) {
contentList.setAdapter(viewAdapter);
adapterSet = true;
}
else
viewAdapter.notifyDataSetChanged();
if (consumeGoToUrlDefinedPost() && !Session.applySavedScroll) {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelection(goToThisIndex);
}
});
}
else if (Session.applySavedScroll) {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelectionFromTop(Session.savedScrollVal[0], Session.savedScrollVal[1]);
Session.applySavedScroll = false;
}
});
}
else {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelectionAfterHeaderView();
}
});
}
if (ptrLayout.isRefreshing())
ptrLayout.setRefreshComplete();
wtl("GRAIO hNR finishing");
}
/***********************************
* END HNR
* *********************************/
private void processBoards(Document pRes, boolean includeBoardCategories) {
Elements homeTables = pRes.select("table.board");
boolean skippedFirst = false;
for (Element row : homeTables.first().getElementsByTag("tr")) {
if (skippedFirst) {
if (row.hasClass("head")) {
adapterRows.add(new HeaderRowData(row.text()));
}
else {
// [title + link] [topics] [msgs] [last post]
Elements cells = row.children();
Element titleCell = cells.get(0);
String lvlReq = EMPTY_STRING;
String title = EMPTY_STRING;
if (!titleCell.textNodes().isEmpty())
lvlReq = titleCell.textNodes().get(0).toString();
title = titleCell.child(0).text() + lvlReq;
String boardDesc = null;
if (titleCell.children().size() > 2)
boardDesc = titleCell.child(2).text();
String link = titleCell.children().first().attr("href");
if (link.isEmpty())
link = null;
String tCount = null;
String mCount = null;
String lPost = null;
BoardType bvt;
if (cells.size() > 3) {
tCount = cells.get(1).text();
mCount = cells.get(2).text();
lPost = cells.get(3).text();
bvt = BoardType.NORMAL;
}
else
bvt = BoardType.SPLIT;
adapterRows.add(new BoardRowData(title, boardDesc, lPost, tCount, mCount, link, bvt));
}
}
else {
skippedFirst = true;
}
}
if (includeBoardCategories && homeTables.size() > 1) {
int rowX = 0;
for (Element row : homeTables.get(1).getElementsByTag("tr")) {
rowX++;
if (rowX > 2) {
Element cell = row.child(0);
String title = cell.child(0).text();
String link = cell.child(0).attr("href");
String boardDesc = cell.child(2).text();
adapterRows.add(new BoardRowData(title, boardDesc, null, null, null, link, BoardType.LIST));
} else {
if (rowX == 1) {
adapterRows.add(new HeaderRowData("Message Board Categories"));
}
}
}
}
}
private void updatePostingRights(Document pRes, boolean onTopic) {
if (onTopic) {
if (pRes.getElementsByClass("user").first().text().contains("Post New Message")) {
setMenuItemVisible(postIcon, true);
pMode = PostMode.ON_TOPIC;
}
}
else {
if (pRes.getElementsByClass("user").first().text().contains("New Topic")) {
setMenuItemVisible(postIcon, true);
pMode = PostMode.ON_BOARD;
}
}
}
public void postExecuteCleanup(NetDesc desc) {
wtl("GRAIO dPostEC --NEL, desc: " + (desc == null ? "null" : desc.name()));
if (needToSetNavList) {
setNavList(Session.isLoggedIn());
needToSetNavList = false;
}
ptrLayout.setRefreshing(false);
setMenuItemVisible(refreshIcon, true);
if (desc == NetDesc.BOARD || desc == NetDesc.TOPIC)
postCleanup();
if (isRoR)
isRoR = false;
System.gc();
}
private boolean goToUrlDefinedPost = false;
private int goToThisIndex = 0;
public void enableGoToUrlDefinedPost() {goToUrlDefinedPost = true;}
private boolean consumeGoToUrlDefinedPost() {
boolean temp = goToUrlDefinedPost;
goToUrlDefinedPost = false;
return temp;
}
private void updateHeader(String titleIn, String firstPageIn, String prevPageIn, String currPage,
String pageCount, String nextPageIn, String lastPageIn, NetDesc desc) {
title.setText(titleIn);
if (currPage.equals("-1")) {
pageJumperWrapper.setVisibility(View.GONE);
}
else {
pageJumperWrapper.setVisibility(View.VISIBLE);
pageJumperDesc = desc;
pageLabel.setText(currPage + " / " + pageCount);
if (firstPageIn != null) {
firstPageUrl = firstPageIn;
firstPage.setEnabled(true);
}
else {
firstPage.setEnabled(false);
}
if (prevPageIn != null) {
prevPageUrl = prevPageIn;
prevPage.setEnabled(true);
}
else {
prevPage.setEnabled(false);
}
if (nextPageIn != null) {
nextPageUrl = nextPageIn;
nextPage.setEnabled(true);
}
else {
nextPage.setEnabled(false);
}
if (lastPageIn != null) {
lastPageUrl = lastPageIn;
lastPage.setEnabled(true);
}
else {
lastPage.setEnabled(false);
}
}
}
private void updateHeaderNoJumper(String title, NetDesc desc) {
updateHeader(title, null, null, "-1", "-1", null, null, desc);
}
private MessageRowView clickedMsg;
private String quoteSelection;
public void messageMenuClicked(MessageRowView msg) {
clickedMsg = msg;
quoteSelection = clickedMsg.getSelection();
showDialog(MESSAGE_ACTION_DIALOG);
}
private void editPostSetup(String msg, String msgID) {
postBody.setText(msg);
messageIDForEditing = msgID;
postSetup(true);
}
private void quoteSetup(String user, String msg) {
wtl("quoteSetup fired");
String quotedMsg = "<cite>" + user + " posted...</cite>\n" +
"<quote>" + msg + "</quote>\n\n";
int start = Math.max(postBody.getSelectionStart(), 0);
int end = Math.max(postBody.getSelectionEnd(), 0);
postBody.getText().replace(Math.min(start, end), Math.max(start, end), quotedMsg);
if (postWrapper.getVisibility() != View.VISIBLE)
postSetup(true);
else
postBody.setSelection(Math.min(start, end) + quotedMsg.length());
wtl("quoteSetup finishing");
}
private void postSetup(boolean postingOnTopic) {
((ScrollView) findViewById(R.id.aioHTMLScroller)).scrollTo(0, 0);
pageJumperWrapper.setVisibility(View.GONE);
postButton.setEnabled(true);
cancelButton.setEnabled(true);
if (postingOnTopic) {
titleWrapper.setVisibility(View.GONE);
postBody.requestFocus();
postBody.setSelection(postBody.getText().length());
}
else {
titleWrapper.setVisibility(View.VISIBLE);
if (Session.userHasAdvancedPosting()) {
pollButton.setEnabled(true);
pollButton.setVisibility(View.VISIBLE);
pollSep.setVisibility(View.VISIBLE);
}
postTitle.requestFocus();
}
postWrapper.setVisibility(View.VISIBLE);
postPostUrl = session.getLastPath();
if (postPostUrl.contains("#"))
postPostUrl = postPostUrl.substring(0, postPostUrl.indexOf('#'));
}
public void postCancel(View view) {
wtl("postCancel fired --NEL");
if (settings.getBoolean("confirmPostCancel", false)) {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("Cancel this post?");
b.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
postCleanup();
}
});
b.setNegativeButton("No", null);
b.create().show();
}
else
postCleanup();
}
public void postPollOptions(View view) {
showDialog(POLL_OPTIONS_DIALOG);
}
public void postDo(View view) {
wtl("postDo fired");
if (settings.getBoolean("confirmPostSubmit", false)) {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("Submit this post?");
b.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
postSubmit();
}
});
b.setNegativeButton("No", null);
b.create().show();
}
else
postSubmit();
}
private void postSubmit() {
if (titleWrapper.getVisibility() == View.VISIBLE) {
wtl("posting on a board");
// posting on a board
String path = Session.ROOT + "/boards/post.php?board=" + boardID;
int i = path.indexOf('-');
path = path.substring(0, i);
wtl("post path: " + path);
savedPostBody = postBody.getText().toString();
wtl("saved post body: " + savedPostBody);
savedPostTitle = postTitle.getText().toString();
wtl("saved post title: " + savedPostTitle);
wtl("sending topic");
postButton.setEnabled(false);
pollButton.setEnabled(false);
cancelButton.setEnabled(false);
if (pollUse) {
path += "&poll=1";
session.get(NetDesc.POSTTPC_S1, path, null);
}
else if (Session.userHasAdvancedPosting())
session.get(NetDesc.QPOSTTPC_S1, path, null);
else
session.get(NetDesc.POSTTPC_S1, path, null);
}
else {
// posting on a topic
wtl("posting on a topic");
String path = Session.ROOT + "/boards/post.php?board=" + boardID + "&topic=" + topicID;
if (messageIDForEditing != null)
path += "&message=" + messageIDForEditing;
wtl("post path: " + path);
savedPostBody = postBody.getText().toString();
wtl("saved post body: " + savedPostBody);
wtl("sending post");
postButton.setEnabled(false);
cancelButton.setEnabled(false);
if (messageIDForEditing != null)
session.get(NetDesc.QEDIT_MSG, path, null);
else if (Session.userHasAdvancedPosting())
session.get(NetDesc.QPOSTMSG_S1, path, null);
else
session.get(NetDesc.POSTMSG_S1, path, null);
}
}
private String reportCode;
public String getReportCode() {return reportCode;}
/** creates dialogs */
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case SEND_PM_DIALOG:
dialog = createSendPMDialog();
break;
case MESSAGE_ACTION_DIALOG:
dialog = createMessageActionDialog();
break;
case REPORT_MESSAGE_DIALOG:
dialog = createReportMessageDialog();
break;
case POLL_OPTIONS_DIALOG:
dialog = createPollOptionsDialog();
break;
case CHANGE_LOGGED_IN_DIALOG:
dialog = createChangeLoggedInDialog();
break;
}
return dialog;
}
private Dialog createPollOptionsDialog() {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Poll Options");
LayoutInflater inflater = getLayoutInflater();
final View v = inflater.inflate(R.layout.polloptions, null);
b.setView(v);
b.setCancelable(false);
final EditText[] options = new EditText[10];
final CheckBox poUse = (CheckBox) v.findViewById(R.id.poUse);
final EditText poTitle = (EditText) v.findViewById(R.id.poTitle);
options[0] = (EditText) v.findViewById(R.id.po1);
options[1] = (EditText) v.findViewById(R.id.po2);
options[2] = (EditText) v.findViewById(R.id.po3);
options[3] = (EditText) v.findViewById(R.id.po4);
options[4] = (EditText) v.findViewById(R.id.po5);
options[5] = (EditText) v.findViewById(R.id.po6);
options[6] = (EditText) v.findViewById(R.id.po7);
options[7] = (EditText) v.findViewById(R.id.po8);
options[8] = (EditText) v.findViewById(R.id.po9);
options[9] = (EditText) v.findViewById(R.id.po10);
final Spinner minLevel = (Spinner) v.findViewById(R.id.poMinLevel);
poUse.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
poTitle.setEnabled(isChecked);
for (int x = 0; x < 10; x++)
options[x].setEnabled(isChecked);
}
});
for (int x = 0; x < 10; x++)
options[x].setText(pollOptions[x]);
minLevel.setSelection(pollMinLevel);
poTitle.setText(pollTitle);
poUse.setChecked(pollUse);
b.setPositiveButton("Save", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pollUse = poUse.isChecked();
pollTitle = poTitle.getText().toString();
pollMinLevel = minLevel.getSelectedItemPosition();
for (int x = 0; x < 10; x++)
pollOptions[x] = (options[x].getText().toString());
}
});
b.setNegativeButton("Cancel", null);
b.setNeutralButton("Clear", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
clearPoll();
}
});
Dialog dialog = b.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(POLL_OPTIONS_DIALOG);
}
});
return dialog;
}
private void clearPoll() {
pollUse = false;
pollTitle = EMPTY_STRING;
for (int x = 0; x < 10; x++)
pollOptions[x] = EMPTY_STRING; pollMinLevel = -1;
}
private Dialog createReportMessageDialog() {
AlertDialog.Builder reportMsgBuilder = new AlertDialog.Builder(this);
reportMsgBuilder.setTitle("Report Message");
final String[] reportOptions = getResources().getStringArray(R.array.msgReportReasons);
reportMsgBuilder.setItems(reportOptions, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
reportCode = getResources().getStringArray(R.array.msgReportCodes)[which];
session.get(NetDesc.MARKMSG_S1, clickedMsg.getMessageDetailLink(), null);
}
});
reportMsgBuilder.setNegativeButton("Cancel", null);
Dialog dialog = reportMsgBuilder.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(REPORT_MESSAGE_DIALOG);
}
});
return dialog;
}
private Dialog createMessageActionDialog() {
AlertDialog.Builder msgActionBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View v = inflater.inflate(R.layout.msgaction, null);
msgActionBuilder.setView(v);
msgActionBuilder.setTitle("Message Actions");
ArrayList<String> listBuilder = new ArrayList<String>();
if (clickedMsg.isEdited() && clickedMsg.getMessageID() != null)
listBuilder.add("View Previous Version(s)");
if (Session.isLoggedIn()) {
if (postIcon != null && postIcon.isVisible())
listBuilder.add("Quote");
if (Session.getUser().trim().toLowerCase(Locale.US).equals(clickedMsg.getUser().toLowerCase(Locale.US))) {
if (Session.userCanEditMsgs() && clickedMsg.isEditable())
listBuilder.add("Edit");
if (Session.userCanDeleteClose() && clickedMsg.getMessageID() != null)
listBuilder.add("Delete");
}
else if (Session.userCanMarkMsgs())
listBuilder.add("Report");
}
listBuilder.add("Highlight User");
listBuilder.add("User Details");
ListView lv = (ListView) v.findViewById(R.id.maList);
final LinearLayout wrapper = (LinearLayout) v.findViewById(R.id.maWrapper);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
adapter.addAll(listBuilder);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getItemAtPosition(position);
if (selected.equals("View Previous Version(s)")) {
session.get(NetDesc.MESSAGE_DETAIL, clickedMsg.getMessageDetailLink(), null);
}
else if (selected.equals("Quote")) {
String msg = (quoteSelection != null ? quoteSelection : clickedMsg.getMessageForQuoting());
quoteSetup(clickedMsg.getUser(), msg);
}
else if (selected.equals("Edit")) {
editPostSetup(clickedMsg.getMessageForEditing(), clickedMsg.getMessageID());
}
else if (selected.equals("Delete")) {
session.get(NetDesc.DLTMSG_S1, clickedMsg.getMessageDetailLink(), null);
}
else if (selected.equals("Report")) {
showDialog(REPORT_MESSAGE_DIALOG);
}
else if (selected.equals("Highlight User")) {
HighlightedUser user = hlDB.getHighlightedUsers().get(clickedMsg.getUser().toLowerCase(Locale.US));
HighlightListDBHelper.showHighlightUserDialog(AllInOneV2.this, user, clickedMsg.getUser(), null);
}
else if (selected.equals("User Details")) {
session.get(NetDesc.USER_DETAIL, clickedMsg.getUserDetailLink(), null);
}
else {
Crouton.showText(AllInOneV2.this, "not recognized: " + selected, croutonStyle);
}
dismissDialog(MESSAGE_ACTION_DIALOG);
}
});
msgActionBuilder.setNegativeButton("Cancel", null);
Dialog dialog = msgActionBuilder.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(MESSAGE_ACTION_DIALOG);
}
});
dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
if (quoteSelection != null)
Crouton.showText(AllInOneV2.this, "Selected text prepped for quoting.", croutonStyle, wrapper);
}
});
return dialog;
}
private LinearLayout pmSending;
private Dialog createSendPMDialog() {
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View v = inflater.inflate(R.layout.sendpm, null);
b.setView(v);
b.setTitle("Send Private Message");
b.setCancelable(false);
final EditText to = (EditText) v.findViewById(R.id.spTo);
final EditText subject = (EditText) v.findViewById(R.id.spSubject);
final EditText message = (EditText) v.findViewById(R.id.spMessage);
pmSending = (LinearLayout) v.findViewById(R.id.spFootWrapper);
to.setText(savedTo);
subject.setText(savedSubject);
message.setText(savedMessage);
b.setPositiveButton("Send", null);
b.setNegativeButton("Cancel", null);
final AlertDialog d = b.create();
d.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String toContent = to.getText().toString();
String subjectContent = subject.getText().toString();
String messageContent = message.getText().toString();
if (toContent.length() > 0) {
if (subjectContent.length() > 0) {
if (messageContent.length() > 0) {
savedTo = toContent;
savedSubject = subjectContent;
savedMessage = messageContent;
pmSending.setVisibility(View.VISIBLE);
session.get(NetDesc.SEND_PM_S1, "/pm/new", null);
}
else
Crouton.showText(AllInOneV2.this,
"The message can't be empty.",
croutonStyle,
(ViewGroup) to.getParent());
}
else
Crouton.showText(AllInOneV2.this,
"The subject can't be empty.",
croutonStyle,
(ViewGroup) to.getParent());
}
else
Crouton.showText(AllInOneV2.this,
"The recepient can't be empty.",
croutonStyle,
(ViewGroup) to.getParent());
}
});
}
});
d.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
pmSending = null;
removeDialog(SEND_PM_DIALOG);
}
});
return d;
}
private Dialog createChangeLoggedInDialog() {
AlertDialog.Builder accountChanger = new AlertDialog.Builder(this);
String[] keys = accounts.getKeys();
final String[] usernames = new String[keys.length + 1];
usernames[0] = "Log Out";
for (int i = 1; i < usernames.length; i++)
usernames[i] = keys[i - 1].toString();
final String currUser = Session.getUser();
int selected = 0;
for (int x = 1; x < usernames.length; x++)
{
if (usernames[x].equals(currUser))
selected = x;
}
accountChanger.setTitle("Pick an Account");
accountChanger.setSingleChoiceItems(usernames, selected, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0 && currUser != null)
session = new Session(AllInOneV2.this);
else
{
String selUser = usernames[item].toString();
if (!selUser.equals(currUser))
if (session.hasNetworkConnection()) {
session = new Session(AllInOneV2.this,
selUser,
accounts.getString(selUser),
session.getLastPath(),
session.getLastDesc());
}
else
noNetworkConnection();
}
dismissDialog(CHANGE_LOGGED_IN_DIALOG);
}
});
accountChanger.setNegativeButton("Cancel", null);
accountChanger.setPositiveButton("Manage Accounts", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(AllInOneV2.this, SettingsAccount.class));
}
});
final AlertDialog d = accountChanger.create();
d.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button posButton = d.getButton(DialogInterface.BUTTON_POSITIVE);
Button negButton = d.getButton(DialogInterface.BUTTON_NEGATIVE);
LayoutParams posParams = (LayoutParams) posButton.getLayoutParams();
posParams.weight = 1;
posParams.width = LayoutParams.MATCH_PARENT;
LayoutParams negParams = (LayoutParams) negButton.getLayoutParams();
negParams.weight = 1;
negParams.width = LayoutParams.MATCH_PARENT;
posButton.setLayoutParams(posParams);
negButton.setLayoutParams(negParams);
}
});
d.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(CHANGE_LOGGED_IN_DIALOG);
}
});
return d;
}
public String savedTo, savedSubject, savedMessage;
public void pmSetup(String toIn, String subjectIn, String messageIn) {
if (toIn != null && !toIn.equals("null"))
savedTo = toIn;
else
savedTo = EMPTY_STRING;
if (subjectIn != null && !subjectIn.equals("null"))
savedSubject = subjectIn;
else
savedSubject = EMPTY_STRING;
if (messageIn != null && !messageIn.equals("null"))
savedMessage = messageIn;
else
savedMessage = EMPTY_STRING;
savedTo = URLDecoder.decode(savedTo);
savedSubject = URLDecoder.decode(savedSubject);
savedMessage = URLDecoder.decode(savedMessage);
showDialog(SEND_PM_DIALOG);
}
public void pmCleanup(boolean wasSuccessful, String error) {
if (wasSuccessful) {
Crouton.showText(this, "PM sent.", croutonStyle);
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
hideSoftInputFromWindow(pmSending.getWindowToken(), 0);
dismissDialog(SEND_PM_DIALOG);
}
else {
Crouton.showText(this, error, croutonStyle, (ViewGroup) pmSending.getParent());
pmSending.setVisibility(View.GONE);
}
}
public void refreshClicked(View view) {
wtl("refreshClicked fired --NEL");
if (view != null)
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
if (session.getLastPath() == null) {
if (Session.isLoggedIn()) {
wtl("starting new session from refreshClicked, logged in");
session = new Session(this, Session.getUser(), accounts.getString(Session.getUser()));
}
else {
wtl("starting new session from refreshClicked, no login");
session = new Session(this);
}
}
else
session.refresh();
}
public String getSig() {
String sig = EMPTY_STRING;
if (session != null) {
if (Session.isLoggedIn())
sig = settings.getString("customSig" + Session.getUser(), EMPTY_STRING);
}
if (sig.length() == 0)
sig = settings.getString("customSig", EMPTY_STRING);
if (sig.length() == 0)
sig = defaultSig;
try {
sig = sig.replace("*grver*", this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
sig = sig.replace("*grver*", EMPTY_STRING);
e.printStackTrace();
}
return sig;
}
private static long lastNano = 0;
public void wtl(String msg) {
if (!isReleaseBuild) {
long currNano = System.nanoTime();
msg = msg.replaceAll("\\\\n", "(nl)");
long elapsed;
if (lastNano == 0)
elapsed = 0;
else
elapsed = currNano - lastNano;
elapsed = elapsed / 1000000;
if (elapsed > 100)
Log.w("logger", "time since previous log was over 100 milliseconds");
lastNano = System.nanoTime();
msg = elapsed + "// " + msg;
Log.d("logger", msg);
}
}
public void tryCaught(String url, String desc, Throwable e, String source) {
ACRAConfiguration config = ACRA.getConfig();
config.setResToastText(R.string.bug_toast_text);
ACRA.getErrorReporter().putCustomData("URL", url);
ACRA.getErrorReporter().putCustomData("NetDesc", desc);
ACRA.getErrorReporter().putCustomData("Page Source", StringEscapeUtils.escapeJava(source));
ACRA.getErrorReporter().putCustomData("Last Attempted Path", session.getLastAttemptedPath());
ACRA.getErrorReporter().putCustomData("Last Attempted Desc", session.getLastAttemptedDesc().toString());
ACRA.getErrorReporter().handleException(e);
config.setResToastText(R.string.crash_toast_text);
}
private String parseBoardID(String url) {
wtl("parseBoardID fired");
// board example: http://www.gamefaqs.com/boards/400-current-events
String boardUrl = url.substring(Session.ROOT.length() + 8);
int i = boardUrl.indexOf('/');
if (i != -1) {
String replacer = boardUrl.substring(i);
boardUrl = boardUrl.replace(replacer, EMPTY_STRING);
}
i = boardUrl.indexOf('?');
if (i != -1) {
String replacer = boardUrl.substring(i);
boardUrl = boardUrl.replace(replacer, EMPTY_STRING);
}
i = boardUrl.indexOf('#');
if (i != -1) {
String replacer = boardUrl.substring(i);
boardUrl = boardUrl.replace(replacer, EMPTY_STRING);
}
wtl("boardID: " + boardUrl);
return boardUrl;
}
private String parseTopicID(String url) {
wtl("parseTopicID fired");
// topic example: http://www.gamefaqs.com/boards/400-current-events/64300205
String topicUrl = url.substring(url.indexOf('/', Session.ROOT.length() + 8) + 1);
int i = topicUrl.indexOf('/');
if (i != -1) {
String replacer = topicUrl.substring(i);
topicUrl = topicUrl.replace(replacer, EMPTY_STRING);
}
i = topicUrl.indexOf('?');
if (i != -1) {
String replacer = topicUrl.substring(i);
topicUrl = topicUrl.replace(replacer, EMPTY_STRING);
}
i = topicUrl.indexOf('#');
if (i != -1) {
String replacer = topicUrl.substring(i);
topicUrl = topicUrl.replace(replacer, EMPTY_STRING);
}
wtl("topicID: " + topicUrl);
return topicUrl;
}
private String parseMessageID(String url) {
wtl("parseMessageID fired");
String msgID = url.substring(url.lastIndexOf('/') + 1);
wtl("messageIDForEditing: " + msgID);
return msgID;
}
@Override
public void onBackPressed() {
if (searchIcon != null && searchIcon.isActionViewExpanded()) {
searchIcon.collapseActionView();
}
else if (drawer.isMenuVisible()) {
drawer.closeMenu(true);
}
else if (postWrapper.getVisibility() == View.VISIBLE) {
postCleanup();
}
else {
goBack();
}
}
private void goBack() {
if (session.canGoBack()) {
wtl("back pressed, history exists, going back");
session.goBack(false);
}
else {
wtl("back pressed, no history, exiting app");
session = null;
this.finish();
}
}
public static String buildAMPLink() {
return "/boards/myposts.php?lp=" + settings.getString("ampSortOption", "-1");
}
private String autoCensor(String text) {
StringBuilder builder = new StringBuilder(text);
String textLower = text.toLowerCase(Locale.US);
for (String word : bannedList)
censorWord(builder, textLower, word.toLowerCase(Locale.US));
return builder.toString();
}
private void censorWord(StringBuilder builder, String textLower, String word) {
int length = word.length();
String replacement = "";
for (int x = 0; x < length - 1; x++)
replacement += '*';
while (textLower.contains(word)) {
int start = textLower.indexOf(word);
int end = start + length;
builder.replace(start + 1, end, replacement);
textLower = textLower.replaceFirst(word, replacement + '*');
}
}
public void htmlButtonClicked(View view) {
String open = ((TextView) view).getText().toString();
String close = "</" + open.substring(1);
int start = Math.max(postBody.getSelectionStart(), 0);
int end = Math.max(postBody.getSelectionEnd(), 0);
String insert;
if (start != end)
insert = open + postBody.getText().subSequence(start, end) + close;
else
insert = open + close;
postBody.getText().replace(Math.min(start, end), Math.max(start, end), insert, 0, insert.length());
}
private static final String[] bannedList = {
"***hole",
"68.13.103",
"Arse Hole",
"Arse-hole",
"Ass hole",
"Ass****",
"Ass-hole",
"Asshole",
"�^�",
"Bitch",
"Bukkake",
"Cheat Code Central",
"CheatCC",
"Clit",
"Cunt",
"Dave Allison",
"David Allison",
"Dildo",
"Echo J",
"Fag",
"Format C:",
"FreeFlatScreens.com",
"FreeIPods.com",
"Fuck",
"GFNostalgia",
"Gook",
"Jism",
"Jizm",
"Jizz",
"KingOfChaos",
"Lesbo",
"LUE2.tk",
"Mod Files",
"Mod Pics",
"ModFiles",
"ModPics",
"Nigga",
"Nigger",
"Offiz.bei.t-online.de",
"OutPimp",
"OutWar.com",
"PornStarGuru",
"Pussies",
"Pussy",
"RavenBlack.net",
"Shit",
"Shiz",
"SuprNova",
"Tits",
"Titties",
"Titty",
"UrbanDictionary",
"Wigga",
"Wigger",
"YouDontKnowWhoIAm"};
}
| true | true | public void processContent(NetDesc desc, Document doc, String resUrl) {
wtl("GRAIO hNR fired, desc: " + desc.name());
ptrLayout.setEnabled(false);
setMenuItemVisible(searchIcon, false);
if (searchIcon != null)
searchIcon.collapseActionView();
setMenuItemVisible(postIcon, false);
setMenuItemVisible(addFavIcon, false);
setMenuItemVisible(remFavIcon, false);
setMenuItemVisible(topicListIcon, false);
adapterRows.clear();
boolean isDefaultAcc;
if (Session.getUser() != null &&
Session.getUser().equals(settings.getString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT)))
isDefaultAcc = true;
else
isDefaultAcc = false;
wtl("setting board, topic, message id to null");
boardID = null;
topicID = null;
messageIDForEditing = null;
Element tbody;
Element pj = null;
String headerTitle;
String firstPage = null;
String prevPage = null;
String currPage = "1";
String pageCount = "1";
String nextPage = null;
String lastPage = null;
String bgcolor;
if (usingLightTheme)
bgcolor = "#ffffff";
else
bgcolor = "#000000";
adBuilder.setLength(0);
adBuilder.append("<html>");
adBuilder.append(doc.head().outerHtml());
adBuilder.append("<body bgcolor=\"" + bgcolor + "\">");
for (Element e : doc.getElementsByClass("ad")) {
adBuilder.append(e.outerHtml());
e.remove();
}
for (Element e : doc.getElementsByTag("script")) {
adBuilder.append(e.outerHtml());
}
adBuilder.append("</body></html>");
adBaseUrl = resUrl;
if (web == null)
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(AllInOneV2.getSettingsPref().getBoolean("enableJS", true));
switch (desc) {
case BOARD_JUMPER:
case LOGIN_S2:
updateHeaderNoJumper("Board Jumper", NetDesc.BOARD_JUMPER);
adapterRows.add(new HeaderRowData("Announcements"));
setMenuItemVisible(searchIcon, true);
processBoards(doc, true);
break;
case BOARD_LIST:
updateHeaderNoJumper(doc.getElementsByTag("th").get(4).text(), NetDesc.BOARD_LIST);
processBoards(doc, true);
break;
case PM_INBOX:
tbody = doc.getElementsByTag("tbody").first();
headerTitle = Session.getUser() + "'s PM Inbox";
if (tbody != null) {
pj = doc.select("ul.paginate").first();
if (pj != null) {
String pjText = pj.child(0).text();
if (pjText.contains("Previous"))
pjText = pj.child(1).text();
//Page 1 of 5
int currPageStart = 5;
int ofIndex = pjText.indexOf(" of ");
currPage = pjText.substring(currPageStart, ofIndex);
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4, pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "/pm/";
prevPage = "/pm/?page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = "/pm/?page=" + currPageNum;
lastPage = "/pm/?page=" + (pageCountNum - 1);
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.PM_INBOX);
if (isDefaultAcc)
NotifierService.dismissPMNotif(this);
for (Element row : tbody.getElementsByTag("tr")) {
Elements cells = row.children();
// [icon] [sender] [subject] [time] [check]
boolean isOld = true;
if (cells.get(0).children().first().hasClass("icon-circle"))
isOld = false;
String sender = cells.get(1).text();
Element subjectLinkElem = cells.get(2).children().first();
String subject = subjectLinkElem.text();
String link = subjectLinkElem.attr("href");
String time = cells.get(3).text();
adapterRows.add(new PMRowData(subject, sender, time, link, isOld));
}
}
else {
updateHeaderNoJumper(headerTitle, NetDesc.PM_INBOX);
adapterRows.add(new HeaderRowData("You have no private messages at this time."));
}
setMenuItemVisible(postIcon, true);
pMode = PostMode.NEW_PM;
break;
case PM_DETAIL:
headerTitle = doc.select("h2.title").first().text();
String pmTitle = headerTitle;
if (!pmTitle.startsWith("Re: "))
pmTitle = "Re: " + pmTitle;
String pmMessage = doc.select("div.body").first().outerHtml();
Element foot = doc.select("div.foot").first();
foot.child(1).remove();
String pmFoot = foot.outerHtml();
//Sent by: P4wn4g3 on 6/1/2013 2:15:55 PM
String footText = foot.text();
String sender = footText.substring(9, footText.indexOf(" on "));
updateHeaderNoJumper(pmTitle, NetDesc.PM_DETAIL);
adapterRows.add(new PMDetailRowData(sender, pmTitle, pmMessage + pmFoot));
break;
case AMP_LIST:
wtl("GRAIO hNR determined this is an amp response");
tbody = doc.getElementsByTag("tbody").first();
headerTitle = Session.getUser() + "'s Active Messages";
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")
&& !pj.hasClass("tsort")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page 2 of 3
int currPageStart = 5;
int ofIndex = pjText.indexOf(" of ");
currPage = pjText.substring(currPageStart, ofIndex);
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
String amp = buildAMPLink();
if (currPageNum > 1) {
firstPage = amp;
prevPage = amp + "&page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = amp + "&page=" + currPageNum;
lastPage = amp + "&page=" + (pageCountNum - 1);
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.AMP_LIST);
if (isDefaultAcc)
NotifierService.dismissAMPNotif(this);
if (!tbody.children().isEmpty()) {
if (settings.getBoolean("notifsEnable", false) && isDefaultAcc) {
Element lPost = doc.select("td.lastpost").first();
if (lPost != null) {
try {
String lTime = lPost.text();
Date newDate;
lTime = lTime.replace("Last:", EMPTY_STRING);
if (lTime.contains("AM") || lTime.contains("PM"))
newDate = new SimpleDateFormat("MM'/'dd hh':'mmaa", Locale.US).parse(lTime);
else
newDate = new SimpleDateFormat("MM'/'dd'/'yyyy", Locale.US).parse(lTime);
long newTime = newDate.getTime();
long oldTime = settings.getLong("notifsLastPost", 0);
if (newTime > oldTime) {
wtl("time is newer");
settings.edit().putLong("notifsLastPost", newTime).apply();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
for (Element row : tbody.children()) {
// [board] [title] [msg] [last post] [your last post]
Elements cells = row.children();
String board = cells.get(0).text();
Element titleLinkElem = cells.get(1).child(0);
String title = titleLinkElem.text();
String link = titleLinkElem.attr("href");
String mCount = cells.get(2).textNodes().get(0).text().trim();
Element lPostLinkElem = cells.get(3).child(1);
String lPost = lPostLinkElem.text();
String lPostLink = lPostLinkElem.attr("href");
String ylpLink = cells.get(4).child(1).attr("href");
adapterRows.add(new AMPRowData(title, board, lPost, mCount, link,
lPostLink, ylpLink));
}
}
else {
adapterRows.add(new HeaderRowData("You have no active messages at this time."));
}
wtl("amp response block finished");
break;
case TRACKED_TOPICS:
headerTitle = Session.getUser() + "'s Tracked Topics";
updateHeaderNoJumper(headerTitle, desc);
if (isDefaultAcc)
NotifierService.dismissTTNotif(this);
tbody = doc.getElementsByTag("tbody").first();
if (tbody != null) {
for (Element row : tbody.children()) {
// [remove] [title] [board name] [msgs] [last [pst]
Elements cells = row.children();
String removeLink = cells.get(0).child(0)
.attr("href");
String topicLink = cells.get(1).child(0)
.attr("href");
String topicText = cells.get(1).text();
String board = cells.get(2).text();
String msgs = cells.get(3).text();
String lPostLink = cells.get(4).child(0)
.attr("href");
String lPostText = cells.get(4).text();
adapterRows.add(new TrackedTopicRowData(board, topicText, lPostText,
msgs, topicLink, removeLink, lPostLink));
}
}
else {
adapterRows.add(new HeaderRowData("You have no tracked topics at this time."));
}
break;
case BOARD:
wtl("GRAIO hNR determined this is a board response");
wtl("setting board id");
boardID = parseBoardID(resUrl);
boolean isSplitList = false;
if (doc.getElementsByTag("th").first() != null) {
if (doc.getElementsByTag("th").first().text().equals("Board Title")) {
wtl("is actually a split board list");
updateHeaderNoJumper(doc.select("h1.page-title").first().text(), NetDesc.BOARD);
processBoards(doc, false);
isSplitList = true;
}
}
if (!isSplitList) {
String url = resUrl;
String searchQuery = EMPTY_STRING;
String searchPJAddition = EMPTY_STRING;
if (url.contains("search=")) {
wtl("board search url: " + url);
searchQuery = url.substring(url.indexOf("search=") + 7);
int i = searchQuery.indexOf('&');
if (i != -1)
searchQuery.replace(searchQuery.substring(i), EMPTY_STRING);
searchPJAddition = "&search=" + searchQuery;
searchQuery = URLDecoder.decode(searchQuery);
}
Element headerElem = doc.getElementsByClass("page-title").first();
if (headerElem != null)
headerTitle = headerElem.text();
else
headerTitle = "GFAQs Cache Error, Board Title Not Found";
if (searchQuery.length() > 0)
headerTitle += " (search: " + searchQuery + ")";
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page [dropdown] of 3
// Page 1 of 3
int ofIndex = pjText.indexOf(" of ");
int currPageStart = 5;
if (pj.getElementsByTag("select").isEmpty())
currPage = pjText.substring(currPageStart,
ofIndex);
else
currPage = pj
.select("option[selected=selected]")
.first().text();
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "boards/" + boardID + "?page=0"
+ searchPJAddition;
prevPage = "boards/" + boardID + "?page="
+ (currPageNum - 2)
+ searchPJAddition;
}
if (currPageNum != pageCountNum) {
nextPage = "boards/" + boardID + "?page="
+ currPageNum + searchPJAddition;
lastPage = "boards/" + boardID + "?page="
+ (pageCountNum - 1)
+ searchPJAddition;
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.BOARD);
setMenuItemVisible(searchIcon, true);
if (Session.isLoggedIn()) {
String favtext = doc.getElementsByClass("user").first().text().toLowerCase(Locale.US);
if (favtext.contains("add to favorites")) {
setMenuItemVisible(addFavIcon, true);
fMode = FavMode.ON_BOARD;
}
else if (favtext.contains("remove favorite")) {
setMenuItemVisible(remFavIcon, true);
fMode = FavMode.ON_BOARD;
}
updatePostingRights(doc, false);
}
Element splitList = doc.select("p:contains(this is a split board)").first();
if (splitList != null) {
String splitListLink = splitList.child(0).attr("href");
adapterRows.add(new BoardRowData("This is a Split Board.", "Click here to return to the Split List.",
null, null, null, splitListLink, BoardType.SPLIT));
}
Element table = doc.select("table.board").first();
if (table != null) {
table.getElementsByTag("col").get(2).remove();
table.getElementsByTag("th").get(2).remove();
table.getElementsByTag("col").get(0).remove();
table.getElementsByTag("th").get(0).remove();
wtl("board row parsing start");
boolean skipFirst = true;
Set<String> hlUsers = hlDB.getHighlightedUsers().keySet();
for (Element row : table.getElementsByTag("tr")) {
if (!skipFirst) {
Elements cells = row.getElementsByTag("td");
// cells = [image] [title] [author] [post count] [last post]
String tImg = cells.get(0).child(0).className();
Element titleLinkElem = cells.get(1).child(0);
String title = titleLinkElem.text();
String tUrl = titleLinkElem.attr("href");
String tc = cells.get(2).text();
Element lPostLinkElem = cells.get(4).child(0);
String lastPost = lPostLinkElem.text();
String lpUrl = lPostLinkElem.attr("href");
String mCount = cells.get(3).text();
TopicType type = TopicType.NORMAL;
if (tImg.contains("poll"))
type = TopicType.POLL;
else if (tImg.contains("sticky"))
type = TopicType.PINNED;
else if (tImg.contains("closed"))
type = TopicType.LOCKED;
else if (tImg.contains("archived"))
type = TopicType.ARCHIVED;
wtl(tImg + ", " + type.name());
ReadStatus status = ReadStatus.UNREAD;
if (tImg.endsWith("_read"))
status = ReadStatus.READ;
else if (tImg.endsWith("_unread"))
status = ReadStatus.NEW_POST;
int hlColor = 0;
if (hlUsers.contains(tc.toLowerCase(Locale.US))) {
HighlightedUser hUser = hlDB.getHighlightedUsers().get(tc.toLowerCase(Locale.US));
hlColor = hUser.getColor();
tc += " (" + hUser.getLabel() + ")";
}
adapterRows.add(new TopicRowData(title, tc, lastPost, mCount, tUrl,
lpUrl, type, status, hlColor));
}
else
skipFirst = false;
}
wtl("board row parsing end");
}
else {
adapterRows.add(new HeaderRowData("There are no topics at this time."));
}
}
wtl("board response block finished");
break;
case TOPIC:
boardID = parseBoardID(resUrl);
topicID = parseTopicID(resUrl);
tlUrl = "boards/" + boardID;
wtl(tlUrl);
setMenuItemVisible(topicListIcon, true);
Element headerElem = doc.getElementsByClass("title").first();
if (headerElem != null)
headerTitle = headerElem.text();
else
headerTitle = "GFAQs Cache Error, Title Not Found";
if (headerTitle.equals("Log In to GameFAQs")) {
headerElem = doc.getElementsByClass("title").get(1);
if (headerElem != null)
headerTitle = headerElem.text();
}
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page [dropdown] of 3
// Page 1 of 3
int ofIndex = pjText.indexOf(" of ");
int currPageStart = 5;
if (pj.getElementsByTag("select").isEmpty())
currPage = pjText.substring(currPageStart,
ofIndex);
else
currPage = pj
.select("option[selected=selected]")
.first().text();
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "boards/" + boardID + "/" + topicID;
prevPage = "boards/" + boardID + "/" + topicID
+ "?page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = "boards/" + boardID + "/" + topicID
+ "?page=" + currPageNum;
lastPage = "boards/" + boardID + "/" + topicID
+ "?page=" + (pageCountNum - 1);
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.TOPIC);
if (Session.isLoggedIn()) {
String favtext = doc.getElementsByClass("user").first().text().toLowerCase(Locale.US);
if (favtext.contains("track topic")) {
setMenuItemVisible(addFavIcon, true);
fMode = FavMode.ON_TOPIC;
}
else if (favtext.contains("stop tracking")) {
setMenuItemVisible(remFavIcon, true);
fMode = FavMode.ON_TOPIC;
}
updatePostingRights(doc, true);
}
String goToThisPost = null;
if (goToUrlDefinedPost) {
String url = resUrl;
goToThisPost = url.substring(url.indexOf('#') + 1);
}
Elements rows = doc.select("table.board").first().getElementsByTag("tr");
int rowCount = rows.size();
int msgIndex = 0;
Set<String> hlUsers = hlDB.getHighlightedUsers().keySet();
for (int x = 0; x < rowCount; x++) {
Element row = rows.get(x);
String user = null;
String postNum = null;
String mID = null;
String userTitles = EMPTY_STRING;
String postTimeText = EMPTY_STRING;
String postTime = EMPTY_STRING;
Element msgBody = null;
if (row.hasClass("left")) {
// message poster display set to left of message
Elements authorData = row.getElementsByClass("author_data");
user = row.getElementsByTag("b").first().text();
postNum = row.getElementsByTag("a").first().attr("name");
for (int i = 1; i < authorData.size(); i++) {
Element e = authorData.get(i);
String t = e.text();
if (t.startsWith("("))
userTitles += " " + t;
else if (e.hasClass("tag"))
userTitles += " (tagged as " + t + ")";
else if (t.startsWith("Posted"))
postTime = t;
else if (t.equals("message detail"))
mID = parseMessageID(e.child(0).attr("href"));
}
msgBody = row.child(1).child(0);
}
else {
// message poster display set to above message
List<TextNode> textNodes = row.child(0).child(0).textNodes();
Elements elements = row.child(0).child(0).children();
int textNodesSize = textNodes.size();
for (int y = 0; y < textNodesSize; y++) {
String text = textNodes.get(y).text();
if (text.startsWith("Posted"))
postTimeText = text;
else if (text.contains("(")) {
userTitles += " " + text.substring(text.indexOf('('), text.lastIndexOf(')') + 1);
}
}
user = elements.get(0).text();
int anchorCount = row.getElementsByTag("a").size();
postNum = row.getElementsByTag("a").get((anchorCount > 1 ? 1 : 0)).attr("name");
int elementsSize = elements.size();
for (int y = 0; y < elementsSize; y++) {
Element e = elements.get(y);
if (e.hasClass("tag"))
userTitles += " (tagged as " + e.text() + ")";
else if (e.text().equals("message detail"))
mID = parseMessageID(e.attr("href"));
}
//Posted 11/15/2012 11:20:27 AM | (edited) [if archived]
if (postTimeText.contains("(edited)"))
userTitles += " (edited)";
int endPoint = postTimeText.indexOf('|') - 1;
if (endPoint < 0)
endPoint = postTimeText.length();
postTime = postTimeText.substring(0, endPoint);
x++;
msgBody = rows.get(x).child(0).child(0);
}
int hlColor = 0;
if (hlUsers.contains(user.toLowerCase(Locale.US))) {
HighlightedUser hUser = hlDB
.getHighlightedUsers().get(
user.toLowerCase(Locale.US));
hlColor = hUser.getColor();
userTitles += " (" + hUser.getLabel() + ")";
}
if (goToUrlDefinedPost) {
if (postNum.equals(goToThisPost))
goToThisIndex = msgIndex;
}
wtl("creating messagerowdata object");
adapterRows.add(new MessageRowData(user, userTitles, postNum,
postTime, msgBody, boardID, topicID, mID, hlColor));
msgIndex++;
}
break;
case MESSAGE_DETAIL:
updateHeaderNoJumper("Message Detail", NetDesc.MESSAGE_DETAIL);
boardID = parseBoardID(resUrl);
topicID = parseTopicID(resUrl);
Elements msgDRows = doc.getElementsByTag("tr");
String user = msgDRows.first().child(0).child(0).text();
adapterRows.add(new HeaderRowData("Current Version"));
Element currRow, body;
MessageRowData msg;
String postTime;
String mID = parseMessageID(resUrl);
for (int x = 0; x < msgDRows.size(); x++) {
if (x == 1)
adapterRows.add(new HeaderRowData("Previous Version(s)"));
else {
currRow = msgDRows.get(x);
if (currRow.child(0).textNodes().size() > 1)
postTime = currRow.child(0).textNodes().get(1).text();
else
postTime = currRow.child(0).textNodes().get(0).text();
body = currRow.child(1);
msg = new MessageRowData(user, null, null, postTime, body, boardID, topicID, mID, 0);
msg.disableTopClick();
adapterRows.add(msg);
}
}
break;
case USER_DETAIL:
wtl("starting user detail processing");
tbody = doc.select("table.board").first().getElementsByTag("tbody").first();
Log.d("udtb", tbody.outerHtml());
String name = null;
String ID = null;
String level = null;
String creation = null;
String lVisit = null;
String sig = null;
String karma = null;
String AMP = null;
for (Element row : tbody.children()) {
String label = row.child(0).text().toLowerCase(Locale.US);
wtl("user detail row label: " + label);
if (label.equals("user name"))
name = row.child(1).text();
else if (label.equals("user id"))
ID = row.child(1).text();
else if (label.equals("board user level")) {
level = row.child(1).html();
wtl("set level: " + level);
}
else if (label.equals("account created"))
creation = row.child(1).text();
else if (label.equals("last visit"))
lVisit = row.child(1).text();
else if (label.equals("signature"))
sig = row.child(1).html();
else if (label.equals("karma"))
karma = row.child(1).text();
else if (label.equals("active messages posted"))
AMP = row.child(1).text();
}
updateHeaderNoJumper(name + "'s Details", NetDesc.USER_DETAIL);
adapterRows.add(new UserDetailRowData(name, ID, level, creation, lVisit, sig, karma, AMP));
break;
case GAME_SEARCH:
wtl("GRAIO hNR determined this is a game search response");
String url = resUrl;
wtl("game search url: " + url);
String searchQuery = url.substring(url.indexOf("game=") + 5);
int i = searchQuery.indexOf("&");
if (i != -1)
searchQuery = searchQuery.replace(searchQuery.substring(i), EMPTY_STRING);
int pageIndex = url.indexOf("page=");
if (pageIndex != -1) {
currPage = url.substring(pageIndex + 5);
i = currPage.indexOf("&");
if (i != -1)
currPage = currPage.replace(currPage.substring(i), EMPTY_STRING);
}
else {
currPage = "0";
}
int currPageNum = Integer.parseInt(currPage);
Element nextPageElem = null;
if (!doc.getElementsContainingOwnText("Next Page").isEmpty())
nextPageElem = doc.getElementsContainingOwnText("Next Page").first();
pageCount = "???";
if (nextPageElem != null) {
nextPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum + 1);
}
if (currPageNum > 0) {
prevPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum - 1);
firstPage = "/search/index.html?game=" + searchQuery + "&page=0";
}
headerTitle = "Searching games: " + URLDecoder.decode(searchQuery) + EMPTY_STRING;
updateHeader(headerTitle, firstPage, prevPage, Integer.toString(currPageNum + 1),
pageCount, nextPage, lastPage, NetDesc.GAME_SEARCH);
setMenuItemVisible(searchIcon, true);
Elements gameSearchTables = doc.select("table.results");
int tCount = gameSearchTables.size();
int tCounter = 0;
if (!gameSearchTables.isEmpty()) {
for (Element table : gameSearchTables) {
tCounter++;
if (tCounter < tCount)
adapterRows.add(new HeaderRowData("Best Matches"));
else
adapterRows.add(new HeaderRowData("Good Matches"));
String prevPlatform = EMPTY_STRING;
wtl("board row parsing start");
for (Element row : table.getElementsByTag("tr")) {
Elements cells = row.getElementsByTag("td");
// cells = [platform] [title] [faqs] [codes] [saves] [revs] [mygames] [q&a] [pics] [vids] [board]
String platform = cells.get(0).text();
String bName = cells.get(1).text();
String bUrl = cells.get(9).child(0).attr("href");
if (platform.codePointAt(0) == ('\u00A0')) {
platform = prevPlatform;
}
else {
prevPlatform = platform;
}
adapterRows.add(new GameSearchRowData(bName, platform, bUrl));
}
wtl("board row parsing end");
}
}
else {
adapterRows.add(new HeaderRowData("No results."));
}
wtl("game search response block finished");
break;
default:
wtl("GRAIO hNR determined response type is unhandled");
title.setText("Page unhandled - " + resUrl);
break;
}
try {
((ViewGroup) web.getParent()).removeView(web);
} catch (Exception e1) {}
adapterRows.add(new AdRowData(web));
contentList.post(loadAds);
Element pmInboxLink = doc.select("div.masthead_user").first().select("a[href=/pm/]").first();
String pmButtonLabel = getResources().getString(R.string.pm_inbox);
if (pmInboxLink != null) {
String text = pmInboxLink.text();
int count = 0;
if (text.contains("(")) {
count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')')));
int prevCount = settings.getInt("unreadPMCount", 0);
if (count > prevCount) {
if (count > 1)
Crouton.showText(this, "You have " + count + " unread PMs", croutonStyle);
else
Crouton.showText(this, "You have 1 unread PM", croutonStyle);
}
pmButtonLabel += " (" + count + ")";
}
settings.edit().putInt("unreadPMCount", count).apply();
if (isDefaultAcc)
settings.edit().putInt("notifsUnreadPMCount", count).apply();
}
((Button) findViewById(R.id.dwrPMInbox)).setText(pmButtonLabel);
Element trackedLink = doc.select("div.masthead_user").first().select("a[href=/boards/tracked]").first();
String ttButtonLabel = getResources().getString(R.string.tracked_topics);
if (trackedLink != null) {
String text = trackedLink.text();
int count = 0;
if (text.contains("(")) {
count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')')));
int prevCount = settings.getInt("unreadTTCount", 0);
if (count > prevCount) {
if (count > 1)
Crouton.showText(this, "You have " + count + " unread tracked topics", croutonStyle);
else
Crouton.showText(this, "You have 1 unread tracked topic", croutonStyle);
}
ttButtonLabel += " (" + count + ")";
}
settings.edit().putInt("unreadTTCount", count).apply();
if (isDefaultAcc)
settings.edit().putInt("notifsUnreadTTCount", count).apply();
}
((Button) findViewById(R.id.dwrTrackedTopics)).setText(ttButtonLabel);
ptrLayout.setEnabled(settings.getBoolean("enablePTR", false));
if (!adapterSet) {
contentList.setAdapter(viewAdapter);
adapterSet = true;
}
else
viewAdapter.notifyDataSetChanged();
if (consumeGoToUrlDefinedPost() && !Session.applySavedScroll) {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelection(goToThisIndex);
}
});
}
else if (Session.applySavedScroll) {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelectionFromTop(Session.savedScrollVal[0], Session.savedScrollVal[1]);
Session.applySavedScroll = false;
}
});
}
else {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelectionAfterHeaderView();
}
});
}
if (ptrLayout.isRefreshing())
ptrLayout.setRefreshComplete();
wtl("GRAIO hNR finishing");
}
| public void processContent(NetDesc desc, Document doc, String resUrl) {
wtl("GRAIO hNR fired, desc: " + desc.name());
ptrLayout.setEnabled(false);
setMenuItemVisible(searchIcon, false);
if (searchIcon != null)
searchIcon.collapseActionView();
setMenuItemVisible(postIcon, false);
setMenuItemVisible(addFavIcon, false);
setMenuItemVisible(remFavIcon, false);
setMenuItemVisible(topicListIcon, false);
adapterRows.clear();
boolean isDefaultAcc;
if (Session.getUser() != null &&
Session.getUser().equals(settings.getString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT)))
isDefaultAcc = true;
else
isDefaultAcc = false;
wtl("setting board, topic, message id to null");
boardID = null;
topicID = null;
messageIDForEditing = null;
Element tbody;
Element pj = null;
String headerTitle;
String firstPage = null;
String prevPage = null;
String currPage = "1";
String pageCount = "1";
String nextPage = null;
String lastPage = null;
String bgcolor;
if (usingLightTheme)
bgcolor = "#ffffff";
else
bgcolor = "#000000";
adBuilder.setLength(0);
adBuilder.append("<html>");
adBuilder.append(doc.head().outerHtml());
adBuilder.append("<body bgcolor=\"" + bgcolor + "\">");
for (Element e : doc.getElementsByClass("ad")) {
adBuilder.append(e.outerHtml());
e.remove();
}
for (Element e : doc.getElementsByTag("script")) {
adBuilder.append(e.outerHtml());
}
adBuilder.append("</body></html>");
adBaseUrl = resUrl;
if (web == null)
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(AllInOneV2.getSettingsPref().getBoolean("enableJS", true));
switch (desc) {
case BOARD_JUMPER:
case LOGIN_S2:
updateHeaderNoJumper("Board Jumper", NetDesc.BOARD_JUMPER);
adapterRows.add(new HeaderRowData("Announcements"));
setMenuItemVisible(searchIcon, true);
processBoards(doc, true);
break;
case BOARD_LIST:
updateHeaderNoJumper(doc.getElementsByTag("th").get(4).text(), NetDesc.BOARD_LIST);
processBoards(doc, true);
break;
case PM_INBOX:
tbody = doc.getElementsByTag("tbody").first();
headerTitle = Session.getUser() + "'s PM Inbox";
if (tbody != null) {
pj = doc.select("ul.paginate").first();
if (pj != null) {
String pjText = pj.child(0).text();
if (pjText.contains("Previous"))
pjText = pj.child(1).text();
//Page 1 of 5
int currPageStart = 5;
int ofIndex = pjText.indexOf(" of ");
currPage = pjText.substring(currPageStart, ofIndex);
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4, pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "/pm/";
prevPage = "/pm/?page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = "/pm/?page=" + currPageNum;
lastPage = "/pm/?page=" + (pageCountNum - 1);
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.PM_INBOX);
if (isDefaultAcc)
NotifierService.dismissPMNotif(this);
for (Element row : tbody.getElementsByTag("tr")) {
Elements cells = row.children();
// [icon] [sender] [subject] [time] [check]
boolean isOld = true;
if (cells.get(0).children().first().hasClass("icon-circle"))
isOld = false;
String sender = cells.get(1).text();
Element subjectLinkElem = cells.get(2).children().first();
String subject = subjectLinkElem.text();
String link = subjectLinkElem.attr("href");
String time = cells.get(3).text();
adapterRows.add(new PMRowData(subject, sender, time, link, isOld));
}
}
else {
updateHeaderNoJumper(headerTitle, NetDesc.PM_INBOX);
adapterRows.add(new HeaderRowData("You have no private messages at this time."));
}
setMenuItemVisible(postIcon, true);
pMode = PostMode.NEW_PM;
break;
case PM_DETAIL:
headerTitle = doc.select("h2.title").first().text();
String pmTitle = headerTitle;
if (!pmTitle.startsWith("Re: "))
pmTitle = "Re: " + pmTitle;
String pmMessage = doc.select("div.body").first().outerHtml();
Element foot = doc.select("div.foot").first();
foot.child(1).remove();
String pmFoot = foot.outerHtml();
//Sent by: P4wn4g3 on 6/1/2013 2:15:55 PM
String footText = foot.text();
String sender = footText.substring(9, footText.indexOf(" on "));
updateHeaderNoJumper(headerTitle, NetDesc.PM_DETAIL);
adapterRows.add(new PMDetailRowData(sender, pmTitle, pmMessage + pmFoot));
break;
case AMP_LIST:
wtl("GRAIO hNR determined this is an amp response");
tbody = doc.getElementsByTag("tbody").first();
headerTitle = Session.getUser() + "'s Active Messages";
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")
&& !pj.hasClass("tsort")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page 2 of 3
int currPageStart = 5;
int ofIndex = pjText.indexOf(" of ");
currPage = pjText.substring(currPageStart, ofIndex);
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
String amp = buildAMPLink();
if (currPageNum > 1) {
firstPage = amp;
prevPage = amp + "&page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = amp + "&page=" + currPageNum;
lastPage = amp + "&page=" + (pageCountNum - 1);
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.AMP_LIST);
if (isDefaultAcc)
NotifierService.dismissAMPNotif(this);
if (!tbody.children().isEmpty()) {
if (settings.getBoolean("notifsEnable", false) && isDefaultAcc) {
Element lPost = doc.select("td.lastpost").first();
if (lPost != null) {
try {
String lTime = lPost.text();
Date newDate;
lTime = lTime.replace("Last:", EMPTY_STRING);
if (lTime.contains("AM") || lTime.contains("PM"))
newDate = new SimpleDateFormat("MM'/'dd hh':'mmaa", Locale.US).parse(lTime);
else
newDate = new SimpleDateFormat("MM'/'dd'/'yyyy", Locale.US).parse(lTime);
long newTime = newDate.getTime();
long oldTime = settings.getLong("notifsLastPost", 0);
if (newTime > oldTime) {
wtl("time is newer");
settings.edit().putLong("notifsLastPost", newTime).apply();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
for (Element row : tbody.children()) {
// [board] [title] [msg] [last post] [your last post]
Elements cells = row.children();
String board = cells.get(0).text();
Element titleLinkElem = cells.get(1).child(0);
String title = titleLinkElem.text();
String link = titleLinkElem.attr("href");
String mCount = cells.get(2).textNodes().get(0).text().trim();
Element lPostLinkElem = cells.get(3).child(1);
String lPost = lPostLinkElem.text();
String lPostLink = lPostLinkElem.attr("href");
String ylpLink = cells.get(4).child(1).attr("href");
adapterRows.add(new AMPRowData(title, board, lPost, mCount, link,
lPostLink, ylpLink));
}
}
else {
adapterRows.add(new HeaderRowData("You have no active messages at this time."));
}
wtl("amp response block finished");
break;
case TRACKED_TOPICS:
headerTitle = Session.getUser() + "'s Tracked Topics";
updateHeaderNoJumper(headerTitle, desc);
if (isDefaultAcc)
NotifierService.dismissTTNotif(this);
tbody = doc.getElementsByTag("tbody").first();
if (tbody != null) {
for (Element row : tbody.children()) {
// [remove] [title] [board name] [msgs] [last [pst]
Elements cells = row.children();
String removeLink = cells.get(0).child(0)
.attr("href");
String topicLink = cells.get(1).child(0)
.attr("href");
String topicText = cells.get(1).text();
String board = cells.get(2).text();
String msgs = cells.get(3).text();
String lPostLink = cells.get(4).child(0)
.attr("href");
String lPostText = cells.get(4).text();
adapterRows.add(new TrackedTopicRowData(board, topicText, lPostText,
msgs, topicLink, removeLink, lPostLink));
}
}
else {
adapterRows.add(new HeaderRowData("You have no tracked topics at this time."));
}
break;
case BOARD:
wtl("GRAIO hNR determined this is a board response");
wtl("setting board id");
boardID = parseBoardID(resUrl);
boolean isSplitList = false;
if (doc.getElementsByTag("th").first() != null) {
if (doc.getElementsByTag("th").first().text().equals("Board Title")) {
wtl("is actually a split board list");
updateHeaderNoJumper(doc.select("h1.page-title").first().text(), NetDesc.BOARD);
processBoards(doc, false);
isSplitList = true;
}
}
if (!isSplitList) {
String url = resUrl;
String searchQuery = EMPTY_STRING;
String searchPJAddition = EMPTY_STRING;
if (url.contains("search=")) {
wtl("board search url: " + url);
searchQuery = url.substring(url.indexOf("search=") + 7);
int i = searchQuery.indexOf('&');
if (i != -1)
searchQuery.replace(searchQuery.substring(i), EMPTY_STRING);
searchPJAddition = "&search=" + searchQuery;
searchQuery = URLDecoder.decode(searchQuery);
}
Element headerElem = doc.getElementsByClass("page-title").first();
if (headerElem != null)
headerTitle = headerElem.text();
else
headerTitle = "GFAQs Cache Error, Board Title Not Found";
if (searchQuery.length() > 0)
headerTitle += " (search: " + searchQuery + ")";
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page [dropdown] of 3
// Page 1 of 3
int ofIndex = pjText.indexOf(" of ");
int currPageStart = 5;
if (pj.getElementsByTag("select").isEmpty())
currPage = pjText.substring(currPageStart,
ofIndex);
else
currPage = pj
.select("option[selected=selected]")
.first().text();
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "boards/" + boardID + "?page=0"
+ searchPJAddition;
prevPage = "boards/" + boardID + "?page="
+ (currPageNum - 2)
+ searchPJAddition;
}
if (currPageNum != pageCountNum) {
nextPage = "boards/" + boardID + "?page="
+ currPageNum + searchPJAddition;
lastPage = "boards/" + boardID + "?page="
+ (pageCountNum - 1)
+ searchPJAddition;
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.BOARD);
setMenuItemVisible(searchIcon, true);
if (Session.isLoggedIn()) {
String favtext = doc.getElementsByClass("user").first().text().toLowerCase(Locale.US);
if (favtext.contains("add to favorites")) {
setMenuItemVisible(addFavIcon, true);
fMode = FavMode.ON_BOARD;
}
else if (favtext.contains("remove favorite")) {
setMenuItemVisible(remFavIcon, true);
fMode = FavMode.ON_BOARD;
}
updatePostingRights(doc, false);
}
Element splitList = doc.select("p:contains(this is a split board)").first();
if (splitList != null) {
String splitListLink = splitList.child(0).attr("href");
adapterRows.add(new BoardRowData("This is a Split Board.", "Click here to return to the Split List.",
null, null, null, splitListLink, BoardType.SPLIT));
}
Element table = doc.select("table.board").first();
if (table != null) {
table.getElementsByTag("col").get(2).remove();
table.getElementsByTag("th").get(2).remove();
table.getElementsByTag("col").get(0).remove();
table.getElementsByTag("th").get(0).remove();
wtl("board row parsing start");
boolean skipFirst = true;
Set<String> hlUsers = hlDB.getHighlightedUsers().keySet();
for (Element row : table.getElementsByTag("tr")) {
if (!skipFirst) {
Elements cells = row.getElementsByTag("td");
// cells = [image] [title] [author] [post count] [last post]
String tImg = cells.get(0).child(0).className();
Element titleLinkElem = cells.get(1).child(0);
String title = titleLinkElem.text();
String tUrl = titleLinkElem.attr("href");
String tc = cells.get(2).text();
Element lPostLinkElem = cells.get(4).child(0);
String lastPost = lPostLinkElem.text();
String lpUrl = lPostLinkElem.attr("href");
String mCount = cells.get(3).text();
TopicType type = TopicType.NORMAL;
if (tImg.contains("poll"))
type = TopicType.POLL;
else if (tImg.contains("sticky"))
type = TopicType.PINNED;
else if (tImg.contains("closed"))
type = TopicType.LOCKED;
else if (tImg.contains("archived"))
type = TopicType.ARCHIVED;
wtl(tImg + ", " + type.name());
ReadStatus status = ReadStatus.UNREAD;
if (tImg.endsWith("_read"))
status = ReadStatus.READ;
else if (tImg.endsWith("_unread"))
status = ReadStatus.NEW_POST;
int hlColor = 0;
if (hlUsers.contains(tc.toLowerCase(Locale.US))) {
HighlightedUser hUser = hlDB.getHighlightedUsers().get(tc.toLowerCase(Locale.US));
hlColor = hUser.getColor();
tc += " (" + hUser.getLabel() + ")";
}
adapterRows.add(new TopicRowData(title, tc, lastPost, mCount, tUrl,
lpUrl, type, status, hlColor));
}
else
skipFirst = false;
}
wtl("board row parsing end");
}
else {
adapterRows.add(new HeaderRowData("There are no topics at this time."));
}
}
wtl("board response block finished");
break;
case TOPIC:
boardID = parseBoardID(resUrl);
topicID = parseTopicID(resUrl);
tlUrl = "boards/" + boardID;
wtl(tlUrl);
setMenuItemVisible(topicListIcon, true);
Element headerElem = doc.getElementsByClass("title").first();
if (headerElem != null)
headerTitle = headerElem.text();
else
headerTitle = "GFAQs Cache Error, Title Not Found";
if (headerTitle.equals("Log In to GameFAQs")) {
headerElem = doc.getElementsByClass("title").get(1);
if (headerElem != null)
headerTitle = headerElem.text();
}
if (doc.select("ul.paginate").size() > 1) {
pj = doc.select("ul.paginate").get(1);
if (pj != null && !pj.hasClass("user")) {
int x = 0;
String pjText = pj.child(x).text();
while (pjText.contains("First")
|| pjText.contains("Previous")) {
x++;
pjText = pj.child(x).text();
}
// Page [dropdown] of 3
// Page 1 of 3
int ofIndex = pjText.indexOf(" of ");
int currPageStart = 5;
if (pj.getElementsByTag("select").isEmpty())
currPage = pjText.substring(currPageStart,
ofIndex);
else
currPage = pj
.select("option[selected=selected]")
.first().text();
int pageCountEnd = pjText.length();
pageCount = pjText.substring(ofIndex + 4,
pageCountEnd);
int currPageNum = Integer.parseInt(currPage);
int pageCountNum = Integer.parseInt(pageCount);
if (currPageNum > 1) {
firstPage = "boards/" + boardID + "/" + topicID;
prevPage = "boards/" + boardID + "/" + topicID
+ "?page=" + (currPageNum - 2);
}
if (currPageNum != pageCountNum) {
nextPage = "boards/" + boardID + "/" + topicID
+ "?page=" + currPageNum;
lastPage = "boards/" + boardID + "/" + topicID
+ "?page=" + (pageCountNum - 1);
}
}
}
updateHeader(headerTitle, firstPage, prevPage, currPage,
pageCount, nextPage, lastPage, NetDesc.TOPIC);
if (Session.isLoggedIn()) {
String favtext = doc.getElementsByClass("user").first().text().toLowerCase(Locale.US);
if (favtext.contains("track topic")) {
setMenuItemVisible(addFavIcon, true);
fMode = FavMode.ON_TOPIC;
}
else if (favtext.contains("stop tracking")) {
setMenuItemVisible(remFavIcon, true);
fMode = FavMode.ON_TOPIC;
}
updatePostingRights(doc, true);
}
String goToThisPost = null;
if (goToUrlDefinedPost) {
String url = resUrl;
goToThisPost = url.substring(url.indexOf('#') + 1);
}
Elements rows = doc.select("table.board").first().getElementsByTag("tr");
int rowCount = rows.size();
int msgIndex = 0;
Set<String> hlUsers = hlDB.getHighlightedUsers().keySet();
for (int x = 0; x < rowCount; x++) {
Element row = rows.get(x);
String user = null;
String postNum = null;
String mID = null;
String userTitles = EMPTY_STRING;
String postTimeText = EMPTY_STRING;
String postTime = EMPTY_STRING;
Element msgBody = null;
if (row.hasClass("left")) {
// message poster display set to left of message
Elements authorData = row.getElementsByClass("author_data");
user = row.getElementsByTag("b").first().text();
postNum = row.getElementsByTag("a").first().attr("name");
for (int i = 1; i < authorData.size(); i++) {
Element e = authorData.get(i);
String t = e.text();
if (t.startsWith("("))
userTitles += " " + t;
else if (e.hasClass("tag"))
userTitles += " (tagged as " + t + ")";
else if (t.startsWith("Posted"))
postTime = t;
else if (t.equals("message detail"))
mID = parseMessageID(e.child(0).attr("href"));
}
msgBody = row.child(1).child(0);
}
else {
// message poster display set to above message
List<TextNode> textNodes = row.child(0).child(0).textNodes();
Elements elements = row.child(0).child(0).children();
int textNodesSize = textNodes.size();
for (int y = 0; y < textNodesSize; y++) {
String text = textNodes.get(y).text();
if (text.startsWith("Posted"))
postTimeText = text;
else if (text.contains("(")) {
userTitles += " " + text.substring(text.indexOf('('), text.lastIndexOf(')') + 1);
}
}
user = elements.get(0).text();
int anchorCount = row.getElementsByTag("a").size();
postNum = row.getElementsByTag("a").get((anchorCount > 1 ? 1 : 0)).attr("name");
int elementsSize = elements.size();
for (int y = 0; y < elementsSize; y++) {
Element e = elements.get(y);
if (e.hasClass("tag"))
userTitles += " (tagged as " + e.text() + ")";
else if (e.text().equals("message detail"))
mID = parseMessageID(e.attr("href"));
}
//Posted 11/15/2012 11:20:27 AM | (edited) [if archived]
if (postTimeText.contains("(edited)"))
userTitles += " (edited)";
int endPoint = postTimeText.indexOf('|') - 1;
if (endPoint < 0)
endPoint = postTimeText.length();
postTime = postTimeText.substring(0, endPoint);
x++;
msgBody = rows.get(x).child(0).child(0);
}
int hlColor = 0;
if (hlUsers.contains(user.toLowerCase(Locale.US))) {
HighlightedUser hUser = hlDB
.getHighlightedUsers().get(
user.toLowerCase(Locale.US));
hlColor = hUser.getColor();
userTitles += " (" + hUser.getLabel() + ")";
}
if (goToUrlDefinedPost) {
if (postNum.equals(goToThisPost))
goToThisIndex = msgIndex;
}
wtl("creating messagerowdata object");
adapterRows.add(new MessageRowData(user, userTitles, postNum,
postTime, msgBody, boardID, topicID, mID, hlColor));
msgIndex++;
}
break;
case MESSAGE_DETAIL:
updateHeaderNoJumper("Message Detail", NetDesc.MESSAGE_DETAIL);
boardID = parseBoardID(resUrl);
topicID = parseTopicID(resUrl);
Elements msgDRows = doc.getElementsByTag("tr");
String user = msgDRows.first().child(0).child(0).text();
adapterRows.add(new HeaderRowData("Current Version"));
Element currRow, body;
MessageRowData msg;
String postTime;
String mID = parseMessageID(resUrl);
for (int x = 0; x < msgDRows.size(); x++) {
if (x == 1)
adapterRows.add(new HeaderRowData("Previous Version(s)"));
else {
currRow = msgDRows.get(x);
if (currRow.child(0).textNodes().size() > 1)
postTime = currRow.child(0).textNodes().get(1).text();
else
postTime = currRow.child(0).textNodes().get(0).text();
body = currRow.child(1);
msg = new MessageRowData(user, null, null, postTime, body, boardID, topicID, mID, 0);
msg.disableTopClick();
adapterRows.add(msg);
}
}
break;
case USER_DETAIL:
wtl("starting user detail processing");
tbody = doc.select("table.board").first().getElementsByTag("tbody").first();
Log.d("udtb", tbody.outerHtml());
String name = null;
String ID = null;
String level = null;
String creation = null;
String lVisit = null;
String sig = null;
String karma = null;
String AMP = null;
for (Element row : tbody.children()) {
String label = row.child(0).text().toLowerCase(Locale.US);
wtl("user detail row label: " + label);
if (label.equals("user name"))
name = row.child(1).text();
else if (label.equals("user id"))
ID = row.child(1).text();
else if (label.equals("board user level")) {
level = row.child(1).html();
wtl("set level: " + level);
}
else if (label.equals("account created"))
creation = row.child(1).text();
else if (label.equals("last visit"))
lVisit = row.child(1).text();
else if (label.equals("signature"))
sig = row.child(1).html();
else if (label.equals("karma"))
karma = row.child(1).text();
else if (label.equals("active messages posted"))
AMP = row.child(1).text();
}
updateHeaderNoJumper(name + "'s Details", NetDesc.USER_DETAIL);
adapterRows.add(new UserDetailRowData(name, ID, level, creation, lVisit, sig, karma, AMP));
break;
case GAME_SEARCH:
wtl("GRAIO hNR determined this is a game search response");
String url = resUrl;
wtl("game search url: " + url);
String searchQuery = url.substring(url.indexOf("game=") + 5);
int i = searchQuery.indexOf("&");
if (i != -1)
searchQuery = searchQuery.replace(searchQuery.substring(i), EMPTY_STRING);
int pageIndex = url.indexOf("page=");
if (pageIndex != -1) {
currPage = url.substring(pageIndex + 5);
i = currPage.indexOf("&");
if (i != -1)
currPage = currPage.replace(currPage.substring(i), EMPTY_STRING);
}
else {
currPage = "0";
}
int currPageNum = Integer.parseInt(currPage);
Element nextPageElem = null;
if (!doc.getElementsContainingOwnText("Next Page").isEmpty())
nextPageElem = doc.getElementsContainingOwnText("Next Page").first();
pageCount = "???";
if (nextPageElem != null) {
nextPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum + 1);
}
if (currPageNum > 0) {
prevPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum - 1);
firstPage = "/search/index.html?game=" + searchQuery + "&page=0";
}
headerTitle = "Searching games: " + URLDecoder.decode(searchQuery) + EMPTY_STRING;
updateHeader(headerTitle, firstPage, prevPage, Integer.toString(currPageNum + 1),
pageCount, nextPage, lastPage, NetDesc.GAME_SEARCH);
setMenuItemVisible(searchIcon, true);
Elements gameSearchTables = doc.select("table.results");
int tCount = gameSearchTables.size();
int tCounter = 0;
if (!gameSearchTables.isEmpty()) {
for (Element table : gameSearchTables) {
tCounter++;
if (tCounter < tCount)
adapterRows.add(new HeaderRowData("Best Matches"));
else
adapterRows.add(new HeaderRowData("Good Matches"));
String prevPlatform = EMPTY_STRING;
wtl("board row parsing start");
for (Element row : table.getElementsByTag("tr")) {
Elements cells = row.getElementsByTag("td");
// cells = [platform] [title] [faqs] [codes] [saves] [revs] [mygames] [q&a] [pics] [vids] [board]
String platform = cells.get(0).text();
String bName = cells.get(1).text();
String bUrl = cells.get(9).child(0).attr("href");
if (platform.codePointAt(0) == ('\u00A0')) {
platform = prevPlatform;
}
else {
prevPlatform = platform;
}
adapterRows.add(new GameSearchRowData(bName, platform, bUrl));
}
wtl("board row parsing end");
}
}
else {
adapterRows.add(new HeaderRowData("No results."));
}
wtl("game search response block finished");
break;
default:
wtl("GRAIO hNR determined response type is unhandled");
title.setText("Page unhandled - " + resUrl);
break;
}
try {
((ViewGroup) web.getParent()).removeView(web);
} catch (Exception e1) {}
adapterRows.add(new AdRowData(web));
contentList.post(loadAds);
Element pmInboxLink = doc.select("div.masthead_user").first().select("a[href=/pm/]").first();
String pmButtonLabel = getResources().getString(R.string.pm_inbox);
if (pmInboxLink != null) {
String text = pmInboxLink.text();
int count = 0;
if (text.contains("(")) {
count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')')));
int prevCount = settings.getInt("unreadPMCount", 0);
if (count > prevCount) {
if (count > 1)
Crouton.showText(this, "You have " + count + " unread PMs", croutonStyle);
else
Crouton.showText(this, "You have 1 unread PM", croutonStyle);
}
pmButtonLabel += " (" + count + ")";
}
settings.edit().putInt("unreadPMCount", count).apply();
if (isDefaultAcc)
settings.edit().putInt("notifsUnreadPMCount", count).apply();
}
((Button) findViewById(R.id.dwrPMInbox)).setText(pmButtonLabel);
Element trackedLink = doc.select("div.masthead_user").first().select("a[href=/boards/tracked]").first();
String ttButtonLabel = getResources().getString(R.string.tracked_topics);
if (trackedLink != null) {
String text = trackedLink.text();
int count = 0;
if (text.contains("(")) {
count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')')));
int prevCount = settings.getInt("unreadTTCount", 0);
if (count > prevCount) {
if (count > 1)
Crouton.showText(this, "You have " + count + " unread tracked topics", croutonStyle);
else
Crouton.showText(this, "You have 1 unread tracked topic", croutonStyle);
}
ttButtonLabel += " (" + count + ")";
}
settings.edit().putInt("unreadTTCount", count).apply();
if (isDefaultAcc)
settings.edit().putInt("notifsUnreadTTCount", count).apply();
}
((Button) findViewById(R.id.dwrTrackedTopics)).setText(ttButtonLabel);
ptrLayout.setEnabled(settings.getBoolean("enablePTR", false));
if (!adapterSet) {
contentList.setAdapter(viewAdapter);
adapterSet = true;
}
else
viewAdapter.notifyDataSetChanged();
if (consumeGoToUrlDefinedPost() && !Session.applySavedScroll) {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelection(goToThisIndex);
}
});
}
else if (Session.applySavedScroll) {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelectionFromTop(Session.savedScrollVal[0], Session.savedScrollVal[1]);
Session.applySavedScroll = false;
}
});
}
else {
contentList.post(new Runnable() {
@Override
public void run() {
contentList.setSelectionAfterHeaderView();
}
});
}
if (ptrLayout.isRefreshing())
ptrLayout.setRefreshComplete();
wtl("GRAIO hNR finishing");
}
|
diff --git a/emailsync/src/com/android/emailsync/SyncManager.java b/emailsync/src/com/android/emailsync/SyncManager.java
index e4e155e91..0500837fd 100644
--- a/emailsync/src/com/android/emailsync/SyncManager.java
+++ b/emailsync/src/com/android/emailsync/SyncManager.java
@@ -1,2269 +1,2271 @@
/*
* Copyright (C) 2008-2009 Marc Blank
* Licensed to 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.emailsync;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Process;
import android.os.RemoteException;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.provider.ContactsContract;
import android.util.Log;
import com.android.emailcommon.TempDirectory;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.Body;
import com.android.emailcommon.provider.EmailContent.BodyColumns;
import com.android.emailcommon.provider.EmailContent.MailboxColumns;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.provider.EmailContent.MessageColumns;
import com.android.emailcommon.provider.EmailContent.SyncColumns;
import com.android.emailcommon.provider.HostAuth;
import com.android.emailcommon.provider.Mailbox;
import com.android.emailcommon.provider.Policy;
import com.android.emailcommon.provider.ProviderUnavailableException;
import com.android.emailcommon.service.AccountServiceProxy;
import com.android.emailcommon.service.EmailServiceProxy;
import com.android.emailcommon.service.EmailServiceStatus;
import com.android.emailcommon.service.IEmailServiceCallback.Stub;
import com.android.emailcommon.service.PolicyServiceProxy;
import com.android.emailcommon.utility.EmailAsyncTask;
import com.android.emailcommon.utility.EmailClientConnectionManager;
import com.android.emailcommon.utility.Utility;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* The SyncServiceManager handles the lifecycle of various sync adapters used by services that
* cannot rely on the system SyncManager
*
* SyncServiceManager uses ContentObservers to detect changes to accounts, mailboxes, & messages in
* order to maintain proper 2-way syncing of data. (More documentation to follow)
*
*/
public abstract class SyncManager extends Service implements Runnable {
private static final String TAG = "SyncServiceManager";
// The SyncServiceManager's mailbox "id"
public static final int EXTRA_MAILBOX_ID = -1;
public static final int SYNC_SERVICE_MAILBOX_ID = 0;
private static final int SECONDS = 1000;
private static final int MINUTES = 60*SECONDS;
private static final int ONE_DAY_MINUTES = 1440;
private static final int SYNC_SERVICE_HEARTBEAT_TIME = 15*MINUTES;
private static final int CONNECTIVITY_WAIT_TIME = 10*MINUTES;
// Sync hold constants for services with transient errors
private static final int HOLD_DELAY_MAXIMUM = 4*MINUTES;
// Reason codes when SyncServiceManager.kick is called (mainly for debugging)
// UI has changed data, requiring an upsync of changes
public static final int SYNC_UPSYNC = 0;
// A scheduled sync (when not using push)
public static final int SYNC_SCHEDULED = 1;
// Mailbox was marked push
public static final int SYNC_PUSH = 2;
// A ping (EAS push signal) was received
public static final int SYNC_PING = 3;
// Misc.
public static final int SYNC_KICK = 4;
// A part request (attachment load, for now) was sent to SyncServiceManager
public static final int SYNC_SERVICE_PART_REQUEST = 5;
// Requests >= SYNC_CALLBACK_START generate callbacks to the UI
public static final int SYNC_CALLBACK_START = 6;
// startSync was requested of SyncServiceManager (other than due to user request)
public static final int SYNC_SERVICE_START_SYNC = SYNC_CALLBACK_START + 0;
// startSync was requested of SyncServiceManager (due to user request)
public static final int SYNC_UI_REQUEST = SYNC_CALLBACK_START + 1;
protected static final String WHERE_IN_ACCOUNT_AND_PUSHABLE =
MailboxColumns.ACCOUNT_KEY + "=? and type in (" + Mailbox.TYPE_INBOX + ','
+ Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + ',' + Mailbox.TYPE_CONTACTS + ','
+ Mailbox.TYPE_CALENDAR + ')';
protected static final String WHERE_IN_ACCOUNT_AND_TYPE_INBOX =
MailboxColumns.ACCOUNT_KEY + "=? and type = " + Mailbox.TYPE_INBOX ;
private static final String WHERE_MAILBOX_KEY = Message.MAILBOX_KEY + "=?";
private static final String WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN =
"(" + MailboxColumns.TYPE + '=' + Mailbox.TYPE_OUTBOX
+ " or " + MailboxColumns.SYNC_INTERVAL + "!=" + Mailbox.CHECK_INTERVAL_NEVER + ')'
+ " and " + MailboxColumns.ACCOUNT_KEY + " in (";
public static final int SEND_FAILED = 1;
public static final String MAILBOX_KEY_AND_NOT_SEND_FAILED =
MessageColumns.MAILBOX_KEY + "=? and (" + SyncColumns.SERVER_ID + " is null or " +
SyncColumns.SERVER_ID + "!=" + SEND_FAILED + ')';
public static final String CALENDAR_SELECTION =
Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?";
private static final String WHERE_CALENDAR_ID = Events.CALENDAR_ID + "=?";
// Offsets into the syncStatus data for EAS that indicate type, exit status, and change count
// The format is S<type_char>:<exit_char>:<change_count>
public static final int STATUS_TYPE_CHAR = 1;
public static final int STATUS_EXIT_CHAR = 3;
public static final int STATUS_CHANGE_COUNT_OFFSET = 5;
// Ready for ping
public static final int PING_STATUS_OK = 0;
// Service already running (can't ping)
public static final int PING_STATUS_RUNNING = 1;
// Service waiting after I/O error (can't ping)
public static final int PING_STATUS_WAITING = 2;
// Service had a fatal error; can't run
public static final int PING_STATUS_UNABLE = 3;
// Service is disabled by user (checkbox)
public static final int PING_STATUS_DISABLED = 4;
private static final int MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS = 1;
// We synchronize on this for all actions affecting the service and error maps
private static final Object sSyncLock = new Object();
// All threads can use this lock to wait for connectivity
public static final Object sConnectivityLock = new Object();
public static boolean sConnectivityHold = false;
// Keeps track of running services (by mailbox id)
public final HashMap<Long, AbstractSyncService> mServiceMap =
new HashMap<Long, AbstractSyncService>();
// Keeps track of services whose last sync ended with an error (by mailbox id)
/*package*/ public ConcurrentHashMap<Long, SyncError> mSyncErrorMap =
new ConcurrentHashMap<Long, SyncError>();
// Keeps track of which services require a wake lock (by mailbox id)
private final HashMap<Long, Boolean> mWakeLocks = new HashMap<Long, Boolean>();
// Keeps track of PendingIntents for mailbox alarms (by mailbox id)
private final HashMap<Long, PendingIntent> mPendingIntents = new HashMap<Long, PendingIntent>();
// The actual WakeLock obtained by SyncServiceManager
private WakeLock mWakeLock = null;
// Keep our cached list of active Accounts here
public final AccountList mAccountList = new AccountList();
// Observers that we use to look for changed mail-related data
private final Handler mHandler = new Handler();
private AccountObserver mAccountObserver;
private MailboxObserver mMailboxObserver;
private SyncedMessageObserver mSyncedMessageObserver;
// Concurrent because CalendarSyncAdapter can modify the map during a wipe
private final ConcurrentHashMap<Long, CalendarObserver> mCalendarObservers =
new ConcurrentHashMap<Long, CalendarObserver>();
public ContentResolver mResolver;
// The singleton SyncServiceManager object, with its thread and stop flag
protected static SyncManager INSTANCE;
protected static Thread sServiceThread = null;
// Cached unique device id
protected static String sDeviceId = null;
// HashMap of ConnectionManagers that all EAS threads can use (by HostAuth id)
private static HashMap<Long, EmailClientConnectionManager> sClientConnectionManagers =
new HashMap<Long, EmailClientConnectionManager>();
// Count of ClientConnectionManager shutdowns
private static volatile int sClientConnectionManagerShutdownCount = 0;
private static volatile boolean sStartingUp = false;
private static volatile boolean sStop = false;
// The reason for SyncServiceManager's next wakeup call
private String mNextWaitReason;
// Whether we have an unsatisfied "kick" pending
private boolean mKicked = false;
// Receiver of connectivity broadcasts
private ConnectivityReceiver mConnectivityReceiver = null;
private ConnectivityReceiver mBackgroundDataSettingReceiver = null;
private volatile boolean mBackgroundData = true;
// The most current NetworkInfo (from ConnectivityManager)
private NetworkInfo mNetworkInfo;
// For sync logging
protected static boolean sUserLog = false;
protected static boolean sFileLog = false;
/**
* Return an AccountObserver for this manager; the subclass must implement the newAccount()
* method, which is called whenever the observer discovers that a new account has been created.
* The subclass should do any housekeeping necessary
* @param handler a Handler
* @return the AccountObserver
*/
public abstract AccountObserver getAccountObserver(Handler handler);
/**
* Perform any housekeeping necessary upon startup of the manager
*/
public abstract void onStartup();
/**
* Returns a String that can be used as a WHERE clause in SQLite that selects accounts whose
* syncs are managed by this manager
* @return the account selector String
*/
public abstract String getAccountsSelector();
/**
* Returns an appropriate sync service for the passed in mailbox
* @param context the caller's context
* @param mailbox the Mailbox to be synced
* @return a service that will sync the Mailbox
*/
public abstract AbstractSyncService getServiceForMailbox(Context context, Mailbox mailbox);
/**
* Return a list of all Accounts in EmailProvider. Because the result of this call may be used
* in account reconciliation, an exception is thrown if the result cannot be guaranteed accurate
* @param context the caller's context
* @param accounts a list that Accounts will be added into
* @return the list of Accounts
* @throws ProviderUnavailableException if the list of Accounts cannot be guaranteed valid
*/
public abstract AccountList collectAccounts(Context context, AccountList accounts);
/**
* Returns the AccountManager type (e.g. com.android.exchange) for this sync service
*/
public abstract String getAccountManagerType();
/**
* Returns the intent action used for this sync service
*/
public abstract String getServiceIntentAction();
/**
* Returns the callback proxy used for communicating back with the Email app
*/
public abstract Stub getCallbackProxy();
public class AccountList extends ArrayList<Account> {
private static final long serialVersionUID = 1L;
@Override
public boolean add(Account account) {
// Cache the account manager account
account.mAmAccount = new android.accounts.Account(
account.mEmailAddress, getAccountManagerType());
super.add(account);
return true;
}
public boolean contains(long id) {
for (Account account : this) {
if (account.mId == id) {
return true;
}
}
return false;
}
public Account getById(long id) {
for (Account account : this) {
if (account.mId == id) {
return account;
}
}
return null;
}
public Account getByName(String accountName) {
for (Account account : this) {
if (account.mEmailAddress.equalsIgnoreCase(accountName)) {
return account;
}
}
return null;
}
}
public static void setUserDebug(int state) {
sUserLog = (state & EmailServiceProxy.DEBUG_BIT) != 0;
sFileLog = (state & EmailServiceProxy.DEBUG_FILE_BIT) != 0;
if (sFileLog) {
sUserLog = true;
}
Log.d("Sync Debug", "Logging: " + (sUserLog ? "User " : "") + (sFileLog ? "File" : ""));
}
private boolean onSecurityHold(Account account) {
return (account.mFlags & Account.FLAGS_SECURITY_HOLD) != 0;
}
public static String getAccountSelector() {
SyncManager ssm = INSTANCE;
if (ssm == null) return "";
return ssm.getAccountsSelector();
}
public abstract class AccountObserver extends ContentObserver {
String mSyncableMailboxSelector = null;
String mAccountSelector = null;
// Runs when SyncServiceManager first starts
@SuppressWarnings("deprecation")
public AccountObserver(Handler handler) {
super(handler);
// At startup, we want to see what EAS accounts exist and cache them
// TODO: Move database work out of UI thread
Context context = getContext();
synchronized (mAccountList) {
try {
collectAccounts(context, mAccountList);
} catch (ProviderUnavailableException e) {
// Just leave if EmailProvider is unavailable
return;
}
// Create an account mailbox for any account without one
for (Account account : mAccountList) {
int cnt = Mailbox.count(context, Mailbox.CONTENT_URI, "accountKey="
+ account.mId, null);
if (cnt == 0) {
// This case handles a newly created account
newAccount(account.mId);
}
}
}
// Run through accounts and update account hold information
Utility.runAsync(new Runnable() {
@Override
public void run() {
synchronized (mAccountList) {
for (Account account : mAccountList) {
if (onSecurityHold(account)) {
// If we're in a security hold, and our policies are active, release
// the hold
if (PolicyServiceProxy.isActive(SyncManager.this, null)) {
PolicyServiceProxy.setAccountHoldFlag(SyncManager.this,
account, false);
log("isActive true; release hold for " + account.mDisplayName);
}
}
}
}
}});
}
/**
* Returns a String suitable for appending to a where clause that selects for all syncable
* mailboxes in all eas accounts
* @return a complex selection string that is not to be cached
*/
public String getSyncableMailboxWhere() {
if (mSyncableMailboxSelector == null) {
StringBuilder sb = new StringBuilder(WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN);
boolean first = true;
synchronized (mAccountList) {
for (Account account : mAccountList) {
if (!first) {
sb.append(',');
} else {
first = false;
}
sb.append(account.mId);
}
}
sb.append(')');
mSyncableMailboxSelector = sb.toString();
}
return mSyncableMailboxSelector;
}
private void onAccountChanged() {
try {
maybeStartSyncServiceManagerThread();
Context context = getContext();
// A change to the list requires us to scan for deletions (stop running syncs)
// At startup, we want to see what accounts exist and cache them
AccountList currentAccounts = new AccountList();
try {
collectAccounts(context, currentAccounts);
} catch (ProviderUnavailableException e) {
// Just leave if EmailProvider is unavailable
return;
}
synchronized (mAccountList) {
for (Account account : mAccountList) {
boolean accountIncomplete =
(account.mFlags & Account.FLAGS_INCOMPLETE) != 0;
// If the current list doesn't include this account and the account wasn't
// incomplete, then this is a deletion
if (!currentAccounts.contains(account.mId) && !accountIncomplete) {
// The implication is that the account has been deleted; let's find out
alwaysLog("Observer found deleted account: " + account.mDisplayName);
// Run the reconciler (the reconciliation itself runs in the Email app)
runAccountReconcilerSync(SyncManager.this);
// See if the account is still around
Account deletedAccount =
Account.restoreAccountWithId(context, account.mId);
if (deletedAccount != null) {
// It is; add it to our account list
alwaysLog("Account still in provider: " + account.mDisplayName);
currentAccounts.add(account);
} else {
// It isn't; stop syncs and clear our selectors
alwaysLog("Account deletion confirmed: " + account.mDisplayName);
stopAccountSyncs(account.mId, true);
mSyncableMailboxSelector = null;
mAccountSelector = null;
}
} else {
// Get the newest version of this account
Account updatedAccount =
Account.restoreAccountWithId(context, account.mId);
if (updatedAccount == null) continue;
if (account.mSyncInterval != updatedAccount.mSyncInterval
|| account.mSyncLookback != updatedAccount.mSyncLookback) {
// Set the inbox interval to the interval of the Account
// This setting should NOT affect other boxes
ContentValues cv = new ContentValues();
cv.put(MailboxColumns.SYNC_INTERVAL, updatedAccount.mSyncInterval);
getContentResolver().update(Mailbox.CONTENT_URI, cv,
WHERE_IN_ACCOUNT_AND_TYPE_INBOX, new String[] {
Long.toString(account.mId)
});
// Stop all current syncs; the appropriate ones will restart
log("Account " + account.mDisplayName + " changed; stop syncs");
stopAccountSyncs(account.mId, true);
}
// See if this account is no longer on security hold
if (onSecurityHold(account) && !onSecurityHold(updatedAccount)) {
releaseSyncHolds(SyncManager.this,
AbstractSyncService.EXIT_SECURITY_FAILURE, account);
}
// Put current values into our cached account
account.mSyncInterval = updatedAccount.mSyncInterval;
account.mSyncLookback = updatedAccount.mSyncLookback;
account.mFlags = updatedAccount.mFlags;
}
}
// Look for new accounts
for (Account account : currentAccounts) {
if (!mAccountList.contains(account.mId)) {
// Don't forget to cache the HostAuth
HostAuth ha = HostAuth.restoreHostAuthWithId(getContext(),
account.mHostAuthKeyRecv);
if (ha == null) continue;
account.mHostAuthRecv = ha;
// This is an addition; create our magic hidden mailbox...
log("Account observer found new account: " + account.mDisplayName);
newAccount(account.mId);
mAccountList.add(account);
mSyncableMailboxSelector = null;
mAccountSelector = null;
}
}
// Finally, make sure our account list is up to date
mAccountList.clear();
mAccountList.addAll(currentAccounts);
}
// See if there's anything to do...
kick("account changed");
} catch (ProviderUnavailableException e) {
alwaysLog("Observer failed; provider unavailable");
}
}
@Override
public void onChange(boolean selfChange) {
new Thread(new Runnable() {
@Override
public void run() {
onAccountChanged();
}}, "Account Observer").start();
}
public abstract void newAccount(long acctId);
}
/**
* Register a specific Calendar's data observer; we need to recognize when the SYNC_EVENTS
* column has changed (when sync has turned off or on)
* @param account the Account whose Calendar we're observing
*/
private void registerCalendarObserver(Account account) {
// Get a new observer
CalendarObserver observer = new CalendarObserver(mHandler, account);
if (observer.mCalendarId != 0) {
// If we find the Calendar (and we'd better) register it and store it in the map
mCalendarObservers.put(account.mId, observer);
mResolver.registerContentObserver(
ContentUris.withAppendedId(Calendars.CONTENT_URI, observer.mCalendarId), false,
observer);
}
}
/**
* Unregister all CalendarObserver's
*/
static public void unregisterCalendarObservers() {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
ContentResolver resolver = ssm.mResolver;
for (CalendarObserver observer: ssm.mCalendarObservers.values()) {
resolver.unregisterContentObserver(observer);
}
ssm.mCalendarObservers.clear();
}
public static Uri asSyncAdapter(Uri uri, String account, String accountType) {
return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build();
}
/**
* Return the syncable state of an account's calendar, as determined by the sync_events column
* of our Calendar (from CalendarProvider2)
* Note that the current state of sync_events is cached in our CalendarObserver
* @param accountId the id of the account whose calendar we are checking
* @return whether or not syncing of events is enabled
*/
private boolean isCalendarEnabled(long accountId) {
CalendarObserver observer = mCalendarObservers.get(accountId);
if (observer != null) {
return (observer.mSyncEvents == 1);
}
// If there's no observer, there's no Calendar in CalendarProvider2, so we return true
// to allow Calendar creation
return true;
}
private class CalendarObserver extends ContentObserver {
final long mAccountId;
final String mAccountName;
long mCalendarId;
long mSyncEvents;
public CalendarObserver(Handler handler, Account account) {
super(handler);
mAccountId = account.mId;
mAccountName = account.mEmailAddress;
// Find the Calendar for this account
Cursor c = mResolver.query(Calendars.CONTENT_URI,
new String[] {Calendars._ID, Calendars.SYNC_EVENTS},
CALENDAR_SELECTION,
new String[] {account.mEmailAddress, getAccountManagerType()},
null);
if (c != null) {
// Save its id and its sync events status
try {
if (c.moveToFirst()) {
mCalendarId = c.getLong(0);
mSyncEvents = c.getLong(1);
}
} finally {
c.close();
}
}
}
@Override
public synchronized void onChange(boolean selfChange) {
// See if the user has changed syncing of our calendar
if (!selfChange) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Cursor c = mResolver.query(Calendars.CONTENT_URI,
new String[] {Calendars.SYNC_EVENTS}, Calendars._ID + "=?",
new String[] {Long.toString(mCalendarId)}, null);
if (c == null) return;
// Get its sync events; if it's changed, we've got work to do
try {
if (c.moveToFirst()) {
long newSyncEvents = c.getLong(0);
if (newSyncEvents != mSyncEvents) {
log("_sync_events changed for calendar in " + mAccountName);
Mailbox mailbox = Mailbox.restoreMailboxOfType(INSTANCE,
mAccountId, Mailbox.TYPE_CALENDAR);
// Sanity check for mailbox deletion
if (mailbox == null) return;
ContentValues cv = new ContentValues();
if (newSyncEvents == 0) {
// When sync is disabled, we're supposed to delete
// all events in the calendar
log("Deleting events and setting syncKey to 0 for " +
mAccountName);
// First, stop any sync that's ongoing
stopManualSync(mailbox.mId);
// Set the syncKey to 0 (reset)
AbstractSyncService service = getServiceForMailbox(
INSTANCE, mailbox);
service.resetCalendarSyncKey();
// Reset the sync key locally and stop syncing
cv.put(Mailbox.SYNC_KEY, "0");
cv.put(Mailbox.SYNC_INTERVAL,
Mailbox.CHECK_INTERVAL_NEVER);
mResolver.update(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, mailbox.mId), cv, null,
null);
// Delete all events using the sync adapter
// parameter so that the deletion is only local
Uri eventsAsSyncAdapter =
asSyncAdapter(
Events.CONTENT_URI,
mAccountName,
getAccountManagerType());
mResolver.delete(eventsAsSyncAdapter, WHERE_CALENDAR_ID,
new String[] {Long.toString(mCalendarId)});
} else {
// Make this a push mailbox and kick; this will start
// a resync of the Calendar; the account mailbox will
// ping on this during the next cycle of the ping loop
cv.put(Mailbox.SYNC_INTERVAL,
Mailbox.CHECK_INTERVAL_PUSH);
mResolver.update(ContentUris.withAppendedId(
Mailbox.CONTENT_URI, mailbox.mId), cv, null,
null);
kick("calendar sync changed");
}
// Save away the new value
mSyncEvents = newSyncEvents;
}
}
} finally {
c.close();
}
} catch (ProviderUnavailableException e) {
Log.w(TAG, "Observer failed; provider unavailable");
}
}}, "Calendar Observer").start();
}
}
}
private class MailboxObserver extends ContentObserver {
public MailboxObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
// See if there's anything to do...
if (!selfChange) {
kick("mailbox changed");
}
}
}
private class SyncedMessageObserver extends ContentObserver {
Intent syncAlarmIntent = new Intent(INSTANCE, EmailSyncAlarmReceiver.class);
PendingIntent syncAlarmPendingIntent =
PendingIntent.getBroadcast(INSTANCE, 0, syncAlarmIntent, 0);
AlarmManager alarmManager = (AlarmManager)INSTANCE.getSystemService(Context.ALARM_SERVICE);
public SyncedMessageObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
alarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 10*SECONDS, syncAlarmPendingIntent);
}
}
static public Account getAccountById(long accountId) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
AccountList accountList = ssm.mAccountList;
synchronized (accountList) {
return accountList.getById(accountId);
}
}
return null;
}
static public Account getAccountByName(String accountName) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
AccountList accountList = ssm.mAccountList;
synchronized (accountList) {
return accountList.getByName(accountName);
}
}
return null;
}
public class SyncStatus {
static public final int NOT_RUNNING = 0;
static public final int DIED = 1;
static public final int SYNC = 2;
static public final int IDLE = 3;
}
/*package*/ public class SyncError {
int reason;
public boolean fatal = false;
long holdDelay = 15*SECONDS;
public long holdEndTime = System.currentTimeMillis() + holdDelay;
public SyncError(int _reason, boolean _fatal) {
reason = _reason;
fatal = _fatal;
}
/**
* We double the holdDelay from 15 seconds through 8 mins
*/
void escalate() {
if (holdDelay <= HOLD_DELAY_MAXIMUM) {
holdDelay *= 2;
}
holdEndTime = System.currentTimeMillis() + holdDelay;
}
}
private void logSyncHolds() {
if (sUserLog) {
log("Sync holds:");
long time = System.currentTimeMillis();
for (long mailboxId : mSyncErrorMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
log("Mailbox " + mailboxId + " no longer exists");
} else {
SyncError error = mSyncErrorMap.get(mailboxId);
if (error != null) {
log("Mailbox " + m.mDisplayName + ", error = " + error.reason
+ ", fatal = " + error.fatal);
if (error.holdEndTime > 0) {
log("Hold ends in " + ((error.holdEndTime - time) / 1000) + "s");
}
}
}
}
}
}
/**
* Release security holds for the specified account
* @param account the account whose Mailboxes should be released from security hold
*/
static public void releaseSecurityHold(Account account) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.releaseSyncHolds(INSTANCE, AbstractSyncService.EXIT_SECURITY_FAILURE,
account);
}
}
/**
* Release a specific type of hold (the reason) for the specified Account; if the account
* is null, mailboxes from all accounts with the specified hold will be released
* @param reason the reason for the SyncError (AbstractSyncService.EXIT_XXX)
* @param account an Account whose mailboxes should be released (or all if null)
* @return whether or not any mailboxes were released
*/
public /*package*/ boolean releaseSyncHolds(Context context, int reason, Account account) {
boolean holdWasReleased = releaseSyncHoldsImpl(context, reason, account);
kick("security release");
return holdWasReleased;
}
private boolean releaseSyncHoldsImpl(Context context, int reason, Account account) {
boolean holdWasReleased = false;
for (long mailboxId: mSyncErrorMap.keySet()) {
if (account != null) {
Mailbox m = Mailbox.restoreMailboxWithId(context, mailboxId);
if (m == null) {
mSyncErrorMap.remove(mailboxId);
} else if (m.mAccountKey != account.mId) {
continue;
}
}
SyncError error = mSyncErrorMap.get(mailboxId);
if (error != null && error.reason == reason) {
mSyncErrorMap.remove(mailboxId);
holdWasReleased = true;
}
}
return holdWasReleased;
}
public static void log(String str) {
log(TAG, str);
}
public static void log(String tag, String str) {
if (sUserLog) {
Log.d(tag, str);
if (sFileLog) {
FileLogger.log(tag, str);
}
}
}
public static void alwaysLog(String str) {
if (!sUserLog) {
Log.d(TAG, str);
} else {
log(str);
}
}
/**
* EAS requires a unique device id, so that sync is possible from a variety of different
* devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other
* device that doesn't provide one, we can create it as "device".
* This would work on a real device as well, but it would be better to use the "real" id if
* it's available
*/
static public String getDeviceId(Context context) throws IOException {
if (sDeviceId == null) {
sDeviceId = new AccountServiceProxy(context).getDeviceId();
alwaysLog("Received deviceId from Email app: " + sDeviceId);
}
return sDeviceId;
}
static public ConnPerRoute sConnPerRoute = new ConnPerRoute() {
@Override
public int getMaxForRoute(HttpRoute route) {
return 8;
}
};
static public synchronized EmailClientConnectionManager getClientConnectionManager(
Context context, HostAuth hostAuth) {
// We'll use a different connection manager for each HostAuth
EmailClientConnectionManager mgr = null;
// We don't save managers for validation/autodiscover
if (hostAuth.mId != HostAuth.NOT_SAVED) {
mgr = sClientConnectionManagers.get(hostAuth.mId);
}
if (mgr == null) {
// After two tries, kill the process. Most likely, this will happen in the background
// The service will restart itself after about 5 seconds
if (sClientConnectionManagerShutdownCount > MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS) {
alwaysLog("Shutting down process to unblock threads");
Process.killProcess(Process.myPid());
}
HttpParams params = new BasicHttpParams();
params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute);
boolean ssl = hostAuth.shouldUseSsl();
int port = hostAuth.mPort;
mgr = EmailClientConnectionManager.newInstance(context, params, hostAuth);
log("Creating connection manager for port " + port + ", ssl: " + ssl);
sClientConnectionManagers.put(hostAuth.mId, mgr);
}
// Null is a valid return result if we get an exception
return mgr;
}
static private synchronized void shutdownConnectionManager() {
log("Shutting down ClientConnectionManagers");
for (EmailClientConnectionManager mgr: sClientConnectionManagers.values()) {
mgr.shutdown();
}
sClientConnectionManagers.clear();
}
public static void stopAccountSyncs(long acctId) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.stopAccountSyncs(acctId, true);
}
}
public void stopAccountSyncs(long acctId, boolean includeAccountMailbox) {
synchronized (sSyncLock) {
List<Long> deletedBoxes = new ArrayList<Long>();
for (Long mid : mServiceMap.keySet()) {
Mailbox box = Mailbox.restoreMailboxWithId(this, mid);
if (box != null) {
if (box.mAccountKey == acctId) {
if (!includeAccountMailbox &&
box.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
AbstractSyncService svc = mServiceMap.get(mid);
if (svc != null) {
svc.stop();
}
continue;
}
AbstractSyncService svc = mServiceMap.get(mid);
if (svc != null) {
svc.stop();
Thread t = svc.mThread;
if (t != null) {
t.interrupt();
}
}
deletedBoxes.add(mid);
}
}
}
for (Long mid : deletedBoxes) {
releaseMailbox(mid);
}
}
}
/**
* Informs SyncServiceManager that an account has a new folder list; as a result, any existing
* folder might have become invalid. Therefore, we act as if the account has been deleted, and
* then we reinitialize it.
*
* @param acctId
*/
static public void stopNonAccountMailboxSyncsForAccount(long acctId) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.stopAccountSyncs(acctId, false);
kick("reload folder list");
}
}
private void acquireWakeLock(long id) {
synchronized (mWakeLocks) {
Boolean lock = mWakeLocks.get(id);
if (lock == null) {
if (mWakeLock == null) {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE");
mWakeLock.acquire();
//log("+WAKE LOCK ACQUIRED");
}
mWakeLocks.put(id, true);
}
}
}
private void releaseWakeLock(long id) {
synchronized (mWakeLocks) {
Boolean lock = mWakeLocks.get(id);
if (lock != null) {
mWakeLocks.remove(id);
if (mWakeLocks.isEmpty()) {
if (mWakeLock != null) {
mWakeLock.release();
}
mWakeLock = null;
//log("+WAKE LOCK RELEASED");
} else {
}
}
}
}
static public String alarmOwner(long id) {
if (id == EXTRA_MAILBOX_ID) {
return TAG;
} else {
String name = Long.toString(id);
if (sUserLog && INSTANCE != null) {
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, id);
if (m != null) {
name = m.mDisplayName + '(' + m.mAccountKey + ')';
}
}
return "Mailbox " + name;
}
}
private void clearAlarm(long id) {
synchronized (mPendingIntents) {
PendingIntent pi = mPendingIntents.get(id);
if (pi != null) {
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pi);
//log("+Alarm cleared for " + alarmOwner(id));
mPendingIntents.remove(id);
}
}
}
private void setAlarm(long id, long millis) {
synchronized (mPendingIntents) {
PendingIntent pi = mPendingIntents.get(id);
if (pi == null) {
Intent i = new Intent(this, MailboxAlarmReceiver.class);
i.putExtra("mailbox", id);
i.setData(Uri.parse("Box" + id));
pi = PendingIntent.getBroadcast(this, 0, i, 0);
mPendingIntents.put(id, pi);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pi);
//log("+Alarm set for " + alarmOwner(id) + ", " + millis/1000 + "s");
}
}
}
private void clearAlarms() {
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
synchronized (mPendingIntents) {
for (PendingIntent pi : mPendingIntents.values()) {
alarmManager.cancel(pi);
}
mPendingIntents.clear();
}
}
static public void runAwake(long id) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.acquireWakeLock(id);
ssm.clearAlarm(id);
}
}
static public void runAsleep(long id, long millis) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.setAlarm(id, millis);
ssm.releaseWakeLock(id);
}
}
static public void clearWatchdogAlarm(long id) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.clearAlarm(id);
}
}
static public void setWatchdogAlarm(long id, long millis) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.setAlarm(id, millis);
}
}
static public void alert(Context context, final long id) {
final SyncManager ssm = INSTANCE;
checkSyncServiceManagerServiceRunning();
if (id < 0) {
log("SyncServiceManager alert");
kick("ping SyncServiceManager");
} else if (ssm == null) {
context.startService(new Intent(context, SyncManager.class));
} else {
final AbstractSyncService service = ssm.mServiceMap.get(id);
if (service != null) {
// Handle alerts in a background thread, as we are typically called from a
// broadcast receiver, and are therefore running in the UI thread
String threadName = "SyncServiceManager Alert: ";
if (service.mMailbox != null) {
threadName += service.mMailbox.mDisplayName;
}
new Thread(new Runnable() {
@Override
public void run() {
Mailbox m = Mailbox.restoreMailboxWithId(ssm, id);
if (m != null) {
// We ignore drafts completely (doesn't sync). Changes in Outbox are
// handled in the checkMailboxes loop, so we can ignore these pings.
if (sUserLog) {
Log.d(TAG, "Alert for mailbox " + id + " (" + m.mDisplayName + ")");
}
if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) {
String[] args = new String[] {Long.toString(m.mId)};
ContentResolver resolver = INSTANCE.mResolver;
resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY,
args);
resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY,
args);
return;
}
service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey);
service.mMailbox = m;
// Send the alarm to the sync service
if (!service.alarm()) {
// A false return means that we were forced to interrupt the thread
// In this case, we release the mailbox so that we can start another
// thread to do the work
log("Alarm failed; releasing mailbox");
synchronized(sSyncLock) {
ssm.releaseMailbox(id);
}
// Shutdown the connection manager; this should close all of our
// sockets and generate IOExceptions all around.
SyncManager.shutdownConnectionManager();
}
}
}}, threadName).start();
}
}
}
public class ConnectivityReceiver extends BroadcastReceiver {
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Bundle b = intent.getExtras();
if (b != null) {
NetworkInfo a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_NETWORK_INFO);
String info = "Connectivity alert for " + a.getTypeName();
State state = a.getState();
if (state == State.CONNECTED) {
info += " CONNECTED";
log(info);
synchronized (sConnectivityLock) {
sConnectivityLock.notifyAll();
}
kick("connected");
} else if (state == State.DISCONNECTED) {
info += " DISCONNECTED";
log(info);
kick("disconnected");
}
}
} else if (intent.getAction().equals(
ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED)) {
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
mBackgroundData = cm.getBackgroundDataSetting();
// If background data is now on, we want to kick SyncServiceManager
if (mBackgroundData) {
kick("background data on");
log("Background data on; restart syncs");
// Otherwise, stop all syncs
} else {
log("Background data off: stop all syncs");
EmailAsyncTask.runAsyncParallel(new Runnable() {
@Override
public void run() {
synchronized (mAccountList) {
for (Account account : mAccountList)
SyncManager.stopAccountSyncs(account.mId);
}
}});
}
}
}
}
/**
* Starts a service thread and enters it into the service map
* This is the point of instantiation of all sync threads
* @param service the service to start
* @param m the Mailbox on which the service will operate
*/
private void startServiceThread(AbstractSyncService service) {
synchronized (sSyncLock) {
Mailbox mailbox = service.mMailbox;
String mailboxName = mailbox.mDisplayName;
String accountName = service.mAccount.mDisplayName;
Thread thread = new Thread(service, mailboxName + "[" + accountName + "]");
log("Starting thread for " + mailboxName + " in account " + accountName);
thread.start();
mServiceMap.put(mailbox.mId, service);
runAwake(mailbox.mId);
if (mailbox.mServerId != null && mailbox.mType != Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
stopPing(mailbox.mAccountKey);
}
}
}
/**
* Stop any ping in progress for the given account
* @param accountId
*/
private void stopPing(long accountId) {
// Go through our active mailboxes looking for the right one
synchronized (sSyncLock) {
AbstractSyncService serviceToReset = null;
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m != null) {
String serverId = m.mServerId;
if (m.mAccountKey == accountId && serverId != null &&
m.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
// Here's our account mailbox; reset him (stopping pings)
serviceToReset = mServiceMap.get(mailboxId);
break;
}
}
}
if (serviceToReset != null) {
serviceToReset.reset();
}
}
}
private void requestSync(Mailbox m, int reason, Request req) {
int syncStatus = EmailContent.SYNC_STATUS_BACKGROUND;
// Don't sync if there's no connectivity
if (sConnectivityHold || (m == null) || sStop) {
if (reason >= SYNC_CALLBACK_START) {
try {
Stub proxy = getCallbackProxy();
if (proxy != null) {
proxy.syncMailboxStatus(m.mId, EmailServiceStatus.CONNECTION_ERROR, 0);
}
} catch (RemoteException e) {
// We tried...
}
}
return;
}
synchronized (sSyncLock) {
Account acct = Account.restoreAccountWithId(this, m.mAccountKey);
if (acct != null) {
// Always make sure there's not a running instance of this service
AbstractSyncService service = mServiceMap.get(m.mId);
if (service == null) {
service = getServiceForMailbox(this, m);
if (!service.mIsValid) return;
service.mSyncReason = reason;
if (req != null) {
service.addRequest(req);
}
startServiceThread(service);
if (reason >= SYNC_CALLBACK_START) {
syncStatus = EmailContent.SYNC_STATUS_USER;
}
setMailboxSyncStatus(m.mId, syncStatus);
}
}
}
}
public void setMailboxSyncStatus(long id, int status) {
ContentValues values = new ContentValues();
values.put(Mailbox.UI_SYNC_STATUS, status);
mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, null);
}
public void setMailboxLastSyncResult(long id, int result) {
ContentValues values = new ContentValues();
values.put(Mailbox.UI_LAST_SYNC_RESULT, result);
mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, null);
}
private void stopServiceThreads() {
synchronized (sSyncLock) {
ArrayList<Long> toStop = new ArrayList<Long>();
// Keep track of which services to stop
for (Long mailboxId : mServiceMap.keySet()) {
toStop.add(mailboxId);
}
// Shut down all of those running services
for (Long mailboxId : toStop) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc != null) {
log("Stopping " + svc.mAccount.mDisplayName + '/' + svc.mMailbox.mDisplayName);
svc.stop();
if (svc.mThread != null) {
svc.mThread.interrupt();
}
}
releaseWakeLock(mailboxId);
}
}
}
private void waitForConnectivity() {
boolean waiting = false;
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
while (!sStop) {
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
mNetworkInfo = info;
// We're done if there's an active network
if (waiting) {
// If we've been waiting, release any I/O error holds
releaseSyncHolds(this, AbstractSyncService.EXIT_IO_ERROR, null);
// And log what's still being held
logSyncHolds();
}
return;
} else {
// If this is our first time through the loop, shut down running service threads
if (!waiting) {
waiting = true;
stopServiceThreads();
}
// Wait until a network is connected (or 10 mins), but let the device sleep
// We'll set an alarm just in case we don't get notified (bugs happen)
synchronized (sConnectivityLock) {
runAsleep(EXTRA_MAILBOX_ID, CONNECTIVITY_WAIT_TIME+5*SECONDS);
try {
log("Connectivity lock...");
sConnectivityHold = true;
sConnectivityLock.wait(CONNECTIVITY_WAIT_TIME);
log("Connectivity lock released...");
} catch (InterruptedException e) {
// This is fine; we just go around the loop again
} finally {
sConnectivityHold = false;
}
runAwake(EXTRA_MAILBOX_ID);
}
}
}
}
/**
* Note that there are two ways the EAS SyncServiceManager service can be created:
*
* 1) as a background service instantiated via startService (which happens on boot, when the
* first EAS account is created, etc), in which case the service thread is spun up, mailboxes
* sync, etc. and
* 2) to execute an RPC call from the UI, in which case the background service will already be
* running most of the time (unless we're creating a first EAS account)
*
* If the running background service detects that there are no EAS accounts (on boot, if none
* were created, or afterward if the last remaining EAS account is deleted), it will call
* stopSelf() to terminate operation.
*
* The goal is to ensure that the background service is running at all times when there is at
* least one EAS account in existence
*
* Because there are edge cases in which our process can crash (typically, this has been seen
* in UI crashes, ANR's, etc.), it's possible for the UI to start up again without the
* background service having been started. We explicitly try to start the service in Welcome
* (to handle the case of the app having been reloaded). We also start the service on any
* startSync call (if it isn't already running)
*/
@SuppressWarnings("deprecation")
@Override
public void onCreate() {
Utility.runAsync(new Runnable() {
@Override
public void run() {
// Quick checks first, before getting the lock
if (sStartingUp) return;
synchronized (sSyncLock) {
alwaysLog("!!! EAS SyncServiceManager, onCreate");
// Try to start up properly; we might be coming back from a crash that the Email
// application isn't aware of.
startService(new Intent(getServiceIntentAction()));
if (sStop) {
return;
}
}
}});
}
@SuppressWarnings("deprecation")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
alwaysLog("!!! EAS SyncServiceManager, onStartCommand, startingUp = " + sStartingUp +
", running = " + (INSTANCE != null));
if (!sStartingUp && INSTANCE == null) {
sStartingUp = true;
Utility.runAsync(new Runnable() {
@Override
public void run() {
try {
synchronized (sSyncLock) {
// SyncServiceManager cannot start unless we connect to AccountService
if (!new AccountServiceProxy(SyncManager.this).test()) {
alwaysLog("!!! Email application not found; stopping self");
stopSelf();
}
if (sDeviceId == null) {
try {
String deviceId = getDeviceId(SyncManager.this);
if (deviceId != null) {
sDeviceId = deviceId;
}
} catch (IOException e) {
}
if (sDeviceId == null) {
alwaysLog("!!! deviceId unknown; stopping self and retrying");
stopSelf();
// Try to restart ourselves in a few seconds
Utility.runAsync(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
startService(new Intent(getServiceIntentAction()));
}});
return;
}
}
// Run the reconciler and clean up mismatched accounts - if we weren't
// running when accounts were deleted, it won't have been called.
runAccountReconcilerSync(SyncManager.this);
// Update other services depending on final account configuration
maybeStartSyncServiceManagerThread();
if (sServiceThread == null) {
log("!!! EAS SyncServiceManager, stopping self");
stopSelf();
} else if (sStop) {
// If we were trying to stop, attempt a restart in 5 secs
setAlarm(SYNC_SERVICE_MAILBOX_ID, 5*SECONDS);
}
}
} finally {
sStartingUp = false;
}
}});
}
return Service.START_STICKY;
}
public static void reconcileAccounts(Context context) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.runAccountReconcilerSync(context);
}
}
protected abstract void runAccountReconcilerSync(Context context);
@SuppressWarnings("deprecation")
@Override
public void onDestroy() {
log("!!! EAS SyncServiceManager, onDestroy");
// Handle shutting down off the UI thread
Utility.runAsync(new Runnable() {
@Override
public void run() {
// Quick checks first, before getting the lock
if (INSTANCE == null || sServiceThread == null) return;
synchronized(sSyncLock) {
// Stop the sync manager thread and return
if (sServiceThread != null) {
sStop = true;
sServiceThread.interrupt();
}
}
}});
}
void maybeStartSyncServiceManagerThread() {
// Start our thread...
// See if there are any EAS accounts; otherwise, just go away
if (sServiceThread == null || !sServiceThread.isAlive()) {
AccountList currentAccounts = new AccountList();
try {
collectAccounts(this, currentAccounts);
} catch (ProviderUnavailableException e) {
// Just leave if EmailProvider is unavailable
return;
}
if (!currentAccounts.isEmpty()) {
log(sServiceThread == null ? "Starting thread..." : "Restarting thread...");
sServiceThread = new Thread(this, TAG);
INSTANCE = this;
sServiceThread.start();
}
}
}
/**
* Start up the SyncServiceManager service if it's not already running
* This is a stopgap for cases in which SyncServiceManager died (due to a crash somewhere in
* com.android.email) and hasn't been restarted. See the comment for onCreate for details
*/
static void checkSyncServiceManagerServiceRunning() {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
if (sServiceThread == null) {
log("!!! checkSyncServiceManagerServiceRunning; starting service...");
ssm.startService(new Intent(ssm, SyncManager.class));
}
}
@SuppressWarnings("deprecation")
@Override
public void run() {
sStop = false;
alwaysLog("SyncServiceManager thread running");
TempDirectory.setTempDirectory(this);
// Synchronize here to prevent a shutdown from happening while we initialize our observers
// and receivers
synchronized (sSyncLock) {
if (INSTANCE != null) {
mResolver = getContentResolver();
// Set up our observers; we need them to know when to start/stop various syncs based
// on the insert/delete/update of mailboxes and accounts
// We also observe synced messages to trigger upsyncs at the appropriate time
mAccountObserver = getAccountObserver(mHandler);
mResolver.registerContentObserver(Account.NOTIFIER_URI, true, mAccountObserver);
mMailboxObserver = new MailboxObserver(mHandler);
mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver);
mSyncedMessageObserver = new SyncedMessageObserver(mHandler);
mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true,
mSyncedMessageObserver);
// Set up receivers for connectivity and background data setting
mConnectivityReceiver = new ConnectivityReceiver();
registerReceiver(mConnectivityReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
mBackgroundDataSettingReceiver = new ConnectivityReceiver();
registerReceiver(mBackgroundDataSettingReceiver, new IntentFilter(
ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
// Save away the current background data setting; we'll keep track of it with the
// receiver we just registered
ConnectivityManager cm = (ConnectivityManager)getSystemService(
Context.CONNECTIVITY_SERVICE);
mBackgroundData = cm.getBackgroundDataSetting();
onStartup();
}
}
try {
// Loop indefinitely until we're shut down
while (!sStop) {
runAwake(EXTRA_MAILBOX_ID);
waitForConnectivity();
mNextWaitReason = null;
long nextWait = checkMailboxes();
try {
synchronized (this) {
if (!mKicked) {
if (nextWait < 0) {
log("Negative wait? Setting to 1s");
nextWait = 1*SECONDS;
}
if (nextWait > 10*SECONDS) {
if (mNextWaitReason != null) {
log("Next awake " + nextWait / 1000 + "s: " + mNextWaitReason);
}
runAsleep(EXTRA_MAILBOX_ID, nextWait + (3*SECONDS));
}
wait(nextWait);
}
}
} catch (InterruptedException e) {
// Needs to be caught, but causes no problem
log("SyncServiceManager interrupted");
} finally {
synchronized (this) {
if (mKicked) {
//log("Wait deferred due to kick");
mKicked = false;
}
}
}
}
log("Shutdown requested");
} catch (ProviderUnavailableException pue) {
// Shutdown cleanly in this case
// NOTE: Sync adapters will also crash with this error, but that is already handled
// in the adapters themselves, i.e. they return cleanly via done(). When the Email
// process starts running again, remote processes will be started again in due course
Log.e(TAG, "EmailProvider unavailable; shutting down");
// Ask for our service to be restarted; this should kick-start the Email process as well
startService(new Intent(this, SyncManager.class));
} catch (RuntimeException e) {
// Crash; this is a completely unexpected runtime error
Log.e(TAG, "RuntimeException in SyncServiceManager", e);
throw e;
} finally {
shutdown();
}
}
private void shutdown() {
synchronized (sSyncLock) {
// If INSTANCE is null, we've already been shut down
if (INSTANCE != null) {
log("SyncServiceManager shutting down...");
// Stop our running syncs
stopServiceThreads();
// Stop receivers
if (mConnectivityReceiver != null) {
unregisterReceiver(mConnectivityReceiver);
}
if (mBackgroundDataSettingReceiver != null) {
unregisterReceiver(mBackgroundDataSettingReceiver);
}
// Unregister observers
ContentResolver resolver = getContentResolver();
if (mSyncedMessageObserver != null) {
resolver.unregisterContentObserver(mSyncedMessageObserver);
mSyncedMessageObserver = null;
}
if (mAccountObserver != null) {
resolver.unregisterContentObserver(mAccountObserver);
mAccountObserver = null;
}
if (mMailboxObserver != null) {
resolver.unregisterContentObserver(mMailboxObserver);
mMailboxObserver = null;
}
unregisterCalendarObservers();
// Clear pending alarms and associated Intents
clearAlarms();
// Release our wake lock, if we have one
synchronized (mWakeLocks) {
if (mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
}
}
INSTANCE = null;
sServiceThread = null;
sStop = false;
log("Goodbye");
}
}
}
/**
* Release a mailbox from the service map and release its wake lock.
* NOTE: This method MUST be called while holding sSyncLock!
*
* @param mailboxId the id of the mailbox to be released
*/
public void releaseMailbox(long mailboxId) {
mServiceMap.remove(mailboxId);
releaseWakeLock(mailboxId);
}
/**
* Check whether an Outbox (referenced by a Cursor) has any messages that can be sent
* @param c the cursor to an Outbox
* @return true if there is mail to be sent
*/
private boolean hasSendableMessages(Cursor outboxCursor) {
Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION,
MAILBOX_KEY_AND_NOT_SEND_FAILED,
new String[] {Long.toString(outboxCursor.getLong(Mailbox.CONTENT_ID_COLUMN))},
null);
try {
while (c.moveToNext()) {
if (!Utility.hasUnloadedAttachments(this, c.getLong(Message.CONTENT_ID_COLUMN))) {
return true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Taken from ConnectivityManager using public constants
*/
public static boolean isNetworkTypeMobile(int networkType) {
switch (networkType) {
case ConnectivityManager.TYPE_MOBILE:
case ConnectivityManager.TYPE_MOBILE_MMS:
case ConnectivityManager.TYPE_MOBILE_SUPL:
case ConnectivityManager.TYPE_MOBILE_DUN:
case ConnectivityManager.TYPE_MOBILE_HIPRI:
return true;
default:
return false;
}
}
/**
* Determine whether the account is allowed to sync automatically, as opposed to manually, based
* on whether the "require manual sync when roaming" policy is in force and applicable
* @param account the account
* @return whether or not the account can sync automatically
*/
/*package*/ public static boolean canAutoSync(Account account) {
SyncManager ssm = INSTANCE;
if (ssm == null) {
return false;
}
NetworkInfo networkInfo = ssm.mNetworkInfo;
// Enforce manual sync only while roaming here
long policyKey = account.mPolicyKey;
// Quick exit from this check
if ((policyKey != 0) && (networkInfo != null) &&
isNetworkTypeMobile(networkInfo.getType())) {
// We'll cache the Policy data here
Policy policy = account.mPolicy;
if (policy == null) {
policy = Policy.restorePolicyWithId(INSTANCE, policyKey);
account.mPolicy = policy;
if (!PolicyServiceProxy.isActive(ssm, policy)) return false;
}
if (policy != null && policy.mRequireManualSyncWhenRoaming && networkInfo.isRoaming()) {
return false;
}
}
return true;
}
/**
* Convenience method to determine whether Email sync is enabled for a given account
* @param account the Account in question
* @return whether Email sync is enabled
*/
private boolean canSyncEmail(android.accounts.Account account) {
return ContentResolver.getSyncAutomatically(account, EmailContent.AUTHORITY);
}
/**
* Determine whether a mailbox of a given type in a given account can be synced automatically
* by SyncServiceManager. This is an increasingly complex determination, taking into account
* security policies and user settings (both within the Email application and in the Settings
* application)
*
* @param account the Account that the mailbox is in
* @param type the type of the Mailbox
* @return whether or not to start a sync
*/
private boolean isMailboxSyncable(Account account, int type) {
// This 'if' statement performs checks to see whether or not a mailbox is a
// candidate for syncing based on policies, user settings, & other restrictions
if (type == Mailbox.TYPE_OUTBOX) {
// Outbox is always syncable
return true;
} else if (type == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
// Always sync EAS mailbox unless master sync is off
return ContentResolver.getMasterSyncAutomatically();
} else if (type == Mailbox.TYPE_CONTACTS || type == Mailbox.TYPE_CALENDAR) {
// Contacts/Calendar obey this setting from ContentResolver
if (!ContentResolver.getMasterSyncAutomatically()) {
return false;
}
// Get the right authority for the mailbox
String authority;
if (type == Mailbox.TYPE_CONTACTS) {
authority = ContactsContract.AUTHORITY;
} else {
authority = CalendarContract.AUTHORITY;
if (!mCalendarObservers.containsKey(account.mId)){
// Make sure we have an observer for this Calendar, as
// we need to be able to detect sync state changes, sigh
registerCalendarObserver(account);
}
}
// See if "sync automatically" is set; if not, punt
if (!ContentResolver.getSyncAutomatically(account.mAmAccount, authority)) {
return false;
// See if the calendar is enabled from the Calendar app UI; if not, punt
} else if ((type == Mailbox.TYPE_CALENDAR) && !isCalendarEnabled(account.mId)) {
return false;
}
// Never automatically sync trash
} else if (type == Mailbox.TYPE_TRASH) {
return false;
// For non-outbox, non-account mail, we do three checks:
// 1) are we restricted by policy (i.e. manual sync only),
// 2) has the user checked the "Sync Email" box in Account Settings, and
// 3) does the user have the master "background data" box checked in Settings
} else if (!canAutoSync(account) || !canSyncEmail(account.mAmAccount) || !mBackgroundData) {
return false;
}
return true;
}
private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncLock) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_SERVICE_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
if (mAccountObserver == null) {
log("mAccountObserver null; service died??");
return nextWait;
}
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableMailboxWhere(), null, null);
if (c == null) throw new ProviderUnavailableException();
try {
while (c.moveToNext()) {
long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncLock) {
service = mServiceMap.get(mailboxId);
}
if (service == null) {
// Get the cached account
Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account == null) continue;
// We handle a few types of mailboxes specially
int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (!isMailboxSyncable(account, mailboxType)) {
continue;
}
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mailboxId);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// Otherwise, we use the sync interval
long syncInterval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (syncInterval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_PUSH, null);
} else if (mailboxType == Mailbox.TYPE_OUTBOX) {
if (hasSendableMessages(c)) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startServiceThread(getServiceForMailbox(this, m));
}
} else if (syncInterval > 0 && syncInterval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
long toNextSync = syncInterval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (sUserLog) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (sUserLog) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died and remove them from the map
if (thread != null && !thread.isAlive()) {
if (sUserLog) {
log("Dead thread, mailbox released: " +
c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN));
}
- releaseMailbox(mailboxId);
+ synchronized (sSyncLock) {
+ releaseMailbox(mailboxId);
+ }
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (timeToRequest <= 0) {
service.mRequestTime = 0;
service.alarm();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
static public void serviceRequest(long mailboxId, int reason) {
serviceRequest(mailboxId, 5*SECONDS, reason);
}
/**
* Return a boolean indicating whether the mailbox can be synced
* @param m the mailbox
* @return whether or not the mailbox can be synced
*/
public static boolean isSyncable(Mailbox m) {
return m.mType != Mailbox.TYPE_DRAFTS
&& m.mType != Mailbox.TYPE_OUTBOX
&& m.mType != Mailbox.TYPE_SEARCH
&& m.mType < Mailbox.TYPE_NOT_SYNCABLE;
}
static public void serviceRequest(long mailboxId, long ms, int reason) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (m == null || !isSyncable(m)) return;
try {
AbstractSyncService service = ssm.mServiceMap.get(mailboxId);
if (service != null) {
service.mRequestTime = System.currentTimeMillis() + ms;
kick("service request");
} else {
startManualSync(mailboxId, reason, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
static public void serviceRequestImmediate(long mailboxId) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
AbstractSyncService service = ssm.mServiceMap.get(mailboxId);
if (service != null) {
service.mRequestTime = System.currentTimeMillis();
Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (m != null) {
service.mAccount = Account.restoreAccountWithId(ssm, m.mAccountKey);
service.mMailbox = m;
kick("service request immediate");
}
}
}
static public void sendMessageRequest(Request req) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
Message msg = Message.restoreMessageWithId(ssm, req.mMessageId);
if (msg == null) return;
long mailboxId = msg.mMailboxKey;
Mailbox mailbox = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (mailbox == null) return;
// If we're loading an attachment for Outbox, we want to look at the source message
// to find the loading mailbox
if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
long sourceId = Utility.getFirstRowLong(ssm, Body.CONTENT_URI,
new String[] {BodyColumns.SOURCE_MESSAGE_KEY},
BodyColumns.MESSAGE_KEY + "=?",
new String[] {Long.toString(msg.mId)}, null, 0, -1L);
if (sourceId != -1L) {
EmailContent.Message sourceMsg =
EmailContent.Message.restoreMessageWithId(ssm, sourceId);
if (sourceMsg != null) {
mailboxId = sourceMsg.mMailboxKey;
}
}
}
sendRequest(mailboxId, req);
}
static public void sendRequest(long mailboxId, Request req) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
AbstractSyncService service = ssm.mServiceMap.get(mailboxId);
if (service == null) {
startManualSync(mailboxId, SYNC_SERVICE_PART_REQUEST, req);
kick("part request");
} else {
service.addRequest(req);
}
}
/**
* Determine whether a given Mailbox can be synced, i.e. is not already syncing and is not in
* an error state
*
* @param mailboxId
* @return whether or not the Mailbox is available for syncing (i.e. is a valid push target)
*/
static public int pingStatus(long mailboxId) {
SyncManager ssm = INSTANCE;
if (ssm == null) return PING_STATUS_OK;
// Already syncing...
if (ssm.mServiceMap.get(mailboxId) != null) {
return PING_STATUS_RUNNING;
}
// No errors or a transient error, don't ping...
SyncError error = ssm.mSyncErrorMap.get(mailboxId);
if (error != null) {
if (error.fatal) {
return PING_STATUS_UNABLE;
} else if (error.holdEndTime > 0) {
return PING_STATUS_WAITING;
}
}
return PING_STATUS_OK;
}
static public void startManualSync(long mailboxId, int reason, Request req) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
synchronized (sSyncLock) {
AbstractSyncService svc = ssm.mServiceMap.get(mailboxId);
if (svc == null) {
ssm.mSyncErrorMap.remove(mailboxId);
Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (m != null) {
log("Starting sync for " + m.mDisplayName);
ssm.requestSync(m, reason, req);
}
} else {
// If this is a ui request, set the sync reason for the service
if (reason >= SYNC_CALLBACK_START) {
svc.mSyncReason = reason;
}
}
}
}
// DO NOT CALL THIS IN A LOOP ON THE SERVICEMAP
static public void stopManualSync(long mailboxId) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
synchronized (sSyncLock) {
AbstractSyncService svc = ssm.mServiceMap.get(mailboxId);
if (svc != null) {
log("Stopping sync for " + svc.mMailboxName);
svc.stop();
svc.mThread.interrupt();
ssm.releaseWakeLock(mailboxId);
}
}
}
/**
* Wake up SyncServiceManager to check for mailboxes needing service
*/
static public void kick(String reason) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
synchronized (ssm) {
//INSTANCE.log("Kick: " + reason);
ssm.mKicked = true;
ssm.notify();
}
}
if (sConnectivityLock != null) {
synchronized (sConnectivityLock) {
sConnectivityLock.notify();
}
}
}
/**
* Tell SyncServiceManager to remove the mailbox from the map of mailboxes with sync errors
* @param mailboxId the id of the mailbox
*/
static public void removeFromSyncErrorMap(long mailboxId) {
SyncManager ssm = INSTANCE;
if (ssm != null) {
ssm.mSyncErrorMap.remove(mailboxId);
}
}
private boolean isRunningInServiceThread(long mailboxId) {
AbstractSyncService syncService = mServiceMap.get(mailboxId);
Thread thisThread = Thread.currentThread();
return syncService != null && syncService.mThread != null &&
thisThread == syncService.mThread;
}
/**
* Sent by services indicating that their thread is finished; action depends on the exitStatus
* of the service.
*
* @param svc the service that is finished
*/
static public void done(AbstractSyncService svc) {
SyncManager ssm = INSTANCE;
if (ssm == null) return;
synchronized(sSyncLock) {
long mailboxId = svc.mMailboxId;
// If we're no longer the syncing thread for the mailbox, just return
if (!ssm.isRunningInServiceThread(mailboxId)) {
return;
}
ssm.releaseMailbox(mailboxId);
ssm.setMailboxSyncStatus(mailboxId, EmailContent.SYNC_STATUS_NONE);
ConcurrentHashMap<Long, SyncError> errorMap = ssm.mSyncErrorMap;
SyncError syncError = errorMap.get(mailboxId);
int exitStatus = svc.mExitStatus;
Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
if (m == null) return;
if (exitStatus != AbstractSyncService.EXIT_LOGIN_FAILURE) {
long accountId = m.mAccountKey;
Account account = Account.restoreAccountWithId(ssm, accountId);
if (account == null) return;
if (ssm.releaseSyncHolds(ssm,
AbstractSyncService.EXIT_LOGIN_FAILURE, account)) {
new AccountServiceProxy(ssm).notifyLoginSucceeded(accountId);
}
}
int lastResult = EmailContent.LAST_SYNC_RESULT_SUCCESS;
// For error states, whether the error is fatal (won't automatically be retried)
boolean errorIsFatal = true;
try {
switch (exitStatus) {
case AbstractSyncService.EXIT_DONE:
if (svc.hasPendingRequests()) {
// TODO Handle this case
}
errorMap.remove(mailboxId);
// If we've had a successful sync, clear the shutdown count
synchronized (SyncManager.class) {
sClientConnectionManagerShutdownCount = 0;
}
// Leave now; other statuses are errors
return;
// I/O errors get retried at increasing intervals
case AbstractSyncService.EXIT_IO_ERROR:
if (syncError != null) {
syncError.escalate();
log(m.mDisplayName + " held for " + syncError.holdDelay + "ms");
return;
} else {
log(m.mDisplayName + " added to syncErrorMap, hold for 15s");
}
lastResult = EmailContent.LAST_SYNC_RESULT_CONNECTION_ERROR;
errorIsFatal = false;
break;
// These errors are not retried automatically
case AbstractSyncService.EXIT_LOGIN_FAILURE:
new AccountServiceProxy(ssm).notifyLoginFailed(m.mAccountKey, svc.mExitReason);
lastResult = EmailContent.LAST_SYNC_RESULT_AUTH_ERROR;
break;
case AbstractSyncService.EXIT_SECURITY_FAILURE:
case AbstractSyncService.EXIT_ACCESS_DENIED:
lastResult = EmailContent.LAST_SYNC_RESULT_SECURITY_ERROR;
break;
case AbstractSyncService.EXIT_EXCEPTION:
lastResult = EmailContent.LAST_SYNC_RESULT_INTERNAL_ERROR;
break;
}
// Add this box to the error map
errorMap.put(mailboxId, ssm.new SyncError(exitStatus, errorIsFatal));
} finally {
// Always set the last result
ssm.setMailboxLastSyncResult(mailboxId, lastResult);
kick("sync completed");
}
}
}
/**
* Given the status string from a Mailbox, return the type code for the last sync
* @param status the syncStatus column of a Mailbox
* @return
*/
static public int getStatusType(String status) {
if (status == null) {
return -1;
} else {
return status.charAt(STATUS_TYPE_CHAR) - '0';
}
}
/**
* Given the status string from a Mailbox, return the change count for the last sync
* The change count is the number of adds + deletes + changes in the last sync
* @param status the syncStatus column of a Mailbox
* @return
*/
static public int getStatusChangeCount(String status) {
try {
String s = status.substring(STATUS_CHANGE_COUNT_OFFSET);
return Integer.parseInt(s);
} catch (RuntimeException e) {
return -1;
}
}
static public Context getContext() {
return INSTANCE;
}
}
| true | true | private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncLock) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_SERVICE_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
if (mAccountObserver == null) {
log("mAccountObserver null; service died??");
return nextWait;
}
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableMailboxWhere(), null, null);
if (c == null) throw new ProviderUnavailableException();
try {
while (c.moveToNext()) {
long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncLock) {
service = mServiceMap.get(mailboxId);
}
if (service == null) {
// Get the cached account
Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account == null) continue;
// We handle a few types of mailboxes specially
int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (!isMailboxSyncable(account, mailboxType)) {
continue;
}
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mailboxId);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// Otherwise, we use the sync interval
long syncInterval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (syncInterval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_PUSH, null);
} else if (mailboxType == Mailbox.TYPE_OUTBOX) {
if (hasSendableMessages(c)) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startServiceThread(getServiceForMailbox(this, m));
}
} else if (syncInterval > 0 && syncInterval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
long toNextSync = syncInterval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (sUserLog) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (sUserLog) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died and remove them from the map
if (thread != null && !thread.isAlive()) {
if (sUserLog) {
log("Dead thread, mailbox released: " +
c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN));
}
releaseMailbox(mailboxId);
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (timeToRequest <= 0) {
service.mRequestTime = 0;
service.alarm();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
| private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncLock) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_SERVICE_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
if (mAccountObserver == null) {
log("mAccountObserver null; service died??");
return nextWait;
}
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableMailboxWhere(), null, null);
if (c == null) throw new ProviderUnavailableException();
try {
while (c.moveToNext()) {
long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncLock) {
service = mServiceMap.get(mailboxId);
}
if (service == null) {
// Get the cached account
Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account == null) continue;
// We handle a few types of mailboxes specially
int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (!isMailboxSyncable(account, mailboxType)) {
continue;
}
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mailboxId);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// Otherwise, we use the sync interval
long syncInterval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (syncInterval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_PUSH, null);
} else if (mailboxType == Mailbox.TYPE_OUTBOX) {
if (hasSendableMessages(c)) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startServiceThread(getServiceForMailbox(this, m));
}
} else if (syncInterval > 0 && syncInterval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
long toNextSync = syncInterval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
requestSync(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (sUserLog) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (sUserLog) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died and remove them from the map
if (thread != null && !thread.isAlive()) {
if (sUserLog) {
log("Dead thread, mailbox released: " +
c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN));
}
synchronized (sSyncLock) {
releaseMailbox(mailboxId);
}
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (timeToRequest <= 0) {
service.mRequestTime = 0;
service.alarm();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
|
diff --git a/services/java/com/android/server/pm/PackageManagerService.java b/services/java/com/android/server/pm/PackageManagerService.java
index 0b0505a5..fc81033c 100644
--- a/services/java/com/android/server/pm/PackageManagerService.java
+++ b/services/java/com/android/server/pm/PackageManagerService.java
@@ -1,11143 +1,11146 @@
/*
* Copyright (C) 2006 The Android Open Source Project
* This code has been modified. Portions copyright (C) 2010, T-Mobile USA, 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.android.server.pm;
import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
import static com.android.internal.util.ArrayUtils.appendInt;
import static com.android.internal.util.ArrayUtils.removeInt;
import static libcore.io.OsConstants.S_IRWXU;
import static libcore.io.OsConstants.S_IRGRP;
import static libcore.io.OsConstants.S_IXGRP;
import static libcore.io.OsConstants.S_IROTH;
import static libcore.io.OsConstants.S_IXOTH;
import com.android.internal.app.IAssetRedirectionManager;
import com.android.internal.app.IMediaContainerService;
import com.android.internal.app.ResolverActivity;
import com.android.internal.content.NativeLibraryHelper;
import com.android.internal.content.PackageHelper;
import com.android.internal.util.FastXmlSerializer;
import com.android.internal.util.XmlUtils;
import com.android.server.DeviceStorageMonitorService;
import com.android.server.EventLogTags;
import com.android.server.IntentResolver;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.admin.IDevicePolicyManager;
import android.app.backup.IBackupManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.IIntentReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.IntentSender.SendIntentException;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ContainerEncryptionParams;
import android.content.pm.FeatureInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageDeleteObserver;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.IPackageManager;
import android.content.pm.IPackageMoveObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.InstrumentationInfo;
import android.content.pm.PackageCleanItem;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInfoLite;
import android.content.pm.PackageManager;
import android.content.pm.PackageParser;
import android.content.pm.PackageUserState;
import android.content.pm.PackageParser.ActivityIntentInfo;
import android.content.pm.PackageStats;
import android.content.pm.ParceledListSlice;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.Signature;
import android.content.pm.ManifestDigest;
import android.content.pm.VerificationParams;
import android.content.pm.VerifierDeviceIdentity;
import android.content.pm.VerifierInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.os.FileUtils;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.RemoteException;
import android.os.SELinux;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.Environment.UserEnvironment;
import android.os.UserManager;
import android.provider.Settings.Secure;
import android.security.KeyStore;
import android.security.SystemKeyStore;
import android.util.DisplayMetrics;
import android.util.EventLog;
import android.util.Log;
import android.util.LogPrinter;
import android.util.Slog;
import android.util.SparseArray;
import android.util.Xml;
import android.view.Display;
import android.view.WindowManager;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import libcore.io.ErrnoException;
import libcore.io.IoUtils;
import libcore.io.Libcore;
import libcore.io.StructStat;
/**
* Keep track of all those .apks everywhere.
*
* This is very central to the platform's security; please run the unit
* tests whenever making modifications here:
*
mmm frameworks/base/tests/AndroidTests
adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
*
* {@hide}
*/
public class PackageManagerService extends IPackageManager.Stub {
static final String TAG = "PackageManager";
static final boolean DEBUG_SETTINGS = false;
static final boolean DEBUG_PREFERRED = false;
static final boolean DEBUG_UPGRADE = false;
private static final boolean DEBUG_INSTALL = false;
private static final boolean DEBUG_REMOVE = false;
private static final boolean DEBUG_BROADCASTS = false;
private static final boolean DEBUG_SHOW_INFO = false;
private static final boolean DEBUG_PACKAGE_INFO = false;
private static final boolean DEBUG_INTENT_MATCHING = false;
private static final boolean DEBUG_PACKAGE_SCANNING = false;
private static final boolean DEBUG_APP_DIR_OBSERVER = false;
private static final boolean DEBUG_VERIFY = false;
private static final int RADIO_UID = Process.PHONE_UID;
private static final int LOG_UID = Process.LOG_UID;
private static final int NFC_UID = Process.NFC_UID;
private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
private static final int SHELL_UID = Process.SHELL_UID;
private static final boolean GET_CERTIFICATES = true;
private static final int REMOVE_EVENTS =
FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
private static final int ADD_EVENTS =
FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
// Suffix used during package installation when copying/moving
// package apks to install directory.
private static final String INSTALL_PACKAGE_SUFFIX = "-";
private static final int THEME_MAMANER_GUID = 1300;
static final int SCAN_MONITOR = 1<<0;
static final int SCAN_NO_DEX = 1<<1;
static final int SCAN_FORCE_DEX = 1<<2;
static final int SCAN_UPDATE_SIGNATURE = 1<<3;
static final int SCAN_NEW_INSTALL = 1<<4;
static final int SCAN_NO_PATHS = 1<<5;
static final int SCAN_UPDATE_TIME = 1<<6;
static final int SCAN_DEFER_DEX = 1<<7;
static final int SCAN_BOOTING = 1<<8;
static final int REMOVE_CHATTY = 1<<16;
/**
* Whether verification is enabled by default.
*/
private static final boolean DEFAULT_VERIFY_ENABLE = true;
/**
* The default maximum time to wait for the verification agent to return in
* milliseconds.
*/
private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
/**
* The default response for package verification timeout.
*
* This can be either PackageManager.VERIFICATION_ALLOW or
* PackageManager.VERIFICATION_REJECT.
*/
private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
DEFAULT_CONTAINER_PACKAGE,
"com.android.defcontainer.DefaultContainerService");
private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
private static final String LIB_DIR_NAME = "lib";
static final String mTempContainerPrefix = "smdl2tmp";
final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
Process.THREAD_PRIORITY_BACKGROUND);
final PackageHandler mHandler;
final int mSdkVersion = Build.VERSION.SDK_INT;
final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
? null : Build.VERSION.CODENAME;
final Context mContext;
final boolean mFactoryTest;
final boolean mOnlyCore;
final boolean mNoDexOpt;
final DisplayMetrics mMetrics;
final int mDefParseFlags;
final String[] mSeparateProcesses;
// This is where all application persistent data goes.
final File mAppDataDir;
// This is where all application persistent data goes for secondary users.
final File mUserAppDataDir;
/** The location for ASEC container files on internal storage. */
final String mAsecInternalPath;
// This is the object monitoring the framework dir.
final FileObserver mFrameworkInstallObserver;
// This is the object monitoring the system app dir.
final FileObserver mSystemInstallObserver;
// This is the object monitoring the system app dir.
final FileObserver mVendorInstallObserver;
// This is the object monitoring mAppInstallDir.
final FileObserver mAppInstallObserver;
// This is the object monitoring mDrmAppPrivateInstallDir.
final FileObserver mDrmAppInstallObserver;
// Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
// LOCK HELD. Can be called with mInstallLock held.
final Installer mInstaller;
final File mFrameworkDir;
final File mSystemAppDir;
final File mVendorAppDir;
final File mAppInstallDir;
final File mDalvikCacheDir;
/**
* Directory to which applications installed internally have native
* libraries copied.
*/
private File mAppLibInstallDir;
// Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
// apps.
final File mDrmAppPrivateInstallDir;
// ----------------------------------------------------------------
// Lock for state used when installing and doing other long running
// operations. Methods that must be called with this lock held have
// the prefix "LI".
final Object mInstallLock = new Object();
// These are the directories in the 3rd party applications installed dir
// that we have currently loaded packages from. Keys are the application's
// installed zip file (absolute codePath), and values are Package.
final HashMap<String, PackageParser.Package> mAppDirs =
new HashMap<String, PackageParser.Package>();
// Information for the parser to write more useful error messages.
File mScanningPath;
int mLastScanError;
// ----------------------------------------------------------------
// Keys are String (package name), values are Package. This also serves
// as the lock for the global state. Methods that must be called with
// this lock held have the prefix "LP".
final HashMap<String, PackageParser.Package> mPackages =
new HashMap<String, PackageParser.Package>();
final Settings mSettings;
boolean mRestoredSettings;
// Group-ids that are given to all packages as read from etc/permissions/*.xml.
int[] mGlobalGids;
// These are the built-in uid -> permission mappings that were read from the
// etc/permissions.xml file.
final SparseArray<HashSet<String>> mSystemPermissions =
new SparseArray<HashSet<String>>();
static final class SharedLibraryEntry {
final String path;
final String apk;
SharedLibraryEntry(String _path, String _apk) {
path = _path;
apk = _apk;
}
}
// These are the built-in shared libraries that were read from the
// etc/permissions.xml file.
final HashMap<String, SharedLibraryEntry> mSharedLibraries
= new HashMap<String, SharedLibraryEntry>();
// Temporary for building the final shared libraries for an .apk.
String[] mTmpSharedLibraries = null;
// These are the features this devices supports that were read from the
// etc/permissions.xml file.
final HashMap<String, FeatureInfo> mAvailableFeatures =
new HashMap<String, FeatureInfo>();
// If mac_permissions.xml was found for seinfo labeling.
boolean mFoundPolicyFile;
// All available activities, for your resolving pleasure.
final ActivityIntentResolver mActivities =
new ActivityIntentResolver();
// All available receivers, for your resolving pleasure.
final ActivityIntentResolver mReceivers =
new ActivityIntentResolver();
// All available services, for your resolving pleasure.
final ServiceIntentResolver mServices = new ServiceIntentResolver();
// Keys are String (provider class name), values are Provider.
final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
new HashMap<ComponentName, PackageParser.Provider>();
// Mapping from provider base names (first directory in content URI codePath)
// to the provider information.
final HashMap<String, PackageParser.Provider> mProviders =
new HashMap<String, PackageParser.Provider>();
// Mapping from instrumentation class names to info about them.
final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
new HashMap<ComponentName, PackageParser.Instrumentation>();
// Mapping from permission names to info about them.
final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
new HashMap<String, PackageParser.PermissionGroup>();
// Packages whose data we have transfered into another package, thus
// should no longer exist.
final HashSet<String> mTransferedPackages = new HashSet<String>();
// Broadcast actions that are only available to the system.
final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
/** List of packages waiting for verification. */
final SparseArray<PackageVerificationState> mPendingVerification
= new SparseArray<PackageVerificationState>();
HashSet<PackageParser.Package> mDeferredDexOpt = null;
/** Token for keys in mPendingVerification. */
private int mPendingVerificationToken = 0;
boolean mSystemReady;
boolean mSafeMode;
boolean mHasSystemUidErrors;
ApplicationInfo mAndroidApplication;
final ActivityInfo mResolveActivity = new ActivityInfo();
final ResolveInfo mResolveInfo = new ResolveInfo();
ComponentName mResolveComponentName;
PackageParser.Package mPlatformPackage;
IAssetRedirectionManager mAssetRedirectionManager;
// Set of pending broadcasts for aggregating enable/disable of components.
static class PendingPackageBroadcasts {
// for each user id, a map of <package name -> components within that package>
final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
public PendingPackageBroadcasts() {
mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>();
}
public ArrayList<String> get(int userId, String packageName) {
HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
return packages.get(packageName);
}
public void put(int userId, String packageName, ArrayList<String> components) {
HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
packages.put(packageName, components);
}
public void remove(int userId, String packageName) {
HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
if (packages != null) {
packages.remove(packageName);
}
}
public void remove(int userId) {
mUidMap.remove(userId);
}
public int userIdCount() {
return mUidMap.size();
}
public int userIdAt(int n) {
return mUidMap.keyAt(n);
}
public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
return mUidMap.get(userId);
}
public int size() {
// total number of pending broadcast entries across all userIds
int num = 0;
for (int i = 0; i< mUidMap.size(); i++) {
num += mUidMap.valueAt(i).size();
}
return num;
}
public void clear() {
mUidMap.clear();
}
private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
if (map == null) {
map = new HashMap<String, ArrayList<String>>();
mUidMap.put(userId, map);
}
return map;
}
}
final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
// Service Connection to remote media container service to copy
// package uri's from external media onto secure containers
// or internal storage.
private IMediaContainerService mContainerService = null;
static final int SEND_PENDING_BROADCAST = 1;
static final int MCS_BOUND = 3;
static final int END_COPY = 4;
static final int INIT_COPY = 5;
static final int MCS_UNBIND = 6;
static final int START_CLEANING_PACKAGE = 7;
static final int FIND_INSTALL_LOC = 8;
static final int POST_INSTALL = 9;
static final int MCS_RECONNECT = 10;
static final int MCS_GIVE_UP = 11;
static final int UPDATED_MEDIA_STATUS = 12;
static final int WRITE_SETTINGS = 13;
static final int WRITE_PACKAGE_RESTRICTIONS = 14;
static final int PACKAGE_VERIFIED = 15;
static final int CHECK_PENDING_VERIFICATION = 16;
static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
// Delay time in millisecs
static final int BROADCAST_DELAY = 10 * 1000;
static UserManagerService sUserManager;
// Stores a list of users whose package restrictions file needs to be updated
private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
final private DefaultContainerConnection mDefContainerConn =
new DefaultContainerConnection();
class DefaultContainerConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder service) {
if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
IMediaContainerService imcs =
IMediaContainerService.Stub.asInterface(service);
mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
}
public void onServiceDisconnected(ComponentName name) {
if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
}
};
// Recordkeeping of restore-after-install operations that are currently in flight
// between the Package Manager and the Backup Manager
class PostInstallData {
public InstallArgs args;
public PackageInstalledInfo res;
PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
args = _a;
res = _r;
}
};
final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
private final String mRequiredVerifierPackage;
class PackageHandler extends Handler {
private boolean mBound = false;
final ArrayList<HandlerParams> mPendingInstalls =
new ArrayList<HandlerParams>();
private boolean connectToService() {
if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
" DefaultContainerService");
Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
if (mContext.bindServiceAsUser(service, mDefContainerConn,
Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
mBound = true;
return true;
}
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return false;
}
private void disconnectService() {
mContainerService = null;
mBound = false;
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
mContext.unbindService(mDefContainerConn);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
PackageHandler(Looper looper) {
super(looper);
}
public void handleMessage(Message msg) {
try {
doHandleMessage(msg);
} finally {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
void doHandleMessage(Message msg) {
switch (msg.what) {
case INIT_COPY: {
HandlerParams params = (HandlerParams) msg.obj;
int idx = mPendingInstalls.size();
if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
// If a bind was already initiated we dont really
// need to do anything. The pending install
// will be processed later on.
if (!mBound) {
// If this is the only one pending we might
// have to bind to the service again.
if (!connectToService()) {
Slog.e(TAG, "Failed to bind to media container service");
params.serviceError();
return;
} else {
// Once we bind to the service, the first
// pending request will be processed.
mPendingInstalls.add(idx, params);
}
} else {
mPendingInstalls.add(idx, params);
// Already bound to the service. Just make
// sure we trigger off processing the first request.
if (idx == 0) {
mHandler.sendEmptyMessage(MCS_BOUND);
}
}
break;
}
case MCS_BOUND: {
if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
if (msg.obj != null) {
mContainerService = (IMediaContainerService) msg.obj;
}
if (mContainerService == null) {
// Something seriously wrong. Bail out
Slog.e(TAG, "Cannot bind to media container service");
for (HandlerParams params : mPendingInstalls) {
// Indicate service bind error
params.serviceError();
}
mPendingInstalls.clear();
} else if (mPendingInstalls.size() > 0) {
HandlerParams params = mPendingInstalls.get(0);
if (params != null) {
if (params.startCopy()) {
// We are done... look for more work or to
// go idle.
if (DEBUG_SD_INSTALL) Log.i(TAG,
"Checking for more work or unbind...");
// Delete pending install
if (mPendingInstalls.size() > 0) {
mPendingInstalls.remove(0);
}
if (mPendingInstalls.size() == 0) {
if (mBound) {
if (DEBUG_SD_INSTALL) Log.i(TAG,
"Posting delayed MCS_UNBIND");
removeMessages(MCS_UNBIND);
Message ubmsg = obtainMessage(MCS_UNBIND);
// Unbind after a little delay, to avoid
// continual thrashing.
sendMessageDelayed(ubmsg, 10000);
}
} else {
// There are more pending requests in queue.
// Just post MCS_BOUND message to trigger processing
// of next pending install.
if (DEBUG_SD_INSTALL) Log.i(TAG,
"Posting MCS_BOUND for next woek");
mHandler.sendEmptyMessage(MCS_BOUND);
}
}
}
} else {
// Should never happen ideally.
Slog.w(TAG, "Empty queue");
}
break;
}
case MCS_RECONNECT: {
if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
if (mPendingInstalls.size() > 0) {
if (mBound) {
disconnectService();
}
if (!connectToService()) {
Slog.e(TAG, "Failed to bind to media container service");
for (HandlerParams params : mPendingInstalls) {
// Indicate service bind error
params.serviceError();
}
mPendingInstalls.clear();
}
}
break;
}
case MCS_UNBIND: {
// If there is no actual work left, then time to unbind.
if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
if (mBound) {
if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
disconnectService();
}
} else if (mPendingInstalls.size() > 0) {
// There are more pending requests in queue.
// Just post MCS_BOUND message to trigger processing
// of next pending install.
mHandler.sendEmptyMessage(MCS_BOUND);
}
break;
}
case MCS_GIVE_UP: {
if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
mPendingInstalls.remove(0);
break;
}
case SEND_PENDING_BROADCAST: {
String packages[];
ArrayList<String> components[];
int size = 0;
int uids[];
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
synchronized (mPackages) {
if (mPendingBroadcasts == null) {
return;
}
size = mPendingBroadcasts.size();
if (size <= 0) {
// Nothing to be done. Just return
return;
}
packages = new String[size];
components = new ArrayList[size];
uids = new int[size];
int i = 0; // filling out the above arrays
for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
int packageUserId = mPendingBroadcasts.userIdAt(n);
Iterator<Map.Entry<String, ArrayList<String>>> it
= mPendingBroadcasts.packagesForUserId(packageUserId)
.entrySet().iterator();
while (it.hasNext() && i < size) {
Map.Entry<String, ArrayList<String>> ent = it.next();
packages[i] = ent.getKey();
components[i] = ent.getValue();
PackageSetting ps = mSettings.mPackages.get(ent.getKey());
uids[i] = (ps != null)
? UserHandle.getUid(packageUserId, ps.appId)
: -1;
i++;
}
}
size = i;
mPendingBroadcasts.clear();
}
// Send broadcasts
for (int i = 0; i < size; i++) {
sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
}
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
break;
}
case START_CLEANING_PACKAGE: {
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
final String packageName = (String)msg.obj;
final int userId = msg.arg1;
final boolean andCode = msg.arg2 != 0;
synchronized (mPackages) {
if (userId == UserHandle.USER_ALL) {
int[] users = sUserManager.getUserIds();
for (int user : users) {
mSettings.addPackageToCleanLPw(
new PackageCleanItem(user, packageName, andCode));
}
} else {
mSettings.addPackageToCleanLPw(
new PackageCleanItem(userId, packageName, andCode));
}
}
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
startCleaningPackages();
} break;
case POST_INSTALL: {
if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
PostInstallData data = mRunningInstalls.get(msg.arg1);
mRunningInstalls.delete(msg.arg1);
boolean deleteOld = false;
if (data != null) {
InstallArgs args = data.args;
PackageInstalledInfo res = data.res;
if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
res.removedInfo.sendBroadcast(false, true, false, false);
Bundle extras = new Bundle(1);
extras.putInt(Intent.EXTRA_UID, res.uid);
// Determine the set of users who are adding this
// package for the first time vs. those who are seeing
// an update.
int[] firstUsers;
int[] updateUsers = new int[0];
if (res.origUsers == null || res.origUsers.length == 0) {
firstUsers = res.newUsers;
} else {
firstUsers = new int[0];
for (int i=0; i<res.newUsers.length; i++) {
int user = res.newUsers[i];
boolean isNew = true;
for (int j=0; j<res.origUsers.length; j++) {
if (res.origUsers[j] == user) {
isNew = false;
break;
}
}
if (isNew) {
int[] newFirst = new int[firstUsers.length+1];
System.arraycopy(firstUsers, 0, newFirst, 0,
firstUsers.length);
newFirst[firstUsers.length] = user;
firstUsers = newFirst;
} else {
int[] newUpdate = new int[updateUsers.length+1];
System.arraycopy(updateUsers, 0, newUpdate, 0,
updateUsers.length);
newUpdate[updateUsers.length] = user;
updateUsers = newUpdate;
}
}
}
sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
res.pkg.applicationInfo.packageName, null,
extras, null, null, firstUsers);
final boolean update = res.removedInfo.removedPackage != null;
if (update) {
extras.putBoolean(Intent.EXTRA_REPLACING, true);
}
String category = null;
if(res.pkg.mIsThemeApk) {
category = Intent.CATEGORY_THEME_PACKAGE_INSTALLED_STATE_CHANGE;
}
sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
res.pkg.applicationInfo.packageName, category,
extras, null, null, updateUsers);
if (update) {
sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
res.pkg.applicationInfo.packageName, category,
extras, null, null, updateUsers);
sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
null, null, null,
res.pkg.applicationInfo.packageName, null, updateUsers);
}
if (res.removedInfo.args != null) {
// Remove the replaced package's older resources safely now
deleteOld = true;
}
// Log current value of "unknown sources" setting
EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
getUnknownSourcesSettings());
}
// Force a gc to clear up things
Runtime.getRuntime().gc();
// We delete after a gc for applications on sdcard.
if (deleteOld) {
synchronized (mInstallLock) {
res.removedInfo.args.doPostDeleteLI(true);
}
}
if (args.observer != null) {
try {
args.observer.packageInstalled(res.name, res.returnCode);
} catch (RemoteException e) {
Slog.i(TAG, "Observer no longer exists.");
}
}
} else {
Slog.e(TAG, "Bogus post-install token " + msg.arg1);
}
} break;
case UPDATED_MEDIA_STATUS: {
if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
boolean reportStatus = msg.arg1 == 1;
boolean doGc = msg.arg2 == 1;
if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
if (doGc) {
// Force a gc to clear up stale containers.
Runtime.getRuntime().gc();
}
if (msg.obj != null) {
@SuppressWarnings("unchecked")
Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
// Unload containers
unloadAllContainers(args);
}
if (reportStatus) {
try {
if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
PackageHelper.getMountService().finishMediaUpdate();
} catch (RemoteException e) {
Log.e(TAG, "MountService not running?");
}
}
} break;
case WRITE_SETTINGS: {
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
synchronized (mPackages) {
removeMessages(WRITE_SETTINGS);
removeMessages(WRITE_PACKAGE_RESTRICTIONS);
mSettings.writeLPr();
mDirtyUsers.clear();
}
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
} break;
case WRITE_PACKAGE_RESTRICTIONS: {
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
synchronized (mPackages) {
removeMessages(WRITE_PACKAGE_RESTRICTIONS);
for (int userId : mDirtyUsers) {
mSettings.writePackageRestrictionsLPr(userId);
}
mDirtyUsers.clear();
}
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
} break;
case CHECK_PENDING_VERIFICATION: {
final int verificationId = msg.arg1;
final PackageVerificationState state = mPendingVerification.get(verificationId);
if ((state != null) && !state.timeoutExtended()) {
final InstallArgs args = state.getInstallArgs();
Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
mPendingVerification.remove(verificationId);
int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
Slog.i(TAG, "Continuing with installation of "
+ args.packageURI.toString());
state.setVerifierResponse(Binder.getCallingUid(),
PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
broadcastPackageVerified(verificationId, args.packageURI,
PackageManager.VERIFICATION_ALLOW,
state.getInstallArgs().getUser());
try {
ret = args.copyApk(mContainerService, true);
} catch (RemoteException e) {
Slog.e(TAG, "Could not contact the ContainerService");
}
} else {
broadcastPackageVerified(verificationId, args.packageURI,
PackageManager.VERIFICATION_REJECT,
state.getInstallArgs().getUser());
}
processPendingInstall(args, ret);
mHandler.sendEmptyMessage(MCS_UNBIND);
}
break;
}
case PACKAGE_VERIFIED: {
final int verificationId = msg.arg1;
final PackageVerificationState state = mPendingVerification.get(verificationId);
if (state == null) {
Slog.w(TAG, "Invalid verification token " + verificationId + " received");
break;
}
final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
state.setVerifierResponse(response.callerUid, response.code);
if (state.isVerificationComplete()) {
mPendingVerification.remove(verificationId);
final InstallArgs args = state.getInstallArgs();
int ret;
if (state.isInstallAllowed()) {
ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
broadcastPackageVerified(verificationId, args.packageURI,
response.code, state.getInstallArgs().getUser());
try {
ret = args.copyApk(mContainerService, true);
} catch (RemoteException e) {
Slog.e(TAG, "Could not contact the ContainerService");
}
} else {
ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
}
processPendingInstall(args, ret);
mHandler.sendEmptyMessage(MCS_UNBIND);
}
break;
}
}
}
}
void scheduleWriteSettingsLocked() {
if (!mHandler.hasMessages(WRITE_SETTINGS)) {
mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
}
}
void scheduleWritePackageRestrictionsLocked(int userId) {
if (!sUserManager.exists(userId)) return;
mDirtyUsers.add(userId);
if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
}
}
public static final IPackageManager main(Context context, Installer installer,
boolean factoryTest, boolean onlyCore) {
PackageManagerService m = new PackageManagerService(context, installer,
factoryTest, onlyCore);
ServiceManager.addService("package", m);
return m;
}
static String[] splitString(String str, char sep) {
int count = 1;
int i = 0;
while ((i=str.indexOf(sep, i)) >= 0) {
count++;
i++;
}
String[] res = new String[count];
i=0;
count = 0;
int lastI=0;
while ((i=str.indexOf(sep, i)) >= 0) {
res[count] = str.substring(lastI, i);
count++;
i++;
lastI = i;
}
res[count] = str.substring(lastI, str.length());
return res;
}
public PackageManagerService(Context context, Installer installer,
boolean factoryTest, boolean onlyCore) {
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
SystemClock.uptimeMillis());
if (mSdkVersion <= 0) {
Slog.w(TAG, "**** ro.build.version.sdk not set!");
}
mContext = context;
mFactoryTest = factoryTest;
mOnlyCore = onlyCore;
mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
mMetrics = new DisplayMetrics();
mSettings = new Settings(context);
mSettings.addSharedUserLPw("android.uid.system",
Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM);
mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM);
mSettings.addSharedUserLPw("com.tmobile.thememanager", THEME_MAMANER_GUID, ApplicationInfo.FLAG_SYSTEM);
mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM);
mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM);
mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, ApplicationInfo.FLAG_SYSTEM);
String separateProcesses = SystemProperties.get("debug.separate_processes");
if (separateProcesses != null && separateProcesses.length() > 0) {
if ("*".equals(separateProcesses)) {
mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
mSeparateProcesses = null;
Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
} else {
mDefParseFlags = 0;
mSeparateProcesses = separateProcesses.split(",");
Slog.w(TAG, "Running with debug.separate_processes: "
+ separateProcesses);
}
} else {
mDefParseFlags = 0;
mSeparateProcesses = null;
}
mInstaller = installer;
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display d = wm.getDefaultDisplay();
d.getMetrics(mMetrics);
synchronized (mInstallLock) {
// writer
synchronized (mPackages) {
mHandlerThread.start();
mHandler = new PackageHandler(mHandlerThread.getLooper());
File dataDir = Environment.getDataDirectory();
mAppDataDir = new File(dataDir, "data");
mAppInstallDir = new File(dataDir, "app");
mAppLibInstallDir = new File(dataDir, "app-lib");
mAsecInternalPath = new File(dataDir, "app-asec").getPath();
mUserAppDataDir = new File(dataDir, "user");
mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
sUserManager = new UserManagerService(context, this,
mInstallLock, mPackages);
readPermissions();
mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
mSdkVersion, mOnlyCore);
long startTime = SystemClock.uptimeMillis();
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
startTime);
// Set flag to monitor and not change apk file paths when
// scanning install directories.
int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
if (mNoDexOpt) {
Slog.w(TAG, "Running ENG build: no pre-dexopt!");
scanMode |= SCAN_NO_DEX;
}
final HashSet<String> libFiles = new HashSet<String>();
mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
mDalvikCacheDir = new File(dataDir, "dalvik-cache");
boolean didDexOpt = false;
/**
* Out of paranoia, ensure that everything in the boot class
* path has been dexed.
*/
String bootClassPath = System.getProperty("java.boot.class.path");
if (bootClassPath != null) {
String[] paths = splitString(bootClassPath, ':');
for (int i=0; i<paths.length; i++) {
try {
if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
libFiles.add(paths[i]);
mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
didDexOpt = true;
}
} catch (FileNotFoundException e) {
Slog.w(TAG, "Boot class path not found: " + paths[i]);
} catch (IOException e) {
Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? "
+ e.getMessage());
}
}
} else {
Slog.w(TAG, "No BOOTCLASSPATH found!");
}
/**
* Also ensure all external libraries have had dexopt run on them.
*/
if (mSharedLibraries.size() > 0) {
Iterator<SharedLibraryEntry> libs = mSharedLibraries.values().iterator();
while (libs.hasNext()) {
String lib = libs.next().path;
if (lib == null) {
continue;
}
try {
if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
libFiles.add(lib);
mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
didDexOpt = true;
}
} catch (FileNotFoundException e) {
Slog.w(TAG, "Library not found: " + lib);
} catch (IOException e) {
Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
+ e.getMessage());
}
}
}
// Gross hack for now: we know this file doesn't contain any
// code, so don't dexopt it to avoid the resulting log spew.
libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
/**
* And there are a number of commands implemented in Java, which
* we currently need to do the dexopt on so that they can be
* run from a non-root shell.
*/
String[] frameworkFiles = mFrameworkDir.list();
if (frameworkFiles != null) {
for (int i=0; i<frameworkFiles.length; i++) {
File libPath = new File(mFrameworkDir, frameworkFiles[i]);
String path = libPath.getPath();
// Skip the file if we alrady did it.
if (libFiles.contains(path)) {
continue;
}
// Skip the file if it is not a type we want to dexopt.
if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
continue;
}
try {
if (dalvik.system.DexFile.isDexOptNeeded(path)) {
mInstaller.dexopt(path, Process.SYSTEM_UID, true);
didDexOpt = true;
}
} catch (FileNotFoundException e) {
Slog.w(TAG, "Jar not found: " + path);
} catch (IOException e) {
Slog.w(TAG, "Exception reading jar: " + path, e);
}
}
}
if (didDexOpt) {
// If we had to do a dexopt of one of the previous
// things, then something on the system has changed.
// Consider this significant, and wipe away all other
// existing dexopt files to ensure we don't leave any
// dangling around.
String[] files = mDalvikCacheDir.list();
if (files != null) {
for (int i=0; i<files.length; i++) {
String fn = files[i];
if (fn.startsWith("data@app@")
|| fn.startsWith("data@app-private@")) {
Slog.i(TAG, "Pruning dalvik file: " + fn);
(new File(mDalvikCacheDir, fn)).delete();
}
}
}
}
// Find base frameworks (resource packages without code).
mFrameworkInstallObserver = new AppDirObserver(
mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
mFrameworkInstallObserver.startWatching();
scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
| PackageParser.PARSE_IS_SYSTEM_DIR,
scanMode | SCAN_NO_DEX, 0);
// Collect all system packages.
mSystemAppDir = new File(Environment.getRootDirectory(), "app");
mSystemInstallObserver = new AppDirObserver(
mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
mSystemInstallObserver.startWatching();
scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
| PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
// Collect all vendor packages.
mVendorAppDir = new File("/vendor/app");
mVendorInstallObserver = new AppDirObserver(
mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
mVendorInstallObserver.startWatching();
scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
| PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
mInstaller.moveFiles();
// Prune any system packages that no longer exist.
final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
if (!mOnlyCore) {
Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
while (psit.hasNext()) {
PackageSetting ps = psit.next();
/*
* If this is not a system app, it can't be a
* disable system app.
*/
if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
continue;
}
/*
* If the package is scanned, it's not erased.
*/
final PackageParser.Package scannedPkg = mPackages.get(ps.name);
if (scannedPkg != null) {
/*
* If the system app is both scanned and in the
* disabled packages list, then it must have been
* added via OTA. Remove it from the currently
* scanned package so the previously user-installed
* application can be scanned.
*/
if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
Slog.i(TAG, "Expecting better updatd system app for " + ps.name
+ "; removing system app");
removePackageLI(ps, true);
}
continue;
}
if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
psit.remove();
String msg = "System package " + ps.name
+ " no longer exists; wiping its data";
reportSettingsProblem(Log.WARN, msg);
removeDataDirsLI(ps.name);
} else {
final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
possiblyDeletedUpdatedSystemApps.add(ps.name);
}
}
}
}
//look for any incomplete package installations
ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
//clean up list
for(int i = 0; i < deletePkgsList.size(); i++) {
//clean up here
cleanupInstallFailedPackage(deletePkgsList.get(i));
}
//delete tmp files
deleteTempPackageFiles();
if (!mOnlyCore) {
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
SystemClock.uptimeMillis());
mAppInstallObserver = new AppDirObserver(
mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
mAppInstallObserver.startWatching();
scanDirLI(mAppInstallDir, 0, scanMode, 0);
mDrmAppInstallObserver = new AppDirObserver(
mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
mDrmAppInstallObserver.startWatching();
scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
scanMode, 0);
/**
* Remove disable package settings for any updated system
* apps that were removed via an OTA. If they're not a
* previously-updated app, remove them completely.
* Otherwise, just revoke their system-level permissions.
*/
for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
mSettings.removeDisabledSystemPackageLPw(deletedAppName);
String msg;
if (deletedPkg == null) {
msg = "Updated system package " + deletedAppName
+ " no longer exists; wiping its data";
removeDataDirsLI(deletedAppName);
} else {
msg = "Updated system app + " + deletedAppName
+ " no longer present; removing system privileges for "
+ deletedAppName;
deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
}
reportSettingsProblem(Log.WARN, msg);
}
} else {
mAppInstallObserver = null;
mDrmAppInstallObserver = null;
}
// Now that we know all of the shared libraries, update all clients to have
// the correct library paths.
updateAllSharedLibrariesLPw();
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
SystemClock.uptimeMillis());
Slog.i(TAG, "Time to scan packages: "
+ ((SystemClock.uptimeMillis()-startTime)/1000f)
+ " seconds");
// If the platform SDK has changed since the last time we booted,
// we need to re-grant app permission to catch any new ones that
// appear. This is really a hack, and means that apps can in some
// cases get permissions that the user didn't initially explicitly
// allow... it would be nice to have some better way to handle
// this situation.
final boolean regrantPermissions = mSettings.mInternalSdkPlatform
!= mSdkVersion;
if (regrantPermissions) Slog.i(TAG, "Platform changed from "
+ mSettings.mInternalSdkPlatform + " to " + mSdkVersion
+ "; regranting permissions for internal storage");
mSettings.mInternalSdkPlatform = mSdkVersion;
updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
| (regrantPermissions
? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
: 0));
// If this is the first boot, and it is a normal boot, then
// we need to initialize the default preferred apps.
if (!mRestoredSettings && !onlyCore) {
mSettings.readDefaultPreferredAppsLPw(this, 0);
}
// can downgrade to reader
mSettings.writeLPr();
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
SystemClock.uptimeMillis());
// Now after opening every single application zip, make sure they
// are all flushed. Not really needed, but keeps things nice and
// tidy.
Runtime.getRuntime().gc();
mRequiredVerifierPackage = getRequiredVerifierLPr();
} // synchronized (mPackages)
} // synchronized (mInstallLock)
}
public boolean isFirstBoot() {
return !mRestoredSettings;
}
public boolean isOnlyCoreApps() {
return mOnlyCore;
}
private String getRequiredVerifierLPr() {
final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
String requiredVerifier = null;
final int N = receivers.size();
for (int i = 0; i < N; i++) {
final ResolveInfo info = receivers.get(i);
if (info.activityInfo == null) {
continue;
}
final String packageName = info.activityInfo.packageName;
final PackageSetting ps = mSettings.mPackages.get(packageName);
if (ps == null) {
continue;
}
final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
if (!gp.grantedPermissions
.contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
continue;
}
if (requiredVerifier != null) {
throw new RuntimeException("There can be only one required verifier");
}
requiredVerifier = packageName;
}
return requiredVerifier;
}
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
try {
return super.onTransact(code, data, reply, flags);
} catch (RuntimeException e) {
if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Slog.e(TAG, "Package Manager Crash", e);
}
throw e;
}
}
void cleanupInstallFailedPackage(PackageSetting ps) {
Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
removeDataDirsLI(ps.name);
if (ps.codePath != null) {
if (!ps.codePath.delete()) {
Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
}
}
if (ps.resourcePath != null) {
if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
}
}
mSettings.removePackageLPw(ps.name);
}
void readPermissions() {
// Read permissions from .../etc/permission directory.
File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Slog.w(TAG, "No directory " + libraryDir + ", skipping");
return;
}
if (!libraryDir.canRead()) {
Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
return;
}
// Iterate over the files in the directory and scan .xml files
for (File f : libraryDir.listFiles()) {
// We'll read platform.xml last
if (f.getPath().endsWith("etc/permissions/platform.xml")) {
continue;
}
if (!f.getPath().endsWith(".xml")) {
Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
continue;
}
if (!f.canRead()) {
Slog.w(TAG, "Permissions library file " + f + " cannot be read");
continue;
}
readPermissionsFromXml(f);
}
// Read permissions from .../etc/permissions/platform.xml last so it will take precedence
final File permFile = new File(Environment.getRootDirectory(),
"etc/permissions/platform.xml");
readPermissionsFromXml(permFile);
}
private void readPermissionsFromXml(File permFile) {
FileReader permReader = null;
try {
permReader = new FileReader(permFile);
} catch (FileNotFoundException e) {
Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
return;
}
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(permReader);
XmlUtils.beginDocument(parser, "permissions");
while (true) {
XmlUtils.nextElement(parser);
if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
break;
}
String name = parser.getName();
if ("group".equals(name)) {
String gidStr = parser.getAttributeValue(null, "gid");
if (gidStr != null) {
int gid = Process.getGidForName(gidStr);
mGlobalGids = appendInt(mGlobalGids, gid);
} else {
Slog.w(TAG, "<group> without gid at "
+ parser.getPositionDescription());
}
XmlUtils.skipCurrentTag(parser);
continue;
} else if ("permission".equals(name)) {
String perm = parser.getAttributeValue(null, "name");
if (perm == null) {
Slog.w(TAG, "<permission> without name at "
+ parser.getPositionDescription());
XmlUtils.skipCurrentTag(parser);
continue;
}
perm = perm.intern();
readPermission(parser, perm);
} else if ("assign-permission".equals(name)) {
String perm = parser.getAttributeValue(null, "name");
if (perm == null) {
Slog.w(TAG, "<assign-permission> without name at "
+ parser.getPositionDescription());
XmlUtils.skipCurrentTag(parser);
continue;
}
String uidStr = parser.getAttributeValue(null, "uid");
if (uidStr == null) {
Slog.w(TAG, "<assign-permission> without uid at "
+ parser.getPositionDescription());
XmlUtils.skipCurrentTag(parser);
continue;
}
int uid = Process.getUidForName(uidStr);
if (uid < 0) {
Slog.w(TAG, "<assign-permission> with unknown uid \""
+ uidStr + "\" at "
+ parser.getPositionDescription());
XmlUtils.skipCurrentTag(parser);
continue;
}
perm = perm.intern();
HashSet<String> perms = mSystemPermissions.get(uid);
if (perms == null) {
perms = new HashSet<String>();
mSystemPermissions.put(uid, perms);
}
perms.add(perm);
XmlUtils.skipCurrentTag(parser);
} else if ("library".equals(name)) {
String lname = parser.getAttributeValue(null, "name");
String lfile = parser.getAttributeValue(null, "file");
if (lname == null) {
Slog.w(TAG, "<library> without name at "
+ parser.getPositionDescription());
} else if (lfile == null) {
Slog.w(TAG, "<library> without file at "
+ parser.getPositionDescription());
} else {
//Log.i(TAG, "Got library " + lname + " in " + lfile);
mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
}
XmlUtils.skipCurrentTag(parser);
continue;
} else if ("feature".equals(name)) {
String fname = parser.getAttributeValue(null, "name");
if (fname == null) {
Slog.w(TAG, "<feature> without name at "
+ parser.getPositionDescription());
} else {
//Log.i(TAG, "Got feature " + fname);
FeatureInfo fi = new FeatureInfo();
fi.name = fname;
mAvailableFeatures.put(fname, fi);
}
XmlUtils.skipCurrentTag(parser);
continue;
} else {
XmlUtils.skipCurrentTag(parser);
continue;
}
}
permReader.close();
} catch (XmlPullParserException e) {
Slog.w(TAG, "Got execption parsing permissions.", e);
} catch (IOException e) {
Slog.w(TAG, "Got execption parsing permissions.", e);
}
}
void readPermission(XmlPullParser parser, String name)
throws IOException, XmlPullParserException {
name = name.intern();
BasePermission bp = mSettings.mPermissions.get(name);
if (bp == null) {
bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
mSettings.mPermissions.put(name, bp);
}
int outerDepth = parser.getDepth();
int type;
while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG
|| parser.getDepth() > outerDepth)) {
if (type == XmlPullParser.END_TAG
|| type == XmlPullParser.TEXT) {
continue;
}
String tagName = parser.getName();
if ("group".equals(tagName)) {
String gidStr = parser.getAttributeValue(null, "gid");
if (gidStr != null) {
int gid = Process.getGidForName(gidStr);
bp.gids = appendInt(bp.gids, gid);
} else {
Slog.w(TAG, "<group> without gid at "
+ parser.getPositionDescription());
}
}
XmlUtils.skipCurrentTag(parser);
}
}
static int[] appendInts(int[] cur, int[] add) {
if (add == null) return cur;
if (cur == null) return add;
final int N = add.length;
for (int i=0; i<N; i++) {
cur = appendInt(cur, add[i]);
}
return cur;
}
static int[] removeInts(int[] cur, int[] rem) {
if (rem == null) return cur;
if (cur == null) return cur;
final int N = rem.length;
for (int i=0; i<N; i++) {
cur = removeInt(cur, rem[i]);
}
return cur;
}
PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
PackageInfo pi;
final PackageSetting ps = (PackageSetting) p.mExtras;
if (ps == null) {
return null;
}
final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
final PackageUserState state = ps.readUserState(userId);
return PackageParser.generatePackageInfo(p, gp.gids, flags,
ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
state, userId);
}
@Override
public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
// reader
synchronized (mPackages) {
PackageParser.Package p = mPackages.get(packageName);
if (DEBUG_PACKAGE_INFO)
Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
if (p != null) {
return generatePackageInfo(p, flags, userId);
}
if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
}
}
return null;
}
public String[] currentToCanonicalPackageNames(String[] names) {
String[] out = new String[names.length];
// reader
synchronized (mPackages) {
for (int i=names.length-1; i>=0; i--) {
PackageSetting ps = mSettings.mPackages.get(names[i]);
out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
}
}
return out;
}
public String[] canonicalToCurrentPackageNames(String[] names) {
String[] out = new String[names.length];
// reader
synchronized (mPackages) {
for (int i=names.length-1; i>=0; i--) {
String cur = mSettings.mRenamedPackages.get(names[i]);
out[i] = cur != null ? cur : names[i];
}
}
return out;
}
@Override
public int getPackageUid(String packageName, int userId) {
if (!sUserManager.exists(userId)) return -1;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
// reader
synchronized (mPackages) {
PackageParser.Package p = mPackages.get(packageName);
if(p != null) {
return UserHandle.getUid(userId, p.applicationInfo.uid);
}
PackageSetting ps = mSettings.mPackages.get(packageName);
if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
return -1;
}
p = ps.pkg;
return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
}
}
public int[] getPackageGids(String packageName) {
final boolean enforcedDefault = isPermissionEnforcedDefault(READ_EXTERNAL_STORAGE);
// reader
synchronized (mPackages) {
PackageParser.Package p = mPackages.get(packageName);
if (DEBUG_PACKAGE_INFO)
Log.v(TAG, "getPackageGids" + packageName + ": " + p);
if (p != null) {
final PackageSetting ps = (PackageSetting)p.mExtras;
final SharedUserSetting suid = ps.sharedUser;
int[] gids = suid != null ? suid.gids : ps.gids;
// include GIDs for any unenforced permissions
if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE, enforcedDefault)) {
final BasePermission basePerm = mSettings.mPermissions.get(
READ_EXTERNAL_STORAGE);
gids = appendInts(gids, basePerm.gids);
}
return gids;
}
}
// stupid thing to indicate an error.
return new int[0];
}
static final PermissionInfo generatePermissionInfo(
BasePermission bp, int flags) {
if (bp.perm != null) {
return PackageParser.generatePermissionInfo(bp.perm, flags);
}
PermissionInfo pi = new PermissionInfo();
pi.name = bp.name;
pi.packageName = bp.sourcePackage;
pi.nonLocalizedLabel = bp.name;
pi.protectionLevel = bp.protectionLevel;
return pi;
}
public PermissionInfo getPermissionInfo(String name, int flags) {
// reader
synchronized (mPackages) {
final BasePermission p = mSettings.mPermissions.get(name);
if (p != null) {
return generatePermissionInfo(p, flags);
}
return null;
}
}
public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
// reader
synchronized (mPackages) {
ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
for (BasePermission p : mSettings.mPermissions.values()) {
if (group == null) {
if (p.perm == null || p.perm.info.group == null) {
out.add(generatePermissionInfo(p, flags));
}
} else {
if (p.perm != null && group.equals(p.perm.info.group)) {
out.add(PackageParser.generatePermissionInfo(p.perm, flags));
}
}
}
if (out.size() > 0) {
return out;
}
return mPermissionGroups.containsKey(group) ? out : null;
}
}
public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
// reader
synchronized (mPackages) {
return PackageParser.generatePermissionGroupInfo(
mPermissionGroups.get(name), flags);
}
}
public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
// reader
synchronized (mPackages) {
final int N = mPermissionGroups.size();
ArrayList<PermissionGroupInfo> out
= new ArrayList<PermissionGroupInfo>(N);
for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
}
return out;
}
}
private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
int userId) {
if (!sUserManager.exists(userId)) return null;
PackageSetting ps = mSettings.mPackages.get(packageName);
if (ps != null) {
if (ps.pkg == null) {
PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
flags, userId);
if (pInfo != null) {
return pInfo.applicationInfo;
}
return null;
}
return PackageParser.generateApplicationInfo(ps.pkg, flags,
ps.readUserState(userId), userId);
}
return null;
}
private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
int userId) {
if (!sUserManager.exists(userId)) return null;
PackageSetting ps = mSettings.mPackages.get(packageName);
if (ps != null) {
PackageParser.Package pkg = ps.pkg;
if (pkg == null) {
if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
return null;
}
pkg = new PackageParser.Package(packageName);
pkg.applicationInfo.packageName = packageName;
pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
pkg.applicationInfo.sourceDir = ps.codePathString;
pkg.applicationInfo.dataDir =
getDataPathForPackage(packageName, 0).getPath();
pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
}
// pkg.mSetEnabled = ps.getEnabled(userId);
// pkg.mSetStopped = ps.getStopped(userId);
return generatePackageInfo(pkg, flags, userId);
}
return null;
}
@Override
public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
// writer
synchronized (mPackages) {
PackageParser.Package p = mPackages.get(packageName);
if (DEBUG_PACKAGE_INFO) Log.v(
TAG, "getApplicationInfo " + packageName
+ ": " + p);
if (p != null) {
PackageSetting ps = mSettings.mPackages.get(packageName);
if (ps == null) return null;
// Note: isEnabledLP() does not apply here - always return info
return PackageParser.generateApplicationInfo(
p, flags, ps.readUserState(userId), userId);
}
if ("android".equals(packageName)||"system".equals(packageName)) {
return mAndroidApplication;
}
if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
}
}
return null;
}
public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.CLEAR_APP_CACHE, null);
// Queue up an async operation since clearing cache may take a little while.
mHandler.post(new Runnable() {
public void run() {
mHandler.removeCallbacks(this);
int retCode = -1;
synchronized (mInstallLock) {
retCode = mInstaller.freeCache(freeStorageSize);
if (retCode < 0) {
Slog.w(TAG, "Couldn't clear application caches");
}
}
if (observer != null) {
try {
observer.onRemoveCompleted(null, (retCode >= 0));
} catch (RemoteException e) {
Slog.w(TAG, "RemoveException when invoking call back");
}
}
}
});
}
public void freeStorage(final long freeStorageSize, final IntentSender pi) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.CLEAR_APP_CACHE, null);
// Queue up an async operation since clearing cache may take a little while.
mHandler.post(new Runnable() {
public void run() {
mHandler.removeCallbacks(this);
int retCode = -1;
synchronized (mInstallLock) {
retCode = mInstaller.freeCache(freeStorageSize);
if (retCode < 0) {
Slog.w(TAG, "Couldn't clear application caches");
}
}
if(pi != null) {
try {
// Callback via pending intent
int code = (retCode >= 0) ? 1 : 0;
pi.sendIntent(null, code, null,
null, null);
} catch (SendIntentException e1) {
Slog.i(TAG, "Failed to send pending intent");
}
}
}
});
}
@Override
public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
synchronized (mPackages) {
PackageParser.Activity a = mActivities.mActivities.get(component);
if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
if (ps == null) return null;
return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
userId);
}
if (mResolveComponentName.equals(component)) {
return mResolveActivity;
}
}
return null;
}
@Override
public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
synchronized (mPackages) {
PackageParser.Activity a = mReceivers.mActivities.get(component);
if (DEBUG_PACKAGE_INFO) Log.v(
TAG, "getReceiverInfo " + component + ": " + a);
if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
if (ps == null) return null;
return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
userId);
}
}
return null;
}
@Override
public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
synchronized (mPackages) {
PackageParser.Service s = mServices.mServices.get(component);
if (DEBUG_PACKAGE_INFO) Log.v(
TAG, "getServiceInfo " + component + ": " + s);
if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
if (ps == null) return null;
return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
userId);
}
}
return null;
}
@Override
public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
synchronized (mPackages) {
PackageParser.Provider p = mProvidersByComponent.get(component);
if (DEBUG_PACKAGE_INFO) Log.v(
TAG, "getProviderInfo " + component + ": " + p);
if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
if (ps == null) return null;
return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
userId);
}
}
return null;
}
public String[] getSystemSharedLibraryNames() {
Set<String> libSet;
synchronized (mPackages) {
libSet = mSharedLibraries.keySet();
int size = libSet.size();
if (size > 0) {
String[] libs = new String[size];
libSet.toArray(libs);
return libs;
}
}
return null;
}
public FeatureInfo[] getSystemAvailableFeatures() {
Collection<FeatureInfo> featSet;
synchronized (mPackages) {
featSet = mAvailableFeatures.values();
int size = featSet.size();
if (size > 0) {
FeatureInfo[] features = new FeatureInfo[size+1];
featSet.toArray(features);
FeatureInfo fi = new FeatureInfo();
fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
FeatureInfo.GL_ES_VERSION_UNDEFINED);
features[size] = fi;
return features;
}
}
return null;
}
public boolean hasSystemFeature(String name) {
synchronized (mPackages) {
return mAvailableFeatures.containsKey(name);
}
}
private void checkValidCaller(int uid, int userId) {
if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
return;
throw new SecurityException("Caller uid=" + uid
+ " is not privileged to communicate with user=" + userId);
}
public int checkPermission(String permName, String pkgName) {
final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
synchronized (mPackages) {
PackageParser.Package p = mPackages.get(pkgName);
if (p != null && p.mExtras != null) {
PackageSetting ps = (PackageSetting)p.mExtras;
if (ps.sharedUser != null) {
if (ps.sharedUser.grantedPermissions.contains(permName)) {
return PackageManager.PERMISSION_GRANTED;
}
} else if (ps.grantedPermissions.contains(permName)) {
return PackageManager.PERMISSION_GRANTED;
}
}
if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
return PackageManager.PERMISSION_GRANTED;
}
}
return PackageManager.PERMISSION_DENIED;
}
public int checkUidPermission(String permName, int uid) {
final boolean enforcedDefault = isPermissionEnforcedDefault(permName);
synchronized (mPackages) {
Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
if (obj != null) {
GrantedPermissions gp = (GrantedPermissions)obj;
if (gp.grantedPermissions.contains(permName)) {
return PackageManager.PERMISSION_GRANTED;
}
} else {
HashSet<String> perms = mSystemPermissions.get(uid);
if (perms != null && perms.contains(permName)) {
return PackageManager.PERMISSION_GRANTED;
}
}
if (!isPermissionEnforcedLocked(permName, enforcedDefault)) {
return PackageManager.PERMISSION_GRANTED;
}
}
return PackageManager.PERMISSION_DENIED;
}
/**
* Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
* or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
* @param message the message to log on security exception
* @return
*/
private void enforceCrossUserPermission(int callingUid, int userId,
boolean requireFullPermission, String message) {
if (userId < 0) {
throw new IllegalArgumentException("Invalid userId " + userId);
}
if (userId == UserHandle.getUserId(callingUid)) return;
if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
if (requireFullPermission) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
} else {
try {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
} catch (SecurityException se) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.INTERACT_ACROSS_USERS, message);
}
}
}
}
private BasePermission findPermissionTreeLP(String permName) {
for(BasePermission bp : mSettings.mPermissionTrees.values()) {
if (permName.startsWith(bp.name) &&
permName.length() > bp.name.length() &&
permName.charAt(bp.name.length()) == '.') {
return bp;
}
}
return null;
}
private BasePermission checkPermissionTreeLP(String permName) {
if (permName != null) {
BasePermission bp = findPermissionTreeLP(permName);
if (bp != null) {
if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
return bp;
}
throw new SecurityException("Calling uid "
+ Binder.getCallingUid()
+ " is not allowed to add to permission tree "
+ bp.name + " owned by uid " + bp.uid);
}
}
throw new SecurityException("No permission tree found for " + permName);
}
static boolean compareStrings(CharSequence s1, CharSequence s2) {
if (s1 == null) {
return s2 == null;
}
if (s2 == null) {
return false;
}
if (s1.getClass() != s2.getClass()) {
return false;
}
return s1.equals(s2);
}
static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
if (pi1.icon != pi2.icon) return false;
if (pi1.logo != pi2.logo) return false;
if (pi1.protectionLevel != pi2.protectionLevel) return false;
if (!compareStrings(pi1.name, pi2.name)) return false;
if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
// We'll take care of setting this one.
if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
// These are not currently stored in settings.
//if (!compareStrings(pi1.group, pi2.group)) return false;
//if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
//if (pi1.labelRes != pi2.labelRes) return false;
//if (pi1.descriptionRes != pi2.descriptionRes) return false;
return true;
}
boolean addPermissionLocked(PermissionInfo info, boolean async) {
if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
throw new SecurityException("Label must be specified in permission");
}
BasePermission tree = checkPermissionTreeLP(info.name);
BasePermission bp = mSettings.mPermissions.get(info.name);
boolean added = bp == null;
boolean changed = true;
int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
if (added) {
bp = new BasePermission(info.name, tree.sourcePackage,
BasePermission.TYPE_DYNAMIC);
} else if (bp.type != BasePermission.TYPE_DYNAMIC) {
throw new SecurityException(
"Not allowed to modify non-dynamic permission "
+ info.name);
} else {
if (bp.protectionLevel == fixedLevel
&& bp.perm.owner.equals(tree.perm.owner)
&& bp.uid == tree.uid
&& comparePermissionInfos(bp.perm.info, info)) {
changed = false;
}
}
bp.protectionLevel = fixedLevel;
info = new PermissionInfo(info);
info.protectionLevel = fixedLevel;
bp.perm = new PackageParser.Permission(tree.perm.owner, info);
bp.perm.info.packageName = tree.perm.info.packageName;
bp.uid = tree.uid;
if (added) {
mSettings.mPermissions.put(info.name, bp);
}
if (changed) {
if (!async) {
mSettings.writeLPr();
} else {
scheduleWriteSettingsLocked();
}
}
return added;
}
public boolean addPermission(PermissionInfo info) {
synchronized (mPackages) {
return addPermissionLocked(info, false);
}
}
public boolean addPermissionAsync(PermissionInfo info) {
synchronized (mPackages) {
return addPermissionLocked(info, true);
}
}
public void removePermission(String name) {
synchronized (mPackages) {
checkPermissionTreeLP(name);
BasePermission bp = mSettings.mPermissions.get(name);
if (bp != null) {
if (bp.type != BasePermission.TYPE_DYNAMIC) {
throw new SecurityException(
"Not allowed to modify non-dynamic permission "
+ name);
}
mSettings.mPermissions.remove(name);
mSettings.writeLPr();
}
}
}
private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
int index = pkg.requestedPermissions.indexOf(bp.name);
if (index == -1) {
throw new SecurityException("Package " + pkg.packageName
+ " has not requested permission " + bp.name);
}
boolean isNormal =
((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
== PermissionInfo.PROTECTION_NORMAL);
boolean isDangerous =
((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
== PermissionInfo.PROTECTION_DANGEROUS);
boolean isDevelopment =
((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
if (!isNormal && !isDangerous && !isDevelopment) {
throw new SecurityException("Permission " + bp.name
+ " is not a changeable permission type");
}
if (isNormal || isDangerous) {
if (pkg.requestedPermissionsRequired.get(index)) {
throw new SecurityException("Can't change " + bp.name
+ ". It is required by the application");
}
}
}
public void grantPermission(String packageName, String permissionName) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
synchronized (mPackages) {
final PackageParser.Package pkg = mPackages.get(packageName);
if (pkg == null) {
throw new IllegalArgumentException("Unknown package: " + packageName);
}
final BasePermission bp = mSettings.mPermissions.get(permissionName);
if (bp == null) {
throw new IllegalArgumentException("Unknown permission: " + permissionName);
}
checkGrantRevokePermissions(pkg, bp);
final PackageSetting ps = (PackageSetting) pkg.mExtras;
if (ps == null) {
return;
}
final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
if (gp.grantedPermissions.add(permissionName)) {
if (ps.haveGids) {
gp.gids = appendInts(gp.gids, bp.gids);
}
mSettings.writeLPr();
}
}
}
public void revokePermission(String packageName, String permissionName) {
int changedAppId = -1;
synchronized (mPackages) {
final PackageParser.Package pkg = mPackages.get(packageName);
if (pkg == null) {
throw new IllegalArgumentException("Unknown package: " + packageName);
}
if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
}
final BasePermission bp = mSettings.mPermissions.get(permissionName);
if (bp == null) {
throw new IllegalArgumentException("Unknown permission: " + permissionName);
}
checkGrantRevokePermissions(pkg, bp);
final PackageSetting ps = (PackageSetting) pkg.mExtras;
if (ps == null) {
return;
}
final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
if (gp.grantedPermissions.remove(permissionName)) {
gp.grantedPermissions.remove(permissionName);
if (ps.haveGids) {
gp.gids = removeInts(gp.gids, bp.gids);
}
mSettings.writeLPr();
changedAppId = ps.appId;
}
}
if (changedAppId >= 0) {
// We changed the perm on someone, kill its processes.
IActivityManager am = ActivityManagerNative.getDefault();
if (am != null) {
final int callingUserId = UserHandle.getCallingUserId();
final long ident = Binder.clearCallingIdentity();
try {
//XXX we should only revoke for the calling user's app permissions,
// but for now we impact all users.
//am.killUid(UserHandle.getUid(callingUserId, changedAppId),
// "revoke " + permissionName);
int[] users = sUserManager.getUserIds();
for (int user : users) {
am.killUid(UserHandle.getUid(user, changedAppId),
"revoke " + permissionName);
}
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(ident);
}
}
}
}
public boolean isProtectedBroadcast(String actionName) {
synchronized (mPackages) {
return mProtectedBroadcasts.contains(actionName);
}
}
public int checkSignatures(String pkg1, String pkg2) {
synchronized (mPackages) {
final PackageParser.Package p1 = mPackages.get(pkg1);
final PackageParser.Package p2 = mPackages.get(pkg2);
if (p1 == null || p1.mExtras == null
|| p2 == null || p2.mExtras == null) {
return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
}
return compareSignatures(p1.mSignatures, p2.mSignatures);
}
}
public int checkUidSignatures(int uid1, int uid2) {
// Map to base uids.
uid1 = UserHandle.getAppId(uid1);
uid2 = UserHandle.getAppId(uid2);
// reader
synchronized (mPackages) {
Signature[] s1;
Signature[] s2;
Object obj = mSettings.getUserIdLPr(uid1);
if (obj != null) {
if (obj instanceof SharedUserSetting) {
s1 = ((SharedUserSetting)obj).signatures.mSignatures;
} else if (obj instanceof PackageSetting) {
s1 = ((PackageSetting)obj).signatures.mSignatures;
} else {
return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
}
} else {
return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
}
obj = mSettings.getUserIdLPr(uid2);
if (obj != null) {
if (obj instanceof SharedUserSetting) {
s2 = ((SharedUserSetting)obj).signatures.mSignatures;
} else if (obj instanceof PackageSetting) {
s2 = ((PackageSetting)obj).signatures.mSignatures;
} else {
return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
}
} else {
return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
}
return compareSignatures(s1, s2);
}
}
static int compareSignatures(Signature[] s1, Signature[] s2) {
if (s1 == null) {
return s2 == null
? PackageManager.SIGNATURE_NEITHER_SIGNED
: PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
}
if (s2 == null) {
return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
}
HashSet<Signature> set1 = new HashSet<Signature>();
for (Signature sig : s1) {
set1.add(sig);
}
HashSet<Signature> set2 = new HashSet<Signature>();
for (Signature sig : s2) {
set2.add(sig);
}
// Make sure s2 contains all signatures in s1.
if (set1.equals(set2)) {
return PackageManager.SIGNATURE_MATCH;
}
return PackageManager.SIGNATURE_NO_MATCH;
}
public String[] getPackagesForUid(int uid) {
uid = UserHandle.getAppId(uid);
// reader
synchronized (mPackages) {
Object obj = mSettings.getUserIdLPr(uid);
if (obj instanceof SharedUserSetting) {
final SharedUserSetting sus = (SharedUserSetting) obj;
final int N = sus.packages.size();
final String[] res = new String[N];
final Iterator<PackageSetting> it = sus.packages.iterator();
int i = 0;
while (it.hasNext()) {
res[i++] = it.next().name;
}
return res;
} else if (obj instanceof PackageSetting) {
final PackageSetting ps = (PackageSetting) obj;
return new String[] { ps.name };
}
}
return null;
}
public String getNameForUid(int uid) {
// reader
synchronized (mPackages) {
Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
if (obj instanceof SharedUserSetting) {
final SharedUserSetting sus = (SharedUserSetting) obj;
return sus.name + ":" + sus.userId;
} else if (obj instanceof PackageSetting) {
final PackageSetting ps = (PackageSetting) obj;
return ps.name;
}
}
return null;
}
public int getUidForSharedUser(String sharedUserName) {
if(sharedUserName == null) {
return -1;
}
// reader
synchronized (mPackages) {
final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
if (suid == null) {
return -1;
}
return suid.userId;
}
}
@Override
public ResolveInfo resolveIntent(Intent intent, String resolvedType,
int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
return chooseBestActivity(intent, resolvedType, flags, query, userId);
}
private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
int flags, List<ResolveInfo> query, int userId) {
if (query != null) {
final int N = query.size();
if (N == 1) {
return query.get(0);
} else if (N > 1) {
// If there is more than one activity with the same priority,
// then let the user decide between them.
ResolveInfo r0 = query.get(0);
ResolveInfo r1 = query.get(1);
if (DEBUG_INTENT_MATCHING) {
Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
+ r1.activityInfo.name + "=" + r1.priority);
}
// If the first activity has a higher priority, or a different
// default, then it is always desireable to pick it.
if (r0.priority != r1.priority
|| r0.preferredOrder != r1.preferredOrder
|| r0.isDefault != r1.isDefault) {
return query.get(0);
}
// If we have saved a preference for a preferred activity for
// this Intent, use that.
ResolveInfo ri = findPreferredActivity(intent, resolvedType,
flags, query, r0.priority, userId);
if (ri != null) {
return ri;
}
if (userId != 0) {
ri = new ResolveInfo(mResolveInfo);
ri.activityInfo = new ActivityInfo(ri.activityInfo);
ri.activityInfo.applicationInfo = new ApplicationInfo(
ri.activityInfo.applicationInfo);
ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
return ri;
}
return mResolveInfo;
}
}
return null;
}
ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
int flags, List<ResolveInfo> query, int priority, int userId) {
if (!sUserManager.exists(userId)) return null;
// writer
synchronized (mPackages) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
}
if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
List<PreferredActivity> prefs = pir != null
? pir.queryIntent(intent, resolvedType,
(flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
: null;
if (prefs != null && prefs.size() > 0) {
// First figure out how good the original match set is.
// We will only allow preferred activities that came
// from the same match quality.
int match = 0;
if (DEBUG_PREFERRED) {
Log.v(TAG, "Figuring out best match...");
}
final int N = query.size();
for (int j=0; j<N; j++) {
final ResolveInfo ri = query.get(j);
if (DEBUG_PREFERRED) {
Log.v(TAG, "Match for " + ri.activityInfo + ": 0x"
+ Integer.toHexString(match));
}
if (ri.match > match) {
match = ri.match;
}
}
if (DEBUG_PREFERRED) {
Log.v(TAG, "Best match: 0x" + Integer.toHexString(match));
}
match &= IntentFilter.MATCH_CATEGORY_MASK;
final int M = prefs.size();
for (int i=0; i<M; i++) {
final PreferredActivity pa = prefs.get(i);
if (pa.mPref.mMatch != match) {
continue;
}
final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
if (DEBUG_PREFERRED) {
Log.v(TAG, "Got preferred activity:");
if (ai != null) {
ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
} else {
Log.v(TAG, " null");
}
}
if (ai == null) {
// This previously registered preferred activity
// component is no longer known. Most likely an update
// to the app was installed and in the new version this
// component no longer exists. Clean it up by removing
// it from the preferred activities list, and skip it.
Slog.w(TAG, "Removing dangling preferred activity: "
+ pa.mPref.mComponent);
pir.removeFilter(pa);
continue;
}
for (int j=0; j<N; j++) {
final ResolveInfo ri = query.get(j);
if (!ri.activityInfo.applicationInfo.packageName
.equals(ai.applicationInfo.packageName)) {
continue;
}
if (!ri.activityInfo.name.equals(ai.name)) {
continue;
}
// Okay we found a previously set preferred app.
// If the result set is different from when this
// was created, we need to clear it and re-ask the
// user their preference.
if (!pa.mPref.sameSet(query, priority)) {
Slog.i(TAG, "Result set changed, dropping preferred activity for "
+ intent + " type " + resolvedType);
pir.removeFilter(pa);
return null;
}
// Yay!
return ri;
}
}
}
}
return null;
}
@Override
public List<ResolveInfo> queryIntentActivities(Intent intent,
String resolvedType, int flags, int userId) {
if (!sUserManager.exists(userId)) return Collections.emptyList();
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
ComponentName comp = intent.getComponent();
if (comp == null) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
comp = intent.getComponent();
}
}
if (comp != null) {
final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
final ActivityInfo ai = getActivityInfo(comp, flags, userId);
if (ai != null) {
final ResolveInfo ri = new ResolveInfo();
ri.activityInfo = ai;
list.add(ri);
}
return list;
}
// reader
synchronized (mPackages) {
final String pkgName = intent.getPackage();
if (pkgName == null) {
return mActivities.queryIntent(intent, resolvedType, flags, userId);
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
return mActivities.queryIntentForPackage(intent, resolvedType, flags,
pkg.activities, userId);
}
return new ArrayList<ResolveInfo>();
}
}
@Override
public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
Intent[] specifics, String[] specificTypes, Intent intent,
String resolvedType, int flags, int userId) {
if (!sUserManager.exists(userId)) return Collections.emptyList();
enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
"query intent activity options");
final String resultsAction = intent.getAction();
List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
| PackageManager.GET_RESOLVED_FILTER, userId);
if (DEBUG_INTENT_MATCHING) {
Log.v(TAG, "Query " + intent + ": " + results);
}
int specificsPos = 0;
int N;
// todo: note that the algorithm used here is O(N^2). This
// isn't a problem in our current environment, but if we start running
// into situations where we have more than 5 or 10 matches then this
// should probably be changed to something smarter...
// First we go through and resolve each of the specific items
// that were supplied, taking care of removing any corresponding
// duplicate items in the generic resolve list.
if (specifics != null) {
for (int i=0; i<specifics.length; i++) {
final Intent sintent = specifics[i];
if (sintent == null) {
continue;
}
if (DEBUG_INTENT_MATCHING) {
Log.v(TAG, "Specific #" + i + ": " + sintent);
}
String action = sintent.getAction();
if (resultsAction != null && resultsAction.equals(action)) {
// If this action was explicitly requested, then don't
// remove things that have it.
action = null;
}
ResolveInfo ri = null;
ActivityInfo ai = null;
ComponentName comp = sintent.getComponent();
if (comp == null) {
ri = resolveIntent(
sintent,
specificTypes != null ? specificTypes[i] : null,
flags, userId);
if (ri == null) {
continue;
}
if (ri == mResolveInfo) {
// ACK! Must do something better with this.
}
ai = ri.activityInfo;
comp = new ComponentName(ai.applicationInfo.packageName,
ai.name);
} else {
ai = getActivityInfo(comp, flags, userId);
if (ai == null) {
continue;
}
}
// Look for any generic query activities that are duplicates
// of this specific one, and remove them from the results.
if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
N = results.size();
int j;
for (j=specificsPos; j<N; j++) {
ResolveInfo sri = results.get(j);
if ((sri.activityInfo.name.equals(comp.getClassName())
&& sri.activityInfo.applicationInfo.packageName.equals(
comp.getPackageName()))
|| (action != null && sri.filter.matchAction(action))) {
results.remove(j);
if (DEBUG_INTENT_MATCHING) Log.v(
TAG, "Removing duplicate item from " + j
+ " due to specific " + specificsPos);
if (ri == null) {
ri = sri;
}
j--;
N--;
}
}
// Add this specific item to its proper place.
if (ri == null) {
ri = new ResolveInfo();
ri.activityInfo = ai;
}
results.add(specificsPos, ri);
ri.specificIndex = i;
specificsPos++;
}
}
// Now we go through the remaining generic results and remove any
// duplicate actions that are found here.
N = results.size();
for (int i=specificsPos; i<N-1; i++) {
final ResolveInfo rii = results.get(i);
if (rii.filter == null) {
continue;
}
// Iterate over all of the actions of this result's intent
// filter... typically this should be just one.
final Iterator<String> it = rii.filter.actionsIterator();
if (it == null) {
continue;
}
while (it.hasNext()) {
final String action = it.next();
if (resultsAction != null && resultsAction.equals(action)) {
// If this action was explicitly requested, then don't
// remove things that have it.
continue;
}
for (int j=i+1; j<N; j++) {
final ResolveInfo rij = results.get(j);
if (rij.filter != null && rij.filter.hasAction(action)) {
results.remove(j);
if (DEBUG_INTENT_MATCHING) Log.v(
TAG, "Removing duplicate item from " + j
+ " due to action " + action + " at " + i);
j--;
N--;
}
}
}
// If the caller didn't request filter information, drop it now
// so we don't have to marshall/unmarshall it.
if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
rii.filter = null;
}
}
// Filter out the caller activity if so requested.
if (caller != null) {
N = results.size();
for (int i=0; i<N; i++) {
ActivityInfo ainfo = results.get(i).activityInfo;
if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
&& caller.getClassName().equals(ainfo.name)) {
results.remove(i);
break;
}
}
}
// If the caller didn't request filter information,
// drop them now so we don't have to
// marshall/unmarshall it.
if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
N = results.size();
for (int i=0; i<N; i++) {
results.get(i).filter = null;
}
}
if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
return results;
}
@Override
public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
int userId) {
if (!sUserManager.exists(userId)) return Collections.emptyList();
ComponentName comp = intent.getComponent();
if (comp == null) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
comp = intent.getComponent();
}
}
if (comp != null) {
List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
ActivityInfo ai = getReceiverInfo(comp, flags, userId);
if (ai != null) {
ResolveInfo ri = new ResolveInfo();
ri.activityInfo = ai;
list.add(ri);
}
return list;
}
// reader
synchronized (mPackages) {
String pkgName = intent.getPackage();
if (pkgName == null) {
return mReceivers.queryIntent(intent, resolvedType, flags, userId);
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
userId);
}
return null;
}
}
@Override
public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
if (!sUserManager.exists(userId)) return null;
if (query != null) {
if (query.size() >= 1) {
// If there is more than one service with the same priority,
// just arbitrarily pick the first one.
return query.get(0);
}
}
return null;
}
@Override
public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
int userId) {
if (!sUserManager.exists(userId)) return Collections.emptyList();
ComponentName comp = intent.getComponent();
if (comp == null) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
comp = intent.getComponent();
}
}
if (comp != null) {
final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
final ServiceInfo si = getServiceInfo(comp, flags, userId);
if (si != null) {
final ResolveInfo ri = new ResolveInfo();
ri.serviceInfo = si;
list.add(ri);
}
return list;
}
// reader
synchronized (mPackages) {
String pkgName = intent.getPackage();
if (pkgName == null) {
return mServices.queryIntent(intent, resolvedType, flags, userId);
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
userId);
}
return null;
}
}
@Override
public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
// writer
synchronized (mPackages) {
ArrayList<PackageInfo> list;
if (listUninstalled) {
list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
for (PackageSetting ps : mSettings.mPackages.values()) {
PackageInfo pi;
if (ps.pkg != null) {
pi = generatePackageInfo(ps.pkg, flags, userId);
} else {
pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
}
if (pi != null) {
list.add(pi);
}
}
} else {
list = new ArrayList<PackageInfo>(mPackages.size());
for (PackageParser.Package p : mPackages.values()) {
PackageInfo pi = generatePackageInfo(p, flags, userId);
if (pi != null) {
list.add(pi);
}
}
}
return new ParceledListSlice<PackageInfo>(list);
}
}
private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
String[] permissions, boolean[] tmp, int flags, int userId) {
int numMatch = 0;
final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
for (int i=0; i<permissions.length; i++) {
if (gp.grantedPermissions.contains(permissions[i])) {
tmp[i] = true;
numMatch++;
} else {
tmp[i] = false;
}
}
if (numMatch == 0) {
return;
}
PackageInfo pi;
if (ps.pkg != null) {
pi = generatePackageInfo(ps.pkg, flags, userId);
} else {
pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
}
if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
if (numMatch == permissions.length) {
pi.requestedPermissions = permissions;
} else {
pi.requestedPermissions = new String[numMatch];
numMatch = 0;
for (int i=0; i<permissions.length; i++) {
if (tmp[i]) {
pi.requestedPermissions[numMatch] = permissions[i];
numMatch++;
}
}
}
}
list.add(pi);
}
@Override
public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
String[] permissions, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
// writer
synchronized (mPackages) {
ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
boolean[] tmpBools = new boolean[permissions.length];
if (listUninstalled) {
for (PackageSetting ps : mSettings.mPackages.values()) {
addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
}
} else {
for (PackageParser.Package pkg : mPackages.values()) {
PackageSetting ps = (PackageSetting)pkg.mExtras;
if (ps != null) {
addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
userId);
}
}
}
return new ParceledListSlice<PackageInfo>(list);
}
}
@Override
public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
// writer
synchronized (mPackages) {
ArrayList<ApplicationInfo> list;
if (listUninstalled) {
list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
for (PackageSetting ps : mSettings.mPackages.values()) {
ApplicationInfo ai;
if (ps.pkg != null) {
ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
ps.readUserState(userId), userId);
} else {
ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
}
if (ai != null) {
list.add(ai);
}
}
} else {
list = new ArrayList<ApplicationInfo>(mPackages.size());
for (PackageParser.Package p : mPackages.values()) {
if (p.mExtras != null) {
ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
((PackageSetting)p.mExtras).readUserState(userId), userId);
if (ai != null) {
list.add(ai);
}
}
}
}
return new ParceledListSlice<ApplicationInfo>(list);
}
}
public List<ApplicationInfo> getPersistentApplications(int flags) {
final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
// reader
synchronized (mPackages) {
final Iterator<PackageParser.Package> i = mPackages.values().iterator();
final int userId = UserHandle.getCallingUserId();
while (i.hasNext()) {
final PackageParser.Package p = i.next();
if (p.applicationInfo != null
&& (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
&& (!mSafeMode || isSystemApp(p))) {
PackageSetting ps = mSettings.mPackages.get(p.packageName);
if (ps != null) {
ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
ps.readUserState(userId), userId);
if (ai != null) {
finalList.add(ai);
}
}
}
}
}
return finalList;
}
@Override
public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
// reader
synchronized (mPackages) {
final PackageParser.Provider provider = mProviders.get(name);
PackageSetting ps = provider != null
? mSettings.mPackages.get(provider.owner.packageName)
: null;
return ps != null
&& mSettings.isEnabledLPr(provider.info, flags, userId)
&& (!mSafeMode || (provider.info.applicationInfo.flags
&ApplicationInfo.FLAG_SYSTEM) != 0)
? PackageParser.generateProviderInfo(provider, flags,
ps.readUserState(userId), userId)
: null;
}
}
/**
* @deprecated
*/
@Deprecated
public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
// reader
synchronized (mPackages) {
final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet()
.iterator();
final int userId = UserHandle.getCallingUserId();
while (i.hasNext()) {
Map.Entry<String, PackageParser.Provider> entry = i.next();
PackageParser.Provider p = entry.getValue();
PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
if (ps != null && p.syncable
&& (!mSafeMode || (p.info.applicationInfo.flags
&ApplicationInfo.FLAG_SYSTEM) != 0)) {
ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
ps.readUserState(userId), userId);
if (info != null) {
outNames.add(entry.getKey());
outInfo.add(info);
}
}
}
}
}
public List<ProviderInfo> queryContentProviders(String processName,
int uid, int flags) {
ArrayList<ProviderInfo> finalList = null;
// reader
synchronized (mPackages) {
final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
final int userId = processName != null ?
UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
while (i.hasNext()) {
final PackageParser.Provider p = i.next();
PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
if (ps != null && p.info.authority != null
&& (processName == null
|| (p.info.processName.equals(processName)
&& UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
&& mSettings.isEnabledLPr(p.info, flags, userId)
&& (!mSafeMode
|| (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
if (finalList == null) {
finalList = new ArrayList<ProviderInfo>(3);
}
ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
ps.readUserState(userId), userId);
if (info != null) {
finalList.add(info);
}
}
}
}
if (finalList != null) {
Collections.sort(finalList, mProviderInitOrderSorter);
}
return finalList;
}
public InstrumentationInfo getInstrumentationInfo(ComponentName name,
int flags) {
// reader
synchronized (mPackages) {
final PackageParser.Instrumentation i = mInstrumentation.get(name);
return PackageParser.generateInstrumentationInfo(i, flags);
}
}
public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
int flags) {
ArrayList<InstrumentationInfo> finalList =
new ArrayList<InstrumentationInfo>();
// reader
synchronized (mPackages) {
final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
while (i.hasNext()) {
final PackageParser.Instrumentation p = i.next();
if (targetPackage == null
|| targetPackage.equals(p.info.targetPackage)) {
InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
flags);
if (ii != null) {
finalList.add(ii);
}
}
}
}
return finalList;
}
private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
String[] files = dir.list();
if (files == null) {
Log.d(TAG, "No files in app dir " + dir);
return;
}
if (DEBUG_PACKAGE_SCANNING) {
Log.d(TAG, "Scanning app dir " + dir);
}
int i;
for (i=0; i<files.length; i++) {
File file = new File(dir, files[i]);
if (!isPackageFilename(files[i])) {
// Ignore entries which are not apk's
continue;
}
PackageParser.Package pkg = scanPackageLI(file,
flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
// Don't mess around with apps in system partition.
if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
// Delete the apk
Slog.w(TAG, "Cleaning up failed install of " + file);
file.delete();
}
}
}
private static File getSettingsProblemFile() {
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
File fname = new File(systemDir, "uiderrors.txt");
return fname;
}
static void reportSettingsProblem(int priority, String msg) {
try {
File fname = getSettingsProblemFile();
FileOutputStream out = new FileOutputStream(fname, true);
PrintWriter pw = new PrintWriter(out);
SimpleDateFormat formatter = new SimpleDateFormat();
String dateString = formatter.format(new Date(System.currentTimeMillis()));
pw.println(dateString + ": " + msg);
pw.close();
FileUtils.setPermissions(
fname.toString(),
FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
-1, -1);
} catch (java.io.IOException e) {
}
Slog.println(priority, TAG, msg);
}
private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
PackageParser.Package pkg, File srcFile, int parseFlags) {
if (GET_CERTIFICATES) {
if (ps != null
&& ps.codePath.equals(srcFile)
&& ps.timeStamp == srcFile.lastModified()) {
if (ps.signatures.mSignatures != null
&& ps.signatures.mSignatures.length != 0) {
// Optimization: reuse the existing cached certificates
// if the package appears to be unchanged.
pkg.mSignatures = ps.signatures.mSignatures;
return true;
}
Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
} else {
Log.i(TAG, srcFile.toString() + " changed; collecting certs");
}
if (!pp.collectCertificates(pkg, parseFlags)) {
mLastScanError = pp.getParseError();
return false;
}
}
return true;
}
/*
* Scan a package and return the newly parsed package.
* Returns null in case of errors and the error code is stored in mLastScanError
*/
private PackageParser.Package scanPackageLI(File scanFile,
int parseFlags, int scanMode, long currentTime, UserHandle user) {
mLastScanError = PackageManager.INSTALL_SUCCEEDED;
String scanPath = scanFile.getPath();
if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
parseFlags |= mDefParseFlags;
PackageParser pp = new PackageParser(scanPath);
pp.setSeparateProcesses(mSeparateProcesses);
pp.setOnlyCoreApps(mOnlyCore);
final PackageParser.Package pkg = pp.parsePackage(scanFile,
scanPath, mMetrics, parseFlags);
if (pkg == null) {
mLastScanError = pp.getParseError();
return null;
}
PackageSetting ps = null;
PackageSetting updatedPkg;
// reader
synchronized (mPackages) {
// Look to see if we already know about this package.
String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
// This package has been renamed to its original name. Let's
// use that.
ps = mSettings.peekPackageLPr(oldName);
}
// If there was no original package, see one for the real package name.
if (ps == null) {
ps = mSettings.peekPackageLPr(pkg.packageName);
}
// Check to see if this package could be hiding/updating a system
// package. Must look for it either under the original or real
// package name depending on our state.
updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
}
// First check if this is a system package that may involve an update
if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
if (ps != null && !ps.codePath.equals(scanFile)) {
// The path has changed from what was last scanned... check the
// version of the new path against what we have stored to determine
// what to do.
if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
if (pkg.mVersionCode < ps.versionCode) {
// The system package has been updated and the code path does not match
// Ignore entry. Skip it.
Log.i(TAG, "Package " + ps.name + " at " + scanFile
+ " ignored: updated version " + ps.versionCode
+ " better than this " + pkg.mVersionCode);
if (!updatedPkg.codePath.equals(scanFile)) {
Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
+ ps.name + " changing from " + updatedPkg.codePathString
+ " to " + scanFile);
updatedPkg.codePath = scanFile;
updatedPkg.codePathString = scanFile.toString();
}
updatedPkg.pkg = pkg;
mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
return null;
} else {
// The current app on the system partion is better than
// what we have updated to on the data partition; switch
// back to the system partition version.
// At this point, its safely assumed that package installation for
// apps in system partition will go through. If not there won't be a working
// version of the app
// writer
synchronized (mPackages) {
// Just remove the loaded entries from package lists.
mPackages.remove(ps.name);
}
Slog.w(TAG, "Package " + ps.name + " at " + scanFile
+ "reverting from " + ps.codePathString
+ ": new version " + pkg.mVersionCode
+ " better than installed " + ps.versionCode);
InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
synchronized (mInstallLock) {
args.cleanUpResourcesLI();
}
synchronized (mPackages) {
mSettings.enableSystemPackageLPw(ps.name);
}
}
}
}
if (updatedPkg != null) {
// An updated system app will not have the PARSE_IS_SYSTEM flag set
// initially
parseFlags |= PackageParser.PARSE_IS_SYSTEM;
}
// Verify certificates against what was last scanned
if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
return null;
}
/*
* A new system app appeared, but we already had a non-system one of the
* same name installed earlier.
*/
boolean shouldHideSystemApp = false;
if (updatedPkg == null && ps != null
&& (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
/*
* Check to make sure the signatures match first. If they don't,
* wipe the installed application and its data.
*/
if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
!= PackageManager.SIGNATURE_MATCH) {
if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
ps = null;
} else {
/*
* If the newly-added system app is an older version than the
* already installed version, hide it. It will be scanned later
* and re-added like an update.
*/
if (pkg.mVersionCode < ps.versionCode) {
shouldHideSystemApp = true;
} else {
/*
* The newly found system app is a newer version that the
* one previously installed. Simply remove the
* already-installed application and replace it with our own
* while keeping the application data.
*/
Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
+ ps.codePathString + ": new version " + pkg.mVersionCode
+ " better than installed " + ps.versionCode);
InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString);
synchronized (mInstallLock) {
args.cleanUpResourcesLI();
}
}
}
}
// The apk is forward locked (not public) if its code and resources
// are kept in different files.
// TODO grab this value from PackageSettings
if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
}
String codePath = null;
String resPath = null;
if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
if (ps != null && ps.resourcePathString != null) {
resPath = ps.resourcePathString;
} else {
// Should not happen at all. Just log an error.
Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
}
} else {
resPath = pkg.mScanPath;
}
codePath = pkg.mScanPath;
// Set application objects path explicitly.
setApplicationInfoPaths(pkg, codePath, resPath);
// Note that we invoke the following method only if we are about to unpack an application
PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
| SCAN_UPDATE_SIGNATURE, currentTime, user);
/*
* If the system app should be overridden by a previously installed
* data, hide the system app now and let the /data/app scan pick it up
* again.
*/
if (shouldHideSystemApp) {
synchronized (mPackages) {
/*
* We have to grant systems permissions before we hide, because
* grantPermissions will assume the package update is trying to
* expand its permissions.
*/
grantPermissionsLPw(pkg, true);
mSettings.disableSystemPackageLPw(pkg.packageName);
}
}
return scannedPkg;
}
private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
String destResPath) {
pkg.mPath = pkg.mScanPath = destCodePath;
pkg.applicationInfo.sourceDir = destCodePath;
pkg.applicationInfo.publicSourceDir = destResPath;
}
private static String fixProcessName(String defProcessName,
String processName, int uid) {
if (processName == null) {
return defProcessName;
}
return processName;
}
private boolean verifySignaturesLP(PackageSetting pkgSetting,
PackageParser.Package pkg) {
if (pkgSetting.signatures.mSignatures != null) {
// Already existing package. Make sure signatures match
if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
PackageManager.SIGNATURE_MATCH) {
Slog.e(TAG, "Package " + pkg.packageName
+ " signatures do not match the previously installed version; ignoring!");
mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
return false;
}
}
// Check for shared user signatures
if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
Slog.e(TAG, "Package " + pkg.packageName
+ " has no signatures that match those in shared user "
+ pkgSetting.sharedUser.name + "; ignoring!");
mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
return false;
}
}
return true;
}
/**
* Enforces that only the system UID or root's UID can call a method exposed
* via Binder.
*
* @param message used as message if SecurityException is thrown
* @throws SecurityException if the caller is not system or root
*/
private static final void enforceSystemOrRoot(String message) {
final int uid = Binder.getCallingUid();
if (uid != Process.SYSTEM_UID && uid != 0) {
throw new SecurityException(message);
}
}
public void performBootDexOpt() {
HashSet<PackageParser.Package> pkgs = null;
synchronized (mPackages) {
pkgs = mDeferredDexOpt;
mDeferredDexOpt = null;
}
if (pkgs != null) {
int i = 0;
for (PackageParser.Package pkg : pkgs) {
if (!isFirstBoot()) {
i++;
try {
ActivityManagerNative.getDefault().showBootMessage(
mContext.getResources().getString(
com.android.internal.R.string.android_upgrading_apk,
i, pkgs.size()), true);
} catch (RemoteException e) {
}
}
PackageParser.Package p = pkg;
synchronized (mInstallLock) {
if (!p.mDidDexOpt) {
performDexOptLI(p, false, false, true);
}
}
}
}
}
public boolean performDexOpt(String packageName) {
enforceSystemOrRoot("Only the system can request dexopt be performed");
if (!mNoDexOpt) {
return false;
}
PackageParser.Package p;
synchronized (mPackages) {
p = mPackages.get(packageName);
if (p == null || p.mDidDexOpt) {
return false;
}
}
synchronized (mInstallLock) {
return performDexOptLI(p, false, false, true) == DEX_OPT_PERFORMED;
}
}
private void performDexOptLibsLI(ArrayList<String> libs, boolean forceDex, boolean defer,
HashSet<String> done) {
for (int i=0; i<libs.size(); i++) {
PackageParser.Package libPkg;
String libName;
synchronized (mPackages) {
libName = libs.get(i);
SharedLibraryEntry lib = mSharedLibraries.get(libName);
if (lib != null && lib.apk != null) {
libPkg = mPackages.get(lib.apk);
} else {
libPkg = null;
}
}
if (libPkg != null && !done.contains(libName)) {
performDexOptLI(libPkg, forceDex, defer, done);
}
}
}
static final int DEX_OPT_SKIPPED = 0;
static final int DEX_OPT_PERFORMED = 1;
static final int DEX_OPT_DEFERRED = 2;
static final int DEX_OPT_FAILED = -1;
private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
HashSet<String> done) {
boolean performed = false;
if (done != null) {
done.add(pkg.packageName);
if (pkg.usesLibraries != null) {
performDexOptLibsLI(pkg.usesLibraries, forceDex, defer, done);
}
if (pkg.usesOptionalLibraries != null) {
performDexOptLibsLI(pkg.usesOptionalLibraries, forceDex, defer, done);
}
}
if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
String path = pkg.mScanPath;
int ret = 0;
try {
if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
if (!forceDex && defer) {
if (mDeferredDexOpt == null) {
mDeferredDexOpt = new HashSet<PackageParser.Package>();
}
mDeferredDexOpt.add(pkg);
return DEX_OPT_DEFERRED;
} else {
Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg));
pkg.mDidDexOpt = true;
performed = true;
}
}
} catch (FileNotFoundException e) {
Slog.w(TAG, "Apk not found for dexopt: " + path);
ret = -1;
} catch (IOException e) {
Slog.w(TAG, "IOException reading apk: " + path, e);
ret = -1;
} catch (dalvik.system.StaleDexCacheError e) {
Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
ret = -1;
} catch (Exception e) {
Slog.w(TAG, "Exception when doing dexopt : ", e);
ret = -1;
}
if (ret < 0) {
//error from installer
return DEX_OPT_FAILED;
}
}
return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
}
private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
boolean inclDependencies) {
HashSet<String> done;
boolean performed = false;
if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
done = new HashSet<String>();
done.add(pkg.packageName);
} else {
done = null;
}
return performDexOptLI(pkg, forceDex, defer, done);
}
private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Slog.w(TAG, "Unable to update from " + oldPkg.name
+ " to " + newPkg.packageName
+ ": old package not in system partition");
return false;
} else if (mPackages.get(oldPkg.name) != null) {
Slog.w(TAG, "Unable to update from " + oldPkg.name
+ " to " + newPkg.packageName
+ ": old package still exists");
return false;
}
return true;
}
File getDataPathForUser(int userId) {
return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
}
private File getDataPathForPackage(String packageName, int userId) {
/*
* Until we fully support multiple users, return the directory we
* previously would have. The PackageManagerTests will need to be
* revised when this is changed back..
*/
if (userId == 0) {
return new File(mAppDataDir, packageName);
} else {
return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
+ File.separator + packageName);
}
}
private int createDataDirsLI(String packageName, int uid, String seinfo) {
int[] users = sUserManager.getUserIds();
int res = mInstaller.install(packageName, uid, uid, seinfo);
if (res < 0) {
return res;
}
for (int user : users) {
if (user != 0) {
res = mInstaller.createUserData(packageName,
UserHandle.getUid(user, uid), user);
if (res < 0) {
return res;
}
}
}
return res;
}
private int removeDataDirsLI(String packageName) {
int[] users = sUserManager.getUserIds();
int res = 0;
for (int user : users) {
int resInner = mInstaller.remove(packageName, user);
if (resInner < 0) {
res = resInner;
}
}
final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
if (!nativeLibraryFile.delete()) {
Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
}
return res;
}
private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
PackageParser.Package changingLib) {
if (file.path != null) {
mTmpSharedLibraries[num] = file.path;
return num+1;
}
PackageParser.Package p = mPackages.get(file.apk);
if (changingLib != null && changingLib.packageName.equals(file.apk)) {
// If we are doing this while in the middle of updating a library apk,
// then we need to make sure to use that new apk for determining the
// dependencies here. (We haven't yet finished committing the new apk
// to the package manager state.)
if (p == null || p.packageName.equals(changingLib.packageName)) {
p = changingLib;
}
}
if (p != null) {
String path = p.mPath;
for (int i=0; i<num; i++) {
if (mTmpSharedLibraries[i].equals(path)) {
return num;
}
}
mTmpSharedLibraries[num] = p.mPath;
return num+1;
}
return num;
}
private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
PackageParser.Package changingLib) {
if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
if (mTmpSharedLibraries == null ||
mTmpSharedLibraries.length < mSharedLibraries.size()) {
mTmpSharedLibraries = new String[mSharedLibraries.size()];
}
int num = 0;
int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
for (int i=0; i<N; i++) {
final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
if (file == null) {
Slog.e(TAG, "Package " + pkg.packageName
+ " requires unavailable shared library "
+ pkg.usesLibraries.get(i) + "; failing!");
mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
return false;
}
num = addSharedLibraryLPw(file, num, changingLib);
}
N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
for (int i=0; i<N; i++) {
final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
if (file == null) {
Slog.w(TAG, "Package " + pkg.packageName
+ " desires unavailable shared library "
+ pkg.usesOptionalLibraries.get(i) + "; ignoring!");
} else {
num = addSharedLibraryLPw(file, num, changingLib);
}
}
if (num > 0) {
pkg.usesLibraryFiles = new String[num];
System.arraycopy(mTmpSharedLibraries, 0,
pkg.usesLibraryFiles, 0, num);
} else {
pkg.usesLibraryFiles = null;
}
}
return true;
}
private static boolean hasString(List<String> list, List<String> which) {
if (list == null) {
return false;
}
for (int i=list.size()-1; i>=0; i--) {
for (int j=which.size()-1; j>=0; j--) {
if (which.get(j).equals(list.get(i))) {
return true;
}
}
}
return false;
}
private void updateAllSharedLibrariesLPw() {
for (PackageParser.Package pkg : mPackages.values()) {
updateSharedLibrariesLPw(pkg, null);
}
}
private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
PackageParser.Package changingPkg) {
ArrayList<PackageParser.Package> res = null;
for (PackageParser.Package pkg : mPackages.values()) {
if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
|| hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
if (res == null) {
res = new ArrayList<PackageParser.Package>();
}
res.add(pkg);
updateSharedLibrariesLPw(pkg, changingPkg);
}
}
return res;
}
private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
int parseFlags, int scanMode, long currentTime, UserHandle user) {
File scanFile = new File(pkg.mScanPath);
if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
pkg.applicationInfo.publicSourceDir == null) {
// Bail out. The resource and code paths haven't been set.
Slog.w(TAG, " Code and resource paths haven't been set correctly");
mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
return null;
}
mScanningPath = scanFile;
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
}
if (pkg.packageName.equals("android")) {
synchronized (mPackages) {
if (mAndroidApplication != null) {
Slog.w(TAG, "*************************************************");
Slog.w(TAG, "Core android package being redefined. Skipping.");
Slog.w(TAG, " file=" + mScanningPath);
Slog.w(TAG, "*************************************************");
mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
return null;
}
// Set up information for our fall-back user intent resolution
// activity.
mPlatformPackage = pkg;
pkg.mVersionCode = mSdkVersion;
mAndroidApplication = pkg.applicationInfo;
mResolveActivity.applicationInfo = mAndroidApplication;
mResolveActivity.name = ResolverActivity.class.getName();
mResolveActivity.packageName = mAndroidApplication.packageName;
mResolveActivity.processName = "system:ui";
mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
mResolveActivity.exported = true;
mResolveActivity.enabled = true;
mResolveInfo.activityInfo = mResolveActivity;
mResolveInfo.priority = 0;
mResolveInfo.preferredOrder = 0;
mResolveInfo.match = 0;
mResolveComponentName = new ComponentName(
mAndroidApplication.packageName, mResolveActivity.name);
}
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Scanning package " + pkg.packageName);
}
if (mPackages.containsKey(pkg.packageName)
|| mSharedLibraries.containsKey(pkg.packageName)) {
Slog.w(TAG, "Application package " + pkg.packageName
+ " already installed. Skipping duplicate.");
mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
return null;
}
if (!pkg.applicationInfo.sourceDir.startsWith(Environment.getRootDirectory().getPath()) &&
!pkg.applicationInfo.sourceDir.startsWith("/vendor")) {
Object obj = mSettings.getUserIdLPr(1000);
Signature[] s1 = null;
if (obj instanceof SharedUserSetting) {
s1 = ((SharedUserSetting)obj).signatures.mSignatures;
}
if ((compareSignatures(pkg.mSignatures, s1) == PackageManager.SIGNATURE_MATCH)) {
Slog.w(TAG, "Cannot install platform packages to user storage");
mLastScanError = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
return null;
}
}
// Initialize package source and resource directories
File destCodeFile = new File(pkg.applicationInfo.sourceDir);
File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
SharedUserSetting suid = null;
PackageSetting pkgSetting = null;
if (!isSystemApp(pkg)) {
// Only system apps can use these features.
pkg.mOriginalPackages = null;
pkg.mRealPackage = null;
pkg.mAdoptPermissions = null;
}
// writer
synchronized (mPackages) {
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
// Check all shared libraries and map to their actual file path.
// We only do this here for apps not on a system dir, because those
// are the only ones that can fail an install due to this. We
// will take care of the system apps by updating all of their
// library paths after the scan is done.
if (!updateSharedLibrariesLPw(pkg, null)) {
return null;
}
}
if (pkg.mSharedUserId != null) {
suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
pkg.applicationInfo.flags, true);
if (suid == null) {
Slog.w(TAG, "Creating application package " + pkg.packageName
+ " for shared user failed");
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
+ "): packages=" + suid.packages);
}
}
// Check if we are renaming from an original package name.
PackageSetting origPackage = null;
String realName = null;
if (pkg.mOriginalPackages != null) {
// This package may need to be renamed to a previously
// installed name. Let's check on that...
final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
if (pkg.mOriginalPackages.contains(renamed)) {
// This package had originally been installed as the
// original name, and we have already taken care of
// transitioning to the new one. Just update the new
// one to continue using the old name.
realName = pkg.mRealPackage;
if (!pkg.packageName.equals(renamed)) {
// Callers into this function may have already taken
// care of renaming the package; only do it here if
// it is not already done.
pkg.setPackageName(renamed);
}
} else {
for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
if ((origPackage = mSettings.peekPackageLPr(
pkg.mOriginalPackages.get(i))) != null) {
// We do have the package already installed under its
// original name... should we use it?
if (!verifyPackageUpdateLPr(origPackage, pkg)) {
// New package is not compatible with original.
origPackage = null;
continue;
} else if (origPackage.sharedUser != null) {
// Make sure uid is compatible between packages.
if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Slog.w(TAG, "Unable to migrate data from " + origPackage.name
+ " to " + pkg.packageName + ": old uid "
+ origPackage.sharedUser.name
+ " differs from " + pkg.mSharedUserId);
origPackage = null;
continue;
}
} else {
if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
+ pkg.packageName + " to old name " + origPackage.name);
}
break;
}
}
}
}
if (mTransferedPackages.contains(pkg.packageName)) {
Slog.w(TAG, "Package " + pkg.packageName
+ " was transferred to another, but its .apk remains");
}
// Just create the setting, don't add it yet. For already existing packages
// the PkgSetting exists already and doesn't have to be created.
pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
destResourceFile, pkg.applicationInfo.nativeLibraryDir,
pkg.applicationInfo.flags, user, false);
if (pkgSetting == null) {
Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (pkgSetting.origPackage != null) {
// If we are first transitioning from an original package,
// fix up the new package's name now. We need to do this after
// looking up the package under its new name, so getPackageLP
// can take care of fiddling things correctly.
pkg.setPackageName(origPackage.name);
// File a report about this.
String msg = "New package " + pkgSetting.realName
+ " renamed to replace old package " + pkgSetting.name;
reportSettingsProblem(Log.WARN, msg);
// Make a note of it.
mTransferedPackages.add(origPackage.name);
// No longer need to retain this.
pkgSetting.origPackage = null;
}
if (realName != null) {
// Make a note of it.
mTransferedPackages.add(pkg.packageName);
}
if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
}
if (mFoundPolicyFile) {
SELinuxMMAC.assignSeinfoValue(pkg);
}
pkg.applicationInfo.uid = pkgSetting.appId;
pkg.mExtras = pkgSetting;
if (!verifySignaturesLP(pkgSetting, pkg)) {
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
return null;
}
// The signature has changed, but this package is in the system
// image... let's recover!
pkgSetting.signatures.mSignatures = pkg.mSignatures;
// However... if this package is part of a shared user, but it
// doesn't match the signature of the shared user, let's fail.
// What this means is that you can't change the signatures
// associated with an overall shared user, which doesn't seem all
// that unreasonable.
if (pkgSetting.sharedUser != null) {
if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
return null;
}
}
// File a report about this.
String msg = "System package " + pkg.packageName
+ " signature changed; retaining data.";
reportSettingsProblem(Log.WARN, msg);
}
// Verify that this new package doesn't have any content providers
// that conflict with existing packages. Only do this if the
// package isn't already installed, since we don't want to break
// things that are installed.
if ((scanMode&SCAN_NEW_INSTALL) != 0) {
final int N = pkg.providers.size();
int i;
for (i=0; i<N; i++) {
PackageParser.Provider p = pkg.providers.get(i);
if (p.info.authority != null) {
String names[] = p.info.authority.split(";");
for (int j = 0; j < names.length; j++) {
if (mProviders.containsKey(names[j])) {
PackageParser.Provider other = mProviders.get(names[j]);
Slog.w(TAG, "Can't install because provider name " + names[j] +
" (in package " + pkg.applicationInfo.packageName +
") is already used by "
+ ((other != null && other.getComponentName() != null)
? other.getComponentName().getPackageName() : "?"));
mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
return null;
}
}
}
}
}
if (pkg.mAdoptPermissions != null) {
// This package wants to adopt ownership of permissions from
// another package.
for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
final String origName = pkg.mAdoptPermissions.get(i);
final PackageSetting orig = mSettings.peekPackageLPr(origName);
if (orig != null) {
if (verifyPackageUpdateLPr(orig, pkg)) {
Slog.i(TAG, "Adopting permissions from " + origName + " to "
+ pkg.packageName);
mSettings.transferPermissionsLPw(origName, pkg.packageName);
}
}
}
}
}
final String pkgName = pkg.packageName;
final long scanFileTime = scanFile.lastModified();
final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
pkg.applicationInfo.processName = fixProcessName(
pkg.applicationInfo.packageName,
pkg.applicationInfo.processName,
pkg.applicationInfo.uid);
File dataPath;
if (mPlatformPackage == pkg) {
// The system package is special.
dataPath = new File (Environment.getDataDirectory(), "system");
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
// This is a normal package, need to make its data directory.
dataPath = getDataPathForPackage(pkg.packageName, 0);
boolean uidError = false;
if (dataPath.exists()) {
int currentUid = 0;
try {
StructStat stat = Libcore.os.stat(dataPath.getPath());
currentUid = stat.st_uid;
} catch (ErrnoException e) {
Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
}
// If we have mismatched owners for the data path, we have a problem.
if (currentUid != pkg.applicationInfo.uid) {
boolean recovered = false;
if (currentUid == 0) {
// The directory somehow became owned by root. Wow.
// This is probably because the system was stopped while
// installd was in the middle of messing with its libs
// directory. Ask installd to fix that.
int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.uid);
if (ret >= 0) {
recovered = true;
String msg = "Package " + pkg.packageName
+ " unexpectedly changed to uid 0; recovered to " +
+ pkg.applicationInfo.uid;
reportSettingsProblem(Log.WARN, msg);
}
}
if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
|| (scanMode&SCAN_BOOTING) != 0)) {
// If this is a system app, we can at least delete its
// current data so the application will still work.
int ret = removeDataDirsLI(pkgName);
if (ret >= 0) {
// TODO: Kill the processes first
// Old data gone!
String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
? "System package " : "Third party package ";
String msg = prefix + pkg.packageName
+ " has changed from uid: "
+ currentUid + " to "
+ pkg.applicationInfo.uid + "; old data erased";
reportSettingsProblem(Log.WARN, msg);
recovered = true;
// And now re-install the app.
ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.seinfo);
if (ret == -1) {
// Ack should not happen!
msg = prefix + pkg.packageName
+ " could not have data directory re-created after delete.";
reportSettingsProblem(Log.WARN, msg);
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
}
if (!recovered) {
mHasSystemUidErrors = true;
}
} else if (!recovered) {
// If we allow this install to proceed, we will be broken.
// Abort, abort!
mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
return null;
}
if (!recovered) {
pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
+ pkg.applicationInfo.uid + "/fs_"
+ currentUid;
pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
String msg = "Package " + pkg.packageName
+ " has mismatched uid: "
+ currentUid + " on disk, "
+ pkg.applicationInfo.uid + " in settings";
// writer
synchronized (mPackages) {
mSettings.mReadMessages.append(msg);
mSettings.mReadMessages.append('\n');
uidError = true;
if (!pkgSetting.uidError) {
reportSettingsProblem(Log.ERROR, msg);
}
}
}
}
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.v(TAG, "Want this data dir: " + dataPath);
}
//invoke installer to do the actual installation
int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.seinfo);
if (ret < 0) {
// Error from installer
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (dataPath.exists()) {
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
Slog.w(TAG, "Unable to create data directory: " + dataPath);
pkg.applicationInfo.dataDir = null;
}
}
/*
* Set the data dir to the default "/data/data/<package name>/lib"
* if we got here without anyone telling us different (e.g., apps
* stored on SD card have their native libraries stored in the ASEC
* container with the APK).
*
* This happens during an upgrade from a package settings file that
* doesn't have a native library path attribute at all.
*/
if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
if (pkgSetting.nativeLibraryPathString == null) {
setInternalAppNativeLibraryPath(pkg, pkgSetting);
} else {
pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
}
}
pkgSetting.uidError = uidError;
}
String path = scanFile.getPath();
/* Note: We don't want to unpack the native binaries for
* system applications, unless they have been updated
* (the binaries are already under /system/lib).
* Also, don't unpack libs for apps on the external card
* since they should have their libraries in the ASEC
* container already.
*
* In other words, we're going to unpack the binaries
* only for non-system apps and system app upgrades.
*/
if (pkg.applicationInfo.nativeLibraryDir != null) {
try {
File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
final String dataPathString = dataPath.getCanonicalPath();
if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
/*
* Upgrading from a previous version of the OS sometimes
* leaves native libraries in the /data/data/<app>/lib
* directory for system apps even when they shouldn't be.
* Recent changes in the JNI library search path
* necessitates we remove those to match previous behavior.
*/
if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Log.i(TAG, "removed obsolete native libraries for system package "
+ path);
}
} else {
if (!isForwardLocked(pkg) && !isExternal(pkg)) {
/*
* Update native library dir if it starts with
* /data/data
*/
- if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
+ // For devices using /datadata, dataPathString will point
+ // to /datadata while nativeLibraryDir will point to /data/data.
+ // Thus, compare to /data/data directly to avoid problems.
+ if (nativeLibraryDir.getPath().startsWith("/data/data")) {
setInternalAppNativeLibraryPath(pkg, pkgSetting);
nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
}
try {
if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
Slog.e(TAG, "Unable to copy native libraries");
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
} catch (IOException e) {
Slog.e(TAG, "Unable to copy native libraries", e);
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
}
if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
final int[] userIds = sUserManager.getUserIds();
synchronized (mInstallLock) {
for (int userId : userIds) {
if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
Slog.w(TAG, "Failed linking native library dir (user=" + userId
+ ")");
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
}
}
}
} catch (IOException ioe) {
Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
}
}
pkg.mScanPath = path;
if ((scanMode&SCAN_NO_DEX) == 0) {
if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
== DEX_OPT_FAILED) {
mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
return null;
}
}
if (mFactoryTest && pkg.requestedPermissions.contains(
android.Manifest.permission.FACTORY_TEST)) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
}
ArrayList<PackageParser.Package> clientLibPkgs = null;
// writer
synchronized (mPackages) {
if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
// Only system apps can add new shared libraries.
if (pkg.libraryNames != null) {
for (int i=0; i<pkg.libraryNames.size(); i++) {
String name = pkg.libraryNames.get(i);
boolean allowed = false;
if (isUpdatedSystemApp(pkg)) {
// New library entries can only be added through the
// system image. This is important to get rid of a lot
// of nasty edge cases: for example if we allowed a non-
// system update of the app to add a library, then uninstalling
// the update would make the library go away, and assumptions
// we made such as through app install filtering would now
// have allowed apps on the device which aren't compatible
// with it. Better to just have the restriction here, be
// conservative, and create many fewer cases that can negatively
// impact the user experience.
final PackageSetting sysPs = mSettings
.getDisabledSystemPkgLPr(pkg.packageName);
if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
if (name.equals(sysPs.pkg.libraryNames.get(j))) {
allowed = true;
allowed = true;
break;
}
}
}
} else {
allowed = true;
}
if (allowed) {
if (!mSharedLibraries.containsKey(name)) {
mSharedLibraries.put(name, new SharedLibraryEntry(null,
pkg.packageName));
} else if (!name.equals(pkg.packageName)) {
Slog.w(TAG, "Package " + pkg.packageName + " library "
+ name + " already exists; skipping");
}
} else {
Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
+ name + " that is not declared on system image; skipping");
}
}
if ((scanMode&SCAN_BOOTING) == 0) {
// If we are not booting, we need to update any applications
// that are clients of our shared library. If we are booting,
// this will all be done once the scan is complete.
clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
}
}
}
}
// We also need to dexopt any apps that are dependent on this library. Note that
// if these fail, we should abort the install since installing the library will
// result in some apps being broken.
if (clientLibPkgs != null) {
if ((scanMode&SCAN_NO_DEX) == 0) {
for (int i=0; i<clientLibPkgs.size(); i++) {
PackageParser.Package clientPkg = clientLibPkgs.get(i);
if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
== DEX_OPT_FAILED) {
mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
return null;
}
}
}
}
// Request the ActivityManager to kill the process(only for existing packages)
// so that we do not end up in a confused state while the user is still using the older
// version of the application while the new one gets installed.
if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
killApplication(pkg.applicationInfo.packageName,
pkg.applicationInfo.uid);
}
// Also need to kill any apps that are dependent on the library.
if (clientLibPkgs != null) {
for (int i=0; i<clientLibPkgs.size(); i++) {
PackageParser.Package clientPkg = clientLibPkgs.get(i);
killApplication(clientPkg.applicationInfo.packageName,
clientPkg.applicationInfo.uid);
}
}
// writer
synchronized (mPackages) {
// We don't expect installation to fail beyond this point,
if ((scanMode&SCAN_MONITOR) != 0) {
mAppDirs.put(pkg.mPath, pkg);
}
// Add the new setting to mSettings
mSettings.insertPackageSettingLPw(pkgSetting, pkg);
// Add the new setting to mPackages
mPackages.put(pkg.applicationInfo.packageName, pkg);
// Make sure we don't accidentally delete its data.
final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
while (iter.hasNext()) {
PackageCleanItem item = iter.next();
if (pkgName.equals(item.packageName)) {
iter.remove();
}
}
// Take care of first install / last update times.
if (currentTime != 0) {
if (pkgSetting.firstInstallTime == 0) {
pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
} else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
pkgSetting.lastUpdateTime = currentTime;
}
} else if (pkgSetting.firstInstallTime == 0) {
// We need *something*. Take time time stamp of the file.
pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
} else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
if (scanFileTime != pkgSetting.timeStamp) {
// A package on the system image has changed; consider this
// to be an update.
pkgSetting.lastUpdateTime = scanFileTime;
}
}
int N = pkg.providers.size();
StringBuilder r = null;
int i;
for (i=0; i<N; i++) {
PackageParser.Provider p = pkg.providers.get(i);
p.info.processName = fixProcessName(pkg.applicationInfo.processName,
p.info.processName, pkg.applicationInfo.uid);
mProvidersByComponent.put(new ComponentName(p.info.packageName,
p.info.name), p);
p.syncable = p.info.isSyncable;
if (p.info.authority != null) {
String names[] = p.info.authority.split(";");
p.info.authority = null;
for (int j = 0; j < names.length; j++) {
if (j == 1 && p.syncable) {
// We only want the first authority for a provider to possibly be
// syncable, so if we already added this provider using a different
// authority clear the syncable flag. We copy the provider before
// changing it because the mProviders object contains a reference
// to a provider that we don't want to change.
// Only do this for the second authority since the resulting provider
// object can be the same for all future authorities for this provider.
p = new PackageParser.Provider(p);
p.syncable = false;
}
if (!mProviders.containsKey(names[j])) {
mProviders.put(names[j], p);
if (p.info.authority == null) {
p.info.authority = names[j];
} else {
p.info.authority = p.info.authority + ";" + names[j];
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Registered content provider: " + names[j]
+ ", className = " + p.info.name + ", isSyncable = "
+ p.info.isSyncable);
}
} else {
PackageParser.Provider other = mProviders.get(names[j]);
Slog.w(TAG, "Skipping provider name " + names[j] +
" (in package " + pkg.applicationInfo.packageName +
"): name already used by "
+ ((other != null && other.getComponentName() != null)
? other.getComponentName().getPackageName() : "?"));
}
}
}
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(p.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
}
N = pkg.services.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Service s = pkg.services.get(i);
s.info.processName = fixProcessName(pkg.applicationInfo.processName,
s.info.processName, pkg.applicationInfo.uid);
mServices.addService(s);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(s.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
}
N = pkg.receivers.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Activity a = pkg.receivers.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName, pkg.applicationInfo.uid);
mReceivers.addActivity(a, "receiver");
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
}
N = pkg.activities.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Activity a = pkg.activities.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName, pkg.applicationInfo.uid);
mActivities.addActivity(a, "activity");
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
}
N = pkg.permissionGroups.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
if (cur == null) {
mPermissionGroups.put(pg.info.name, pg);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(pg.info.name);
}
} else {
Slog.w(TAG, "Permission group " + pg.info.name + " from package "
+ pg.info.packageName + " ignored: original from "
+ cur.info.packageName);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append("DUP:");
r.append(pg.info.name);
}
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
}
N = pkg.permissions.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Permission p = pkg.permissions.get(i);
HashMap<String, BasePermission> permissionMap =
p.tree ? mSettings.mPermissionTrees
: mSettings.mPermissions;
p.group = mPermissionGroups.get(p.info.group);
if (p.info.group == null || p.group != null) {
BasePermission bp = permissionMap.get(p.info.name);
if (bp == null) {
bp = new BasePermission(p.info.name, p.info.packageName,
BasePermission.TYPE_NORMAL);
permissionMap.put(p.info.name, bp);
}
if (bp.perm == null) {
if (bp.sourcePackage == null
|| bp.sourcePackage.equals(p.info.packageName)) {
BasePermission tree = findPermissionTreeLP(p.info.name);
if (tree == null
|| tree.sourcePackage.equals(p.info.packageName)) {
bp.packageSetting = pkgSetting;
bp.perm = p;
bp.uid = pkg.applicationInfo.uid;
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(p.info.name);
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: base tree "
+ tree.name + " is from package "
+ tree.sourcePackage);
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: original from "
+ bp.sourcePackage);
}
} else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append("DUP:");
r.append(p.info.name);
}
if (bp.perm == p) {
bp.protectionLevel = p.info.protectionLevel;
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: no group "
+ p.group);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
}
N = pkg.instrumentation.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Instrumentation a = pkg.instrumentation.get(i);
a.info.packageName = pkg.applicationInfo.packageName;
a.info.sourceDir = pkg.applicationInfo.sourceDir;
a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
a.info.dataDir = pkg.applicationInfo.dataDir;
a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
mInstrumentation.put(a.getComponentName(), a);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
}
if (pkg.protectedBroadcasts != null) {
N = pkg.protectedBroadcasts.size();
for (i=0; i<N; i++) {
mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
}
}
pkgSetting.setTimeStamp(scanFileTime);
}
return pkg;
}
private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
PackageSetting pkgSetting) {
final String apkLibPath = getApkName(pkgSetting.codePathString);
final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath();
pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
pkgSetting.nativeLibraryPathString = nativeLibraryPath;
}
private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
throws IOException {
if (!nativeLibraryDir.isDirectory()) {
nativeLibraryDir.delete();
if (!nativeLibraryDir.mkdir()) {
throw new IOException("Cannot create " + nativeLibraryDir.getPath());
}
try {
Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH
| S_IXOTH);
} catch (ErrnoException e) {
throw new IOException("Cannot chmod native library directory "
+ nativeLibraryDir.getPath(), e);
}
} else if (!SELinux.restorecon(nativeLibraryDir)) {
throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
}
/*
* If this is an internal application or our nativeLibraryPath points to
* the app-lib directory, unpack the libraries if necessary.
*/
return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir);
}
private void killApplication(String pkgName, int appId) {
// Request the ActivityManager to kill the process(only for existing packages)
// so that we do not end up in a confused state while the user is still using the older
// version of the application while the new one gets installed.
IActivityManager am = ActivityManagerNative.getDefault();
if (am != null) {
try {
am.killApplicationWithAppId(pkgName, appId);
} catch (RemoteException e) {
}
}
}
// NOTE: this method can return null if the SystemServer is still
// initializing
public IAssetRedirectionManager getAssetRedirectionManager() {
if (mAssetRedirectionManager != null) {
return mAssetRedirectionManager;
}
IBinder b = ServiceManager.getService("assetredirection");
mAssetRedirectionManager = IAssetRedirectionManager.Stub.asInterface(b);
return mAssetRedirectionManager;
}
private void cleanAssetRedirections(PackageParser.Package pkg) {
IAssetRedirectionManager rm = getAssetRedirectionManager();
if (rm == null) {
return;
}
try {
if (pkg.mIsThemeApk) {
rm.clearRedirectionMapsByTheme(pkg.packageName, null);
} else {
rm.clearPackageRedirectionMap(pkg.packageName);
}
} catch (RemoteException e) {
}
}
void removePackageLI(PackageSetting ps, boolean chatty) {
if (DEBUG_INSTALL) {
if (chatty)
Log.d(TAG, "Removing package " + ps.name);
}
// writer
synchronized (mPackages) {
mPackages.remove(ps.name);
if (ps.codePathString != null) {
mAppDirs.remove(ps.codePathString);
}
final PackageParser.Package pkg = ps.pkg;
if (pkg != null) {
cleanPackageDataStructuresLILPw(pkg, chatty);
}
}
}
void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
if (DEBUG_INSTALL) {
if (chatty)
Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
}
// writer
synchronized (mPackages) {
cleanAssetRedirections(pkg);
mPackages.remove(pkg.applicationInfo.packageName);
if (pkg.mPath != null) {
mAppDirs.remove(pkg.mPath);
}
cleanPackageDataStructuresLILPw(pkg, chatty);
}
}
void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
int N = pkg.providers.size();
StringBuilder r = null;
int i;
for (i=0; i<N; i++) {
PackageParser.Provider p = pkg.providers.get(i);
mProvidersByComponent.remove(new ComponentName(p.info.packageName,
p.info.name));
if (p.info.authority == null) {
/* There was another ContentProvider with this authority when
* this app was installed so this authority is null,
* Ignore it as we don't have to unregister the provider.
*/
continue;
}
String names[] = p.info.authority.split(";");
for (int j = 0; j < names.length; j++) {
if (mProviders.get(names[j]) == p) {
mProviders.remove(names[j]);
if (DEBUG_REMOVE) {
if (chatty)
Log.d(TAG, "Unregistered content provider: " + names[j]
+ ", className = " + p.info.name + ", isSyncable = "
+ p.info.isSyncable);
}
}
}
if (DEBUG_REMOVE && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(p.info.name);
}
}
if (r != null) {
if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
}
N = pkg.services.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Service s = pkg.services.get(i);
mServices.removeService(s);
if (chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(s.info.name);
}
}
if (r != null) {
if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
}
N = pkg.receivers.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Activity a = pkg.receivers.get(i);
mReceivers.removeActivity(a, "receiver");
if (DEBUG_REMOVE && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
}
N = pkg.activities.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Activity a = pkg.activities.get(i);
mActivities.removeActivity(a, "activity");
if (DEBUG_REMOVE && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
}
N = pkg.permissions.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Permission p = pkg.permissions.get(i);
BasePermission bp = mSettings.mPermissions.get(p.info.name);
if (bp == null) {
bp = mSettings.mPermissionTrees.get(p.info.name);
}
if (bp != null && bp.perm == p) {
bp.perm = null;
if (DEBUG_REMOVE && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(p.info.name);
}
}
}
if (r != null) {
if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
}
N = pkg.instrumentation.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Instrumentation a = pkg.instrumentation.get(i);
mInstrumentation.remove(a.getComponentName());
if (DEBUG_REMOVE && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
}
r = null;
if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
// Only system apps can hold shared libraries.
if (pkg.libraryNames != null) {
for (i=0; i<pkg.libraryNames.size(); i++) {
String name = pkg.libraryNames.get(i);
SharedLibraryEntry cur = mSharedLibraries.get(name);
if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
mSharedLibraries.remove(name);
if (DEBUG_REMOVE && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(name);
}
}
}
}
}
if (r != null) {
if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
}
}
private static final boolean isPackageFilename(String name) {
return name != null && name.endsWith(".apk");
}
private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
return true;
}
}
return false;
}
static final int UPDATE_PERMISSIONS_ALL = 1<<0;
static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
private void updatePermissionsLPw(String changingPkg,
PackageParser.Package pkgInfo, int flags) {
// Make sure there are no dangling permission trees.
Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
while (it.hasNext()) {
final BasePermission bp = it.next();
if (bp.packageSetting == null) {
// We may not yet have parsed the package, so just see if
// we still know about its settings.
bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
}
if (bp.packageSetting == null) {
Slog.w(TAG, "Removing dangling permission tree: " + bp.name
+ " from package " + bp.sourcePackage);
it.remove();
} else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
Slog.i(TAG, "Removing old permission tree: " + bp.name
+ " from package " + bp.sourcePackage);
flags |= UPDATE_PERMISSIONS_ALL;
it.remove();
}
}
}
// Make sure all dynamic permissions have been assigned to a package,
// and make sure there are no dangling permissions.
it = mSettings.mPermissions.values().iterator();
while (it.hasNext()) {
final BasePermission bp = it.next();
if (bp.type == BasePermission.TYPE_DYNAMIC) {
if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
+ bp.name + " pkg=" + bp.sourcePackage
+ " info=" + bp.pendingInfo);
if (bp.packageSetting == null && bp.pendingInfo != null) {
final BasePermission tree = findPermissionTreeLP(bp.name);
if (tree != null && tree.perm != null) {
bp.packageSetting = tree.packageSetting;
bp.perm = new PackageParser.Permission(tree.perm.owner,
new PermissionInfo(bp.pendingInfo));
bp.perm.info.packageName = tree.perm.info.packageName;
bp.perm.info.name = bp.name;
bp.uid = tree.uid;
}
}
}
if (bp.packageSetting == null) {
// We may not yet have parsed the package, so just see if
// we still know about its settings.
bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
}
if (bp.packageSetting == null) {
Slog.w(TAG, "Removing dangling permission: " + bp.name
+ " from package " + bp.sourcePackage);
it.remove();
} else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
Slog.i(TAG, "Removing old permission: " + bp.name
+ " from package " + bp.sourcePackage);
flags |= UPDATE_PERMISSIONS_ALL;
it.remove();
}
}
}
// Now update the permissions for all packages, in particular
// replace the granted permissions of the system packages.
if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
for (PackageParser.Package pkg : mPackages.values()) {
if (pkg != pkgInfo) {
grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
}
}
}
if (pkgInfo != null) {
grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
}
}
private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
final PackageSetting ps = (PackageSetting) pkg.mExtras;
if (ps == null) {
return;
}
final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
HashSet<String> origPermissions = gp.grantedPermissions;
boolean changedPermission = false;
if (replace) {
ps.permissionsFixed = false;
if (gp == ps) {
origPermissions = new HashSet<String>(gp.grantedPermissions);
gp.grantedPermissions.clear();
gp.gids = mGlobalGids;
}
}
if (gp.gids == null) {
gp.gids = mGlobalGids;
}
final int N = pkg.requestedPermissions.size();
for (int i=0; i<N; i++) {
final String name = pkg.requestedPermissions.get(i);
final boolean required = pkg.requestedPermissionsRequired.get(i);
final BasePermission bp = mSettings.mPermissions.get(name);
if (DEBUG_INSTALL) {
if (gp != ps) {
Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
}
}
if (bp == null || bp.packageSetting == null) {
Slog.w(TAG, "Unknown permission " + name
+ " in package " + pkg.packageName);
continue;
}
final String perm = bp.name;
boolean allowed;
boolean allowedSig = false;
final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
if (level == PermissionInfo.PROTECTION_NORMAL
|| level == PermissionInfo.PROTECTION_DANGEROUS) {
// We grant a normal or dangerous permission if any of the following
// are true:
// 1) The permission is required
// 2) The permission is optional, but was granted in the past
// 3) The permission is optional, but was requested by an
// app in /system (not /data)
//
// Otherwise, reject the permission.
allowed = (required || origPermissions.contains(perm)
|| (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
} else if (bp.packageSetting == null) {
// This permission is invalid; skip it.
allowed = false;
} else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
if (allowed) {
allowedSig = true;
}
} else {
allowed = false;
}
if (DEBUG_INSTALL) {
if (gp != ps) {
Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
}
}
if (allowed) {
if (!isSystemApp(ps) && ps.permissionsFixed) {
// If this is an existing, non-system package, then
// we can't add any new permissions to it.
if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
// Except... if this is a permission that was added
// to the platform (note: need to only do this when
// updating the platform).
allowed = isNewPlatformPermissionForPackage(perm, pkg);
}
}
if (allowed) {
if (!gp.grantedPermissions.contains(perm)) {
changedPermission = true;
gp.grantedPermissions.add(perm);
gp.gids = appendInts(gp.gids, bp.gids);
} else if (!ps.haveGids) {
gp.gids = appendInts(gp.gids, bp.gids);
}
} else {
Slog.w(TAG, "Not granting permission " + perm
+ " to package " + pkg.packageName
+ " because it was previously installed without");
}
} else {
if (gp.grantedPermissions.remove(perm)) {
changedPermission = true;
gp.gids = removeInts(gp.gids, bp.gids);
Slog.i(TAG, "Un-granting permission " + perm
+ " from package " + pkg.packageName
+ " (protectionLevel=" + bp.protectionLevel
+ " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
+ ")");
} else {
Slog.w(TAG, "Not granting permission " + perm
+ " to package " + pkg.packageName
+ " (protectionLevel=" + bp.protectionLevel
+ " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
+ ")");
}
}
}
if ((changedPermission || replace) && !ps.permissionsFixed &&
!isSystemApp(ps) || isUpdatedSystemApp(ps)){
// This is the first that we have heard about this package, so the
// permissions we have now selected are fixed until explicitly
// changed.
ps.permissionsFixed = true;
}
ps.haveGids = true;
}
private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
boolean allowed = false;
final int NP = PackageParser.NEW_PERMISSIONS.length;
for (int ip=0; ip<NP; ip++) {
final PackageParser.NewPermissionInfo npi
= PackageParser.NEW_PERMISSIONS[ip];
if (npi.name.equals(perm)
&& pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
allowed = true;
Log.i(TAG, "Auto-granting " + perm + " to old pkg "
+ pkg.packageName);
break;
}
}
return allowed;
}
private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
BasePermission bp, HashSet<String> origPermissions) {
boolean allowed;
allowed = (compareSignatures(
bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
== PackageManager.SIGNATURE_MATCH)
|| (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
== PackageManager.SIGNATURE_MATCH);
if (!allowed && (bp.protectionLevel
& PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
if (isSystemApp(pkg)) {
// For updated system applications, a system permission
// is granted only if it had been defined by the original application.
if (isUpdatedSystemApp(pkg)) {
final PackageSetting sysPs = mSettings
.getDisabledSystemPkgLPr(pkg.packageName);
final GrantedPermissions origGp = sysPs.sharedUser != null
? sysPs.sharedUser : sysPs;
if (origGp.grantedPermissions.contains(perm)) {
allowed = true;
} else {
// The system apk may have been updated with an older
// version of the one on the data partition, but which
// granted a new system permission that it didn't have
// before. In this case we do want to allow the app to
// now get the new permission, because it is allowed by
// the system image.
allowed = false;
if (sysPs.pkg != null) {
for (int j=0;
j<sysPs.pkg.requestedPermissions.size(); j++) {
if (perm.equals(
sysPs.pkg.requestedPermissions.get(j))) {
allowed = true;
break;
}
}
}
}
} else {
allowed = true;
}
}
}
if (!allowed && (bp.protectionLevel
& PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
// For development permissions, a development permission
// is granted only if it was already granted.
allowed = origPermissions.contains(perm);
}
return allowed;
}
final class ActivityIntentResolver
extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
boolean defaultOnly, int userId) {
if (!sUserManager.exists(userId)) return null;
mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
return super.queryIntent(intent, resolvedType, defaultOnly, userId);
}
public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
int userId) {
if (!sUserManager.exists(userId)) return null;
mFlags = flags;
return super.queryIntent(intent, resolvedType,
(flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
}
public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
if (!sUserManager.exists(userId)) return null;
if (packageActivities == null) {
return null;
}
mFlags = flags;
final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
final int N = packageActivities.size();
ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
for (int i = 0; i < N; ++i) {
intentFilters = packageActivities.get(i).intents;
if (intentFilters != null && intentFilters.size() > 0) {
PackageParser.ActivityIntentInfo[] array =
new PackageParser.ActivityIntentInfo[intentFilters.size()];
intentFilters.toArray(array);
listCut.add(array);
}
}
return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
}
public final void addActivity(PackageParser.Activity a, String type) {
final boolean systemApp = isSystemApp(a.info.applicationInfo);
mActivities.put(a.getComponentName(), a);
if (DEBUG_SHOW_INFO)
Log.v(
TAG, " " + type + " " +
(a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
if (DEBUG_SHOW_INFO)
Log.v(TAG, " Class=" + a.info.name);
final int NI = a.intents.size();
for (int j=0; j<NI; j++) {
PackageParser.ActivityIntentInfo intent = a.intents.get(j);
if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
intent.setPriority(0);
Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
+ a.className + " with priority > 0, forcing to 0");
}
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " IntentFilter:");
intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
}
if (!intent.debugCheck()) {
Log.w(TAG, "==> For Activity " + a.info.name);
}
addFilter(intent);
}
}
public final void removeActivity(PackageParser.Activity a, String type) {
mActivities.remove(a.getComponentName());
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " " + type + " "
+ (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
: a.info.name) + ":");
Log.v(TAG, " Class=" + a.info.name);
}
final int NI = a.intents.size();
for (int j=0; j<NI; j++) {
PackageParser.ActivityIntentInfo intent = a.intents.get(j);
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " IntentFilter:");
intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
}
removeFilter(intent);
}
}
@Override
protected boolean allowFilterResult(
PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
ActivityInfo filterAi = filter.activity.info;
for (int i=dest.size()-1; i>=0; i--) {
ActivityInfo destAi = dest.get(i).activityInfo;
if (destAi.name == filterAi.name
&& destAi.packageName == filterAi.packageName) {
return false;
}
}
return true;
}
@Override
protected ActivityIntentInfo[] newArray(int size) {
return new ActivityIntentInfo[size];
}
@Override
protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
if (!sUserManager.exists(userId)) return true;
PackageParser.Package p = filter.activity.owner;
if (p != null) {
PackageSetting ps = (PackageSetting)p.mExtras;
if (ps != null) {
// System apps are never considered stopped for purposes of
// filtering, because there may be no way for the user to
// actually re-launch them.
return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
&& ps.getStopped(userId);
}
}
return false;
}
@Override
protected boolean isPackageForFilter(String packageName,
PackageParser.ActivityIntentInfo info) {
return packageName.equals(info.activity.owner.packageName);
}
@Override
protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
int match, int userId) {
if (!sUserManager.exists(userId)) return null;
if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
return null;
}
final PackageParser.Activity activity = info.activity;
if (mSafeMode && (activity.info.applicationInfo.flags
&ApplicationInfo.FLAG_SYSTEM) == 0) {
return null;
}
PackageSetting ps = (PackageSetting) activity.owner.mExtras;
if (ps == null) {
return null;
}
ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
ps.readUserState(userId), userId);
if (ai == null) {
return null;
}
final ResolveInfo res = new ResolveInfo();
res.activityInfo = ai;
if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
res.filter = info;
}
res.priority = info.getPriority();
res.preferredOrder = activity.owner.mPreferredOrder;
//System.out.println("Result: " + res.activityInfo.className +
// " = " + res.priority);
res.match = match;
res.isDefault = info.hasDefault;
res.labelRes = info.labelRes;
res.nonLocalizedLabel = info.nonLocalizedLabel;
res.icon = info.icon;
res.system = isSystemApp(res.activityInfo.applicationInfo);
return res;
}
@Override
protected void sortResults(List<ResolveInfo> results) {
Collections.sort(results, mResolvePrioritySorter);
}
@Override
protected void dumpFilter(PrintWriter out, String prefix,
PackageParser.ActivityIntentInfo filter) {
out.print(prefix); out.print(
Integer.toHexString(System.identityHashCode(filter.activity)));
out.print(' ');
out.print(filter.activity.getComponentShortName());
out.print(" filter ");
out.println(Integer.toHexString(System.identityHashCode(filter)));
}
// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
// final List<ResolveInfo> retList = Lists.newArrayList();
// while (i.hasNext()) {
// final ResolveInfo resolveInfo = i.next();
// if (isEnabledLP(resolveInfo.activityInfo)) {
// retList.add(resolveInfo);
// }
// }
// return retList;
// }
// Keys are String (activity class name), values are Activity.
private final HashMap<ComponentName, PackageParser.Activity> mActivities
= new HashMap<ComponentName, PackageParser.Activity>();
private int mFlags;
}
private final class ServiceIntentResolver
extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
boolean defaultOnly, int userId) {
mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
return super.queryIntent(intent, resolvedType, defaultOnly, userId);
}
public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
int userId) {
if (!sUserManager.exists(userId)) return null;
mFlags = flags;
return super.queryIntent(intent, resolvedType,
(flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
}
public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
if (!sUserManager.exists(userId)) return null;
if (packageServices == null) {
return null;
}
mFlags = flags;
final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
final int N = packageServices.size();
ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
for (int i = 0; i < N; ++i) {
intentFilters = packageServices.get(i).intents;
if (intentFilters != null && intentFilters.size() > 0) {
PackageParser.ServiceIntentInfo[] array =
new PackageParser.ServiceIntentInfo[intentFilters.size()];
intentFilters.toArray(array);
listCut.add(array);
}
}
return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
}
public final void addService(PackageParser.Service s) {
mServices.put(s.getComponentName(), s);
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " "
+ (s.info.nonLocalizedLabel != null
? s.info.nonLocalizedLabel : s.info.name) + ":");
Log.v(TAG, " Class=" + s.info.name);
}
final int NI = s.intents.size();
int j;
for (j=0; j<NI; j++) {
PackageParser.ServiceIntentInfo intent = s.intents.get(j);
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " IntentFilter:");
intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
}
if (!intent.debugCheck()) {
Log.w(TAG, "==> For Service " + s.info.name);
}
addFilter(intent);
}
}
public final void removeService(PackageParser.Service s) {
mServices.remove(s.getComponentName());
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
? s.info.nonLocalizedLabel : s.info.name) + ":");
Log.v(TAG, " Class=" + s.info.name);
}
final int NI = s.intents.size();
int j;
for (j=0; j<NI; j++) {
PackageParser.ServiceIntentInfo intent = s.intents.get(j);
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " IntentFilter:");
intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
}
removeFilter(intent);
}
}
@Override
protected boolean allowFilterResult(
PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
ServiceInfo filterSi = filter.service.info;
for (int i=dest.size()-1; i>=0; i--) {
ServiceInfo destAi = dest.get(i).serviceInfo;
if (destAi.name == filterSi.name
&& destAi.packageName == filterSi.packageName) {
return false;
}
}
return true;
}
@Override
protected PackageParser.ServiceIntentInfo[] newArray(int size) {
return new PackageParser.ServiceIntentInfo[size];
}
@Override
protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
if (!sUserManager.exists(userId)) return true;
PackageParser.Package p = filter.service.owner;
if (p != null) {
PackageSetting ps = (PackageSetting)p.mExtras;
if (ps != null) {
// System apps are never considered stopped for purposes of
// filtering, because there may be no way for the user to
// actually re-launch them.
return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
&& ps.getStopped(userId);
}
}
return false;
}
@Override
protected boolean isPackageForFilter(String packageName,
PackageParser.ServiceIntentInfo info) {
return packageName.equals(info.service.owner.packageName);
}
@Override
protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
int match, int userId) {
if (!sUserManager.exists(userId)) return null;
final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
return null;
}
final PackageParser.Service service = info.service;
if (mSafeMode && (service.info.applicationInfo.flags
&ApplicationInfo.FLAG_SYSTEM) == 0) {
return null;
}
PackageSetting ps = (PackageSetting) service.owner.mExtras;
if (ps == null) {
return null;
}
ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
ps.readUserState(userId), userId);
if (si == null) {
return null;
}
final ResolveInfo res = new ResolveInfo();
res.serviceInfo = si;
if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
res.filter = filter;
}
res.priority = info.getPriority();
res.preferredOrder = service.owner.mPreferredOrder;
//System.out.println("Result: " + res.activityInfo.className +
// " = " + res.priority);
res.match = match;
res.isDefault = info.hasDefault;
res.labelRes = info.labelRes;
res.nonLocalizedLabel = info.nonLocalizedLabel;
res.icon = info.icon;
res.system = isSystemApp(res.serviceInfo.applicationInfo);
return res;
}
@Override
protected void sortResults(List<ResolveInfo> results) {
Collections.sort(results, mResolvePrioritySorter);
}
@Override
protected void dumpFilter(PrintWriter out, String prefix,
PackageParser.ServiceIntentInfo filter) {
out.print(prefix); out.print(
Integer.toHexString(System.identityHashCode(filter.service)));
out.print(' ');
out.print(filter.service.getComponentShortName());
out.print(" filter ");
out.println(Integer.toHexString(System.identityHashCode(filter)));
}
// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
// final List<ResolveInfo> retList = Lists.newArrayList();
// while (i.hasNext()) {
// final ResolveInfo resolveInfo = (ResolveInfo) i;
// if (isEnabledLP(resolveInfo.serviceInfo)) {
// retList.add(resolveInfo);
// }
// }
// return retList;
// }
// Keys are String (activity class name), values are Activity.
private final HashMap<ComponentName, PackageParser.Service> mServices
= new HashMap<ComponentName, PackageParser.Service>();
private int mFlags;
};
private static final Comparator<ResolveInfo> mResolvePrioritySorter =
new Comparator<ResolveInfo>() {
public int compare(ResolveInfo r1, ResolveInfo r2) {
int v1 = r1.priority;
int v2 = r2.priority;
//System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
if (v1 != v2) {
return (v1 > v2) ? -1 : 1;
}
v1 = r1.preferredOrder;
v2 = r2.preferredOrder;
if (v1 != v2) {
return (v1 > v2) ? -1 : 1;
}
if (r1.isDefault != r2.isDefault) {
return r1.isDefault ? -1 : 1;
}
v1 = r1.match;
v2 = r2.match;
//System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
if (v1 != v2) {
return (v1 > v2) ? -1 : 1;
}
if (r1.system != r2.system) {
return r1.system ? -1 : 1;
}
return 0;
}
};
private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
new Comparator<ProviderInfo>() {
public int compare(ProviderInfo p1, ProviderInfo p2) {
final int v1 = p1.initOrder;
final int v2 = p2.initOrder;
return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
}
};
static final void sendPackageBroadcast(String action, String pkg, String intentCategory,
Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
int[] userIds) {
IActivityManager am = ActivityManagerNative.getDefault();
if (am != null) {
try {
if (userIds == null) {
userIds = am.getRunningUserIds();
}
for (int id : userIds) {
final Intent intent = new Intent(action,
pkg != null ? Uri.fromParts("package", pkg, null) : null);
if (extras != null) {
intent.putExtras(extras);
}
if (targetPkg != null) {
intent.setPackage(targetPkg);
}
// Modify the UID when posting to other users
int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
if (uid > 0 && UserHandle.getUserId(uid) != id) {
uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
intent.putExtra(Intent.EXTRA_UID, uid);
}
intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
if (DEBUG_BROADCASTS) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.d(TAG, "Sending to user " + id + ": "
+ intent.toShortString(false, true, false, false)
+ " " + intent.getExtras(), here);
}
if (intentCategory != null) {
intent.addCategory(intentCategory);
}
am.broadcastIntent(null, intent, null, finishedReceiver,
0, null, null, null, android.app.AppOpsManager.OP_NONE,
finishedReceiver != null, false, id);
}
} catch (RemoteException ex) {
}
}
}
/**
* Check if the external storage media is available. This is true if there
* is a mounted external storage medium or if the external storage is
* emulated.
*/
private boolean isExternalMediaAvailable() {
return mMediaMounted || Environment.isExternalStorageEmulated();
}
public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
// writer
synchronized (mPackages) {
if (!isExternalMediaAvailable()) {
// If the external storage is no longer mounted at this point,
// the caller may not have been able to delete all of this
// packages files and can not delete any more. Bail.
return null;
}
final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
if (lastPackage != null) {
pkgs.remove(lastPackage);
}
if (pkgs.size() > 0) {
return pkgs.get(0);
}
}
return null;
}
void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
if (false) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
+ " andCode=" + andCode, here);
}
mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
userId, andCode ? 1 : 0, packageName));
}
void startCleaningPackages() {
// reader
synchronized (mPackages) {
if (!isExternalMediaAvailable()) {
return;
}
if (mSettings.mPackagesToBeCleaned.isEmpty()) {
return;
}
}
Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
IActivityManager am = ActivityManagerNative.getDefault();
if (am != null) {
try {
am.startService(null, intent, null, UserHandle.USER_OWNER);
} catch (RemoteException e) {
}
}
}
private final class AppDirObserver extends FileObserver {
public AppDirObserver(String path, int mask, boolean isrom) {
super(path, mask);
mRootDir = path;
mIsRom = isrom;
}
public void onEvent(int event, String path) {
String removedPackage = null;
int removedAppId = -1;
int[] removedUsers = null;
String addedPackage = null;
int addedAppId = -1;
int[] addedUsers = null;
String category = null;
// TODO post a message to the handler to obtain serial ordering
synchronized (mInstallLock) {
String fullPathStr = null;
File fullPath = null;
if (path != null) {
fullPath = new File(mRootDir, path);
fullPathStr = fullPath.getPath();
}
if (DEBUG_APP_DIR_OBSERVER)
Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
if (!isPackageFilename(path)) {
if (DEBUG_APP_DIR_OBSERVER)
Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
return;
}
// Ignore packages that are being installed or
// have just been installed.
if (ignoreCodePath(fullPathStr)) {
return;
}
PackageParser.Package p = null;
PackageSetting ps = null;
// reader
synchronized (mPackages) {
p = mAppDirs.get(fullPathStr);
if (p != null) {
if (p.mIsThemeApk) {
category = Intent.CATEGORY_THEME_PACKAGE_INSTALLED_STATE_CHANGE;
}
ps = mSettings.mPackages.get(p.applicationInfo.packageName);
if (ps != null) {
removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
} else {
removedUsers = sUserManager.getUserIds();
}
}
addedUsers = sUserManager.getUserIds();
}
if ((event&REMOVE_EVENTS) != 0) {
if (ps != null) {
if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
removePackageLI(ps, true);
removedPackage = ps.name;
removedAppId = ps.appId;
}
}
if ((event&ADD_EVENTS) != 0) {
if (p == null) {
if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
p = scanPackageLI(fullPath,
(mIsRom ? PackageParser.PARSE_IS_SYSTEM
| PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
PackageParser.PARSE_CHATTY |
PackageParser.PARSE_MUST_BE_APK,
SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
System.currentTimeMillis(), UserHandle.ALL);
if (p != null) {
/*
* TODO this seems dangerous as the package may have
* changed since we last acquired the mPackages
* lock.
*/
// writer
synchronized (mPackages) {
updatePermissionsLPw(p.packageName, p,
p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
}
addedPackage = p.applicationInfo.packageName;
addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
}
}
if (p != null && p.mIsThemeApk) {
category = Intent.CATEGORY_THEME_PACKAGE_INSTALLED_STATE_CHANGE;
}
}
// reader
synchronized (mPackages) {
mSettings.writeLPr();
}
}
if (removedPackage != null) {
Bundle extras = new Bundle(1);
extras.putInt(Intent.EXTRA_UID, removedAppId);
extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, category,
extras, null, null, removedUsers);
}
if (addedPackage != null) {
Bundle extras = new Bundle(1);
extras.putInt(Intent.EXTRA_UID, addedAppId);
sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, category,
extras, null, null, addedUsers);
}
}
private final String mRootDir;
private final boolean mIsRom;
}
/* Called when a downloaded package installation has been confirmed by the user */
public void installPackage(
final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
installPackage(packageURI, observer, flags, null);
}
/* Called when a downloaded package installation has been confirmed by the user */
public void installPackage(
final Uri packageURI, final IPackageInstallObserver observer, final int flags,
final String installerPackageName) {
installPackageWithVerification(packageURI, observer, flags, installerPackageName, null,
null, null);
}
@Override
public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
int flags, String installerPackageName, Uri verificationURI,
ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
VerificationParams.NO_UID, manifestDigest);
installPackageWithVerificationAndEncryption(packageURI, observer, flags,
installerPackageName, verificationParams, encryptionParams);
}
public void installPackageWithVerificationAndEncryption(Uri packageURI,
IPackageInstallObserver observer, int flags, String installerPackageName,
VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
null);
final int uid = Binder.getCallingUid();
if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
try {
observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
} catch (RemoteException re) {
}
return;
}
UserHandle user;
if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
user = UserHandle.ALL;
} else {
user = new UserHandle(UserHandle.getUserId(uid));
}
final int filteredFlags;
if (uid == Process.SHELL_UID || uid == 0) {
if (DEBUG_INSTALL) {
Slog.v(TAG, "Install from ADB");
}
filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
} else {
filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
}
verificationParams.setInstallerUid(uid);
final Message msg = mHandler.obtainMessage(INIT_COPY);
msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName,
verificationParams, encryptionParams, user);
mHandler.sendMessage(msg);
}
/**
* @hide
*/
@Override
public int installExistingPackageAsUser(String packageName, int userId) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
null);
PackageSetting pkgSetting;
final int uid = Binder.getCallingUid();
if (UserHandle.getUserId(uid) != userId) {
mContext.enforceCallingPermission(
android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
"installExistingPackage for user " + userId);
}
if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
}
long callingId = Binder.clearCallingIdentity();
try {
boolean sendAdded = false;
Bundle extras = new Bundle(1);
// writer
synchronized (mPackages) {
pkgSetting = mSettings.mPackages.get(packageName);
if (pkgSetting == null) {
return PackageManager.INSTALL_FAILED_INVALID_URI;
}
if (!pkgSetting.getInstalled(userId)) {
pkgSetting.setInstalled(true, userId);
mSettings.writePackageRestrictionsLPr(userId);
extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
sendAdded = true;
}
}
if (sendAdded) {
sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, null,
packageName, extras, null, null, new int[] {userId});
try {
IActivityManager am = ActivityManagerNative.getDefault();
final boolean isSystem =
isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
if (isSystem && am.isUserRunning(userId, false)) {
// The just-installed/enabled app is bundled on the system, so presumed
// to be able to run automatically without needing an explicit launch.
// Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
.setPackage(packageName);
am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
android.app.AppOpsManager.OP_NONE, false, false, userId);
}
} catch (RemoteException e) {
// shouldn't happen
Slog.w(TAG, "Unable to bootstrap installed package", e);
}
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
return PackageManager.INSTALL_SUCCEEDED;
}
private boolean isUserRestricted(int userId, String restrictionKey) {
Bundle restrictions = sUserManager.getUserRestrictions(userId);
if (restrictions.getBoolean(restrictionKey, false)) {
Log.w(TAG, "User is restricted: " + restrictionKey);
return true;
}
return false;
}
@Override
public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
"Only package verification agents can verify applications");
final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
final PackageVerificationResponse response = new PackageVerificationResponse(
verificationCode, Binder.getCallingUid());
msg.arg1 = id;
msg.obj = response;
mHandler.sendMessage(msg);
}
@Override
public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
long millisecondsToDelay) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
"Only package verification agents can extend verification timeouts");
final PackageVerificationState state = mPendingVerification.get(id);
final PackageVerificationResponse response = new PackageVerificationResponse(
verificationCodeAtTimeout, Binder.getCallingUid());
if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
}
if (millisecondsToDelay < 0) {
millisecondsToDelay = 0;
}
if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
&& (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
}
if ((state != null) && !state.timeoutExtended()) {
state.extendTimeout();
final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
msg.arg1 = id;
msg.obj = response;
mHandler.sendMessageDelayed(msg, millisecondsToDelay);
}
}
private void broadcastPackageVerified(int verificationId, Uri packageUri,
int verificationCode, UserHandle user) {
final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
mContext.sendBroadcastAsUser(intent, user,
android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
}
private ComponentName matchComponentForVerifier(String packageName,
List<ResolveInfo> receivers) {
ActivityInfo targetReceiver = null;
final int NR = receivers.size();
for (int i = 0; i < NR; i++) {
final ResolveInfo info = receivers.get(i);
if (info.activityInfo == null) {
continue;
}
if (packageName.equals(info.activityInfo.packageName)) {
targetReceiver = info.activityInfo;
break;
}
}
if (targetReceiver == null) {
return null;
}
return new ComponentName(targetReceiver.packageName, targetReceiver.name);
}
private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
if (pkgInfo.verifiers.length == 0) {
return null;
}
final int N = pkgInfo.verifiers.length;
final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
for (int i = 0; i < N; i++) {
final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
receivers);
if (comp == null) {
continue;
}
final int verifierUid = getUidForVerifier(verifierInfo);
if (verifierUid == -1) {
continue;
}
if (DEBUG_VERIFY) {
Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
+ " with the correct signature");
}
sufficientVerifiers.add(comp);
verificationState.addSufficientVerifier(verifierUid);
}
return sufficientVerifiers;
}
private int getUidForVerifier(VerifierInfo verifierInfo) {
synchronized (mPackages) {
final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
if (pkg == null) {
return -1;
} else if (pkg.mSignatures.length != 1) {
Slog.i(TAG, "Verifier package " + verifierInfo.packageName
+ " has more than one signature; ignoring");
return -1;
}
/*
* If the public key of the package's signature does not match
* our expected public key, then this is a different package and
* we should skip.
*/
final byte[] expectedPublicKey;
try {
final Signature verifierSig = pkg.mSignatures[0];
final PublicKey publicKey = verifierSig.getPublicKey();
expectedPublicKey = publicKey.getEncoded();
} catch (CertificateException e) {
return -1;
}
final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
Slog.i(TAG, "Verifier package " + verifierInfo.packageName
+ " does not have the expected public key; ignoring");
return -1;
}
return pkg.applicationInfo.uid;
}
}
public void finishPackageInstall(int token) {
enforceSystemOrRoot("Only the system is allowed to finish installs");
if (DEBUG_INSTALL) {
Slog.v(TAG, "BM finishing package install for " + token);
}
final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
mHandler.sendMessage(msg);
}
/**
* Get the verification agent timeout.
*
* @return verification timeout in milliseconds
*/
private long getVerificationTimeout() {
return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
DEFAULT_VERIFICATION_TIMEOUT);
}
/**
* Get the default verification agent response code.
*
* @return default verification response code
*/
private int getDefaultVerificationResponse() {
return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
DEFAULT_VERIFICATION_RESPONSE);
}
/**
* Check whether or not package verification has been enabled.
*
* @return true if verification should be performed
*/
private boolean isVerificationEnabled(int flags) {
if (!DEFAULT_VERIFY_ENABLE) {
return false;
}
// Check if installing from ADB
if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
// Do not run verification in a test harness environment
if (ActivityManager.isRunningInTestHarness()) {
return false;
}
// Check if the developer does not want package verification for ADB installs
if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
return false;
}
}
return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
}
/**
* Get the "allow unknown sources" setting.
*
* @return the current "allow unknown sources" setting
*/
private int getUnknownSourcesSettings() {
return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
-1);
}
public void setInstallerPackageName(String targetPackage, String installerPackageName) {
final int uid = Binder.getCallingUid();
// writer
synchronized (mPackages) {
PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
if (targetPackageSetting == null) {
throw new IllegalArgumentException("Unknown target package: " + targetPackage);
}
PackageSetting installerPackageSetting;
if (installerPackageName != null) {
installerPackageSetting = mSettings.mPackages.get(installerPackageName);
if (installerPackageSetting == null) {
throw new IllegalArgumentException("Unknown installer package: "
+ installerPackageName);
}
} else {
installerPackageSetting = null;
}
Signature[] callerSignature;
Object obj = mSettings.getUserIdLPr(uid);
if (obj != null) {
if (obj instanceof SharedUserSetting) {
callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
} else if (obj instanceof PackageSetting) {
callerSignature = ((PackageSetting)obj).signatures.mSignatures;
} else {
throw new SecurityException("Bad object " + obj + " for uid " + uid);
}
} else {
throw new SecurityException("Unknown calling uid " + uid);
}
// Verify: can't set installerPackageName to a package that is
// not signed with the same cert as the caller.
if (installerPackageSetting != null) {
if (compareSignatures(callerSignature,
installerPackageSetting.signatures.mSignatures)
!= PackageManager.SIGNATURE_MATCH) {
throw new SecurityException(
"Caller does not have same cert as new installer package "
+ installerPackageName);
}
}
// Verify: if target already has an installer package, it must
// be signed with the same cert as the caller.
if (targetPackageSetting.installerPackageName != null) {
PackageSetting setting = mSettings.mPackages.get(
targetPackageSetting.installerPackageName);
// If the currently set package isn't valid, then it's always
// okay to change it.
if (setting != null) {
if (compareSignatures(callerSignature,
setting.signatures.mSignatures)
!= PackageManager.SIGNATURE_MATCH) {
throw new SecurityException(
"Caller does not have same cert as old installer package "
+ targetPackageSetting.installerPackageName);
}
}
}
// Okay!
targetPackageSetting.installerPackageName = installerPackageName;
scheduleWriteSettingsLocked();
}
}
private void processPendingInstall(final InstallArgs args, final int currentStatus) {
// Queue up an async operation since the package installation may take a little while.
mHandler.post(new Runnable() {
public void run() {
mHandler.removeCallbacks(this);
// Result object to be returned
PackageInstalledInfo res = new PackageInstalledInfo();
res.returnCode = currentStatus;
res.uid = -1;
res.pkg = null;
res.removedInfo = new PackageRemovedInfo();
if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
args.doPreInstall(res.returnCode);
synchronized (mInstallLock) {
installPackageLI(args, true, res);
}
args.doPostInstall(res.returnCode, res.uid);
}
// A restore should be performed at this point if (a) the install
// succeeded, (b) the operation is not an update, and (c) the new
// package has a backupAgent defined.
final boolean update = res.removedInfo.removedPackage != null;
boolean doRestore = (!update
&& res.pkg != null
&& res.pkg.applicationInfo.backupAgentName != null);
// Set up the post-install work request bookkeeping. This will be used
// and cleaned up by the post-install event handling regardless of whether
// there's a restore pass performed. Token values are >= 1.
int token;
if (mNextInstallToken < 0) mNextInstallToken = 1;
token = mNextInstallToken++;
PostInstallData data = new PostInstallData(args, res);
mRunningInstalls.put(token, data);
if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
// Pass responsibility to the Backup Manager. It will perform a
// restore if appropriate, then pass responsibility back to the
// Package Manager to run the post-install observer callbacks
// and broadcasts.
IBackupManager bm = IBackupManager.Stub.asInterface(
ServiceManager.getService(Context.BACKUP_SERVICE));
if (bm != null) {
if (DEBUG_INSTALL) Log.v(TAG, "token " + token
+ " to BM for possible restore");
try {
bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
} catch (RemoteException e) {
// can't happen; the backup manager is local
} catch (Exception e) {
Slog.e(TAG, "Exception trying to enqueue restore", e);
doRestore = false;
}
} else {
Slog.e(TAG, "Backup Manager not found!");
doRestore = false;
}
}
if (!doRestore) {
// No restore possible, or the Backup Manager was mysteriously not
// available -- just fire the post-install work request directly.
if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
mHandler.sendMessage(msg);
}
}
});
}
private abstract class HandlerParams {
private static final int MAX_RETRIES = 4;
/**
* Number of times startCopy() has been attempted and had a non-fatal
* error.
*/
private int mRetries = 0;
/** User handle for the user requesting the information or installation. */
private final UserHandle mUser;
HandlerParams(UserHandle user) {
mUser = user;
}
UserHandle getUser() {
return mUser;
}
final boolean startCopy() {
boolean res;
try {
if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
if (++mRetries > MAX_RETRIES) {
Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
mHandler.sendEmptyMessage(MCS_GIVE_UP);
handleServiceError();
return false;
} else {
handleStartCopy();
res = true;
}
} catch (RemoteException e) {
if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
mHandler.sendEmptyMessage(MCS_RECONNECT);
res = false;
}
handleReturnCode();
return res;
}
final void serviceError() {
if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
handleServiceError();
handleReturnCode();
}
abstract void handleStartCopy() throws RemoteException;
abstract void handleServiceError();
abstract void handleReturnCode();
}
class MeasureParams extends HandlerParams {
private final PackageStats mStats;
private boolean mSuccess;
private final IPackageStatsObserver mObserver;
public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
super(new UserHandle(stats.userHandle));
mObserver = observer;
mStats = stats;
}
@Override
public String toString() {
return "MeasureParams{"
+ Integer.toHexString(System.identityHashCode(this))
+ " " + mStats.packageName + "}";
}
@Override
void handleStartCopy() throws RemoteException {
synchronized (mInstallLock) {
mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
}
final boolean mounted;
if (Environment.isExternalStorageEmulated()) {
mounted = true;
} else {
final String status = Environment.getExternalStorageState();
mounted = (Environment.MEDIA_MOUNTED.equals(status)
|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
}
if (mounted) {
final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
final File externalCacheDir = userEnv
.getExternalStorageAppCacheDirectory(mStats.packageName);
final long externalCacheSize = mContainerService
.calculateDirectorySize(externalCacheDir.getPath());
mStats.externalCacheSize = externalCacheSize;
final File externalDataDir = userEnv
.getExternalStorageAppDataDirectory(mStats.packageName);
long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
.getPath());
if (externalCacheDir.getParentFile().equals(externalDataDir)) {
externalDataSize -= externalCacheSize;
}
mStats.externalDataSize = externalDataSize;
final File externalMediaDir = userEnv
.getExternalStorageAppMediaDirectory(mStats.packageName);
mStats.externalMediaSize = mContainerService
.calculateDirectorySize(externalMediaDir.getPath());
final File externalObbDir = userEnv
.getExternalStorageAppObbDirectory(mStats.packageName);
mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
.getPath());
}
}
@Override
void handleReturnCode() {
if (mObserver != null) {
try {
mObserver.onGetStatsCompleted(mStats, mSuccess);
} catch (RemoteException e) {
Slog.i(TAG, "Observer no longer exists.");
}
}
}
@Override
void handleServiceError() {
Slog.e(TAG, "Could not measure application " + mStats.packageName
+ " external storage");
}
}
class InstallParams extends HandlerParams {
final IPackageInstallObserver observer;
int flags;
private final Uri mPackageURI;
final String installerPackageName;
final VerificationParams verificationParams;
private InstallArgs mArgs;
private int mRet;
private File mTempPackage;
final ContainerEncryptionParams encryptionParams;
InstallParams(Uri packageURI,
IPackageInstallObserver observer, int flags,
String installerPackageName, VerificationParams verificationParams,
ContainerEncryptionParams encryptionParams, UserHandle user) {
super(user);
this.mPackageURI = packageURI;
this.flags = flags;
this.observer = observer;
this.installerPackageName = installerPackageName;
this.verificationParams = verificationParams;
this.encryptionParams = encryptionParams;
}
@Override
public String toString() {
return "InstallParams{"
+ Integer.toHexString(System.identityHashCode(this))
+ " " + mPackageURI + "}";
}
public ManifestDigest getManifestDigest() {
if (verificationParams == null) {
return null;
}
return verificationParams.getManifestDigest();
}
private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
String packageName = pkgLite.packageName;
int installLocation = pkgLite.installLocation;
boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
// reader
synchronized (mPackages) {
PackageParser.Package pkg = mPackages.get(packageName);
if (pkg != null) {
if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
// Check for downgrading.
if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
if (pkgLite.versionCode < pkg.mVersionCode) {
Slog.w(TAG, "Can't install update of " + packageName
+ " update version " + pkgLite.versionCode
+ " is older than installed version "
+ pkg.mVersionCode);
return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
}
}
// Check for updated system application.
if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
if (onSd) {
Slog.w(TAG, "Cannot install update to system app on sdcard");
return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
}
return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
} else {
if (onSd) {
// Install flag overrides everything.
return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
}
// If current upgrade specifies particular preference
if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
// Application explicitly specified internal.
return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
} else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
// App explictly prefers external. Let policy decide
} else {
// Prefer previous location
if (isExternal(pkg)) {
return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
}
return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
}
}
} else {
// Invalid install. Return error code
return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
}
}
}
// All the special cases have been taken care of.
// Return result based on recommended install location.
if (onSd) {
return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
}
return pkgLite.recommendedInstallLocation;
}
/*
* Invoke remote method to get package information and install
* location values. Override install location based on default
* policy if needed and then create install arguments based
* on the install location.
*/
public void handleStartCopy() throws RemoteException {
int ret = PackageManager.INSTALL_SUCCEEDED;
final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
PackageInfoLite pkgLite = null;
if (onInt && onSd) {
// Check if both bits are set.
Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
} else {
final long lowThreshold;
final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
.getService(DeviceStorageMonitorService.SERVICE);
if (dsm == null) {
Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
lowThreshold = 0L;
} else {
lowThreshold = dsm.getMemoryLowThreshold();
}
try {
mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
final File packageFile;
if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
if (mTempPackage != null) {
ParcelFileDescriptor out;
try {
out = ParcelFileDescriptor.open(mTempPackage,
ParcelFileDescriptor.MODE_READ_WRITE);
} catch (FileNotFoundException e) {
out = null;
Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
}
// Make a temporary file for decryption.
ret = mContainerService
.copyResource(mPackageURI, encryptionParams, out);
IoUtils.closeQuietly(out);
packageFile = mTempPackage;
FileUtils.setPermissions(packageFile.getAbsolutePath(),
FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
| FileUtils.S_IROTH,
-1, -1);
} else {
packageFile = null;
}
} else {
packageFile = new File(mPackageURI.getPath());
}
if (packageFile != null) {
// Remote call to find out default install location
final String packageFilePath = packageFile.getAbsolutePath();
pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
lowThreshold);
/*
* If we have too little free space, try to free cache
* before giving up.
*/
if (pkgLite.recommendedInstallLocation
== PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
final long size = mContainerService.calculateInstalledSize(
packageFilePath, isForwardLocked());
if (mInstaller.freeCache(size + lowThreshold) >= 0) {
pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
flags, lowThreshold);
}
/*
* The cache free must have deleted the file we
* downloaded to install.
*
* TODO: fix the "freeCache" call to not delete
* the file we care about.
*/
if (pkgLite.recommendedInstallLocation
== PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
pkgLite.recommendedInstallLocation
= PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
}
}
}
} finally {
mContext.revokeUriPermission(mPackageURI,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (ret == PackageManager.INSTALL_SUCCEEDED) {
int loc = pkgLite.recommendedInstallLocation;
if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
} else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
} else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
} else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
ret = PackageManager.INSTALL_FAILED_INVALID_APK;
} else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
ret = PackageManager.INSTALL_FAILED_INVALID_URI;
} else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
} else {
// Override with defaults if needed.
loc = installLocationPolicy(pkgLite, flags);
if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
} else if (!onSd && !onInt) {
// Override install location with flags
if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
// Set the flag to install on external media.
flags |= PackageManager.INSTALL_EXTERNAL;
flags &= ~PackageManager.INSTALL_INTERNAL;
} else {
// Make sure the flag for installing on external
// media is unset
flags |= PackageManager.INSTALL_INTERNAL;
flags &= ~PackageManager.INSTALL_EXTERNAL;
}
}
}
}
final InstallArgs args = createInstallArgs(this);
mArgs = args;
if (ret == PackageManager.INSTALL_SUCCEEDED) {
/*
* ADB installs appear as UserHandle.USER_ALL, and can only be performed by
* UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
*/
int userIdentifier = getUser().getIdentifier();
if (userIdentifier == UserHandle.USER_ALL
&& ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
userIdentifier = UserHandle.USER_OWNER;
}
/*
* Determine if we have any installed package verifiers. If we
* do, then we'll defer to them to verify the packages.
*/
final int requiredUid = mRequiredVerifierPackage == null ? -1
: getPackageUid(mRequiredVerifierPackage, userIdentifier);
if (requiredUid != -1 && isVerificationEnabled(flags)) {
final Intent verification = new Intent(
Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
final List<ResolveInfo> receivers = queryIntentReceivers(verification,
PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
0 /* TODO: Which userId? */);
if (DEBUG_VERIFY) {
Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
+ verification.toString() + " with " + pkgLite.verifiers.length
+ " optional verifiers");
}
final int verificationId = mPendingVerificationToken++;
verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
installerPackageName);
verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
pkgLite.packageName);
verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
pkgLite.versionCode);
if (verificationParams != null) {
if (verificationParams.getVerificationURI() != null) {
verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
verificationParams.getVerificationURI());
}
if (verificationParams.getOriginatingURI() != null) {
verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
verificationParams.getOriginatingURI());
}
if (verificationParams.getReferrer() != null) {
verification.putExtra(Intent.EXTRA_REFERRER,
verificationParams.getReferrer());
}
if (verificationParams.getOriginatingUid() >= 0) {
verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
verificationParams.getOriginatingUid());
}
if (verificationParams.getInstallerUid() >= 0) {
verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
verificationParams.getInstallerUid());
}
}
final PackageVerificationState verificationState = new PackageVerificationState(
requiredUid, args);
mPendingVerification.append(verificationId, verificationState);
final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
receivers, verificationState);
/*
* If any sufficient verifiers were listed in the package
* manifest, attempt to ask them.
*/
if (sufficientVerifiers != null) {
final int N = sufficientVerifiers.size();
if (N == 0) {
Slog.i(TAG, "Additional verifiers required, but none installed.");
ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
} else {
for (int i = 0; i < N; i++) {
final ComponentName verifierComponent = sufficientVerifiers.get(i);
final Intent sufficientIntent = new Intent(verification);
sufficientIntent.setComponent(verifierComponent);
mContext.sendBroadcastAsUser(sufficientIntent, getUser());
}
}
}
final ComponentName requiredVerifierComponent = matchComponentForVerifier(
mRequiredVerifierPackage, receivers);
if (ret == PackageManager.INSTALL_SUCCEEDED
&& mRequiredVerifierPackage != null) {
/*
* Send the intent to the required verification agent,
* but only start the verification timeout after the
* target BroadcastReceivers have run.
*/
verification.setComponent(requiredVerifierComponent);
mContext.sendOrderedBroadcastAsUser(verification, getUser(),
android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final Message msg = mHandler
.obtainMessage(CHECK_PENDING_VERIFICATION);
msg.arg1 = verificationId;
mHandler.sendMessageDelayed(msg, getVerificationTimeout());
}
}, null, 0, null, null);
/*
* We don't want the copy to proceed until verification
* succeeds, so null out this field.
*/
mArgs = null;
}
} else {
/*
* No package verification is enabled, so immediately start
* the remote call to initiate copy using temporary file.
*/
ret = args.copyApk(mContainerService, true);
}
}
mRet = ret;
}
@Override
void handleReturnCode() {
// If mArgs is null, then MCS couldn't be reached. When it
// reconnects, it will try again to install. At that point, this
// will succeed.
if (mArgs != null) {
processPendingInstall(mArgs, mRet);
if (mTempPackage != null) {
if (!mTempPackage.delete()) {
Slog.w(TAG, "Couldn't delete temporary file: " +
mTempPackage.getAbsolutePath());
}
}
}
}
@Override
void handleServiceError() {
mArgs = createInstallArgs(this);
mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
}
public boolean isForwardLocked() {
return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
}
public Uri getPackageUri() {
if (mTempPackage != null) {
return Uri.fromFile(mTempPackage);
} else {
return mPackageURI;
}
}
}
/*
* Utility class used in movePackage api.
* srcArgs and targetArgs are not set for invalid flags and make
* sure to do null checks when invoking methods on them.
* We probably want to return ErrorPrams for both failed installs
* and moves.
*/
class MoveParams extends HandlerParams {
final IPackageMoveObserver observer;
final int flags;
final String packageName;
final InstallArgs srcArgs;
final InstallArgs targetArgs;
int uid;
int mRet;
MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
String packageName, String dataDir, int uid, UserHandle user) {
super(user);
this.srcArgs = srcArgs;
this.observer = observer;
this.flags = flags;
this.packageName = packageName;
this.uid = uid;
if (srcArgs != null) {
Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
} else {
targetArgs = null;
}
}
@Override
public String toString() {
return "MoveParams{"
+ Integer.toHexString(System.identityHashCode(this))
+ " " + packageName + "}";
}
public void handleStartCopy() throws RemoteException {
mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
// Check for storage space on target medium
if (!targetArgs.checkFreeStorage(mContainerService)) {
Log.w(TAG, "Insufficient storage to install");
return;
}
mRet = srcArgs.doPreCopy();
if (mRet != PackageManager.INSTALL_SUCCEEDED) {
return;
}
mRet = targetArgs.copyApk(mContainerService, false);
if (mRet != PackageManager.INSTALL_SUCCEEDED) {
srcArgs.doPostCopy(uid);
return;
}
mRet = srcArgs.doPostCopy(uid);
if (mRet != PackageManager.INSTALL_SUCCEEDED) {
return;
}
mRet = targetArgs.doPreInstall(mRet);
if (mRet != PackageManager.INSTALL_SUCCEEDED) {
return;
}
if (DEBUG_SD_INSTALL) {
StringBuilder builder = new StringBuilder();
if (srcArgs != null) {
builder.append("src: ");
builder.append(srcArgs.getCodePath());
}
if (targetArgs != null) {
builder.append(" target : ");
builder.append(targetArgs.getCodePath());
}
Log.i(TAG, builder.toString());
}
}
@Override
void handleReturnCode() {
targetArgs.doPostInstall(mRet, uid);
int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
if (mRet == PackageManager.INSTALL_SUCCEEDED) {
currentStatus = PackageManager.MOVE_SUCCEEDED;
} else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
}
processPendingMove(this, currentStatus);
}
@Override
void handleServiceError() {
mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
}
}
/**
* Used during creation of InstallArgs
*
* @param flags package installation flags
* @return true if should be installed on external storage
*/
private static boolean installOnSd(int flags) {
if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
return false;
}
if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
return true;
}
return false;
}
/**
* Used during creation of InstallArgs
*
* @param flags package installation flags
* @return true if should be installed as forward locked
*/
private static boolean installForwardLocked(int flags) {
return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
}
private InstallArgs createInstallArgs(InstallParams params) {
if (installOnSd(params.flags) || params.isForwardLocked()) {
return new AsecInstallArgs(params);
} else {
return new FileInstallArgs(params);
}
}
private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
String nativeLibraryPath) {
final boolean isInAsec;
if (installOnSd(flags)) {
/* Apps on SD card are always in ASEC containers. */
isInAsec = true;
} else if (installForwardLocked(flags)
&& !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
/*
* Forward-locked apps are only in ASEC containers if they're the
* new style
*/
isInAsec = true;
} else {
isInAsec = false;
}
if (isInAsec) {
return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
installOnSd(flags), installForwardLocked(flags));
} else {
return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
}
}
// Used by package mover
private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
if (installOnSd(flags) || installForwardLocked(flags)) {
String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
+ AsecInstallArgs.RES_FILE_NAME);
return new AsecInstallArgs(packageURI, cid, installOnSd(flags),
installForwardLocked(flags));
} else {
return new FileInstallArgs(packageURI, pkgName, dataDir);
}
}
static abstract class InstallArgs {
final IPackageInstallObserver observer;
// Always refers to PackageManager flags only
final int flags;
final Uri packageURI;
final String installerPackageName;
final ManifestDigest manifestDigest;
final UserHandle user;
InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags,
String installerPackageName, ManifestDigest manifestDigest,
UserHandle user) {
this.packageURI = packageURI;
this.flags = flags;
this.observer = observer;
this.installerPackageName = installerPackageName;
this.manifestDigest = manifestDigest;
this.user = user;
}
abstract void createCopyFile();
abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
abstract int doPreInstall(int status);
abstract boolean doRename(int status, String pkgName, String oldCodePath);
abstract int doPostInstall(int status, int uid);
abstract String getCodePath();
abstract String getResourcePath();
abstract String getNativeLibraryPath();
// Need installer lock especially for dex file removal.
abstract void cleanUpResourcesLI();
abstract boolean doPostDeleteLI(boolean delete);
abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
/**
* Called before the source arguments are copied. This is used mostly
* for MoveParams when it needs to read the source file to put it in the
* destination.
*/
int doPreCopy() {
return PackageManager.INSTALL_SUCCEEDED;
}
/**
* Called after the source arguments are copied. This is used mostly for
* MoveParams when it needs to read the source file to put it in the
* destination.
*
* @return
*/
int doPostCopy(int uid) {
return PackageManager.INSTALL_SUCCEEDED;
}
protected boolean isFwdLocked() {
return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
}
UserHandle getUser() {
return user;
}
}
class FileInstallArgs extends InstallArgs {
File installDir;
String codeFileName;
String resourceFileName;
String libraryPath;
boolean created = false;
FileInstallArgs(InstallParams params) {
super(params.getPackageUri(), params.observer, params.flags,
params.installerPackageName, params.getManifestDigest(),
params.getUser());
}
FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
super(null, null, 0, null, null, null);
File codeFile = new File(fullCodePath);
installDir = codeFile.getParentFile();
codeFileName = fullCodePath;
resourceFileName = fullResourcePath;
libraryPath = nativeLibraryPath;
}
FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
super(packageURI, null, 0, null, null, null);
installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
String apkName = getNextCodePath(null, pkgName, ".apk");
codeFileName = new File(installDir, apkName + ".apk").getPath();
resourceFileName = getResourcePathFromCodePath();
libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
}
boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
final long lowThreshold;
final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
.getService(DeviceStorageMonitorService.SERVICE);
if (dsm == null) {
Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
lowThreshold = 0L;
} else {
if (dsm.isMemoryLow()) {
Log.w(TAG, "Memory is reported as being too low; aborting package install");
return false;
}
lowThreshold = dsm.getMemoryLowThreshold();
}
try {
mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
} finally {
mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
String getCodePath() {
return codeFileName;
}
void createCopyFile() {
installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
codeFileName = createTempPackageFile(installDir).getPath();
resourceFileName = getResourcePathFromCodePath();
libraryPath = getLibraryPathFromCodePath();
created = true;
}
int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
if (temp) {
// Generate temp file name
createCopyFile();
}
// Get a ParcelFileDescriptor to write to the output file
File codeFile = new File(codeFileName);
if (!created) {
try {
codeFile.createNewFile();
// Set permissions
if (!setPermissions()) {
// Failed setting permissions.
return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
}
} catch (IOException e) {
Slog.w(TAG, "Failed to create file " + codeFile);
return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
}
}
ParcelFileDescriptor out = null;
try {
out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
} catch (FileNotFoundException e) {
Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
}
// Copy the resource now
int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
try {
mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
ret = imcs.copyResource(packageURI, null, out);
} finally {
IoUtils.closeQuietly(out);
mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
if (isFwdLocked()) {
final File destResourceFile = new File(getResourcePath());
// Copy the public files
try {
PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
} catch (IOException e) {
Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
+ " forward-locked app.");
destResourceFile.delete();
return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
}
}
final File nativeLibraryFile = new File(getNativeLibraryPath());
Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
if (nativeLibraryFile.exists()) {
NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
nativeLibraryFile.delete();
}
try {
int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
return copyRet;
}
} catch (IOException e) {
Slog.e(TAG, "Copying native libraries failed", e);
ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
}
return ret;
}
int doPreInstall(int status) {
if (status != PackageManager.INSTALL_SUCCEEDED) {
cleanUp();
}
return status;
}
boolean doRename(int status, final String pkgName, String oldCodePath) {
if (status != PackageManager.INSTALL_SUCCEEDED) {
cleanUp();
return false;
} else {
final File oldCodeFile = new File(getCodePath());
final File oldResourceFile = new File(getResourcePath());
final File oldLibraryFile = new File(getNativeLibraryPath());
// Rename APK file based on packageName
final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
final File newCodeFile = new File(installDir, apkName + ".apk");
if (!oldCodeFile.renameTo(newCodeFile)) {
return false;
}
codeFileName = newCodeFile.getPath();
// Rename public resource file if it's forward-locked.
final File newResFile = new File(getResourcePathFromCodePath());
if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
return false;
}
resourceFileName = newResFile.getPath();
// Rename library path
final File newLibraryFile = new File(getLibraryPathFromCodePath());
if (newLibraryFile.exists()) {
NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
newLibraryFile.delete();
}
if (!oldLibraryFile.renameTo(newLibraryFile)) {
Slog.e(TAG, "Cannot rename native library directory "
+ oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
return false;
}
libraryPath = newLibraryFile.getPath();
// Attempt to set permissions
if (!setPermissions()) {
return false;
}
if (!SELinux.restorecon(newCodeFile)) {
return false;
}
return true;
}
}
int doPostInstall(int status, int uid) {
if (status != PackageManager.INSTALL_SUCCEEDED) {
cleanUp();
}
return status;
}
String getResourcePath() {
return resourceFileName;
}
private String getResourcePathFromCodePath() {
final String codePath = getCodePath();
if (isFwdLocked()) {
final StringBuilder sb = new StringBuilder();
sb.append(mAppInstallDir.getPath());
sb.append('/');
sb.append(getApkName(codePath));
sb.append(".zip");
/*
* If our APK is a temporary file, mark the resource as a
* temporary file as well so it can be cleaned up after
* catastrophic failure.
*/
if (codePath.endsWith(".tmp")) {
sb.append(".tmp");
}
return sb.toString();
} else {
return codePath;
}
}
private String getLibraryPathFromCodePath() {
return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
}
@Override
String getNativeLibraryPath() {
if (libraryPath == null) {
libraryPath = getLibraryPathFromCodePath();
}
return libraryPath;
}
private boolean cleanUp() {
boolean ret = true;
String sourceDir = getCodePath();
String publicSourceDir = getResourcePath();
if (sourceDir != null) {
File sourceFile = new File(sourceDir);
if (!sourceFile.exists()) {
Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
ret = false;
}
// Delete application's code and resources
sourceFile.delete();
}
if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
final File publicSourceFile = new File(publicSourceDir);
if (!publicSourceFile.exists()) {
Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
}
if (publicSourceFile.exists()) {
publicSourceFile.delete();
}
}
if (libraryPath != null) {
File nativeLibraryFile = new File(libraryPath);
NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
if (!nativeLibraryFile.delete()) {
Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
}
}
return ret;
}
void cleanUpResourcesLI() {
String sourceDir = getCodePath();
if (cleanUp()) {
int retCode = mInstaller.rmdex(sourceDir);
if (retCode < 0) {
Slog.w(TAG, "Couldn't remove dex file for package: "
+ " at location "
+ sourceDir + ", retcode=" + retCode);
// we don't consider this to be a failure of the core package deletion
}
}
}
private boolean setPermissions() {
// TODO Do this in a more elegant way later on. for now just a hack
if (!isFwdLocked()) {
final int filePermissions =
FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
|FileUtils.S_IROTH;
int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
if (retCode != 0) {
Slog.e(TAG, "Couldn't set new package file permissions for " +
getCodePath()
+ ". The return code was: " + retCode);
// TODO Define new internal error
return false;
}
return true;
}
return true;
}
boolean doPostDeleteLI(boolean delete) {
// XXX err, shouldn't we respect the delete flag?
cleanUpResourcesLI();
return true;
}
}
private boolean isAsecExternal(String cid) {
final String asecPath = PackageHelper.getSdFilesystem(cid);
return !asecPath.startsWith(mAsecInternalPath);
}
/**
* Extract the MountService "container ID" from the full code path of an
* .apk.
*/
static String cidFromCodePath(String fullCodePath) {
int eidx = fullCodePath.lastIndexOf("/");
String subStr1 = fullCodePath.substring(0, eidx);
int sidx = subStr1.lastIndexOf("/");
return subStr1.substring(sidx+1, eidx);
}
class AsecInstallArgs extends InstallArgs {
static final String RES_FILE_NAME = "pkg.apk";
static final String PUBLIC_RES_FILE_NAME = "res.zip";
String cid;
String packagePath;
String resourcePath;
String libraryPath;
AsecInstallArgs(InstallParams params) {
super(params.getPackageUri(), params.observer, params.flags,
params.installerPackageName, params.getManifestDigest(),
params.getUser());
}
AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
boolean isExternal, boolean isForwardLocked) {
super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
| (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
null, null, null);
// Extract cid from fullCodePath
int eidx = fullCodePath.lastIndexOf("/");
String subStr1 = fullCodePath.substring(0, eidx);
int sidx = subStr1.lastIndexOf("/");
cid = subStr1.substring(sidx+1, eidx);
setCachePath(subStr1);
}
AsecInstallArgs(String cid, boolean isForwardLocked) {
super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
| (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
null, null, null);
this.cid = cid;
setCachePath(PackageHelper.getSdDir(cid));
}
AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) {
super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
| (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
null, null, null);
this.cid = cid;
}
void createCopyFile() {
cid = getTempContainerId();
}
boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
try {
mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
} finally {
mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
private final boolean isExternal() {
return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
}
int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
if (temp) {
createCopyFile();
} else {
/*
* Pre-emptively destroy the container since it's destroyed if
* copying fails due to it existing anyway.
*/
PackageHelper.destroySdDir(cid);
}
final String newCachePath;
try {
mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
} finally {
mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
if (newCachePath != null) {
setCachePath(newCachePath);
return PackageManager.INSTALL_SUCCEEDED;
} else {
return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
}
}
@Override
String getCodePath() {
return packagePath;
}
@Override
String getResourcePath() {
return resourcePath;
}
@Override
String getNativeLibraryPath() {
return libraryPath;
}
int doPreInstall(int status) {
if (status != PackageManager.INSTALL_SUCCEEDED) {
// Destroy container
PackageHelper.destroySdDir(cid);
} else {
boolean mounted = PackageHelper.isContainerMounted(cid);
if (!mounted) {
String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
Process.SYSTEM_UID);
if (newCachePath != null) {
setCachePath(newCachePath);
} else {
return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
}
}
}
return status;
}
boolean doRename(int status, final String pkgName,
String oldCodePath) {
String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
String newCachePath = null;
if (PackageHelper.isContainerMounted(cid)) {
// Unmount the container
if (!PackageHelper.unMountSdDir(cid)) {
Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
return false;
}
}
if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
" which might be stale. Will try to clean up.");
// Clean up the stale container and proceed to recreate.
if (!PackageHelper.destroySdDir(newCacheId)) {
Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
return false;
}
// Successfully cleaned up stale container. Try to rename again.
if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
+ " inspite of cleaning it up.");
return false;
}
}
if (!PackageHelper.isContainerMounted(newCacheId)) {
Slog.w(TAG, "Mounting container " + newCacheId);
newCachePath = PackageHelper.mountSdDir(newCacheId,
getEncryptKey(), Process.SYSTEM_UID);
} else {
newCachePath = PackageHelper.getSdDir(newCacheId);
}
if (newCachePath == null) {
Slog.w(TAG, "Failed to get cache path for " + newCacheId);
return false;
}
Log.i(TAG, "Succesfully renamed " + cid +
" to " + newCacheId +
" at new path: " + newCachePath);
cid = newCacheId;
setCachePath(newCachePath);
return true;
}
private void setCachePath(String newCachePath) {
File cachePath = new File(newCachePath);
libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
packagePath = new File(cachePath, RES_FILE_NAME).getPath();
if (isFwdLocked()) {
resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
} else {
resourcePath = packagePath;
}
}
int doPostInstall(int status, int uid) {
if (status != PackageManager.INSTALL_SUCCEEDED) {
cleanUp();
} else {
final int groupOwner;
final String protectedFile;
if (isFwdLocked()) {
groupOwner = UserHandle.getSharedAppGid(uid);
protectedFile = RES_FILE_NAME;
} else {
groupOwner = -1;
protectedFile = null;
}
if (uid < Process.FIRST_APPLICATION_UID
|| !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
Slog.e(TAG, "Failed to finalize " + cid);
PackageHelper.destroySdDir(cid);
return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
}
boolean mounted = PackageHelper.isContainerMounted(cid);
if (!mounted) {
PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
}
}
return status;
}
private void cleanUp() {
if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
// Destroy secure container
PackageHelper.destroySdDir(cid);
}
void cleanUpResourcesLI() {
String sourceFile = getCodePath();
// Remove dex file
int retCode = mInstaller.rmdex(sourceFile);
if (retCode < 0) {
Slog.w(TAG, "Couldn't remove dex file for package: "
+ " at location "
+ sourceFile.toString() + ", retcode=" + retCode);
// we don't consider this to be a failure of the core package deletion
}
cleanUp();
}
boolean matchContainer(String app) {
if (cid.startsWith(app)) {
return true;
}
return false;
}
String getPackageName() {
return getAsecPackageName(cid);
}
boolean doPostDeleteLI(boolean delete) {
boolean ret = false;
boolean mounted = PackageHelper.isContainerMounted(cid);
if (mounted) {
// Unmount first
ret = PackageHelper.unMountSdDir(cid);
}
if (ret && delete) {
cleanUpResourcesLI();
}
return ret;
}
@Override
int doPreCopy() {
if (isFwdLocked()) {
if (!PackageHelper.fixSdPermissions(cid,
getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
}
}
return PackageManager.INSTALL_SUCCEEDED;
}
@Override
int doPostCopy(int uid) {
if (isFwdLocked()) {
if (uid < Process.FIRST_APPLICATION_UID
|| !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
RES_FILE_NAME)) {
Slog.e(TAG, "Failed to finalize " + cid);
PackageHelper.destroySdDir(cid);
return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
}
}
return PackageManager.INSTALL_SUCCEEDED;
}
};
static String getAsecPackageName(String packageCid) {
int idx = packageCid.lastIndexOf("-");
if (idx == -1) {
return packageCid;
}
return packageCid.substring(0, idx);
}
// Utility method used to create code paths based on package name and available index.
private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
String idxStr = "";
int idx = 1;
// Fall back to default value of idx=1 if prefix is not
// part of oldCodePath
if (oldCodePath != null) {
String subStr = oldCodePath;
// Drop the suffix right away
if (subStr.endsWith(suffix)) {
subStr = subStr.substring(0, subStr.length() - suffix.length());
}
// If oldCodePath already contains prefix find out the
// ending index to either increment or decrement.
int sidx = subStr.lastIndexOf(prefix);
if (sidx != -1) {
subStr = subStr.substring(sidx + prefix.length());
if (subStr != null) {
if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
}
try {
idx = Integer.parseInt(subStr);
if (idx <= 1) {
idx++;
} else {
idx--;
}
} catch(NumberFormatException e) {
}
}
}
}
idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
return prefix + idxStr;
}
// Utility method used to ignore ADD/REMOVE events
// by directory observer.
private static boolean ignoreCodePath(String fullPathStr) {
String apkName = getApkName(fullPathStr);
int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
if (idx != -1 && ((idx+1) < apkName.length())) {
// Make sure the package ends with a numeral
String version = apkName.substring(idx+1);
try {
Integer.parseInt(version);
return true;
} catch (NumberFormatException e) {}
}
return false;
}
// Utility method that returns the relative package path with respect
// to the installation directory. Like say for /data/data/com.test-1.apk
// string com.test-1 is returned.
static String getApkName(String codePath) {
if (codePath == null) {
return null;
}
int sidx = codePath.lastIndexOf("/");
int eidx = codePath.lastIndexOf(".");
if (eidx == -1) {
eidx = codePath.length();
} else if (eidx == 0) {
Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
return null;
}
return codePath.substring(sidx+1, eidx);
}
class PackageInstalledInfo {
String name;
int uid;
// The set of users that originally had this package installed.
int[] origUsers;
// The set of users that now have this package installed.
int[] newUsers;
PackageParser.Package pkg;
int returnCode;
PackageRemovedInfo removedInfo;
}
/*
* Install a non-existing package.
*/
private void installNewPackageLI(PackageParser.Package pkg,
int parseFlags, int scanMode, UserHandle user,
String installerPackageName, PackageInstalledInfo res) {
// Remember this for later, in case we need to rollback this install
String pkgName = pkg.packageName;
if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
synchronized(mPackages) {
if (mSettings.mRenamedPackages.containsKey(pkgName)) {
// A package with the same name is already installed, though
// it has been renamed to an older name. The package we
// are trying to install should be installed as an update to
// the existing one, but that has not been requested, so bail.
Slog.w(TAG, "Attempt to re-install " + pkgName
+ " without first uninstalling package running as "
+ mSettings.mRenamedPackages.get(pkgName));
res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
return;
}
if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
// Don't allow installation over an existing package with the same name.
Slog.w(TAG, "Attempt to re-install " + pkgName
+ " without first uninstalling.");
res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
return;
}
}
mLastScanError = PackageManager.INSTALL_SUCCEEDED;
PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
System.currentTimeMillis(), user);
if (newPackage == null) {
Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
}
} else {
updateSettingsLI(newPackage,
installerPackageName,
null, null,
res);
// delete the partially installed application. the data directory will have to be
// restored if it was already existing
if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
// remove package from internal structures. Note that we want deletePackageX to
// delete the package data and cache directories that it created in
// scanPackageLocked, unless those directories existed before we even tried to
// install.
deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
res.removedInfo, true);
}
}
}
private void replacePackageLI(PackageParser.Package pkg,
int parseFlags, int scanMode, UserHandle user,
String installerPackageName, PackageInstalledInfo res) {
PackageParser.Package oldPackage;
String pkgName = pkg.packageName;
int[] allUsers;
boolean[] perUserInstalled;
// First find the old package info and check signatures
synchronized(mPackages) {
oldPackage = mPackages.get(pkgName);
if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
!= PackageManager.SIGNATURE_MATCH) {
Slog.w(TAG, "New package has a different signature: " + pkgName);
res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
return;
}
// In case of rollback, remember per-user/profile install state
PackageSetting ps = mSettings.mPackages.get(pkgName);
allUsers = sUserManager.getUserIds();
perUserInstalled = new boolean[allUsers.length];
for (int i = 0; i < allUsers.length; i++) {
perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
}
}
boolean sysPkg = (isSystemApp(oldPackage));
if (sysPkg) {
replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
user, allUsers, perUserInstalled, installerPackageName, res);
} else {
replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
user, allUsers, perUserInstalled, installerPackageName, res);
}
}
private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
int[] allUsers, boolean[] perUserInstalled,
String installerPackageName, PackageInstalledInfo res) {
PackageParser.Package newPackage = null;
String pkgName = deletedPackage.packageName;
boolean deletedPkg = true;
boolean updatedSettings = false;
if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
+ deletedPackage);
long origUpdateTime;
if (pkg.mExtras != null) {
origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
} else {
origUpdateTime = 0;
}
// First delete the existing package while retaining the data directory
if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
res.removedInfo, true)) {
// If the existing package wasn't successfully deleted
res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
deletedPkg = false;
} else {
// Successfully deleted the old package. Now proceed with re-installation
mLastScanError = PackageManager.INSTALL_SUCCEEDED;
newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
System.currentTimeMillis(), user);
if (newPackage == null) {
Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
}
} else {
updateSettingsLI(newPackage,
installerPackageName,
allUsers, perUserInstalled,
res);
updatedSettings = true;
}
}
if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
// remove package from internal structures. Note that we want deletePackageX to
// delete the package data and cache directories that it created in
// scanPackageLocked, unless those directories existed before we even tried to
// install.
if(updatedSettings) {
if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
deletePackageLI(
pkgName, null, true, allUsers, perUserInstalled,
PackageManager.DELETE_KEEP_DATA,
res.removedInfo, true);
}
// Since we failed to install the new package we need to restore the old
// package that we deleted.
if(deletedPkg) {
if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
File restoreFile = new File(deletedPackage.mPath);
// Parse old package
boolean oldOnSd = isExternal(deletedPackage);
int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
(isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
(oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
| SCAN_UPDATE_TIME;
if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
origUpdateTime, null) == null) {
Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
return;
}
// Restore of old package succeeded. Update permissions.
// writer
synchronized (mPackages) {
updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
UPDATE_PERMISSIONS_ALL);
// can downgrade to reader
mSettings.writeLPr();
}
Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
}
}
}
private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
int[] allUsers, boolean[] perUserInstalled,
String installerPackageName, PackageInstalledInfo res) {
if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
+ ", old=" + deletedPackage);
PackageParser.Package newPackage = null;
boolean updatedSettings = false;
parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
PackageParser.PARSE_IS_SYSTEM;
String packageName = deletedPackage.packageName;
res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
if (packageName == null) {
Slog.w(TAG, "Attempt to delete null packageName.");
return;
}
PackageParser.Package oldPkg;
PackageSetting oldPkgSetting;
// reader
synchronized (mPackages) {
oldPkg = mPackages.get(packageName);
oldPkgSetting = mSettings.mPackages.get(packageName);
if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
(oldPkgSetting == null)) {
Slog.w(TAG, "Couldn't find package:"+packageName+" information");
return;
}
}
killApplication(packageName, oldPkg.applicationInfo.uid);
res.removedInfo.uid = oldPkg.applicationInfo.uid;
res.removedInfo.removedPackage = packageName;
// Remove existing system package
removePackageLI(oldPkgSetting, true);
// writer
synchronized (mPackages) {
if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
// We didn't need to disable the .apk as a current system package,
// which means we are replacing another update that is already
// installed. We need to make sure to delete the older one's .apk.
res.removedInfo.args = createInstallArgs(0,
deletedPackage.applicationInfo.sourceDir,
deletedPackage.applicationInfo.publicSourceDir,
deletedPackage.applicationInfo.nativeLibraryDir);
} else {
res.removedInfo.args = null;
}
}
// Successfully disabled the old package. Now proceed with re-installation
mLastScanError = PackageManager.INSTALL_SUCCEEDED;
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
if (newPackage == null) {
Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
}
} else {
if (newPackage.mExtras != null) {
final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
newPkgSetting.lastUpdateTime = System.currentTimeMillis();
}
updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
updatedSettings = true;
}
if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
// Re installation failed. Restore old information
// Remove new pkg information
if (newPackage != null) {
removeInstalledPackageLI(newPackage, true);
}
// Add back the old system package
scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
// Restore the old system information in Settings
synchronized(mPackages) {
if (updatedSettings) {
mSettings.enableSystemPackageLPw(packageName);
mSettings.setInstallerPackageName(packageName,
oldPkgSetting.installerPackageName);
}
mSettings.writeLPr();
}
}
}
// Utility method used to move dex files during install.
private int moveDexFilesLI(PackageParser.Package newPackage) {
int retCode;
if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
if (retCode != 0) {
if (mNoDexOpt) {
/*
* If we're in an engineering build, programs are lazily run
* through dexopt. If the .dex file doesn't exist yet, it
* will be created when the program is run next.
*/
Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
} else {
Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
}
}
}
return PackageManager.INSTALL_SUCCEEDED;
}
private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
int[] allUsers, boolean[] perUserInstalled,
PackageInstalledInfo res) {
String pkgName = newPackage.packageName;
synchronized (mPackages) {
//write settings. the installStatus will be incomplete at this stage.
//note that the new package setting would have already been
//added to mPackages. It hasn't been persisted yet.
mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
mSettings.writeLPr();
}
if ((res.returnCode = moveDexFilesLI(newPackage))
!= PackageManager.INSTALL_SUCCEEDED) {
// Discontinue if moving dex files failed.
return;
}
if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
cleanAssetRedirections(newPackage);
if (newPackage.mIsThemeApk) {
/* DBS-TODO
boolean isThemePackageDrmProtected = false;
int N = newPackage.mThemeInfos.size();
for (int i = 0; i < N; i++) {
if (newPackage.mThemeInfos.get(i).isDrmProtected) {
isThemePackageDrmProtected = true;
break;
}
}
if (isThemePackageDrmProtected) {
splitThemePackage(newPackage.mPath);
}
*/
}
synchronized (mPackages) {
updatePermissionsLPw(newPackage.packageName, newPackage,
UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
? UPDATE_PERMISSIONS_ALL : 0));
// For system-bundled packages, we assume that installing an upgraded version
// of the package implies that the user actually wants to run that new code,
// so we enable the package.
if (isSystemApp(newPackage)) {
// NB: implicit assumption that system package upgrades apply to all users
if (DEBUG_INSTALL) {
Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
}
PackageSetting ps = mSettings.mPackages.get(pkgName);
if (ps != null) {
if (res.origUsers != null) {
for (int userHandle : res.origUsers) {
ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
userHandle, installerPackageName);
}
}
// Also convey the prior install/uninstall state
if (allUsers != null && perUserInstalled != null) {
for (int i = 0; i < allUsers.length; i++) {
if (DEBUG_INSTALL) {
Slog.d(TAG, " user " + allUsers[i]
+ " => " + perUserInstalled[i]);
}
ps.setInstalled(perUserInstalled[i], allUsers[i]);
}
// these install state changes will be persisted in the
// upcoming call to mSettings.writeLPr().
}
}
}
res.name = pkgName;
res.uid = newPackage.applicationInfo.uid;
res.pkg = newPackage;
mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
mSettings.setInstallerPackageName(pkgName, installerPackageName);
res.returnCode = PackageManager.INSTALL_SUCCEEDED;
//to update install status
mSettings.writeLPr();
}
}
private void deleteLockedZipFileIfExists(String originalPackagePath) {
String lockedZipFilePath = PackageParser.getLockedZipFilePath(originalPackagePath);
File zipFile = new File(lockedZipFilePath);
if (zipFile.exists() && zipFile.isFile()) {
if (!zipFile.delete()) {
Log.w(TAG, "Couldn't delete locked zip file: " + originalPackagePath);
}
}
}
private void splitThemePackage(File originalFile) {
final String originalPackagePath = originalFile.getPath();
final String lockedZipFilePath = PackageParser.getLockedZipFilePath(originalPackagePath);
try {
final List<String> drmProtectedEntries = new ArrayList<String>();
final ZipFile privateZip = new ZipFile(originalFile.getPath());
final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
while (privateZipEntries.hasMoreElements()) {
final ZipEntry zipEntry = privateZipEntries.nextElement();
final String zipEntryName = zipEntry.getName();
if (zipEntryName.startsWith("assets/") && zipEntryName.contains("/locked/")) {
drmProtectedEntries.add(zipEntryName);
}
}
privateZip.close();
String [] args = new String[0];
args = drmProtectedEntries.toArray(args);
int code = mContext.getAssets().splitDrmProtectedThemePackage(
originalPackagePath,
lockedZipFilePath,
args);
if (code != 0) {
Log.e("PackageManagerService",
"splitDrmProtectedThemePackage returned = " + code);
}
code = FileUtils.setPermissions(
lockedZipFilePath,
0640,
-1,
THEME_MAMANER_GUID);
if (code != 0) {
Log.e("PackageManagerService",
"Set permissions for " + lockedZipFilePath + " returned = " + code);
}
code = FileUtils.setPermissions(
originalPackagePath,
0644,
-1, -1);
if (code != 0) {
Log.e("PackageManagerService",
"Set permissions for " + originalPackagePath + " returned = " + code);
}
} catch (IOException e) {
Log.e(TAG, "Failure to generate new zip files for theme");
}
}
private void installPackageLI(InstallArgs args,
boolean newInstall, PackageInstalledInfo res) {
int pFlags = args.flags;
String installerPackageName = args.installerPackageName;
File tmpPackageFile = new File(args.getCodePath());
boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
boolean replace = false;
int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
| (newInstall ? SCAN_NEW_INSTALL : 0);
// Result object to be returned
res.returnCode = PackageManager.INSTALL_SUCCEEDED;
if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
// Retrieve PackageSettings and parse package
int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
| (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
| (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
PackageParser pp = new PackageParser(tmpPackageFile.getPath());
pp.setSeparateProcesses(mSeparateProcesses);
final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
null, mMetrics, parseFlags);
if (pkg == null) {
res.returnCode = pp.getParseError();
return;
}
String pkgName = res.name = pkg.packageName;
if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
return;
}
}
if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
res.returnCode = pp.getParseError();
return;
}
/* If the installer passed in a manifest digest, compare it now. */
if (args.manifestDigest != null) {
if (DEBUG_INSTALL) {
final String parsedManifest = pkg.manifestDigest == null ? "null"
: pkg.manifestDigest.toString();
Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
+ parsedManifest);
}
if (!args.manifestDigest.equals(pkg.manifestDigest)) {
res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
return;
}
} else if (DEBUG_INSTALL) {
final String parsedManifest = pkg.manifestDigest == null
? "null" : pkg.manifestDigest.toString();
Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
}
// Get rid of all references to package scan path via parser.
pp = null;
String oldCodePath = null;
boolean systemApp = false;
synchronized (mPackages) {
// Check if installing already existing package
if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
String oldName = mSettings.mRenamedPackages.get(pkgName);
if (pkg.mOriginalPackages != null
&& pkg.mOriginalPackages.contains(oldName)
&& mPackages.containsKey(oldName)) {
// This package is derived from an original package,
// and this device has been updating from that original
// name. We must continue using the original name, so
// rename the new package here.
pkg.setPackageName(oldName);
pkgName = pkg.packageName;
replace = true;
if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
+ oldName + " pkgName=" + pkgName);
} else if (mPackages.containsKey(pkgName)) {
// This package, under its official name, already exists
// on the device; we should replace it.
replace = true;
if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
}
}
PackageSetting ps = mSettings.mPackages.get(pkgName);
if (ps != null) {
if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
if (ps.pkg != null && ps.pkg.applicationInfo != null) {
systemApp = (ps.pkg.applicationInfo.flags &
ApplicationInfo.FLAG_SYSTEM) != 0;
}
res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
}
}
if (systemApp && onSd) {
// Disable updates to system apps on sdcard
Slog.w(TAG, "Cannot install updates to system apps on sdcard");
res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
return;
}
if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return;
}
// Set application objects path explicitly after the rename
setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
if (replace) {
replacePackageLI(pkg, parseFlags, scanMode, args.user,
installerPackageName, res);
} else {
installNewPackageLI(pkg, parseFlags, scanMode, args.user,
installerPackageName, res);
}
synchronized (mPackages) {
final PackageSetting ps = mSettings.mPackages.get(pkgName);
if (ps != null) {
res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
}
}
}
private static boolean isForwardLocked(PackageParser.Package pkg) {
return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
}
private boolean isForwardLocked(PackageSetting ps) {
return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
}
private static boolean isExternal(PackageParser.Package pkg) {
return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
}
private static boolean isExternal(PackageSetting ps) {
return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
}
private static boolean isSystemApp(PackageParser.Package pkg) {
return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
private static boolean isSystemApp(ApplicationInfo info) {
return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
private static boolean isSystemApp(PackageSetting ps) {
return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
private static boolean isUpdatedSystemApp(PackageSetting ps) {
return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
}
private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
}
private int packageFlagsToInstallFlags(PackageSetting ps) {
int installFlags = 0;
if (isExternal(ps)) {
installFlags |= PackageManager.INSTALL_EXTERNAL;
}
if (isForwardLocked(ps)) {
installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
}
return installFlags;
}
private void deleteTempPackageFiles() {
final FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("vmdl") && name.endsWith(".tmp");
}
};
deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
}
private static final void deleteTempPackageFilesInDirectory(File directory,
FilenameFilter filter) {
final String[] tmpFilesList = directory.list(filter);
if (tmpFilesList == null) {
return;
}
for (int i = 0; i < tmpFilesList.length; i++) {
final File tmpFile = new File(directory, tmpFilesList[i]);
tmpFile.delete();
}
}
private File createTempPackageFile(File installDir) {
File tmpPackageFile;
try {
tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
} catch (IOException e) {
Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
return null;
}
try {
FileUtils.setPermissions(
tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
-1, -1);
if (!SELinux.restorecon(tmpPackageFile)) {
return null;
}
} catch (IOException e) {
Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
return null;
}
return tmpPackageFile;
}
@Override
public void deletePackageAsUser(final String packageName,
final IPackageDeleteObserver observer,
final int userId, final int flags) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.DELETE_PACKAGES, null);
final int uid = Binder.getCallingUid();
if (UserHandle.getUserId(uid) != userId) {
mContext.enforceCallingPermission(
android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
"deletePackage for user " + userId);
}
if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
try {
observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
} catch (RemoteException re) {
}
return;
}
if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
// Queue up an async operation since the package deletion may take a little while.
mHandler.post(new Runnable() {
public void run() {
mHandler.removeCallbacks(this);
final int returnCode = deletePackageX(packageName, userId, flags);
if (observer != null) {
try {
observer.packageDeleted(packageName, returnCode);
} catch (RemoteException e) {
Log.i(TAG, "Observer no longer exists.");
} //end catch
} //end if
} //end run
});
}
/**
* This method is an internal method that could be get invoked either
* to delete an installed package or to clean up a failed installation.
* After deleting an installed package, a broadcast is sent to notify any
* listeners that the package has been installed. For cleaning up a failed
* installation, the broadcast is not necessary since the package's
* installation wouldn't have sent the initial broadcast either
* The key steps in deleting a package are
* deleting the package information in internal structures like mPackages,
* deleting the packages base directories through installd
* updating mSettings to reflect current status
* persisting settings for later use
* sending a broadcast if necessary
*/
private int deletePackageX(String packageName, int userId, int flags) {
final PackageRemovedInfo info = new PackageRemovedInfo();
final boolean res;
IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
try {
if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
|| dpm.isDeviceOwner(packageName))) {
Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
}
} catch (RemoteException e) {
}
boolean removedForAllUsers = false;
boolean systemUpdate = false;
synchronized (mPackages) {
PackageParser.Package p = mPackages.get(packageName);
if (p != null) {
info.isThemeApk = p.mIsThemeApk;
if (info.isThemeApk &&
!info.isRemovedPackageSystemUpdate) {
deleteLockedZipFileIfExists(p.mPath);
}
}
}
// for the uninstall-updates case and restricted profiles, remember the per-
// userhandle installed state
int[] allUsers;
boolean[] perUserInstalled;
synchronized (mPackages) {
PackageSetting ps = mSettings.mPackages.get(packageName);
allUsers = sUserManager.getUserIds();
perUserInstalled = new boolean[allUsers.length];
for (int i = 0; i < allUsers.length; i++) {
perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
}
}
synchronized (mInstallLock) {
if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
res = deletePackageLI(packageName,
(flags & PackageManager.DELETE_ALL_USERS) != 0
? UserHandle.ALL : new UserHandle(userId),
true, allUsers, perUserInstalled,
flags | REMOVE_CHATTY, info, true);
systemUpdate = info.isRemovedPackageSystemUpdate;
if (res && !systemUpdate && mPackages.get(packageName) == null) {
removedForAllUsers = true;
}
if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
+ " removedForAllUsers=" + removedForAllUsers);
}
if (res) {
info.sendBroadcast(true, systemUpdate, removedForAllUsers, true);
// If the removed package was a system update, the old system package
// was re-enabled; we need to broadcast this information
if (systemUpdate) {
Bundle extras = new Bundle(1);
extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
? info.removedAppId : info.uid);
extras.putBoolean(Intent.EXTRA_REPLACING, true);
String category = null;
if (info.isThemeApk) {
category = Intent.CATEGORY_THEME_PACKAGE_INSTALLED_STATE_CHANGE;
}
sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, category,
extras, null, null, null);
sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, category,
extras, null, null, null);
sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, null,
null, packageName, null, null);
}
}
// Force a gc here.
Runtime.getRuntime().gc();
// Delete the resources here after sending the broadcast to let
// other processes clean up before deleting resources.
if (info.args != null) {
synchronized (mInstallLock) {
info.args.doPostDeleteLI(true);
}
}
return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
}
static class PackageRemovedInfo {
String removedPackage;
int uid = -1;
int removedAppId = -1;
int[] removedUsers = null;
boolean isRemovedPackageSystemUpdate = false;
// Clean up resources deleted packages.
InstallArgs args = null;
boolean isThemeApk = false;
void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers,
boolean deleteLockedZipFileIfExists) {
Bundle extras = new Bundle(1);
extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
if (replacing) {
extras.putBoolean(Intent.EXTRA_REPLACING, true);
}
extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
if (removedPackage != null) {
String category = null;
if (isThemeApk) {
category = Intent.CATEGORY_THEME_PACKAGE_INSTALLED_STATE_CHANGE;
}
sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, category,
extras, null, null, removedUsers);
if (fullRemove && !replacing) {
sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, category,
extras, null, null, removedUsers);
}
}
if (removedAppId >= 0) {
sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, null, extras, null, null,
removedUsers);
}
}
}
/*
* This method deletes the package from internal data structures. If the DONT_DELETE_DATA
* flag is not set, the data directory is removed as well.
* make sure this flag is set for partially installed apps. If not its meaningless to
* delete a partially installed application.
*/
private void removePackageDataLI(PackageSetting ps,
int[] allUserHandles, boolean[] perUserInstalled,
PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
String packageName = ps.name;
if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
// Retrieve object to delete permissions for shared user later on
final PackageSetting deletedPs;
// reader
synchronized (mPackages) {
deletedPs = mSettings.mPackages.get(packageName);
if (outInfo != null) {
outInfo.removedPackage = packageName;
outInfo.removedUsers = deletedPs != null
? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
: null;
}
}
if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
removeDataDirsLI(packageName);
schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
}
// writer
synchronized (mPackages) {
if (deletedPs != null) {
if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
if (outInfo != null) {
outInfo.removedAppId = mSettings.removePackageLPw(packageName);
}
if (deletedPs != null) {
updatePermissionsLPw(deletedPs.name, null, 0);
if (deletedPs.sharedUser != null) {
// remove permissions associated with package
mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
}
}
clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
}
// make sure to preserve per-user disabled state if this removal was just
// a downgrade of a system app to the factory package
if (allUserHandles != null && perUserInstalled != null) {
if (DEBUG_REMOVE) {
Slog.d(TAG, "Propagating install state across downgrade");
}
for (int i = 0; i < allUserHandles.length; i++) {
if (DEBUG_REMOVE) {
Slog.d(TAG, " user " + allUserHandles[i]
+ " => " + perUserInstalled[i]);
}
ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
}
}
}
// can downgrade to reader
if (writeSettings) {
// Save settings now
mSettings.writeLPr();
}
}
if (outInfo != null) {
// A user ID was deleted here. Go through all users and remove it
// from KeyStore.
removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
}
}
/*
* Tries to delete system package.
*/
private boolean deleteSystemPackageLI(PackageSetting newPs,
int[] allUserHandles, boolean[] perUserInstalled,
int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
final boolean applyUserRestrictions
= (allUserHandles != null) && (perUserInstalled != null);
PackageSetting disabledPs = null;
// Confirm if the system package has been updated
// An updated system app can be deleted. This will also have to restore
// the system pkg from system partition
// reader
synchronized (mPackages) {
disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
}
if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
+ " disabledPs=" + disabledPs);
if (disabledPs == null) {
Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
return false;
} else if (DEBUG_REMOVE) {
Slog.d(TAG, "Deleting system pkg from data partition");
}
if (DEBUG_REMOVE) {
if (applyUserRestrictions) {
Slog.d(TAG, "Remembering install states:");
for (int i = 0; i < allUserHandles.length; i++) {
Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
}
}
}
// Delete the updated package
outInfo.isRemovedPackageSystemUpdate = true;
if (disabledPs.versionCode < newPs.versionCode) {
// Delete data for downgrades
flags &= ~PackageManager.DELETE_KEEP_DATA;
} else {
// Preserve data by setting flag
flags |= PackageManager.DELETE_KEEP_DATA;
}
boolean ret = deleteInstalledPackageLI(newPs, true, flags,
allUserHandles, perUserInstalled, outInfo, writeSettings);
if (!ret) {
return false;
}
// writer
synchronized (mPackages) {
// Reinstate the old system package
mSettings.enableSystemPackageLPw(newPs.name);
// Remove any native libraries from the upgraded package.
NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
}
// Install the system package
if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
if (newPkg == null) {
Slog.w(TAG, "Failed to restore system package:" + newPs.name
+ " with error:" + mLastScanError);
return false;
}
// writer
synchronized (mPackages) {
updatePermissionsLPw(newPkg.packageName, newPkg,
UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
if (applyUserRestrictions) {
if (DEBUG_REMOVE) {
Slog.d(TAG, "Propagating install state across reinstall");
}
PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
for (int i = 0; i < allUserHandles.length; i++) {
if (DEBUG_REMOVE) {
Slog.d(TAG, " user " + allUserHandles[i]
+ " => " + perUserInstalled[i]);
}
ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
}
// Regardless of writeSettings we need to ensure that this restriction
// state propagation is persisted
mSettings.writeAllUsersPackageRestrictionsLPr();
}
// can downgrade to reader here
if (writeSettings) {
mSettings.writeLPr();
}
}
return true;
}
private boolean deleteInstalledPackageLI(PackageSetting ps,
boolean deleteCodeAndResources, int flags,
int[] allUserHandles, boolean[] perUserInstalled,
PackageRemovedInfo outInfo, boolean writeSettings) {
if (outInfo != null) {
outInfo.uid = ps.appId;
}
// Delete package data from internal structures and also remove data if flag is set
removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
// Delete application code and resources
if (deleteCodeAndResources && (outInfo != null)) {
outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
ps.resourcePathString, ps.nativeLibraryPathString);
}
return true;
}
/*
* This method handles package deletion in general
*/
private boolean deletePackageLI(String packageName, UserHandle user,
boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
int flags, PackageRemovedInfo outInfo,
boolean writeSettings) {
if (packageName == null) {
Slog.w(TAG, "Attempt to delete null packageName.");
return false;
}
if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
PackageSetting ps;
boolean dataOnly = false;
int removeUser = -1;
int appId = -1;
synchronized (mPackages) {
ps = mSettings.mPackages.get(packageName);
if (ps == null) {
Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
return false;
}
if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
&& user.getIdentifier() != UserHandle.USER_ALL) {
// The caller is asking that the package only be deleted for a single
// user. To do this, we just mark its uninstalled state and delete
// its data. If this is a system app, we only allow this to happen if
// they have set the special DELETE_SYSTEM_APP which requests different
// semantics than normal for uninstalling system apps.
if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
ps.setUserState(user.getIdentifier(),
COMPONENT_ENABLED_STATE_DEFAULT,
false, //installed
true, //stopped
true, //notLaunched
null, null, null);
if (!isSystemApp(ps)) {
if (ps.isAnyInstalled(sUserManager.getUserIds())) {
// Other user still have this package installed, so all
// we need to do is clear this user's data and save that
// it is uninstalled.
if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
removeUser = user.getIdentifier();
appId = ps.appId;
mSettings.writePackageRestrictionsLPr(removeUser);
} else {
// We need to set it back to 'installed' so the uninstall
// broadcasts will be sent correctly.
if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
ps.setInstalled(true, user.getIdentifier());
}
} else {
// This is a system app, so we assume that the
// other users still have this package installed, so all
// we need to do is clear this user's data and save that
// it is uninstalled.
if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
removeUser = user.getIdentifier();
appId = ps.appId;
mSettings.writePackageRestrictionsLPr(removeUser);
}
}
}
if (removeUser >= 0) {
// From above, we determined that we are deleting this only
// for a single user. Continue the work here.
if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
if (outInfo != null) {
outInfo.removedPackage = packageName;
outInfo.removedAppId = appId;
outInfo.removedUsers = new int[] {removeUser};
}
mInstaller.clearUserData(packageName, removeUser);
removeKeystoreDataIfNeeded(removeUser, appId);
schedulePackageCleaning(packageName, removeUser, false);
return true;
}
if (dataOnly) {
// Delete application data first
if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
return true;
}
boolean ret = false;
if (isSystemApp(ps)) {
if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
// When an updated system application is deleted we delete the existing resources as well and
// fall back to existing code in system partition
ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
flags, outInfo, writeSettings);
} else {
if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
// Kill application pre-emptively especially for apps on sd.
killApplication(packageName, ps.appId);
ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
allUserHandles, perUserInstalled,
outInfo, writeSettings);
}
return ret;
}
private final class ClearStorageConnection implements ServiceConnection {
IMediaContainerService mContainerService;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
synchronized (this) {
mContainerService = IMediaContainerService.Stub.asInterface(service);
notifyAll();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
final boolean mounted;
if (Environment.isExternalStorageEmulated()) {
mounted = true;
} else {
final String status = Environment.getExternalStorageState();
mounted = status.equals(Environment.MEDIA_MOUNTED)
|| status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
}
if (!mounted) {
return;
}
final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
int[] users;
if (userId == UserHandle.USER_ALL) {
users = sUserManager.getUserIds();
} else {
users = new int[] { userId };
}
final ClearStorageConnection conn = new ClearStorageConnection();
if (mContext.bindServiceAsUser(
containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
try {
for (int curUser : users) {
long timeout = SystemClock.uptimeMillis() + 5000;
synchronized (conn) {
long now = SystemClock.uptimeMillis();
while (conn.mContainerService == null && now < timeout) {
try {
conn.wait(timeout - now);
} catch (InterruptedException e) {
}
}
}
if (conn.mContainerService == null) {
return;
}
final UserEnvironment userEnv = new UserEnvironment(curUser);
final File externalCacheDir = userEnv
.getExternalStorageAppCacheDirectory(packageName);
try {
conn.mContainerService.clearDirectory(externalCacheDir.toString());
} catch (RemoteException e) {
}
if (allData) {
final File externalDataDir = userEnv
.getExternalStorageAppDataDirectory(packageName);
try {
conn.mContainerService.clearDirectory(externalDataDir.toString());
} catch (RemoteException e) {
}
final File externalMediaDir = userEnv
.getExternalStorageAppMediaDirectory(packageName);
try {
conn.mContainerService.clearDirectory(externalMediaDir.toString());
} catch (RemoteException e) {
}
}
}
} finally {
mContext.unbindService(conn);
}
}
}
@Override
public void clearApplicationUserData(final String packageName,
final IPackageDataObserver observer, final int userId) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.CLEAR_APP_USER_DATA, null);
enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
// Queue up an async operation since the package deletion may take a little while.
mHandler.post(new Runnable() {
public void run() {
mHandler.removeCallbacks(this);
final boolean succeeded;
synchronized (mInstallLock) {
succeeded = clearApplicationUserDataLI(packageName, userId);
}
clearExternalStorageDataSync(packageName, userId, true);
if (succeeded) {
// invoke DeviceStorageMonitor's update method to clear any notifications
DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
if (dsm != null) {
dsm.updateMemory();
}
}
if(observer != null) {
try {
observer.onRemoveCompleted(packageName, succeeded);
} catch (RemoteException e) {
Log.i(TAG, "Observer no longer exists.");
}
} //end if observer
} //end run
});
}
private boolean clearApplicationUserDataLI(String packageName, int userId) {
if (packageName == null) {
Slog.w(TAG, "Attempt to delete null packageName.");
return false;
}
PackageParser.Package p;
boolean dataOnly = false;
final int appId;
synchronized (mPackages) {
p = mPackages.get(packageName);
if (p == null) {
dataOnly = true;
PackageSetting ps = mSettings.mPackages.get(packageName);
if ((ps == null) || (ps.pkg == null)) {
Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
return false;
}
p = ps.pkg;
}
if (!dataOnly) {
// need to check this only for fully installed applications
if (p == null) {
Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
return false;
}
final ApplicationInfo applicationInfo = p.applicationInfo;
if (applicationInfo == null) {
Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
return false;
}
}
if (p != null && p.applicationInfo != null) {
appId = p.applicationInfo.uid;
} else {
appId = -1;
}
}
int retCode = mInstaller.clearUserData(packageName, userId);
if (retCode < 0) {
Slog.w(TAG, "Couldn't remove cache files for package: "
+ packageName);
return false;
}
removeKeystoreDataIfNeeded(userId, appId);
return true;
}
/**
* Remove entries from the keystore daemon. Will only remove it if the
* {@code appId} is valid.
*/
private static void removeKeystoreDataIfNeeded(int userId, int appId) {
if (appId < 0) {
return;
}
final KeyStore keyStore = KeyStore.getInstance();
if (keyStore != null) {
if (userId == UserHandle.USER_ALL) {
for (final int individual : sUserManager.getUserIds()) {
keyStore.clearUid(UserHandle.getUid(individual, appId));
}
} else {
keyStore.clearUid(UserHandle.getUid(userId, appId));
}
} else {
Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
}
}
public void deleteApplicationCacheFiles(final String packageName,
final IPackageDataObserver observer) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.DELETE_CACHE_FILES, null);
// Queue up an async operation since the package deletion may take a little while.
final int userId = UserHandle.getCallingUserId();
mHandler.post(new Runnable() {
public void run() {
mHandler.removeCallbacks(this);
final boolean succeded;
synchronized (mInstallLock) {
succeded = deleteApplicationCacheFilesLI(packageName, userId);
}
clearExternalStorageDataSync(packageName, userId, false);
if(observer != null) {
try {
observer.onRemoveCompleted(packageName, succeded);
} catch (RemoteException e) {
Log.i(TAG, "Observer no longer exists.");
}
} //end if observer
} //end run
});
}
private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
if (packageName == null) {
Slog.w(TAG, "Attempt to delete null packageName.");
return false;
}
PackageParser.Package p;
synchronized (mPackages) {
p = mPackages.get(packageName);
}
if (p == null) {
Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
return false;
}
final ApplicationInfo applicationInfo = p.applicationInfo;
if (applicationInfo == null) {
Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
return false;
}
int retCode = mInstaller.deleteCacheFiles(packageName, userId);
if (retCode < 0) {
Slog.w(TAG, "Couldn't remove cache files for package: "
+ packageName + " u" + userId);
return false;
}
return true;
}
public void getPackageSizeInfo(final String packageName, int userHandle,
final IPackageStatsObserver observer) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.GET_PACKAGE_SIZE, null);
PackageStats stats = new PackageStats(packageName, userHandle);
/*
* Queue up an async operation since the package measurement may take a
* little while.
*/
Message msg = mHandler.obtainMessage(INIT_COPY);
msg.obj = new MeasureParams(stats, observer);
mHandler.sendMessage(msg);
}
private boolean getPackageSizeInfoLI(String packageName, int userHandle,
PackageStats pStats) {
if (packageName == null) {
Slog.w(TAG, "Attempt to get size of null packageName.");
return false;
}
PackageParser.Package p;
boolean dataOnly = false;
String libDirPath = null;
String asecPath = null;
synchronized (mPackages) {
p = mPackages.get(packageName);
PackageSetting ps = mSettings.mPackages.get(packageName);
if(p == null) {
dataOnly = true;
if((ps == null) || (ps.pkg == null)) {
Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
return false;
}
p = ps.pkg;
}
if (ps != null) {
libDirPath = ps.nativeLibraryPathString;
}
if (p != null && (isExternal(p) || isForwardLocked(p))) {
String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
if (secureContainerId != null) {
asecPath = PackageHelper.getSdFilesystem(secureContainerId);
}
}
}
String publicSrcDir = null;
if(!dataOnly) {
final ApplicationInfo applicationInfo = p.applicationInfo;
if (applicationInfo == null) {
Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
return false;
}
if (isForwardLocked(p)) {
publicSrcDir = applicationInfo.publicSourceDir;
}
}
int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
publicSrcDir, asecPath, pStats);
if (res < 0) {
return false;
}
// Fix-up for forward-locked applications in ASEC containers.
if (!isExternal(p)) {
pStats.codeSize += pStats.externalCodeSize;
pStats.externalCodeSize = 0L;
}
return true;
}
public void addPackageToPreferred(String packageName) {
Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
}
public void removePackageFromPreferred(String packageName) {
Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
}
public List<PackageInfo> getPreferredPackages(int flags) {
return new ArrayList<PackageInfo>();
}
private int getUidTargetSdkVersionLockedLPr(int uid) {
Object obj = mSettings.getUserIdLPr(uid);
if (obj instanceof SharedUserSetting) {
final SharedUserSetting sus = (SharedUserSetting) obj;
int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
final Iterator<PackageSetting> it = sus.packages.iterator();
while (it.hasNext()) {
final PackageSetting ps = it.next();
if (ps.pkg != null) {
int v = ps.pkg.applicationInfo.targetSdkVersion;
if (v < vers) vers = v;
}
}
return vers;
} else if (obj instanceof PackageSetting) {
final PackageSetting ps = (PackageSetting) obj;
if (ps.pkg != null) {
return ps.pkg.applicationInfo.targetSdkVersion;
}
}
return Build.VERSION_CODES.CUR_DEVELOPMENT;
}
public void addPreferredActivity(IntentFilter filter, int match,
ComponentName[] set, ComponentName activity, int userId) {
// writer
int callingUid = Binder.getCallingUid();
enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
synchronized (mPackages) {
if (mContext.checkCallingOrSelfPermission(
android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
if (getUidTargetSdkVersionLockedLPr(callingUid)
< Build.VERSION_CODES.FROYO) {
Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
+ callingUid);
return;
}
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
}
Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
filter.dump(new LogPrinter(Log.INFO, TAG), " ");
mSettings.editPreferredActivitiesLPw(userId).addFilter(
new PreferredActivity(filter, match, set, activity));
mSettings.writePackageRestrictionsLPr(userId);
}
}
public void replacePreferredActivity(IntentFilter filter, int match,
ComponentName[] set, ComponentName activity) {
if (filter.countActions() != 1) {
throw new IllegalArgumentException(
"replacePreferredActivity expects filter to have only 1 action.");
}
if (filter.countCategories() != 1) {
throw new IllegalArgumentException(
"replacePreferredActivity expects filter to have only 1 category.");
}
if (filter.countDataAuthorities() != 0
|| filter.countDataPaths() != 0
|| filter.countDataSchemes() != 0
|| filter.countDataTypes() != 0) {
throw new IllegalArgumentException(
"replacePreferredActivity expects filter to have no data authorities, " +
"paths, schemes or types.");
}
synchronized (mPackages) {
if (mContext.checkCallingOrSelfPermission(
android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
< Build.VERSION_CODES.FROYO) {
Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
+ Binder.getCallingUid());
return;
}
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
}
final int callingUserId = UserHandle.getCallingUserId();
ArrayList<PreferredActivity> removed = null;
PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
if (pir != null) {
Iterator<PreferredActivity> it = pir.filterIterator();
String action = filter.getAction(0);
String category = filter.getCategory(0);
while (it.hasNext()) {
PreferredActivity pa = it.next();
if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
if (removed == null) {
removed = new ArrayList<PreferredActivity>();
}
removed.add(pa);
Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":");
filter.dump(new LogPrinter(Log.INFO, TAG), " ");
}
}
if (removed != null) {
for (int i=0; i<removed.size(); i++) {
PreferredActivity pa = removed.get(i);
pir.removeFilter(pa);
}
}
}
addPreferredActivity(filter, match, set, activity, callingUserId);
}
}
public void clearPackagePreferredActivities(String packageName) {
final int uid = Binder.getCallingUid();
// writer
synchronized (mPackages) {
PackageParser.Package pkg = mPackages.get(packageName);
if (pkg == null || pkg.applicationInfo.uid != uid) {
if (mContext.checkCallingOrSelfPermission(
android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
< Build.VERSION_CODES.FROYO) {
Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
+ Binder.getCallingUid());
return;
}
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
}
}
int user = UserHandle.getCallingUserId();
if (clearPackagePreferredActivitiesLPw(packageName, user)) {
mSettings.writePackageRestrictionsLPr(user);
scheduleWriteSettingsLocked();
}
}
}
/** This method takes a specific user id as well as UserHandle.USER_ALL. */
boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
ArrayList<PreferredActivity> removed = null;
boolean changed = false;
for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
if (userId != UserHandle.USER_ALL && userId != thisUserId) {
continue;
}
Iterator<PreferredActivity> it = pir.filterIterator();
while (it.hasNext()) {
PreferredActivity pa = it.next();
if (packageName == null ||
pa.mPref.mComponent.getPackageName().equals(packageName)) {
if (removed == null) {
removed = new ArrayList<PreferredActivity>();
}
removed.add(pa);
}
}
if (removed != null) {
for (int j=0; j<removed.size(); j++) {
PreferredActivity pa = removed.get(j);
pir.removeFilter(pa);
}
changed = true;
}
}
return changed;
}
public void resetPreferredActivities(int userId) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
// writer
synchronized (mPackages) {
int user = UserHandle.getCallingUserId();
clearPackagePreferredActivitiesLPw(null, user);
mSettings.readDefaultPreferredAppsLPw(this, user);
mSettings.writePackageRestrictionsLPr(user);
scheduleWriteSettingsLocked();
}
}
public int getPreferredActivities(List<IntentFilter> outFilters,
List<ComponentName> outActivities, String packageName) {
int num = 0;
final int userId = UserHandle.getCallingUserId();
// reader
synchronized (mPackages) {
PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
if (pir != null) {
final Iterator<PreferredActivity> it = pir.filterIterator();
while (it.hasNext()) {
final PreferredActivity pa = it.next();
if (packageName == null
|| pa.mPref.mComponent.getPackageName().equals(packageName)) {
if (outFilters != null) {
outFilters.add(new IntentFilter(pa));
}
if (outActivities != null) {
outActivities.add(pa.mPref.mComponent);
}
}
}
}
}
return num;
}
@Override
public void setApplicationEnabledSetting(String appPackageName,
int newState, int flags, int userId, String callingPackage) {
if (!sUserManager.exists(userId)) return;
if (callingPackage == null) {
callingPackage = Integer.toString(Binder.getCallingUid());
}
setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
}
@Override
public void setComponentEnabledSetting(ComponentName componentName,
int newState, int flags, int userId) {
if (!sUserManager.exists(userId)) return;
setEnabledSetting(componentName.getPackageName(),
componentName.getClassName(), newState, flags, userId, null);
}
private void setEnabledSetting(final String packageName, String className, int newState,
final int flags, int userId, String callingPackage) {
if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
|| newState == COMPONENT_ENABLED_STATE_ENABLED
|| newState == COMPONENT_ENABLED_STATE_DISABLED
|| newState == COMPONENT_ENABLED_STATE_DISABLED_USER
|| newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
throw new IllegalArgumentException("Invalid new component state: "
+ newState);
}
PackageSetting pkgSetting;
final int uid = Binder.getCallingUid();
final int permission = mContext.checkCallingOrSelfPermission(
android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
enforceCrossUserPermission(uid, userId, false, "set enabled");
final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
boolean sendNow = false;
boolean isApp = (className == null);
String componentName = isApp ? packageName : className;
int packageUid = -1;
ArrayList<String> components;
// writer
synchronized (mPackages) {
pkgSetting = mSettings.mPackages.get(packageName);
if (pkgSetting == null) {
if (className == null) {
throw new IllegalArgumentException(
"Unknown package: " + packageName);
}
throw new IllegalArgumentException(
"Unknown component: " + packageName
+ "/" + className);
}
// Allow root and verify that userId is not being specified by a different user
if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
throw new SecurityException(
"Permission Denial: attempt to change component state from pid="
+ Binder.getCallingPid()
+ ", uid=" + uid + ", package uid=" + pkgSetting.appId);
}
if (className == null) {
// We're dealing with an application/package level state change
if (pkgSetting.getEnabled(userId) == newState) {
// Nothing to do
return;
}
if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
|| newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
// Don't care about who enables an app.
callingPackage = null;
}
pkgSetting.setEnabled(newState, userId, callingPackage);
// pkgSetting.pkg.mSetEnabled = newState;
} else {
// We're dealing with a component level state change
// First, verify that this is a valid class name.
PackageParser.Package pkg = pkgSetting.pkg;
if (pkg == null || !pkg.hasComponentClassName(className)) {
if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
throw new IllegalArgumentException("Component class " + className
+ " does not exist in " + packageName);
} else {
Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
+ className + " does not exist in " + packageName);
}
}
switch (newState) {
case COMPONENT_ENABLED_STATE_ENABLED:
if (!pkgSetting.enableComponentLPw(className, userId)) {
return;
}
break;
case COMPONENT_ENABLED_STATE_DISABLED:
if (!pkgSetting.disableComponentLPw(className, userId)) {
return;
}
break;
case COMPONENT_ENABLED_STATE_DEFAULT:
if (!pkgSetting.restoreComponentLPw(className, userId)) {
return;
}
break;
default:
Slog.e(TAG, "Invalid new component state: " + newState);
return;
}
}
mSettings.writePackageRestrictionsLPr(userId);
components = mPendingBroadcasts.get(userId, packageName);
final boolean newPackage = components == null;
if (newPackage) {
components = new ArrayList<String>();
}
if (!components.contains(componentName)) {
components.add(componentName);
}
if ((flags&PackageManager.DONT_KILL_APP) == 0) {
sendNow = true;
// Purge entry from pending broadcast list if another one exists already
// since we are sending one right away.
mPendingBroadcasts.remove(userId, packageName);
} else {
if (newPackage) {
mPendingBroadcasts.put(userId, packageName, components);
}
if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
// Schedule a message
mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
}
}
}
long callingId = Binder.clearCallingIdentity();
try {
if (sendNow) {
packageUid = UserHandle.getUid(userId, pkgSetting.appId);
sendPackageChangedBroadcast(packageName,
(flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
private void sendPackageChangedBroadcast(String packageName,
boolean killFlag, ArrayList<String> componentNames, int packageUid) {
if (DEBUG_INSTALL)
Log.v(TAG, "Sending package changed: package=" + packageName + " components="
+ componentNames);
Bundle extras = new Bundle(4);
extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
String nameList[] = new String[componentNames.size()];
componentNames.toArray(nameList);
extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
extras.putInt(Intent.EXTRA_UID, packageUid);
sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, null, extras, null, null,
new int[] {UserHandle.getUserId(packageUid)});
}
public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
if (!sUserManager.exists(userId)) return;
final int uid = Binder.getCallingUid();
final int permission = mContext.checkCallingOrSelfPermission(
android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
enforceCrossUserPermission(uid, userId, true, "stop package");
// writer
synchronized (mPackages) {
if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
uid, userId)) {
scheduleWritePackageRestrictionsLocked(userId);
}
}
}
public String getInstallerPackageName(String packageName) {
// reader
synchronized (mPackages) {
return mSettings.getInstallerPackageNameLPr(packageName);
}
}
@Override
public int getApplicationEnabledSetting(String packageName, int userId) {
if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
int uid = Binder.getCallingUid();
enforceCrossUserPermission(uid, userId, false, "get enabled");
// reader
synchronized (mPackages) {
return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
}
}
@Override
public int getComponentEnabledSetting(ComponentName componentName, int userId) {
if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
int uid = Binder.getCallingUid();
enforceCrossUserPermission(uid, userId, false, "get component enabled");
// reader
synchronized (mPackages) {
return mSettings.getComponentEnabledSettingLPr(componentName, userId);
}
}
public void enterSafeMode() {
enforceSystemOrRoot("Only the system can request entering safe mode");
if (!mSystemReady) {
mSafeMode = true;
}
}
public void systemReady() {
mSystemReady = true;
// Read the compatibilty setting when the system is ready.
boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
mContext.getContentResolver(),
android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
if (DEBUG_SETTINGS) {
Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
}
synchronized (mPackages) {
// Verify that all of the preferred activity components actually
// exist. It is possible for applications to be updated and at
// that point remove a previously declared activity component that
// had been set as a preferred activity. We try to clean this up
// the next time we encounter that preferred activity, but it is
// possible for the user flow to never be able to return to that
// situation so here we do a sanity check to make sure we haven't
// left any junk around.
ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
removed.clear();
for (PreferredActivity pa : pir.filterSet()) {
if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
removed.add(pa);
}
}
if (removed.size() > 0) {
for (int j=0; j<removed.size(); j++) {
PreferredActivity pa = removed.get(i);
Slog.w(TAG, "Removing dangling preferred activity: "
+ pa.mPref.mComponent);
pir.removeFilter(pa);
}
mSettings.writePackageRestrictionsLPr(
mSettings.mPreferredActivities.keyAt(i));
}
}
}
}
public boolean isSafeMode() {
return mSafeMode;
}
public boolean hasSystemUidErrors() {
return mHasSystemUidErrors;
}
static String arrayToString(int[] array) {
StringBuffer buf = new StringBuffer(128);
buf.append('[');
if (array != null) {
for (int i=0; i<array.length; i++) {
if (i > 0) buf.append(", ");
buf.append(array[i]);
}
}
buf.append(']');
return buf.toString();
}
static class DumpState {
public static final int DUMP_LIBS = 1 << 0;
public static final int DUMP_FEATURES = 1 << 1;
public static final int DUMP_RESOLVERS = 1 << 2;
public static final int DUMP_PERMISSIONS = 1 << 3;
public static final int DUMP_PACKAGES = 1 << 4;
public static final int DUMP_SHARED_USERS = 1 << 5;
public static final int DUMP_MESSAGES = 1 << 6;
public static final int DUMP_PROVIDERS = 1 << 7;
public static final int DUMP_VERIFIERS = 1 << 8;
public static final int DUMP_PREFERRED = 1 << 9;
public static final int DUMP_PREFERRED_XML = 1 << 10;
public static final int OPTION_SHOW_FILTERS = 1 << 0;
private int mTypes;
private int mOptions;
private boolean mTitlePrinted;
private SharedUserSetting mSharedUser;
public boolean isDumping(int type) {
if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
return true;
}
return (mTypes & type) != 0;
}
public void setDump(int type) {
mTypes |= type;
}
public boolean isOptionEnabled(int option) {
return (mOptions & option) != 0;
}
public void setOptionEnabled(int option) {
mOptions |= option;
}
public boolean onTitlePrinted() {
final boolean printed = mTitlePrinted;
mTitlePrinted = true;
return printed;
}
public boolean getTitlePrinted() {
return mTitlePrinted;
}
public void setTitlePrinted(boolean enabled) {
mTitlePrinted = enabled;
}
public SharedUserSetting getSharedUser() {
return mSharedUser;
}
public void setSharedUser(SharedUserSetting user) {
mSharedUser = user;
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
!= PackageManager.PERMISSION_GRANTED) {
pw.println("Permission Denial: can't dump ActivityManager from from pid="
+ Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid()
+ " without permission "
+ android.Manifest.permission.DUMP);
return;
}
DumpState dumpState = new DumpState();
boolean fullPreferred = false;
String packageName = null;
int opti = 0;
while (opti < args.length) {
String opt = args[opti];
if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
break;
}
opti++;
if ("-a".equals(opt)) {
// Right now we only know how to print all.
} else if ("-h".equals(opt)) {
pw.println("Package manager dump options:");
pw.println(" [-h] [-f] [cmd] ...");
pw.println(" -f: print details of intent filters");
pw.println(" -h: print this help");
pw.println(" cmd may be one of:");
pw.println(" l[ibraries]: list known shared libraries");
pw.println(" f[ibraries]: list device features");
pw.println(" r[esolvers]: dump intent resolvers");
pw.println(" perm[issions]: dump permissions");
pw.println(" pref[erred]: print preferred package settings");
pw.println(" preferred-xml [--full]: print preferred package settings as xml");
pw.println(" prov[iders]: dump content providers");
pw.println(" p[ackages]: dump installed packages");
pw.println(" s[hared-users]: dump shared user IDs");
pw.println(" m[essages]: print collected runtime messages");
pw.println(" v[erifiers]: print package verifier info");
pw.println(" <package.name>: info about given package");
return;
} else if ("-f".equals(opt)) {
dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
} else {
pw.println("Unknown argument: " + opt + "; use -h for help");
}
}
// Is the caller requesting to dump a particular piece of data?
if (opti < args.length) {
String cmd = args[opti];
opti++;
// Is this a package name?
if ("android".equals(cmd) || cmd.contains(".")) {
packageName = cmd;
} else if ("l".equals(cmd) || "libraries".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_LIBS);
} else if ("f".equals(cmd) || "features".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_FEATURES);
} else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_RESOLVERS);
} else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_PERMISSIONS);
} else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_PREFERRED);
} else if ("preferred-xml".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
if (opti < args.length && "--full".equals(args[opti])) {
fullPreferred = true;
opti++;
}
} else if ("p".equals(cmd) || "packages".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_PACKAGES);
} else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_SHARED_USERS);
} else if ("prov".equals(cmd) || "providers".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_PROVIDERS);
} else if ("m".equals(cmd) || "messages".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_MESSAGES);
} else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
dumpState.setDump(DumpState.DUMP_VERIFIERS);
}
}
// reader
synchronized (mPackages) {
if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
if (dumpState.onTitlePrinted())
pw.println(" ");
pw.println("Verifiers:");
pw.print(" Required: ");
pw.print(mRequiredVerifierPackage);
pw.print(" (uid=");
pw.print(getPackageUid(mRequiredVerifierPackage, 0));
pw.println(")");
}
if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
if (dumpState.onTitlePrinted())
pw.println(" ");
pw.println("Libraries:");
final Iterator<String> it = mSharedLibraries.keySet().iterator();
while (it.hasNext()) {
String name = it.next();
pw.print(" ");
pw.print(name);
pw.print(" -> ");
SharedLibraryEntry ent = mSharedLibraries.get(name);
if (ent.path != null) {
pw.print("(jar) ");
pw.print(ent.path);
} else {
pw.print("(apk) ");
pw.print(ent.apk);
}
pw.println();
}
}
if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
if (dumpState.onTitlePrinted())
pw.println(" ");
pw.println("Features:");
Iterator<String> it = mAvailableFeatures.keySet().iterator();
while (it.hasNext()) {
String name = it.next();
pw.print(" ");
pw.println(name);
}
}
if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
: "Activity Resolver Table:", " ", packageName,
dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
dumpState.setTitlePrinted(true);
}
if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
: "Receiver Resolver Table:", " ", packageName,
dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
dumpState.setTitlePrinted(true);
}
if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
: "Service Resolver Table:", " ", packageName,
dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
dumpState.setTitlePrinted(true);
}
}
if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
int user = mSettings.mPreferredActivities.keyAt(i);
if (pir.dump(pw,
dumpState.getTitlePrinted()
? "\nPreferred Activities User " + user + ":"
: "Preferred Activities User " + user + ":", " ",
packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
dumpState.setTitlePrinted(true);
}
}
}
if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
pw.flush();
FileOutputStream fout = new FileOutputStream(fd);
BufferedOutputStream str = new BufferedOutputStream(fout);
XmlSerializer serializer = new FastXmlSerializer();
try {
serializer.setOutput(str, "utf-8");
serializer.startDocument(null, true);
serializer.setFeature(
"http://xmlpull.org/v1/doc/features.html#indent-output", true);
mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
serializer.endDocument();
serializer.flush();
} catch (IllegalArgumentException e) {
pw.println("Failed writing: " + e);
} catch (IllegalStateException e) {
pw.println("Failed writing: " + e);
} catch (IOException e) {
pw.println("Failed writing: " + e);
}
}
if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
}
if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
boolean printedSomething = false;
for (PackageParser.Provider p : mProvidersByComponent.values()) {
if (packageName != null && !packageName.equals(p.info.packageName)) {
continue;
}
if (!printedSomething) {
if (dumpState.onTitlePrinted())
pw.println(" ");
pw.println("Registered ContentProviders:");
printedSomething = true;
}
pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":");
pw.print(" "); pw.println(p.toString());
}
printedSomething = false;
for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) {
PackageParser.Provider p = entry.getValue();
if (packageName != null && !packageName.equals(p.info.packageName)) {
continue;
}
if (!printedSomething) {
if (dumpState.onTitlePrinted())
pw.println(" ");
pw.println("ContentProvider Authorities:");
printedSomething = true;
}
pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
pw.print(" "); pw.println(p.toString());
if (p.info != null && p.info.applicationInfo != null) {
final String appInfo = p.info.applicationInfo.toString();
pw.print(" applicationInfo="); pw.println(appInfo);
}
}
}
if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
mSettings.dumpPackagesLPr(pw, packageName, dumpState);
}
if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
}
if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
if (dumpState.onTitlePrinted())
pw.println(" ");
mSettings.dumpReadMessagesLPr(pw, dumpState);
pw.println(" ");
pw.println("Package warning messages:");
final File fname = getSettingsProblemFile();
FileInputStream in = null;
try {
in = new FileInputStream(fname);
final int avail = in.available();
final byte[] data = new byte[avail];
in.read(data);
pw.print(new String(data));
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
}
}
// ------- apps on sdcard specific code -------
static final boolean DEBUG_SD_INSTALL = false;
private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
private static final String SD_ENCRYPTION_ALGORITHM = "AES";
private boolean mMediaMounted = false;
private String getEncryptKey() {
try {
String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
SD_ENCRYPTION_KEYSTORE_NAME);
if (sdEncKey == null) {
sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
if (sdEncKey == null) {
Slog.e(TAG, "Failed to create encryption keys");
return null;
}
}
return sdEncKey;
} catch (NoSuchAlgorithmException nsae) {
Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
return null;
} catch (IOException ioe) {
Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
return null;
}
}
/* package */static String getTempContainerId() {
int tmpIdx = 1;
String list[] = PackageHelper.getSecureContainerList();
if (list != null) {
for (final String name : list) {
// Ignore null and non-temporary container entries
if (name == null || !name.startsWith(mTempContainerPrefix)) {
continue;
}
String subStr = name.substring(mTempContainerPrefix.length());
try {
int cid = Integer.parseInt(subStr);
if (cid >= tmpIdx) {
tmpIdx = cid + 1;
}
} catch (NumberFormatException e) {
}
}
}
return mTempContainerPrefix + tmpIdx;
}
/*
* Update media status on PackageManager.
*/
public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
int callingUid = Binder.getCallingUid();
if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
throw new SecurityException("Media status can only be updated by the system");
}
// reader; this apparently protects mMediaMounted, but should probably
// be a different lock in that case.
synchronized (mPackages) {
Log.i(TAG, "Updating external media status from "
+ (mMediaMounted ? "mounted" : "unmounted") + " to "
+ (mediaStatus ? "mounted" : "unmounted"));
if (DEBUG_SD_INSTALL)
Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
+ ", mMediaMounted=" + mMediaMounted);
if (mediaStatus == mMediaMounted) {
final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
: 0, -1);
mHandler.sendMessage(msg);
return;
}
mMediaMounted = mediaStatus;
}
// Queue up an async operation since the package installation may take a
// little while.
mHandler.post(new Runnable() {
public void run() {
updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
}
});
}
/**
* Called by MountService when the initial ASECs to scan are available.
* Should block until all the ASEC containers are finished being scanned.
*/
public void scanAvailableAsecs() {
updateExternalMediaStatusInner(true, false, false);
}
/*
* Collect information of applications on external media, map them against
* existing containers and update information based on current mount status.
* Please note that we always have to report status if reportStatus has been
* set to true especially when unloading packages.
*/
private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
boolean externalStorage) {
// Collection of uids
int uidArr[] = null;
// Collection of stale containers
HashSet<String> removeCids = new HashSet<String>();
// Collection of packages on external media with valid containers.
HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
// Get list of secure containers.
final String list[] = PackageHelper.getSecureContainerList();
if (list == null || list.length == 0) {
Log.i(TAG, "No secure containers on sdcard");
} else {
// Process list of secure containers and categorize them
// as active or stale based on their package internal state.
int uidList[] = new int[list.length];
int num = 0;
// reader
synchronized (mPackages) {
for (String cid : list) {
if (DEBUG_SD_INSTALL)
Log.i(TAG, "Processing container " + cid);
String pkgName = getAsecPackageName(cid);
if (pkgName == null) {
if (DEBUG_SD_INSTALL)
Log.i(TAG, "Container : " + cid + " stale");
removeCids.add(cid);
continue;
}
if (DEBUG_SD_INSTALL)
Log.i(TAG, "Looking for pkg : " + pkgName);
final PackageSetting ps = mSettings.mPackages.get(pkgName);
if (ps == null) {
Log.i(TAG, "Deleting container with no matching settings " + cid);
removeCids.add(cid);
continue;
}
/*
* Skip packages that are not external if we're unmounting
* external storage.
*/
if (externalStorage && !isMounted && !isExternal(ps)) {
continue;
}
final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps));
// The package status is changed only if the code path
// matches between settings and the container id.
if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
if (DEBUG_SD_INSTALL) {
Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
+ " at code path: " + ps.codePathString);
}
// We do have a valid package installed on sdcard
processCids.put(args, ps.codePathString);
final int uid = ps.appId;
if (uid != -1) {
uidList[num++] = uid;
}
} else {
Log.i(TAG, "Deleting stale container for " + cid);
removeCids.add(cid);
}
}
}
if (num > 0) {
// Sort uid list
Arrays.sort(uidList, 0, num);
// Throw away duplicates
uidArr = new int[num];
uidArr[0] = uidList[0];
int di = 0;
for (int i = 1; i < num; i++) {
if (uidList[i - 1] != uidList[i]) {
uidArr[di++] = uidList[i];
}
}
}
}
// Process packages with valid entries.
if (isMounted) {
if (DEBUG_SD_INSTALL)
Log.i(TAG, "Loading packages");
loadMediaPackages(processCids, uidArr, removeCids);
startCleaningPackages();
} else {
if (DEBUG_SD_INSTALL)
Log.i(TAG, "Unloading packages");
unloadMediaPackages(processCids, uidArr, reportStatus);
}
}
private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
int uidArr[], IIntentReceiver finishedReceiver) {
int size = pkgList.size();
if (size > 0) {
// Send broadcasts here
Bundle extras = new Bundle();
extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
.toArray(new String[size]));
if (uidArr != null) {
extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
}
String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
: Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
sendPackageBroadcast(action, null, null, extras, null, finishedReceiver, null);
}
}
/*
* Look at potentially valid container ids from processCids If package
* information doesn't match the one on record or package scanning fails,
* the cid is added to list of removeCids. We currently don't delete stale
* containers.
*/
private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
HashSet<String> removeCids) {
ArrayList<String> pkgList = new ArrayList<String>();
Set<AsecInstallArgs> keys = processCids.keySet();
boolean doGc = false;
for (AsecInstallArgs args : keys) {
String codePath = processCids.get(args);
if (DEBUG_SD_INSTALL)
Log.i(TAG, "Loading container : " + args.cid);
int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
try {
// Make sure there are no container errors first.
if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Slog.e(TAG, "Failed to mount cid : " + args.cid
+ " when installing from sdcard");
continue;
}
// Check code path here.
if (codePath == null || !codePath.equals(args.getCodePath())) {
Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
+ " does not match one in settings " + codePath);
continue;
}
// Parse package
int parseFlags = mDefParseFlags;
if (args.isExternal()) {
parseFlags |= PackageParser.PARSE_ON_SDCARD;
}
if (args.isFwdLocked()) {
parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
}
doGc = true;
synchronized (mInstallLock) {
final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
0, 0, null);
// Scan the package
if (pkg != null) {
/*
* TODO why is the lock being held? doPostInstall is
* called in other places without the lock. This needs
* to be straightened out.
*/
// writer
synchronized (mPackages) {
retCode = PackageManager.INSTALL_SUCCEEDED;
pkgList.add(pkg.packageName);
// Post process args
args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
pkg.applicationInfo.uid);
}
} else {
Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
}
}
} finally {
if (retCode != PackageManager.INSTALL_SUCCEEDED) {
// Don't destroy container here. Wait till gc clears things
// up.
removeCids.add(args.cid);
}
}
}
// writer
synchronized (mPackages) {
// If the platform SDK has changed since the last time we booted,
// we need to re-grant app permission to catch any new ones that
// appear. This is really a hack, and means that apps can in some
// cases get permissions that the user didn't initially explicitly
// allow... it would be nice to have some better way to handle
// this situation.
final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
if (regrantPermissions)
Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
+ mSdkVersion + "; regranting permissions for external storage");
mSettings.mExternalSdkPlatform = mSdkVersion;
// Make sure group IDs have been assigned, and any permission
// changes in other apps are accounted for
updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
| (regrantPermissions
? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
: 0));
// can downgrade to reader
// Persist settings
mSettings.writeLPr();
}
// Send a broadcast to let everyone know we are done processing
if (pkgList.size() > 0) {
sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
}
// Force gc to avoid any stale parser references that we might have.
if (doGc) {
Runtime.getRuntime().gc();
}
// List stale containers and destroy stale temporary containers.
if (removeCids != null) {
for (String cid : removeCids) {
if (cid.startsWith(mTempContainerPrefix)) {
Log.i(TAG, "Destroying stale temporary container " + cid);
PackageHelper.destroySdDir(cid);
} else {
Log.w(TAG, "Container " + cid + " is stale");
}
}
}
}
/*
* Utility method to unload a list of specified containers
*/
private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
// Just unmount all valid containers.
for (AsecInstallArgs arg : cidArgs) {
synchronized (mInstallLock) {
arg.doPostDeleteLI(false);
}
}
}
/*
* Unload packages mounted on external media. This involves deleting package
* data from internal structures, sending broadcasts about diabled packages,
* gc'ing to free up references, unmounting all secure containers
* corresponding to packages on external media, and posting a
* UPDATED_MEDIA_STATUS message if status has been requested. Please note
* that we always have to post this message if status has been requested no
* matter what.
*/
private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
final boolean reportStatus) {
if (DEBUG_SD_INSTALL)
Log.i(TAG, "unloading media packages");
ArrayList<String> pkgList = new ArrayList<String>();
ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
final Set<AsecInstallArgs> keys = processCids.keySet();
for (AsecInstallArgs args : keys) {
String pkgName = args.getPackageName();
if (DEBUG_SD_INSTALL)
Log.i(TAG, "Trying to unload pkg : " + pkgName);
// Delete package internally
PackageRemovedInfo outInfo = new PackageRemovedInfo();
synchronized (mInstallLock) {
boolean res = deletePackageLI(pkgName, null, false, null, null,
PackageManager.DELETE_KEEP_DATA, outInfo, false);
if (res) {
pkgList.add(pkgName);
} else {
Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
failedList.add(args);
}
}
}
// reader
synchronized (mPackages) {
// We didn't update the settings after removing each package;
// write them now for all packages.
mSettings.writeLPr();
}
// We have to absolutely send UPDATED_MEDIA_STATUS only
// after confirming that all the receivers processed the ordered
// broadcast when packages get disabled, force a gc to clean things up.
// and unload all the containers.
if (pkgList.size() > 0) {
sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
public void performReceive(Intent intent, int resultCode, String data,
Bundle extras, boolean ordered, boolean sticky,
int sendingUser) throws RemoteException {
Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
reportStatus ? 1 : 0, 1, keys);
mHandler.sendMessage(msg);
}
});
} else {
Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
keys);
mHandler.sendMessage(msg);
}
}
/** Binder call */
@Override
public void movePackage(final String packageName, final IPackageMoveObserver observer,
final int flags) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
UserHandle user = new UserHandle(UserHandle.getCallingUserId());
int returnCode = PackageManager.MOVE_SUCCEEDED;
int currFlags = 0;
int newFlags = 0;
// reader
synchronized (mPackages) {
PackageParser.Package pkg = mPackages.get(packageName);
if (pkg == null) {
returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
} else {
// Disable moving fwd locked apps and system packages
if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Slog.w(TAG, "Cannot move system application");
returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
} else if (pkg.mOperationPending) {
Slog.w(TAG, "Attempt to move package which has pending operations");
returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
} else {
// Find install location first
if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
&& (flags & PackageManager.MOVE_INTERNAL) != 0) {
Slog.w(TAG, "Ambigous flags specified for move location.");
returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
} else {
newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
: PackageManager.INSTALL_INTERNAL;
currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
: PackageManager.INSTALL_INTERNAL;
if (newFlags == currFlags) {
Slog.w(TAG, "No move required. Trying to move to same location");
returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
} else {
if (isForwardLocked(pkg)) {
currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
}
}
}
if (returnCode == PackageManager.MOVE_SUCCEEDED) {
pkg.mOperationPending = true;
}
}
}
/*
* TODO this next block probably shouldn't be inside the lock. We
* can't guarantee these won't change after this is fired off
* anyway.
*/
if (returnCode != PackageManager.MOVE_SUCCEEDED) {
processPendingMove(new MoveParams(null, observer, 0, packageName,
null, -1, user),
returnCode);
} else {
Message msg = mHandler.obtainMessage(INIT_COPY);
InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user);
msg.obj = mp;
mHandler.sendMessage(msg);
}
}
}
private void processPendingMove(final MoveParams mp, final int currentStatus) {
// Queue up an async operation since the package deletion may take a
// little while.
mHandler.post(new Runnable() {
public void run() {
// TODO fix this; this does nothing.
mHandler.removeCallbacks(this);
int returnCode = currentStatus;
if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
int uidArr[] = null;
ArrayList<String> pkgList = null;
synchronized (mPackages) {
PackageParser.Package pkg = mPackages.get(mp.packageName);
if (pkg == null) {
Slog.w(TAG, " Package " + mp.packageName
+ " doesn't exist. Aborting move");
returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
} else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
+ mp.srcArgs.getCodePath() + " to "
+ pkg.applicationInfo.sourceDir
+ " Aborting move and returning error");
returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
} else {
uidArr = new int[] {
pkg.applicationInfo.uid
};
pkgList = new ArrayList<String>();
pkgList.add(mp.packageName);
}
}
if (returnCode == PackageManager.MOVE_SUCCEEDED) {
// Send resources unavailable broadcast
sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
// Update package code and resource paths
synchronized (mInstallLock) {
synchronized (mPackages) {
PackageParser.Package pkg = mPackages.get(mp.packageName);
// Recheck for package again.
if (pkg == null) {
Slog.w(TAG, " Package " + mp.packageName
+ " doesn't exist. Aborting move");
returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
} else if (!mp.srcArgs.getCodePath().equals(
pkg.applicationInfo.sourceDir)) {
Slog.w(TAG, "Package " + mp.packageName
+ " code path changed from " + mp.srcArgs.getCodePath()
+ " to " + pkg.applicationInfo.sourceDir
+ " Aborting move and returning error");
returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
} else {
final String oldCodePath = pkg.mPath;
final String newCodePath = mp.targetArgs.getCodePath();
final String newResPath = mp.targetArgs.getResourcePath();
final String newNativePath = mp.targetArgs
.getNativeLibraryPath();
final File newNativeDir = new File(newNativePath);
if (!isForwardLocked(pkg) && !isExternal(pkg)) {
NativeLibraryHelper.copyNativeBinariesIfNeededLI(
new File(newCodePath), newNativeDir);
}
final int[] users = sUserManager.getUserIds();
for (int user : users) {
if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
newNativePath, user) < 0) {
returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
}
}
if (returnCode == PackageManager.MOVE_SUCCEEDED) {
pkg.mPath = newCodePath;
// Move dex files around
if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
// Moving of dex files failed. Set
// error code and abort move.
pkg.mPath = pkg.mScanPath;
returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
}
}
if (returnCode == PackageManager.MOVE_SUCCEEDED) {
pkg.mScanPath = newCodePath;
pkg.applicationInfo.sourceDir = newCodePath;
pkg.applicationInfo.publicSourceDir = newResPath;
pkg.applicationInfo.nativeLibraryDir = newNativePath;
PackageSetting ps = (PackageSetting) pkg.mExtras;
ps.codePath = new File(pkg.applicationInfo.sourceDir);
ps.codePathString = ps.codePath.getPath();
ps.resourcePath = new File(
pkg.applicationInfo.publicSourceDir);
ps.resourcePathString = ps.resourcePath.getPath();
ps.nativeLibraryPathString = newNativePath;
// Set the application info flag
// correctly.
if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
} else {
pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
}
ps.setFlags(pkg.applicationInfo.flags);
mAppDirs.remove(oldCodePath);
mAppDirs.put(newCodePath, pkg);
// Persist settings
mSettings.writeLPr();
}
}
}
}
// Send resources available broadcast
sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
}
}
if (returnCode != PackageManager.MOVE_SUCCEEDED) {
// Clean up failed installation
if (mp.targetArgs != null) {
mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
-1);
}
} else {
// Force a gc to clear things up.
Runtime.getRuntime().gc();
// Delete older code
synchronized (mInstallLock) {
mp.srcArgs.doPostDeleteLI(true);
}
}
// Allow more operations on this file if we didn't fail because
// an operation was already pending for this package.
if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
synchronized (mPackages) {
PackageParser.Package pkg = mPackages.get(mp.packageName);
if (pkg != null) {
pkg.mOperationPending = false;
}
}
}
IPackageMoveObserver observer = mp.observer;
if (observer != null) {
try {
observer.packageMoved(mp.packageName, returnCode);
} catch (RemoteException e) {
Log.i(TAG, "Observer no longer exists.");
}
}
}
});
}
public boolean setInstallLocation(int loc) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
null);
if (getInstallLocation() == loc) {
return true;
}
if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
|| loc == PackageHelper.APP_INSTALL_EXTERNAL) {
android.provider.Settings.Global.putInt(mContext.getContentResolver(),
android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
return true;
}
return false;
}
public int getInstallLocation() {
return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
PackageHelper.APP_INSTALL_AUTO);
}
/** Called by UserManagerService */
void cleanUpUserLILPw(int userHandle) {
mDirtyUsers.remove(userHandle);
mSettings.removeUserLPr(userHandle);
mPendingBroadcasts.remove(userHandle);
if (mInstaller != null) {
// Technically, we shouldn't be doing this with the package lock
// held. However, this is very rare, and there is already so much
// other disk I/O going on, that we'll let it slide for now.
mInstaller.removeUserDataDirs(userHandle);
}
}
/** Called by UserManagerService */
void createNewUserLILPw(int userHandle, File path) {
if (mInstaller != null) {
mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
}
}
@Override
public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
"Only package verification agents can read the verifier device identity");
synchronized (mPackages) {
return mSettings.getVerifierDeviceIdentityLPw();
}
}
@Override
public void setPermissionEnforced(String permission, boolean enforced) {
mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
if (READ_EXTERNAL_STORAGE.equals(permission)) {
synchronized (mPackages) {
if (mSettings.mReadExternalStorageEnforced == null
|| mSettings.mReadExternalStorageEnforced != enforced) {
mSettings.mReadExternalStorageEnforced = enforced;
mSettings.writeLPr();
}
}
// kill any non-foreground processes so we restart them and
// grant/revoke the GID.
final IActivityManager am = ActivityManagerNative.getDefault();
if (am != null) {
final long token = Binder.clearCallingIdentity();
try {
am.killProcessesBelowForeground("setPermissionEnforcement");
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(token);
}
}
} else {
throw new IllegalArgumentException("No selective enforcement for " + permission);
}
}
@Override
public boolean isPermissionEnforced(String permission) {
final boolean enforcedDefault = isPermissionEnforcedDefault(permission);
synchronized (mPackages) {
return isPermissionEnforcedLocked(permission, enforcedDefault);
}
}
/**
* Check if given permission should be enforced by default. Should always be
* called outside of {@link #mPackages} lock.
*/
private boolean isPermissionEnforcedDefault(String permission) {
if (READ_EXTERNAL_STORAGE.equals(permission)) {
return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
android.provider.Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0)
!= 0;
} else {
return true;
}
}
/**
* Check if user has requested that given permission be enforced, using
* given default if undefined.
*/
private boolean isPermissionEnforcedLocked(String permission, boolean enforcedDefault) {
if (READ_EXTERNAL_STORAGE.equals(permission)) {
if (mSettings.mReadExternalStorageEnforced != null) {
return mSettings.mReadExternalStorageEnforced;
} else {
// User hasn't defined; fall back to secure default
return enforcedDefault;
}
} else {
return true;
}
}
public boolean isStorageLow() {
final long token = Binder.clearCallingIdentity();
try {
final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager
.getService(DeviceStorageMonitorService.SERVICE);
return dsm.isMemoryLow();
} finally {
Binder.restoreCallingIdentity(token);
}
}
}
| true | true | private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
int parseFlags, int scanMode, long currentTime, UserHandle user) {
File scanFile = new File(pkg.mScanPath);
if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
pkg.applicationInfo.publicSourceDir == null) {
// Bail out. The resource and code paths haven't been set.
Slog.w(TAG, " Code and resource paths haven't been set correctly");
mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
return null;
}
mScanningPath = scanFile;
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
}
if (pkg.packageName.equals("android")) {
synchronized (mPackages) {
if (mAndroidApplication != null) {
Slog.w(TAG, "*************************************************");
Slog.w(TAG, "Core android package being redefined. Skipping.");
Slog.w(TAG, " file=" + mScanningPath);
Slog.w(TAG, "*************************************************");
mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
return null;
}
// Set up information for our fall-back user intent resolution
// activity.
mPlatformPackage = pkg;
pkg.mVersionCode = mSdkVersion;
mAndroidApplication = pkg.applicationInfo;
mResolveActivity.applicationInfo = mAndroidApplication;
mResolveActivity.name = ResolverActivity.class.getName();
mResolveActivity.packageName = mAndroidApplication.packageName;
mResolveActivity.processName = "system:ui";
mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
mResolveActivity.exported = true;
mResolveActivity.enabled = true;
mResolveInfo.activityInfo = mResolveActivity;
mResolveInfo.priority = 0;
mResolveInfo.preferredOrder = 0;
mResolveInfo.match = 0;
mResolveComponentName = new ComponentName(
mAndroidApplication.packageName, mResolveActivity.name);
}
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Scanning package " + pkg.packageName);
}
if (mPackages.containsKey(pkg.packageName)
|| mSharedLibraries.containsKey(pkg.packageName)) {
Slog.w(TAG, "Application package " + pkg.packageName
+ " already installed. Skipping duplicate.");
mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
return null;
}
if (!pkg.applicationInfo.sourceDir.startsWith(Environment.getRootDirectory().getPath()) &&
!pkg.applicationInfo.sourceDir.startsWith("/vendor")) {
Object obj = mSettings.getUserIdLPr(1000);
Signature[] s1 = null;
if (obj instanceof SharedUserSetting) {
s1 = ((SharedUserSetting)obj).signatures.mSignatures;
}
if ((compareSignatures(pkg.mSignatures, s1) == PackageManager.SIGNATURE_MATCH)) {
Slog.w(TAG, "Cannot install platform packages to user storage");
mLastScanError = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
return null;
}
}
// Initialize package source and resource directories
File destCodeFile = new File(pkg.applicationInfo.sourceDir);
File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
SharedUserSetting suid = null;
PackageSetting pkgSetting = null;
if (!isSystemApp(pkg)) {
// Only system apps can use these features.
pkg.mOriginalPackages = null;
pkg.mRealPackage = null;
pkg.mAdoptPermissions = null;
}
// writer
synchronized (mPackages) {
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
// Check all shared libraries and map to their actual file path.
// We only do this here for apps not on a system dir, because those
// are the only ones that can fail an install due to this. We
// will take care of the system apps by updating all of their
// library paths after the scan is done.
if (!updateSharedLibrariesLPw(pkg, null)) {
return null;
}
}
if (pkg.mSharedUserId != null) {
suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
pkg.applicationInfo.flags, true);
if (suid == null) {
Slog.w(TAG, "Creating application package " + pkg.packageName
+ " for shared user failed");
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
+ "): packages=" + suid.packages);
}
}
// Check if we are renaming from an original package name.
PackageSetting origPackage = null;
String realName = null;
if (pkg.mOriginalPackages != null) {
// This package may need to be renamed to a previously
// installed name. Let's check on that...
final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
if (pkg.mOriginalPackages.contains(renamed)) {
// This package had originally been installed as the
// original name, and we have already taken care of
// transitioning to the new one. Just update the new
// one to continue using the old name.
realName = pkg.mRealPackage;
if (!pkg.packageName.equals(renamed)) {
// Callers into this function may have already taken
// care of renaming the package; only do it here if
// it is not already done.
pkg.setPackageName(renamed);
}
} else {
for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
if ((origPackage = mSettings.peekPackageLPr(
pkg.mOriginalPackages.get(i))) != null) {
// We do have the package already installed under its
// original name... should we use it?
if (!verifyPackageUpdateLPr(origPackage, pkg)) {
// New package is not compatible with original.
origPackage = null;
continue;
} else if (origPackage.sharedUser != null) {
// Make sure uid is compatible between packages.
if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Slog.w(TAG, "Unable to migrate data from " + origPackage.name
+ " to " + pkg.packageName + ": old uid "
+ origPackage.sharedUser.name
+ " differs from " + pkg.mSharedUserId);
origPackage = null;
continue;
}
} else {
if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
+ pkg.packageName + " to old name " + origPackage.name);
}
break;
}
}
}
}
if (mTransferedPackages.contains(pkg.packageName)) {
Slog.w(TAG, "Package " + pkg.packageName
+ " was transferred to another, but its .apk remains");
}
// Just create the setting, don't add it yet. For already existing packages
// the PkgSetting exists already and doesn't have to be created.
pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
destResourceFile, pkg.applicationInfo.nativeLibraryDir,
pkg.applicationInfo.flags, user, false);
if (pkgSetting == null) {
Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (pkgSetting.origPackage != null) {
// If we are first transitioning from an original package,
// fix up the new package's name now. We need to do this after
// looking up the package under its new name, so getPackageLP
// can take care of fiddling things correctly.
pkg.setPackageName(origPackage.name);
// File a report about this.
String msg = "New package " + pkgSetting.realName
+ " renamed to replace old package " + pkgSetting.name;
reportSettingsProblem(Log.WARN, msg);
// Make a note of it.
mTransferedPackages.add(origPackage.name);
// No longer need to retain this.
pkgSetting.origPackage = null;
}
if (realName != null) {
// Make a note of it.
mTransferedPackages.add(pkg.packageName);
}
if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
}
if (mFoundPolicyFile) {
SELinuxMMAC.assignSeinfoValue(pkg);
}
pkg.applicationInfo.uid = pkgSetting.appId;
pkg.mExtras = pkgSetting;
if (!verifySignaturesLP(pkgSetting, pkg)) {
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
return null;
}
// The signature has changed, but this package is in the system
// image... let's recover!
pkgSetting.signatures.mSignatures = pkg.mSignatures;
// However... if this package is part of a shared user, but it
// doesn't match the signature of the shared user, let's fail.
// What this means is that you can't change the signatures
// associated with an overall shared user, which doesn't seem all
// that unreasonable.
if (pkgSetting.sharedUser != null) {
if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
return null;
}
}
// File a report about this.
String msg = "System package " + pkg.packageName
+ " signature changed; retaining data.";
reportSettingsProblem(Log.WARN, msg);
}
// Verify that this new package doesn't have any content providers
// that conflict with existing packages. Only do this if the
// package isn't already installed, since we don't want to break
// things that are installed.
if ((scanMode&SCAN_NEW_INSTALL) != 0) {
final int N = pkg.providers.size();
int i;
for (i=0; i<N; i++) {
PackageParser.Provider p = pkg.providers.get(i);
if (p.info.authority != null) {
String names[] = p.info.authority.split(";");
for (int j = 0; j < names.length; j++) {
if (mProviders.containsKey(names[j])) {
PackageParser.Provider other = mProviders.get(names[j]);
Slog.w(TAG, "Can't install because provider name " + names[j] +
" (in package " + pkg.applicationInfo.packageName +
") is already used by "
+ ((other != null && other.getComponentName() != null)
? other.getComponentName().getPackageName() : "?"));
mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
return null;
}
}
}
}
}
if (pkg.mAdoptPermissions != null) {
// This package wants to adopt ownership of permissions from
// another package.
for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
final String origName = pkg.mAdoptPermissions.get(i);
final PackageSetting orig = mSettings.peekPackageLPr(origName);
if (orig != null) {
if (verifyPackageUpdateLPr(orig, pkg)) {
Slog.i(TAG, "Adopting permissions from " + origName + " to "
+ pkg.packageName);
mSettings.transferPermissionsLPw(origName, pkg.packageName);
}
}
}
}
}
final String pkgName = pkg.packageName;
final long scanFileTime = scanFile.lastModified();
final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
pkg.applicationInfo.processName = fixProcessName(
pkg.applicationInfo.packageName,
pkg.applicationInfo.processName,
pkg.applicationInfo.uid);
File dataPath;
if (mPlatformPackage == pkg) {
// The system package is special.
dataPath = new File (Environment.getDataDirectory(), "system");
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
// This is a normal package, need to make its data directory.
dataPath = getDataPathForPackage(pkg.packageName, 0);
boolean uidError = false;
if (dataPath.exists()) {
int currentUid = 0;
try {
StructStat stat = Libcore.os.stat(dataPath.getPath());
currentUid = stat.st_uid;
} catch (ErrnoException e) {
Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
}
// If we have mismatched owners for the data path, we have a problem.
if (currentUid != pkg.applicationInfo.uid) {
boolean recovered = false;
if (currentUid == 0) {
// The directory somehow became owned by root. Wow.
// This is probably because the system was stopped while
// installd was in the middle of messing with its libs
// directory. Ask installd to fix that.
int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.uid);
if (ret >= 0) {
recovered = true;
String msg = "Package " + pkg.packageName
+ " unexpectedly changed to uid 0; recovered to " +
+ pkg.applicationInfo.uid;
reportSettingsProblem(Log.WARN, msg);
}
}
if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
|| (scanMode&SCAN_BOOTING) != 0)) {
// If this is a system app, we can at least delete its
// current data so the application will still work.
int ret = removeDataDirsLI(pkgName);
if (ret >= 0) {
// TODO: Kill the processes first
// Old data gone!
String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
? "System package " : "Third party package ";
String msg = prefix + pkg.packageName
+ " has changed from uid: "
+ currentUid + " to "
+ pkg.applicationInfo.uid + "; old data erased";
reportSettingsProblem(Log.WARN, msg);
recovered = true;
// And now re-install the app.
ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.seinfo);
if (ret == -1) {
// Ack should not happen!
msg = prefix + pkg.packageName
+ " could not have data directory re-created after delete.";
reportSettingsProblem(Log.WARN, msg);
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
}
if (!recovered) {
mHasSystemUidErrors = true;
}
} else if (!recovered) {
// If we allow this install to proceed, we will be broken.
// Abort, abort!
mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
return null;
}
if (!recovered) {
pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
+ pkg.applicationInfo.uid + "/fs_"
+ currentUid;
pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
String msg = "Package " + pkg.packageName
+ " has mismatched uid: "
+ currentUid + " on disk, "
+ pkg.applicationInfo.uid + " in settings";
// writer
synchronized (mPackages) {
mSettings.mReadMessages.append(msg);
mSettings.mReadMessages.append('\n');
uidError = true;
if (!pkgSetting.uidError) {
reportSettingsProblem(Log.ERROR, msg);
}
}
}
}
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.v(TAG, "Want this data dir: " + dataPath);
}
//invoke installer to do the actual installation
int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.seinfo);
if (ret < 0) {
// Error from installer
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (dataPath.exists()) {
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
Slog.w(TAG, "Unable to create data directory: " + dataPath);
pkg.applicationInfo.dataDir = null;
}
}
/*
* Set the data dir to the default "/data/data/<package name>/lib"
* if we got here without anyone telling us different (e.g., apps
* stored on SD card have their native libraries stored in the ASEC
* container with the APK).
*
* This happens during an upgrade from a package settings file that
* doesn't have a native library path attribute at all.
*/
if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
if (pkgSetting.nativeLibraryPathString == null) {
setInternalAppNativeLibraryPath(pkg, pkgSetting);
} else {
pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
}
}
pkgSetting.uidError = uidError;
}
String path = scanFile.getPath();
/* Note: We don't want to unpack the native binaries for
* system applications, unless they have been updated
* (the binaries are already under /system/lib).
* Also, don't unpack libs for apps on the external card
* since they should have their libraries in the ASEC
* container already.
*
* In other words, we're going to unpack the binaries
* only for non-system apps and system app upgrades.
*/
if (pkg.applicationInfo.nativeLibraryDir != null) {
try {
File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
final String dataPathString = dataPath.getCanonicalPath();
if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
/*
* Upgrading from a previous version of the OS sometimes
* leaves native libraries in the /data/data/<app>/lib
* directory for system apps even when they shouldn't be.
* Recent changes in the JNI library search path
* necessitates we remove those to match previous behavior.
*/
if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Log.i(TAG, "removed obsolete native libraries for system package "
+ path);
}
} else {
if (!isForwardLocked(pkg) && !isExternal(pkg)) {
/*
* Update native library dir if it starts with
* /data/data
*/
if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
setInternalAppNativeLibraryPath(pkg, pkgSetting);
nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
}
try {
if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
Slog.e(TAG, "Unable to copy native libraries");
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
} catch (IOException e) {
Slog.e(TAG, "Unable to copy native libraries", e);
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
}
if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
final int[] userIds = sUserManager.getUserIds();
synchronized (mInstallLock) {
for (int userId : userIds) {
if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
Slog.w(TAG, "Failed linking native library dir (user=" + userId
+ ")");
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
}
}
}
} catch (IOException ioe) {
Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
}
}
pkg.mScanPath = path;
if ((scanMode&SCAN_NO_DEX) == 0) {
if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
== DEX_OPT_FAILED) {
mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
return null;
}
}
if (mFactoryTest && pkg.requestedPermissions.contains(
android.Manifest.permission.FACTORY_TEST)) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
}
ArrayList<PackageParser.Package> clientLibPkgs = null;
// writer
synchronized (mPackages) {
if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
// Only system apps can add new shared libraries.
if (pkg.libraryNames != null) {
for (int i=0; i<pkg.libraryNames.size(); i++) {
String name = pkg.libraryNames.get(i);
boolean allowed = false;
if (isUpdatedSystemApp(pkg)) {
// New library entries can only be added through the
// system image. This is important to get rid of a lot
// of nasty edge cases: for example if we allowed a non-
// system update of the app to add a library, then uninstalling
// the update would make the library go away, and assumptions
// we made such as through app install filtering would now
// have allowed apps on the device which aren't compatible
// with it. Better to just have the restriction here, be
// conservative, and create many fewer cases that can negatively
// impact the user experience.
final PackageSetting sysPs = mSettings
.getDisabledSystemPkgLPr(pkg.packageName);
if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
if (name.equals(sysPs.pkg.libraryNames.get(j))) {
allowed = true;
allowed = true;
break;
}
}
}
} else {
allowed = true;
}
if (allowed) {
if (!mSharedLibraries.containsKey(name)) {
mSharedLibraries.put(name, new SharedLibraryEntry(null,
pkg.packageName));
} else if (!name.equals(pkg.packageName)) {
Slog.w(TAG, "Package " + pkg.packageName + " library "
+ name + " already exists; skipping");
}
} else {
Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
+ name + " that is not declared on system image; skipping");
}
}
if ((scanMode&SCAN_BOOTING) == 0) {
// If we are not booting, we need to update any applications
// that are clients of our shared library. If we are booting,
// this will all be done once the scan is complete.
clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
}
}
}
}
// We also need to dexopt any apps that are dependent on this library. Note that
// if these fail, we should abort the install since installing the library will
// result in some apps being broken.
if (clientLibPkgs != null) {
if ((scanMode&SCAN_NO_DEX) == 0) {
for (int i=0; i<clientLibPkgs.size(); i++) {
PackageParser.Package clientPkg = clientLibPkgs.get(i);
if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
== DEX_OPT_FAILED) {
mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
return null;
}
}
}
}
// Request the ActivityManager to kill the process(only for existing packages)
// so that we do not end up in a confused state while the user is still using the older
// version of the application while the new one gets installed.
if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
killApplication(pkg.applicationInfo.packageName,
pkg.applicationInfo.uid);
}
// Also need to kill any apps that are dependent on the library.
if (clientLibPkgs != null) {
for (int i=0; i<clientLibPkgs.size(); i++) {
PackageParser.Package clientPkg = clientLibPkgs.get(i);
killApplication(clientPkg.applicationInfo.packageName,
clientPkg.applicationInfo.uid);
}
}
// writer
synchronized (mPackages) {
// We don't expect installation to fail beyond this point,
if ((scanMode&SCAN_MONITOR) != 0) {
mAppDirs.put(pkg.mPath, pkg);
}
// Add the new setting to mSettings
mSettings.insertPackageSettingLPw(pkgSetting, pkg);
// Add the new setting to mPackages
mPackages.put(pkg.applicationInfo.packageName, pkg);
// Make sure we don't accidentally delete its data.
final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
while (iter.hasNext()) {
PackageCleanItem item = iter.next();
if (pkgName.equals(item.packageName)) {
iter.remove();
}
}
// Take care of first install / last update times.
if (currentTime != 0) {
if (pkgSetting.firstInstallTime == 0) {
pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
} else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
pkgSetting.lastUpdateTime = currentTime;
}
} else if (pkgSetting.firstInstallTime == 0) {
// We need *something*. Take time time stamp of the file.
pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
} else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
if (scanFileTime != pkgSetting.timeStamp) {
// A package on the system image has changed; consider this
// to be an update.
pkgSetting.lastUpdateTime = scanFileTime;
}
}
int N = pkg.providers.size();
StringBuilder r = null;
int i;
for (i=0; i<N; i++) {
PackageParser.Provider p = pkg.providers.get(i);
p.info.processName = fixProcessName(pkg.applicationInfo.processName,
p.info.processName, pkg.applicationInfo.uid);
mProvidersByComponent.put(new ComponentName(p.info.packageName,
p.info.name), p);
p.syncable = p.info.isSyncable;
if (p.info.authority != null) {
String names[] = p.info.authority.split(";");
p.info.authority = null;
for (int j = 0; j < names.length; j++) {
if (j == 1 && p.syncable) {
// We only want the first authority for a provider to possibly be
// syncable, so if we already added this provider using a different
// authority clear the syncable flag. We copy the provider before
// changing it because the mProviders object contains a reference
// to a provider that we don't want to change.
// Only do this for the second authority since the resulting provider
// object can be the same for all future authorities for this provider.
p = new PackageParser.Provider(p);
p.syncable = false;
}
if (!mProviders.containsKey(names[j])) {
mProviders.put(names[j], p);
if (p.info.authority == null) {
p.info.authority = names[j];
} else {
p.info.authority = p.info.authority + ";" + names[j];
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Registered content provider: " + names[j]
+ ", className = " + p.info.name + ", isSyncable = "
+ p.info.isSyncable);
}
} else {
PackageParser.Provider other = mProviders.get(names[j]);
Slog.w(TAG, "Skipping provider name " + names[j] +
" (in package " + pkg.applicationInfo.packageName +
"): name already used by "
+ ((other != null && other.getComponentName() != null)
? other.getComponentName().getPackageName() : "?"));
}
}
}
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(p.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
}
N = pkg.services.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Service s = pkg.services.get(i);
s.info.processName = fixProcessName(pkg.applicationInfo.processName,
s.info.processName, pkg.applicationInfo.uid);
mServices.addService(s);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(s.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
}
N = pkg.receivers.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Activity a = pkg.receivers.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName, pkg.applicationInfo.uid);
mReceivers.addActivity(a, "receiver");
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
}
N = pkg.activities.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Activity a = pkg.activities.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName, pkg.applicationInfo.uid);
mActivities.addActivity(a, "activity");
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
}
N = pkg.permissionGroups.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
if (cur == null) {
mPermissionGroups.put(pg.info.name, pg);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(pg.info.name);
}
} else {
Slog.w(TAG, "Permission group " + pg.info.name + " from package "
+ pg.info.packageName + " ignored: original from "
+ cur.info.packageName);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append("DUP:");
r.append(pg.info.name);
}
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
}
N = pkg.permissions.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Permission p = pkg.permissions.get(i);
HashMap<String, BasePermission> permissionMap =
p.tree ? mSettings.mPermissionTrees
: mSettings.mPermissions;
p.group = mPermissionGroups.get(p.info.group);
if (p.info.group == null || p.group != null) {
BasePermission bp = permissionMap.get(p.info.name);
if (bp == null) {
bp = new BasePermission(p.info.name, p.info.packageName,
BasePermission.TYPE_NORMAL);
permissionMap.put(p.info.name, bp);
}
if (bp.perm == null) {
if (bp.sourcePackage == null
|| bp.sourcePackage.equals(p.info.packageName)) {
BasePermission tree = findPermissionTreeLP(p.info.name);
if (tree == null
|| tree.sourcePackage.equals(p.info.packageName)) {
bp.packageSetting = pkgSetting;
bp.perm = p;
bp.uid = pkg.applicationInfo.uid;
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(p.info.name);
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: base tree "
+ tree.name + " is from package "
+ tree.sourcePackage);
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: original from "
+ bp.sourcePackage);
}
} else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append("DUP:");
r.append(p.info.name);
}
if (bp.perm == p) {
bp.protectionLevel = p.info.protectionLevel;
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: no group "
+ p.group);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
}
N = pkg.instrumentation.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Instrumentation a = pkg.instrumentation.get(i);
a.info.packageName = pkg.applicationInfo.packageName;
a.info.sourceDir = pkg.applicationInfo.sourceDir;
a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
a.info.dataDir = pkg.applicationInfo.dataDir;
a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
mInstrumentation.put(a.getComponentName(), a);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
}
if (pkg.protectedBroadcasts != null) {
N = pkg.protectedBroadcasts.size();
for (i=0; i<N; i++) {
mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
}
}
pkgSetting.setTimeStamp(scanFileTime);
}
return pkg;
}
| private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
int parseFlags, int scanMode, long currentTime, UserHandle user) {
File scanFile = new File(pkg.mScanPath);
if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
pkg.applicationInfo.publicSourceDir == null) {
// Bail out. The resource and code paths haven't been set.
Slog.w(TAG, " Code and resource paths haven't been set correctly");
mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
return null;
}
mScanningPath = scanFile;
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
}
if (pkg.packageName.equals("android")) {
synchronized (mPackages) {
if (mAndroidApplication != null) {
Slog.w(TAG, "*************************************************");
Slog.w(TAG, "Core android package being redefined. Skipping.");
Slog.w(TAG, " file=" + mScanningPath);
Slog.w(TAG, "*************************************************");
mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
return null;
}
// Set up information for our fall-back user intent resolution
// activity.
mPlatformPackage = pkg;
pkg.mVersionCode = mSdkVersion;
mAndroidApplication = pkg.applicationInfo;
mResolveActivity.applicationInfo = mAndroidApplication;
mResolveActivity.name = ResolverActivity.class.getName();
mResolveActivity.packageName = mAndroidApplication.packageName;
mResolveActivity.processName = "system:ui";
mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
mResolveActivity.exported = true;
mResolveActivity.enabled = true;
mResolveInfo.activityInfo = mResolveActivity;
mResolveInfo.priority = 0;
mResolveInfo.preferredOrder = 0;
mResolveInfo.match = 0;
mResolveComponentName = new ComponentName(
mAndroidApplication.packageName, mResolveActivity.name);
}
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Scanning package " + pkg.packageName);
}
if (mPackages.containsKey(pkg.packageName)
|| mSharedLibraries.containsKey(pkg.packageName)) {
Slog.w(TAG, "Application package " + pkg.packageName
+ " already installed. Skipping duplicate.");
mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
return null;
}
if (!pkg.applicationInfo.sourceDir.startsWith(Environment.getRootDirectory().getPath()) &&
!pkg.applicationInfo.sourceDir.startsWith("/vendor")) {
Object obj = mSettings.getUserIdLPr(1000);
Signature[] s1 = null;
if (obj instanceof SharedUserSetting) {
s1 = ((SharedUserSetting)obj).signatures.mSignatures;
}
if ((compareSignatures(pkg.mSignatures, s1) == PackageManager.SIGNATURE_MATCH)) {
Slog.w(TAG, "Cannot install platform packages to user storage");
mLastScanError = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
return null;
}
}
// Initialize package source and resource directories
File destCodeFile = new File(pkg.applicationInfo.sourceDir);
File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
SharedUserSetting suid = null;
PackageSetting pkgSetting = null;
if (!isSystemApp(pkg)) {
// Only system apps can use these features.
pkg.mOriginalPackages = null;
pkg.mRealPackage = null;
pkg.mAdoptPermissions = null;
}
// writer
synchronized (mPackages) {
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
// Check all shared libraries and map to their actual file path.
// We only do this here for apps not on a system dir, because those
// are the only ones that can fail an install due to this. We
// will take care of the system apps by updating all of their
// library paths after the scan is done.
if (!updateSharedLibrariesLPw(pkg, null)) {
return null;
}
}
if (pkg.mSharedUserId != null) {
suid = mSettings.getSharedUserLPw(pkg.mSharedUserId,
pkg.applicationInfo.flags, true);
if (suid == null) {
Slog.w(TAG, "Creating application package " + pkg.packageName
+ " for shared user failed");
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
+ "): packages=" + suid.packages);
}
}
// Check if we are renaming from an original package name.
PackageSetting origPackage = null;
String realName = null;
if (pkg.mOriginalPackages != null) {
// This package may need to be renamed to a previously
// installed name. Let's check on that...
final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
if (pkg.mOriginalPackages.contains(renamed)) {
// This package had originally been installed as the
// original name, and we have already taken care of
// transitioning to the new one. Just update the new
// one to continue using the old name.
realName = pkg.mRealPackage;
if (!pkg.packageName.equals(renamed)) {
// Callers into this function may have already taken
// care of renaming the package; only do it here if
// it is not already done.
pkg.setPackageName(renamed);
}
} else {
for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
if ((origPackage = mSettings.peekPackageLPr(
pkg.mOriginalPackages.get(i))) != null) {
// We do have the package already installed under its
// original name... should we use it?
if (!verifyPackageUpdateLPr(origPackage, pkg)) {
// New package is not compatible with original.
origPackage = null;
continue;
} else if (origPackage.sharedUser != null) {
// Make sure uid is compatible between packages.
if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Slog.w(TAG, "Unable to migrate data from " + origPackage.name
+ " to " + pkg.packageName + ": old uid "
+ origPackage.sharedUser.name
+ " differs from " + pkg.mSharedUserId);
origPackage = null;
continue;
}
} else {
if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
+ pkg.packageName + " to old name " + origPackage.name);
}
break;
}
}
}
}
if (mTransferedPackages.contains(pkg.packageName)) {
Slog.w(TAG, "Package " + pkg.packageName
+ " was transferred to another, but its .apk remains");
}
// Just create the setting, don't add it yet. For already existing packages
// the PkgSetting exists already and doesn't have to be created.
pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
destResourceFile, pkg.applicationInfo.nativeLibraryDir,
pkg.applicationInfo.flags, user, false);
if (pkgSetting == null) {
Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (pkgSetting.origPackage != null) {
// If we are first transitioning from an original package,
// fix up the new package's name now. We need to do this after
// looking up the package under its new name, so getPackageLP
// can take care of fiddling things correctly.
pkg.setPackageName(origPackage.name);
// File a report about this.
String msg = "New package " + pkgSetting.realName
+ " renamed to replace old package " + pkgSetting.name;
reportSettingsProblem(Log.WARN, msg);
// Make a note of it.
mTransferedPackages.add(origPackage.name);
// No longer need to retain this.
pkgSetting.origPackage = null;
}
if (realName != null) {
// Make a note of it.
mTransferedPackages.add(pkg.packageName);
}
if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
}
if (mFoundPolicyFile) {
SELinuxMMAC.assignSeinfoValue(pkg);
}
pkg.applicationInfo.uid = pkgSetting.appId;
pkg.mExtras = pkgSetting;
if (!verifySignaturesLP(pkgSetting, pkg)) {
if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
return null;
}
// The signature has changed, but this package is in the system
// image... let's recover!
pkgSetting.signatures.mSignatures = pkg.mSignatures;
// However... if this package is part of a shared user, but it
// doesn't match the signature of the shared user, let's fail.
// What this means is that you can't change the signatures
// associated with an overall shared user, which doesn't seem all
// that unreasonable.
if (pkgSetting.sharedUser != null) {
if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
return null;
}
}
// File a report about this.
String msg = "System package " + pkg.packageName
+ " signature changed; retaining data.";
reportSettingsProblem(Log.WARN, msg);
}
// Verify that this new package doesn't have any content providers
// that conflict with existing packages. Only do this if the
// package isn't already installed, since we don't want to break
// things that are installed.
if ((scanMode&SCAN_NEW_INSTALL) != 0) {
final int N = pkg.providers.size();
int i;
for (i=0; i<N; i++) {
PackageParser.Provider p = pkg.providers.get(i);
if (p.info.authority != null) {
String names[] = p.info.authority.split(";");
for (int j = 0; j < names.length; j++) {
if (mProviders.containsKey(names[j])) {
PackageParser.Provider other = mProviders.get(names[j]);
Slog.w(TAG, "Can't install because provider name " + names[j] +
" (in package " + pkg.applicationInfo.packageName +
") is already used by "
+ ((other != null && other.getComponentName() != null)
? other.getComponentName().getPackageName() : "?"));
mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
return null;
}
}
}
}
}
if (pkg.mAdoptPermissions != null) {
// This package wants to adopt ownership of permissions from
// another package.
for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
final String origName = pkg.mAdoptPermissions.get(i);
final PackageSetting orig = mSettings.peekPackageLPr(origName);
if (orig != null) {
if (verifyPackageUpdateLPr(orig, pkg)) {
Slog.i(TAG, "Adopting permissions from " + origName + " to "
+ pkg.packageName);
mSettings.transferPermissionsLPw(origName, pkg.packageName);
}
}
}
}
}
final String pkgName = pkg.packageName;
final long scanFileTime = scanFile.lastModified();
final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
pkg.applicationInfo.processName = fixProcessName(
pkg.applicationInfo.packageName,
pkg.applicationInfo.processName,
pkg.applicationInfo.uid);
File dataPath;
if (mPlatformPackage == pkg) {
// The system package is special.
dataPath = new File (Environment.getDataDirectory(), "system");
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
// This is a normal package, need to make its data directory.
dataPath = getDataPathForPackage(pkg.packageName, 0);
boolean uidError = false;
if (dataPath.exists()) {
int currentUid = 0;
try {
StructStat stat = Libcore.os.stat(dataPath.getPath());
currentUid = stat.st_uid;
} catch (ErrnoException e) {
Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
}
// If we have mismatched owners for the data path, we have a problem.
if (currentUid != pkg.applicationInfo.uid) {
boolean recovered = false;
if (currentUid == 0) {
// The directory somehow became owned by root. Wow.
// This is probably because the system was stopped while
// installd was in the middle of messing with its libs
// directory. Ask installd to fix that.
int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.uid);
if (ret >= 0) {
recovered = true;
String msg = "Package " + pkg.packageName
+ " unexpectedly changed to uid 0; recovered to " +
+ pkg.applicationInfo.uid;
reportSettingsProblem(Log.WARN, msg);
}
}
if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
|| (scanMode&SCAN_BOOTING) != 0)) {
// If this is a system app, we can at least delete its
// current data so the application will still work.
int ret = removeDataDirsLI(pkgName);
if (ret >= 0) {
// TODO: Kill the processes first
// Old data gone!
String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
? "System package " : "Third party package ";
String msg = prefix + pkg.packageName
+ " has changed from uid: "
+ currentUid + " to "
+ pkg.applicationInfo.uid + "; old data erased";
reportSettingsProblem(Log.WARN, msg);
recovered = true;
// And now re-install the app.
ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.seinfo);
if (ret == -1) {
// Ack should not happen!
msg = prefix + pkg.packageName
+ " could not have data directory re-created after delete.";
reportSettingsProblem(Log.WARN, msg);
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
}
if (!recovered) {
mHasSystemUidErrors = true;
}
} else if (!recovered) {
// If we allow this install to proceed, we will be broken.
// Abort, abort!
mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
return null;
}
if (!recovered) {
pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
+ pkg.applicationInfo.uid + "/fs_"
+ currentUid;
pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
String msg = "Package " + pkg.packageName
+ " has mismatched uid: "
+ currentUid + " on disk, "
+ pkg.applicationInfo.uid + " in settings";
// writer
synchronized (mPackages) {
mSettings.mReadMessages.append(msg);
mSettings.mReadMessages.append('\n');
uidError = true;
if (!pkgSetting.uidError) {
reportSettingsProblem(Log.ERROR, msg);
}
}
}
}
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.v(TAG, "Want this data dir: " + dataPath);
}
//invoke installer to do the actual installation
int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
pkg.applicationInfo.seinfo);
if (ret < 0) {
// Error from installer
mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
return null;
}
if (dataPath.exists()) {
pkg.applicationInfo.dataDir = dataPath.getPath();
} else {
Slog.w(TAG, "Unable to create data directory: " + dataPath);
pkg.applicationInfo.dataDir = null;
}
}
/*
* Set the data dir to the default "/data/data/<package name>/lib"
* if we got here without anyone telling us different (e.g., apps
* stored on SD card have their native libraries stored in the ASEC
* container with the APK).
*
* This happens during an upgrade from a package settings file that
* doesn't have a native library path attribute at all.
*/
if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
if (pkgSetting.nativeLibraryPathString == null) {
setInternalAppNativeLibraryPath(pkg, pkgSetting);
} else {
pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
}
}
pkgSetting.uidError = uidError;
}
String path = scanFile.getPath();
/* Note: We don't want to unpack the native binaries for
* system applications, unless they have been updated
* (the binaries are already under /system/lib).
* Also, don't unpack libs for apps on the external card
* since they should have their libraries in the ASEC
* container already.
*
* In other words, we're going to unpack the binaries
* only for non-system apps and system app upgrades.
*/
if (pkg.applicationInfo.nativeLibraryDir != null) {
try {
File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
final String dataPathString = dataPath.getCanonicalPath();
if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
/*
* Upgrading from a previous version of the OS sometimes
* leaves native libraries in the /data/data/<app>/lib
* directory for system apps even when they shouldn't be.
* Recent changes in the JNI library search path
* necessitates we remove those to match previous behavior.
*/
if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Log.i(TAG, "removed obsolete native libraries for system package "
+ path);
}
} else {
if (!isForwardLocked(pkg) && !isExternal(pkg)) {
/*
* Update native library dir if it starts with
* /data/data
*/
// For devices using /datadata, dataPathString will point
// to /datadata while nativeLibraryDir will point to /data/data.
// Thus, compare to /data/data directly to avoid problems.
if (nativeLibraryDir.getPath().startsWith("/data/data")) {
setInternalAppNativeLibraryPath(pkg, pkgSetting);
nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
}
try {
if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) {
Slog.e(TAG, "Unable to copy native libraries");
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
} catch (IOException e) {
Slog.e(TAG, "Unable to copy native libraries", e);
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
}
if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
final int[] userIds = sUserManager.getUserIds();
synchronized (mInstallLock) {
for (int userId : userIds) {
if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
Slog.w(TAG, "Failed linking native library dir (user=" + userId
+ ")");
mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
return null;
}
}
}
}
} catch (IOException ioe) {
Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
}
}
pkg.mScanPath = path;
if ((scanMode&SCAN_NO_DEX) == 0) {
if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
== DEX_OPT_FAILED) {
mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
return null;
}
}
if (mFactoryTest && pkg.requestedPermissions.contains(
android.Manifest.permission.FACTORY_TEST)) {
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
}
ArrayList<PackageParser.Package> clientLibPkgs = null;
// writer
synchronized (mPackages) {
if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
// Only system apps can add new shared libraries.
if (pkg.libraryNames != null) {
for (int i=0; i<pkg.libraryNames.size(); i++) {
String name = pkg.libraryNames.get(i);
boolean allowed = false;
if (isUpdatedSystemApp(pkg)) {
// New library entries can only be added through the
// system image. This is important to get rid of a lot
// of nasty edge cases: for example if we allowed a non-
// system update of the app to add a library, then uninstalling
// the update would make the library go away, and assumptions
// we made such as through app install filtering would now
// have allowed apps on the device which aren't compatible
// with it. Better to just have the restriction here, be
// conservative, and create many fewer cases that can negatively
// impact the user experience.
final PackageSetting sysPs = mSettings
.getDisabledSystemPkgLPr(pkg.packageName);
if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
if (name.equals(sysPs.pkg.libraryNames.get(j))) {
allowed = true;
allowed = true;
break;
}
}
}
} else {
allowed = true;
}
if (allowed) {
if (!mSharedLibraries.containsKey(name)) {
mSharedLibraries.put(name, new SharedLibraryEntry(null,
pkg.packageName));
} else if (!name.equals(pkg.packageName)) {
Slog.w(TAG, "Package " + pkg.packageName + " library "
+ name + " already exists; skipping");
}
} else {
Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
+ name + " that is not declared on system image; skipping");
}
}
if ((scanMode&SCAN_BOOTING) == 0) {
// If we are not booting, we need to update any applications
// that are clients of our shared library. If we are booting,
// this will all be done once the scan is complete.
clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
}
}
}
}
// We also need to dexopt any apps that are dependent on this library. Note that
// if these fail, we should abort the install since installing the library will
// result in some apps being broken.
if (clientLibPkgs != null) {
if ((scanMode&SCAN_NO_DEX) == 0) {
for (int i=0; i<clientLibPkgs.size(); i++) {
PackageParser.Package clientPkg = clientLibPkgs.get(i);
if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
== DEX_OPT_FAILED) {
mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
return null;
}
}
}
}
// Request the ActivityManager to kill the process(only for existing packages)
// so that we do not end up in a confused state while the user is still using the older
// version of the application while the new one gets installed.
if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
killApplication(pkg.applicationInfo.packageName,
pkg.applicationInfo.uid);
}
// Also need to kill any apps that are dependent on the library.
if (clientLibPkgs != null) {
for (int i=0; i<clientLibPkgs.size(); i++) {
PackageParser.Package clientPkg = clientLibPkgs.get(i);
killApplication(clientPkg.applicationInfo.packageName,
clientPkg.applicationInfo.uid);
}
}
// writer
synchronized (mPackages) {
// We don't expect installation to fail beyond this point,
if ((scanMode&SCAN_MONITOR) != 0) {
mAppDirs.put(pkg.mPath, pkg);
}
// Add the new setting to mSettings
mSettings.insertPackageSettingLPw(pkgSetting, pkg);
// Add the new setting to mPackages
mPackages.put(pkg.applicationInfo.packageName, pkg);
// Make sure we don't accidentally delete its data.
final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
while (iter.hasNext()) {
PackageCleanItem item = iter.next();
if (pkgName.equals(item.packageName)) {
iter.remove();
}
}
// Take care of first install / last update times.
if (currentTime != 0) {
if (pkgSetting.firstInstallTime == 0) {
pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
} else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
pkgSetting.lastUpdateTime = currentTime;
}
} else if (pkgSetting.firstInstallTime == 0) {
// We need *something*. Take time time stamp of the file.
pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
} else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
if (scanFileTime != pkgSetting.timeStamp) {
// A package on the system image has changed; consider this
// to be an update.
pkgSetting.lastUpdateTime = scanFileTime;
}
}
int N = pkg.providers.size();
StringBuilder r = null;
int i;
for (i=0; i<N; i++) {
PackageParser.Provider p = pkg.providers.get(i);
p.info.processName = fixProcessName(pkg.applicationInfo.processName,
p.info.processName, pkg.applicationInfo.uid);
mProvidersByComponent.put(new ComponentName(p.info.packageName,
p.info.name), p);
p.syncable = p.info.isSyncable;
if (p.info.authority != null) {
String names[] = p.info.authority.split(";");
p.info.authority = null;
for (int j = 0; j < names.length; j++) {
if (j == 1 && p.syncable) {
// We only want the first authority for a provider to possibly be
// syncable, so if we already added this provider using a different
// authority clear the syncable flag. We copy the provider before
// changing it because the mProviders object contains a reference
// to a provider that we don't want to change.
// Only do this for the second authority since the resulting provider
// object can be the same for all future authorities for this provider.
p = new PackageParser.Provider(p);
p.syncable = false;
}
if (!mProviders.containsKey(names[j])) {
mProviders.put(names[j], p);
if (p.info.authority == null) {
p.info.authority = names[j];
} else {
p.info.authority = p.info.authority + ";" + names[j];
}
if (DEBUG_PACKAGE_SCANNING) {
if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
Log.d(TAG, "Registered content provider: " + names[j]
+ ", className = " + p.info.name + ", isSyncable = "
+ p.info.isSyncable);
}
} else {
PackageParser.Provider other = mProviders.get(names[j]);
Slog.w(TAG, "Skipping provider name " + names[j] +
" (in package " + pkg.applicationInfo.packageName +
"): name already used by "
+ ((other != null && other.getComponentName() != null)
? other.getComponentName().getPackageName() : "?"));
}
}
}
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(p.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
}
N = pkg.services.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Service s = pkg.services.get(i);
s.info.processName = fixProcessName(pkg.applicationInfo.processName,
s.info.processName, pkg.applicationInfo.uid);
mServices.addService(s);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(s.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
}
N = pkg.receivers.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Activity a = pkg.receivers.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName, pkg.applicationInfo.uid);
mReceivers.addActivity(a, "receiver");
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
}
N = pkg.activities.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Activity a = pkg.activities.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName, pkg.applicationInfo.uid);
mActivities.addActivity(a, "activity");
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
}
N = pkg.permissionGroups.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
if (cur == null) {
mPermissionGroups.put(pg.info.name, pg);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(pg.info.name);
}
} else {
Slog.w(TAG, "Permission group " + pg.info.name + " from package "
+ pg.info.packageName + " ignored: original from "
+ cur.info.packageName);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append("DUP:");
r.append(pg.info.name);
}
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
}
N = pkg.permissions.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Permission p = pkg.permissions.get(i);
HashMap<String, BasePermission> permissionMap =
p.tree ? mSettings.mPermissionTrees
: mSettings.mPermissions;
p.group = mPermissionGroups.get(p.info.group);
if (p.info.group == null || p.group != null) {
BasePermission bp = permissionMap.get(p.info.name);
if (bp == null) {
bp = new BasePermission(p.info.name, p.info.packageName,
BasePermission.TYPE_NORMAL);
permissionMap.put(p.info.name, bp);
}
if (bp.perm == null) {
if (bp.sourcePackage == null
|| bp.sourcePackage.equals(p.info.packageName)) {
BasePermission tree = findPermissionTreeLP(p.info.name);
if (tree == null
|| tree.sourcePackage.equals(p.info.packageName)) {
bp.packageSetting = pkgSetting;
bp.perm = p;
bp.uid = pkg.applicationInfo.uid;
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(p.info.name);
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: base tree "
+ tree.name + " is from package "
+ tree.sourcePackage);
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: original from "
+ bp.sourcePackage);
}
} else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append("DUP:");
r.append(p.info.name);
}
if (bp.perm == p) {
bp.protectionLevel = p.info.protectionLevel;
}
} else {
Slog.w(TAG, "Permission " + p.info.name + " from package "
+ p.info.packageName + " ignored: no group "
+ p.group);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
}
N = pkg.instrumentation.size();
r = null;
for (i=0; i<N; i++) {
PackageParser.Instrumentation a = pkg.instrumentation.get(i);
a.info.packageName = pkg.applicationInfo.packageName;
a.info.sourceDir = pkg.applicationInfo.sourceDir;
a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
a.info.dataDir = pkg.applicationInfo.dataDir;
a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
mInstrumentation.put(a.getComponentName(), a);
if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (r != null) {
if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
}
if (pkg.protectedBroadcasts != null) {
N = pkg.protectedBroadcasts.size();
for (i=0; i<N; i++) {
mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
}
}
pkgSetting.setTimeStamp(scanFileTime);
}
return pkg;
}
|
diff --git a/filters/net.sf.okapi.filters.openxml/src/net/sf/okapi/filters/openxml/OpenXMLContentFilter.java b/filters/net.sf.okapi.filters.openxml/src/net/sf/okapi/filters/openxml/OpenXMLContentFilter.java
index 7dfb99319..0d4241cc7 100644
--- a/filters/net.sf.okapi.filters.openxml/src/net/sf/okapi/filters/openxml/OpenXMLContentFilter.java
+++ b/filters/net.sf.okapi.filters.openxml/src/net/sf/okapi/filters/openxml/OpenXMLContentFilter.java
@@ -1,1888 +1,1892 @@
/*===========================================================================
Copyright (C) 2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.filters.openxml;
//import org.apache.log4j.BasicConfigurator;
//import org.apache.log4j.Level;
//import org.apache.log4j.Logger;
import java.io.*;
import java.net.URL;
import java.util.Hashtable;
//import java.util.Iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
//import java.util.TreeMap; // DWH 10-10-08
import java.util.logging.Level;
import java.util.logging.Logger;
import net.htmlparser.jericho.EndTag;
//import net.htmlparser.jericho.EndTagType;
import net.htmlparser.jericho.Segment;
//import net.htmlparser.jericho.StartTagType;
import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.CharacterReference;
import net.htmlparser.jericho.StartTag;
import net.htmlparser.jericho.Tag;
//import net.sf.okapi.common.encoder.IEncoder;
import net.sf.okapi.common.exceptions.OkapiIOException;
import net.sf.okapi.common.Event;
import net.sf.okapi.common.EventType;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.IResource;
import net.sf.okapi.common.filters.FilterConfiguration;
import net.sf.okapi.common.filters.PropertyTextUnitPlaceholder;
import net.sf.okapi.common.filters.PropertyTextUnitPlaceholder.PlaceholderType;
import net.sf.okapi.filters.abstractmarkup.AbstractMarkupFilter;
import net.sf.okapi.filters.yaml.TaggedFilterConfiguration;
import net.sf.okapi.filters.yaml.TaggedFilterConfiguration.RULE_TYPE;
import net.sf.okapi.common.resource.Code;
import net.sf.okapi.common.resource.DocumentPart;
import net.sf.okapi.common.resource.Property;
import net.sf.okapi.common.resource.RawDocument;
import net.sf.okapi.common.resource.TextFragment;
import net.sf.okapi.common.resource.TextUnit;
import net.sf.okapi.common.resource.TextFragment.TagType;
import net.sf.okapi.common.skeleton.GenericSkeleton;
import net.sf.okapi.common.skeleton.GenericSkeletonPart;
/**
* <p>Filters Microsoft Office Word, Excel, and Powerpoint Documents.
* OpenXML is the format of these documents.
*
* <p>Since OpenXML files are Zip files that contain XML documents,
* <b>OpenXMLFilter</b> handles opening and processing the zip file, and
* instantiates this filter to process the XML documents.
*
* <p>This filter extends AbstractBaseMarkupFilter, which extends
* AbstractBaseFilter. It uses the Jericho parser to analyze the
* XML files.
*
* <p>The filter exhibits slightly differnt behavior depending on whether
* the XML file is Word, Excel, Powerpoint, or a chart in Word. The
* tags in these files are configured in yaml configuration files that
* specify the behavior of the tags. These configuration files are
* <p><li>wordConfiguration.yml
* <li>excelConfiguration.yml
* <li>powerpointConfiguration.yml
* <li>wordChartConfiguration.yml
*
* In Word and Powerpoint, text is always surrounded by paragraph tags
* <w:p> or <a:p>, which signal the beginning and end of the text unit
* for this filter, and are marked as TEXT_UNIT_ELEMENTs in the configuration
* files. Inside these are one or more text runs surrounded by <w:r> or <a:r>
* tags and marked as TEXT_RUN_ELEMENTS by the configuration files. The text
* itself occurs between text marker tags <w:t> or <a:t> tags, which are
* designated TEXT_MARKER_ELEMENTS by the configuration files. Tags between
* and including <w:r> and <w:t> (which usually include a <w:rPr> tag sequence
* for character style) are consolidated into a single MARKER_OPENING code. Tags
* between and including </w:t> and </w:r>, which sometimes include graphics
* tags, are consolidated into a single MARKER_CLOSING code. If there is no
* text between <w:r> and </w:r>, a single MARKER_PLACEHOLDER code is created
* for the text run. If there is no character style information,
* <w:r><w:t>text</w:t></w:r> is not surrounded by MARKER_OPENING or
* MARKER_CLOSING codes, to simplify things for translators; these are supplied
* by OpenXMLContentSkeletonWriter during output. The same is true for text
* runs marked by <a:r> and <a:t> in Powerpoint files.
*
* Excel files are simpler, and only mark text by <v>, <t>, and <text> tags
* in worksheet, sharedString, and comment files respectively. These tags
* work like TEXT_UNIT, TEXT_RUN, and TEXT_MARKER elements combined.
*/
public class OpenXMLContentFilter extends AbstractMarkupFilter {
private Logger LOGGER=null;
public final static int MSWORD=1;
public final static int MSEXCEL=2;
public final static int MSPOWERPOINT=3;
public final static int MSWORDCHART=4; // DWH 4-16-09
public final static int MSEXCELCOMMENT=5; // DWH 5-13-09
public final static int MSWORDDOCPROPERTIES=6; // DWH 5-25-09
private int configurationType;
// private Package p=null;
private int filetype=MSWORD; // DWH 4-13-09
private String sConfigFileName; // DWH 10-15-08
private URL urlConfig; // DWH 3-9-09
private Hashtable<String,String> htXMLFileType=null;
private String sInsideTextBox = ""; // DWH 7-23-09 textbox
private boolean bInTextBox = false; // DWH 7-23-09 textbox
private boolean bInTextRun = false; // DWH 4-10-09
private boolean bInSubTextRun = false; // DWH 4-10-09
private boolean bInDeletion = false; // DWH 5-8-09 <w:del> deletion in tracking mode in Word
private boolean bInInsertion = false; // DWH 5-8-09 <w:ins> insertion in tracking mode in Word
private boolean bBetweenTextMarkers=false; // DWH 4-14-09
private boolean bAfterText = false; // DWH 4-10-09
private TextRun trTextRun = null; // DWH 4-10-09
private TextRun trNonTextRun = null; // DWH 5-5-09
private boolean bIgnoredPreRun = false; // DWH 4-10-09
private boolean bBeforeFirstTextRun = true; // DWH 4-15-09
private boolean bInMainFile = false; // DWH 4-15-09
private boolean bExcludeTextInRun = false; // DWH 5-27-09
private boolean bExcludeTextInUnit = false; // DWH 5-29-09
private String sCurrentCharacterStyle = ""; // DWH 5-27-09
private String sCurrentParagraphStyle = ""; // DWH 5-27-09
private boolean bPreferenceTranslateWordHidden = false; // DWH 6-29-09
private boolean bPreferenceTranslateExcelExcludeColors = false;
// DWH 6-12-09 don't translate text in Excel in some colors
private boolean bPreferenceTranslateExcelExcludeColumns = false;
// DWH 6-12-09 don't translate text in Excel in some specified columns
private TreeSet<String> tsExcludeWordStyles = null; // DWH 5-27-09 set of styles to exclude from translation
private TreeSet<String> tsExcelExcludedStyles; // DWH 6-12-09
private TreeSet<String> tsExcelExcludedColumns; // DWH 6-12-09
private TreeMap<Integer,ExcelSharedString> tmSharedStrings=null; // DWH 6-13-09
private boolean bInExcelSharedStringCell=false; // DWH 6-13-09
private boolean bExcludeTranslatingThisExcelCell=false; // DWH 6-13-09
private int nOriginalSharedStringCount=0; // DWH 6-13-09
private int nNextSharedStringCount=0; // DWH 6-13-09
private int nCurrentSharedString=-1; // DWH 6-13-09 if nonzero, text may be excluded from translation
private String sCurrentExcelSheet=""; // DWH 6-25-09 current sheet number
private YamlParameters params=null; // DWH 7-16-09
private TaggedFilterConfiguration config=null; // DWH 7-16-09
private RawDocument rdSource; // Textbox
public OpenXMLContentFilter() {
super(); // 1-6-09
setMimeType("text/xml");
setFilterWriter(createFilterWriter());
tsExcludeWordStyles = new TreeSet<String>();
}
public List<FilterConfiguration> getConfigurations () {
List<FilterConfiguration> list = new ArrayList<FilterConfiguration>();
list.add(new FilterConfiguration(getName(),
"text/xml",
getClass().getName(),
"Microsoft OpenXML Document",
"Microsoft OpenXML files (Used inside Office documents)."));
return list;
}
/**
* Logs information about the event fir the log level is FINEST.
* @param event event to log information about
*/
public void displayOneEvent(Event event) // DWH 4-22-09 LOGGER
{
Set<String> setter;
if (LOGGER.isLoggable(Level.FINEST))
{
String etyp=event.getEventType().toString();
if (event.getEventType() == EventType.TEXT_UNIT) {
// assertTrue(event.getResource() instanceof TextUnit);
} else if (event.getEventType() == EventType.DOCUMENT_PART) {
// assertTrue(event.getResource() instanceof DocumentPart);
} else if (event.getEventType() == EventType.START_GROUP
|| event.getEventType() == EventType.END_GROUP) {
// assertTrue(event.getResource() instanceof StartGroup || event.getResource() instanceof Ending);
}
if (etyp.equals("START"))
LOGGER.log(Level.FINEST,"\n");
LOGGER.log(Level.FINEST,etyp + ": ");
if (event.getResource() != null) {
LOGGER.log(Level.FINEST,"(" + event.getResource().getId()+")");
if (event.getResource() instanceof DocumentPart) {
setter = ((DocumentPart) event.getResource()).getSourcePropertyNames();
for(String seti : setter)
LOGGER.log(Level.FINEST,seti);
} else {
LOGGER.log(Level.FINEST,event.getResource().toString());
}
if (event.getResource().getSkeleton() != null) {
LOGGER.log(Level.FINEST,"*Skeleton: \n" + event.getResource().getSkeleton().toString());
}
}
}
}
/**
* Sets the name of the Yaml configuration file for the current file type, reads the file, and sets the parameters.
* @param filetype type of XML in the current file
*/
public void setUpConfig(int filetype)
{
this.filetype = filetype; // DWH 5-13-09
switch(filetype)
{
case MSWORDCHART:
sConfigFileName = "/net/sf/okapi/filters/openxml/wordChartConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSWORDCHART;
break;
case MSEXCEL:
sConfigFileName = "/net/sf/okapi/filters/openxml/excelConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSEXCEL;
break;
case MSPOWERPOINT:
sConfigFileName = "/net/sf/okapi/filters/openxml/powerpointConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSPOWERPOINT;
break;
case MSEXCELCOMMENT: // DWH 5-13-09
sConfigFileName = "/net/sf/okapi/filters/openxml/excelCommentConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSEXCEL;
break;
case MSWORDDOCPROPERTIES: // DWH 5-13-09
sConfigFileName = "/net/sf/okapi/filters/openxml/wordDocPropertiesConfiguration.yml"; // DWH 5-25-09
configurationType = MSWORDDOCPROPERTIES;
break;
case MSWORD:
default:
sConfigFileName = "/net/sf/okapi/filters/openxml/wordConfiguration.yml"; // DWH 1-5-09 groovy -> yml
configurationType = MSWORD;
break;
}
urlConfig = OpenXMLContentFilter.class.getResource(sConfigFileName); // DWH 3-9-09
config = new TaggedFilterConfiguration(urlConfig);
// setDefaultConfig(urlConfig); // DWH 7-16-09 no longer needed; AbstractMarkup now calls getConfig everywhere
try
{
setParameters(new YamlParameters(urlConfig));
// DWH 3-9-09 it doesn't update automatically from setDefaultConfig 7-16-09 YamlParameters
}
catch(Exception e)
{
LOGGER.log(Level.SEVERE,"Can't read MS Office Filter Configuration File.");
throw new OkapiIOException("Can't read MS Office Filter Configuration File.");
}
}
/**
* Combines contiguous compatible text runs, in order to simplify the inline tags presented
* to a user. Note that MSWord can have embedded <w:r> elements for ruby text. Note
* that Piped streams are used which use a separate thread for this processing.
* @param in input stream of the XML file
* @param in piped output stream for the "squished" output
* @return a PipedInputStream used for further processing of the file
*/
public InputStream combineRepeatedFormat(final InputStream in, final PipedOutputStream pios)
{
+ final OutputStreamWriter osw;
+ final BufferedWriter bw;
+ final InputStreamReader isr;
+ final BufferedReader br;
PipedInputStream piis=null;
// final PipedOutputStream pios = new PipedOutputStream();
try
{
piis = new PipedInputStream(pios);
+ osw = new OutputStreamWriter(pios,"UTF-8");
+ bw = new BufferedWriter(osw);
+ isr = new InputStreamReader(in,"UTF-8");
+ br = new BufferedReader(isr);
}
catch (IOException e)
{
LOGGER.log(Level.SEVERE,"Can't read piped input stream.");
throw new OkapiIOException("Can't read piped input stream.");
}
- final OutputStreamWriter osw = new OutputStreamWriter(pios);
- final BufferedWriter bw = new BufferedWriter(osw);
- final InputStreamReader isr = new InputStreamReader(in);
- final BufferedReader br = new BufferedReader(isr);
Thread readThread = new Thread(new Runnable()
{
char cbuf[] = new char[512];
String curtag="",curtext="",curtagname="",onp="",offp="";
String r1b4text="",r1aftext="",t1="";
String r2b4text="",r2aftext="",t2="";
int i,n;
boolean bIntag=false,bGotname=false,bInap=false,bHavr1=false;
boolean bInsideTextMarkers=false,bInr=false,bB4text=true,bInInnerR=false;
boolean bInsideNastyTextBox=false; // DWH 7-16-09
public void run()
{
try
{
while((n=br.read(cbuf,0,512))!=-1)
{
for(i=0;i<n;i++)
{
handleOneChar(cbuf[i]);
}
}
if (curtext.length()>0)
havtext(curtext);
}
catch(IOException e)
{
LOGGER.log(Level.SEVERE,"Can't read input pipe.");
throw new OkapiIOException("Can't read input pipe.");
}
try {
br.close();
isr.close();
bw.flush();
bw.close();
// osw.flush();
osw.close();
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Can't read piped input.");
throw new OkapiIOException("Can't read piped input.");
}
}
private void handleOneChar(char c)
{
if (c=='>')
{
curtag = curtag + ">";
havatag(curtag,curtagname);
curtag = "";
curtagname = "";
bIntag = false;
}
else if (c=='<')
{
if (!bIntag)
{
if (curtext.length()>0)
{
havtext(curtext);
curtext = "";
}
curtag = curtag + "<";
bIntag = true;
bGotname = false;
}
else
{
curtag = curtag + "<";
}
}
else
{
if (bIntag)
{
curtag = curtag + c;
if (!bGotname)
if (c==' ')
bGotname = true;
else
curtagname = curtagname + c;
}
else
curtext = curtext + c;
}
}
private void havatag(String snug,String tugname) // DWH 5-16-09 snug was tug
{
String tug=snug; // DWH 5-16-09
String b4text; // DWH 5-20-09
boolean bCollapsing=false; // DWH 5-22-09
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes but still remove rsids
{
if (tugname.equals("/v:textbox")) // DWH 7-16-09 ignore textboxes
bInsideNastyTextBox = false;
else
tug = killRevisionIDsAndErrs(snug);
innanar(tug);
}
else if (tugname.equals("v:textbox")) // DWH 7-16-09 ignore textboxes
{
bInsideNastyTextBox = true;
innanar(tug);
}
else if (tugname.equals("w:p") || tugname.equals("a:p"))
{
tug = killRevisionIDsAndErrs(snug);
onp = tug;
if (tug.equals("<w:p/>"))
{
bInap = false; // DWH 5-30-09
offp += tug; // DWH 5-30-09
streamTheCurrentStuff();
}
else
{
bInap = true;
bInr = false;
bInInnerR = false; // DWH 3-9-09
bHavr1 = false;
bB4text = false;
}
}
else if (tugname.equals("/w:p") || tugname.equals("/a:p"))
{
offp = tug;
bInap = false;
streamTheCurrentStuff();
}
else if (tugname.equals("w:t") || tugname.equals("a:t")) // DWH 5-18-09
{
bInsideTextMarkers = true;
innanar(tug);
}
else if (tugname.equals("/w:t") || tugname.equals("/a:t")) // DWH 5-18-09
{
bInsideTextMarkers = false;
innanar(tug);
}
else if (bInap)
{
if (tugname.equals("w:r") ||
tugname.equals("a:r") || tugname.equals("a:fld")) // DWH 5-27-09 a:fld
{
tug = killRevisionIDsAndErrs(snug);
if (bInr)
{
bInInnerR = true; // DWH 3-2-09 ruby text has embedded <w:r> codes
innanar(tug);
}
else
{
if (bHavr1)
r2b4text = tug;
else
r1b4text = tug;
bInr = true;
bB4text = true;
}
}
else if (tugname.equals("/w:r") ||
tugname.equals("/a:r") || tugname.equals("/a:fld")) // DWH 5-27-09 a:fld
{
if (bInInnerR)
{
bInInnerR = false; // DWH 3-2-09
innanar(tug);
}
else
{
bInr = false;
if (bHavr1)
{
r2aftext = r2aftext + tug;
// if (r1b4text.equals(r2b4text) && r1aftext.equals(r2aftext))
if (r1aftext.equals(r2aftext))
{
bCollapsing = false;
b4text = r1b4text;
if (r1b4text.equals(r2b4text))
bCollapsing = true;
else
{
int ndx = r1b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r2b4text.equals(
r1b4text.substring(0,ndx)+":t"+r1b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r1b4text; // choose one with preserve
}
}
ndx = r2b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r1b4text.equals(
r2b4text.substring(0,ndx)+":t"+r2b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r2b4text; // choose one with preserve
}
}
}
if (bCollapsing)
{
r1b4text = b4text; // DWH 5-22-09
t1 = t1 + t2;
r2b4text = "";
r2aftext = "";
t2 = "";
}
else
streamTheCurrentStuff(); // DWH 5-22-09
}
else
streamTheCurrentStuff();
// tug is added by "r1aftext=r1aftext+tug" below or "r2aftext=r2aftext+tug" above
}
else
{
r1aftext = r1aftext + tug;
bHavr1 = true;
}
}
}
else if (bInr)
innanar(tug);
else
{
streamTheCurrentStuff();
onp = tug; // this puts out <w:p> and any previous unoutput <w:r> blocks,
// then puts current tag in onp to be output next
}
}
else if (tugname.equalsIgnoreCase("w:sectPr") ||
tugname.equalsIgnoreCase("a:sectPr"))
{
tug = killRevisionIDsAndErrs(tug);
rat(tug);
}
else
rat(tug);
}
private void innanar(String tug)
{
if (bHavr1)
{
if (bB4text)
r2b4text = r2b4text + tug;
else
r2aftext = r2aftext + tug;
}
else
{
if (bB4text)
r1b4text = r1b4text + tug;
else
r1aftext = r1aftext + tug;
}
}
private String killRevisionIDsAndErrs(String tug) // DWH 5-16-09
{
String tigger;
if (configurationType==MSWORD)
tigger = killRevisionIDs(tug);
else // this will be MSPOWERPOINT
tigger=killErrs(tug);
return tigger;
}
private String killRevisionIDs(String tug) // DWH 5-16-09 remove rsid attributes
{
String snug=tug;
String shrug="";
String slug;
int ndx;
while ((ndx=snug.indexOf(" w:rsid"))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the rsid up to first space
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
break;
}
}
shrug += snug; // add whatever is left
return shrug;
}
private String killErrs(String tug) // DWH 5-16-09 remove err= attribute
{
String snug=tug;
String shrug="";
String slug;
int ndx;
if ((ndx=snug.indexOf(" err="))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the err=
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
}
}
shrug += snug;
return shrug; // add whatever is left
}
private void havtext(String curtext)
{
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes and the text inside them
innanar(curtext);
else if (bInap)
{
if (bInInnerR || !bInsideTextMarkers)
{
// DWH 3-2-09 (just the condition) ruby text has embedded <w:r> codes
// DWH 5-18-09 has to be inside text markers to be counted as text
if (bInr) // DWH 5-21-09
innanar(curtext);
else
{
streamTheCurrentStuff(); // DWH 5-21-09 if not in a text run
streamTheCurrentStuff(); // DWH 5-21-09 put out previous text runs
onp = curtext; // DWH 5-21-09 treat this as new material in p
}
}
else
{
bB4text = false;
if (bHavr1)
{
t2 = curtext;
}
else
t1 = curtext;
}
}
else
rat(curtext);
}
private void streamTheCurrentStuff()
{
if (bInap)
{
rat(onp+r1b4text+t1+r1aftext);
onp = "";
r1b4text = r2b4text;
t1 = t2;
r1aftext = r2aftext;
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
}
else
{
rat(onp+r1b4text+t1+r1aftext+r2b4text+t2+r2aftext+offp);
onp = "";
r1b4text = "";
t1 = "";
r1aftext = "";
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
bHavr1 = false;
}
}
private void rat(String s) // the Texan form of "write"
{
try
{
bw.write(s);
LOGGER.log(Level.FINEST,s); //
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Problem writing piped stream.");
// throw new OkapiIOException("Can't read piped input.");
s = s + " ";
}
}
});
readThread.start();
return piis;
}
/**
* Adds CDATA as a DocumentPart
* @param a tag containing the CDATA
*/
protected void handleCdataSection(Tag tag) { // 1-5-09
if (bInDeletion) // DWH 5-8-09
addToNonTextRun(tag.toString());
else
addToDocumentPart(tag.toString());
}
/**
* Handles text. If in a text run, it ends the text run and
* adds the tags that were in it as a single MARKER_OPENING code.
* This would correspond to <w:r>...<w:t> in MSWord. It will
* then start a new text run anticipating </w:t>...</w:r>. If
* text is found that was not in a text run, i.e. it was not between
* text markers, it is not text to be processed by a user, so it
* becomes part of a new text run which will become part of a
* code. If the text is not in a text unit, then it is added to a
* document part.
* @param text the text to be handled
*/
@Override
protected void handleText(Segment text) {
if (text==null) // DWH 4-14-09
return;
String txt=text.toString();
handleSomeText(txt,text.isWhiteSpace()); // DWH 5-14-09
}
private void handleSomeText(String tixt, boolean bWhiteSpace) // DWH 6-25-09 tixt was txt
{
String txt=tixt; // DWH 6-25-09 added this so txt can be changed for Excel index to shared strings
if (bInDeletion) // DWH 5-8-09
{
addToNonTextRun(txt);
return;
}
// if in excluded state everything is skeleton including text
if (getRuleState().isExludedState()) {
addToDocumentPart(txt);
return;
}
if (bInTextBox)
{
sInsideTextBox += txt;
return;
}
// check for need to modify index in Excel cell pointing to a shared string
if (bInExcelSharedStringCell)
// DWH 6-13-09 Excel options; true if in sheet cell pointing to a shared string
// only possible if (bPreferenceTranslateExcelExcludeColors || bPreferenceTranslateExcelExcludeColumns)
// and this cell is marked as containing a shared string
{
int nSharedStringNumber=-1;
try
{
nSharedStringNumber = new Integer(txt).intValue();
}
catch(Exception e) {};
if (nSharedStringNumber>=0 && nSharedStringNumber<nNextSharedStringCount)
{
ExcelSharedString ess = tmSharedStrings.get(nSharedStringNumber);
if (!ess.getBEncountered()) // first time this string seen in sheets
{
ess.setBEncountered(true);
ess.setBTranslatable(!bExcludeTranslatingThisExcelCell);
}
else if (ess.getBTranslatable() != !bExcludeTranslatingThisExcelCell)
// this shared string should be translated in some columns but not others
{
int oppnum = ess.getNIndex();
if (oppnum > -1) // this already has a shared string elsewhere
txt = (new Integer(oppnum)).toString();
else
{
ExcelSharedString newess = // create twin with opposite translatable status
new ExcelSharedString(true,!bExcludeTranslatingThisExcelCell,nSharedStringNumber,"");
tmSharedStrings.put(new Integer(nNextSharedStringCount),newess); // add twin to list
txt = (new Integer(nNextSharedStringCount)).toString(); // DWH 6-25-09 !!! replace index to shared string with new one pointing to a copy
ess.setNIndex(nNextSharedStringCount++); // point current one to new twin
}
}
}
}
// check for ignorable whitespace and add it to the skeleton
// The Jericho html parser always pulls out the largest stretch of text
// so standalone whitespace should always be ignorable if we are not
// already processing inline text
// if (text.isWhiteSpace() && !isInsideTextRun()) {
if (bWhiteSpace && !isInsideTextRun()) {
addToDocumentPart(txt);
return;
}
if (canStartNewTextUnit())
{
// if (bBetweenTextMarkers)
// startTextUnit(txt);
// else
addToDocumentPart(txt);
}
else
{
if (bInTextRun) // DWH 4-20-09 whole if revised
{
if (bBetweenTextMarkers)
{
if (bExcludeTextInRun || bExcludeTextInUnit || // DWH 5-29-09 don't treat as text if excluding text
(filetype==MSEXCEL && txt!=null && txt.length()>0 && txt.charAt(0)=='='))
addToTextRun(txt); // DWH 5-13-09 don't treat Excel formula as text to be translated
else if (nCurrentSharedString>0 && nCurrentSharedString<nNextSharedStringCount)
// DWH 6-13-09 in Excel Shared Strings File, only if some shared strings excluded from translation
{
ExcelSharedString ess = tmSharedStrings.get(new Integer(nCurrentSharedString));
ess.setS(txt);
int oppEssNum = ess.getNIndex();
if (oppEssNum>-1 && oppEssNum<nNextSharedStringCount)
{
ExcelSharedString oppess = tmSharedStrings.get(new Integer(oppEssNum));
oppess.setS(txt);
}
if (ess.getBTranslatable()) // if this sharedString is translatable, add as text
{
addTextRunToCurrentTextUnit(false); // adds a code for the preceding text run
bAfterText = true;
addToTextUnit(txt); // adds the text
trTextRun = new TextRun(); // then starts a new text run for a code after the text
bInTextRun = true;
}
else
addToTextRun(txt); // if not translatable, add as part of code
}
else
{
addTextRunToCurrentTextUnit(false); // adds a code for the preceding text run
bAfterText = true;
addToTextUnit(txt); // adds the text
trTextRun = new TextRun(); // then starts a new text run for a code after the text
bInTextRun = true;
}
}
else
addToTextRun(txt); // for <w:delText>text</w:delText> don't translate deleted text (will be inside code)
}
else
{
trTextRun = new TextRun();
bInTextRun = true;
addToTextRun(txt); // not inside text markers, so this text will become part of a code
}
}
}
/**
* Handles a tag that is anticipated to be a DocumentPart. Since everything
* between TEXTUNIT markers is treated as an inline code, if there is a
* current TextUnit, this is added as a code in the text unit.
* @param tag a tag
*/
@Override
protected void handleDocumentPart(Tag tag) {
if (canStartNewTextUnit()) // DWH ifline and whole else: is an inline code if inside a text unit
addToDocumentPart(tag.toString()); // 1-5-09
else if (bInDeletion) // DWH 5-8-09
addToNonTextRun(tag.toString());
else
addCodeToCurrentTextUnit(tag);
}
/**
* Handle all numeric entities. Default implementation converts entity to
* Unicode character.
*
* @param entity
* - the numeric entity
*/
protected void handleCharacterEntity(Segment entity) { // DWH 5-14-09
String decodedText = CharacterReference.decode(entity.toString(), false);
/*
if (!isCurrentTextUnit()) {
startTextUnit();
}
addToTextUnit(decodedText);
*/ if (decodedText!=null && !decodedText.equals("")) // DWH 5-14-09 treat CharacterEntities like other text
handleSomeText(decodedText,false);
}
/**
* Handles a start tag. TEXT_UNIT_ELEMENTs start a new TextUnit. TEXT_RUN_ELEMENTs
* start a new text run. TEXT_MARKER_ELEMENTS set a flag that any following
* text will be between text markers. ATTRIBUTES_ONLY tags have translatable text
* in the attributes, so within a text unit, it is added within a text run; otherwise it
* becomes a DocumentPart.
* @param startTagt the start tag to process
*/
@Override
protected void handleStartTag(StartTag startTag) {
String sTagName;
String sTagString;
String sPartName; // DWH 2-26-09 for PartName attribute in [Content_Types].xml
String sContentType; // DWH 2-26-09 for ContentType attribute in [Content_Types].xml
// if in excluded state everything is skeleton including text
String tempTagType; // DWH 5-7-09
String sTagElementType; // DWH 6-13-09
if (startTag==null) // DWH 4-14-09
return;
if (bInDeletion)
{
addToNonTextRun(startTag);
return;
}
sTagName = startTag.getName(); // DWH 2-26-09
sTagString = startTag.toString(); // DWH 2-26-09
sTagElementType = getConfig().getElementType(sTagName); // DWH 6-13-09
if (bInTextBox) // DWH 7-23-09 textbox
{
sInsideTextBox += sTagString;
return;
}
if (getRuleState().isExludedState()) {
addToDocumentPart(sTagString);
// process these tag types to update parser state
switch (getConfig().getMainRuleType(sTagName)) {
// DWH 1-23-09
case EXCLUDED_ELEMENT:
getRuleState().pushExcludedRule(sTagName);
break;
case INCLUDED_ELEMENT:
getRuleState().pushIncludedRule(sTagName);
break;
case PRESERVE_WHITESPACE:
getRuleState().pushPreserverWhitespaceRule(sTagName);
break;
}
return;
}
switch (getConfig().getMainRuleType(sTagName)) {
// DWH 1-23-09
case INLINE_ELEMENT:
if (canStartNewTextUnit()) {
if (sTagElementType.equals("style")) // DWH 6-13-09
// DWH 5-27-09 to exclude hidden styles
sCurrentCharacterStyle = startTag.getAttributeValue("w:styleId");
else if (sTagElementType.equals("hidden")) // DWH 6-13-09
// DWH 5-27-09 to exclude hidden styles
{
if (!sCurrentCharacterStyle.equals(""))
excludeStyle(sCurrentCharacterStyle);
}
else if (sTagElementType.equals("excell")) // DWH 6-13-09 cell in Excel sheet
{
if (bPreferenceTranslateExcelExcludeColors || bPreferenceTranslateExcelExcludeColumns)
bExcludeTranslatingThisExcelCell = evaluateSharedString(startTag);
}
else if (sTagElementType.equals("sharedstring")) // DWH 6-13-09 shared string in Excel
nCurrentSharedString++;
else if (sTagElementType.equals("count")) // DWH 6-13-09 shared string count in Excel
{
sTagString = newSharedStringCount(sTagString);
}
addToDocumentPart(sTagString);
}
else
{
if (sTagElementType.equals("rstyle")) // DWH 6-13-09 text run style
// DWH 5-29-09 in a text unit, some styles shouldn't be translated
{
sCurrentCharacterStyle = startTag.getAttributeValue("w:val");
// if (tsExcludeWordStyles.contains(sCurrentCharacterStyle))
if (containsAString(tsExcludeWordStyles,sCurrentCharacterStyle))
bExcludeTextInRun = true;
}
else if (sTagElementType.equals("pstyle")) // DWH 6-13-09 text unit style
// DWH 5-29-09 in a text unit, some styles shouldn't be translated
{
sCurrentParagraphStyle = startTag.getAttributeValue("w:val");
// if (tsExcludeWordStyles.contains(sCurrentParagraphStyle))
if (containsAString(tsExcludeWordStyles,sCurrentParagraphStyle))
bExcludeTextInUnit = true;
}
else if (sTagElementType.equals("hidden") &&
!bPreferenceTranslateWordHidden)
// DWH 6-13-09 to exclude hidden styles
{
if (bInTextRun)
bExcludeTextInRun = true;
else
bExcludeTextInUnit = true;
}
if (bInTextRun) // DWH 4-9-09
addToTextRun(startTag);
else // DWH 5-7-09
{
if (sTagElementType.equals("delete")) // DWH 6-13-09
bInDeletion = true;
addToNonTextRun(startTag); // DWH 5-5-09
}
}
break;
case ATTRIBUTES_ONLY:
// we assume we have already ended any (non-complex) TextUnit in
// the main while loop above
List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders;
if (canStartNewTextUnit()) // DWH 2-14-09 document part just created is part of inline codes
{
propertyTextUnitPlaceholders = createPropertyTextUnitPlaceholders(startTag); // 1-29-09
if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) { // 1-29-09
startDocumentPart(sTagString, sTagName, propertyTextUnitPlaceholders);
// DWH 1-29-09
endDocumentPart();
} else {
// no attributes that need processing - just treat as skeleton
addToDocumentPart(sTagString);
}
}
else
{
propertyTextUnitPlaceholders = createPropertyTextUnitPlaceholders(startTag); // 1-29-09
if (bInTextRun) // DWH 4-10-09
addToTextRun(startTag,propertyTextUnitPlaceholders);
else
addToNonTextRun(startTag,propertyTextUnitPlaceholders);
}
break;
case GROUP_ELEMENT:
if (!canStartNewTextUnit()) // DWH 6-29-09 for text box: embedded text unit
{
bInTextBox = true; // DWH 7-23-09 textbox
sInsideTextBox = ""; // DWH 7-23-09 textbox
addTextRunToCurrentTextUnit(true); // DWH 7-29-09 add text run stuff as a placeholder
}
getRuleState().pushGroupRule(sTagName);
startGroup(new GenericSkeleton(sTagString),"textbox");
break;
case EXCLUDED_ELEMENT:
getRuleState().pushExcludedRule(sTagName);
addToDocumentPart(sTagString);
break;
case INCLUDED_ELEMENT:
getRuleState().pushIncludedRule(sTagName);
addToDocumentPart(sTagString);
break;
case TEXT_UNIT_ELEMENT:
bExcludeTextInUnit = false; // DWH 5-29-09 only exclude text if specific circumstances occur
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09 trNonTextRun should be null at this point
bBeforeFirstTextRun = true; // DWH 5-5-09 addNonTextRunToCurrentTextUnit sets it false
// if (startTag.isSyntacticalEmptyElementTag()) // means the tag ended with />
if (sTagString.endsWith("/>")) // DWH 3-18-09 in case text unit element is a standalone tag (weird, but Microsoft does it)
addToDocumentPart(sTagString); // 1-5-09
else
{
getRuleState().pushTextUnitRule(sTagName);
startTextUnit(new GenericSkeleton(sTagString)); // DWH 1-29-09
if (configurationType==MSEXCEL ||
configurationType==MSWORDCHART ||
configurationType==MSWORDDOCPROPERTIES)
// DWH 4-16-09 Excel and Word Charts don't have text runs or text markers
{
bInTextRun = true;
bBetweenTextMarkers = true;
}
else
{
bInTextRun = false;
bBetweenTextMarkers = false;
}
}
break;
case TEXT_RUN_ELEMENT: // DWH 4-10-09 smoosh text runs into single <x>text</x>
bExcludeTextInRun = false; // DWH 5-29-09 only exclude text if specific circumstances occur
if (canStartNewTextUnit()) // DWH 5-5-09 shouldn't happen
addToDocumentPart(sTagString);
else
{
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
bBeforeFirstTextRun = false; // DWH 5-5-09
if (getConfig().getElementType(sTagName).equals("insert")) // DWH 5-8-09 w:ins
bInInsertion = true;
else if (bInTextRun)
bInSubTextRun = true;
else
{
bInTextRun = true;
bAfterText = false;
bIgnoredPreRun = false;
bBetweenTextMarkers = false; // DWH 4-16-09
}
addToTextRun(startTag);
}
break;
case TEXT_MARKER_ELEMENT: // DWH 4-14-09 whole case
if (canStartNewTextUnit()) // DWH 5-5-09 shouldn't happen
addToDocumentPart(sTagString);
else
{
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
if (bInTextRun)
{
bBetweenTextMarkers = true;
addToTextRun(startTag);
}
else
addToNonTextRun(sTagString);
}
break;
case PRESERVE_WHITESPACE:
getRuleState().pushPreserverWhitespaceRule(sTagName);
addToDocumentPart(sTagString);
break;
default:
if (sTagName.equals("override")) // DWH 2-26-09 in [Content_Types].xml
{ // it could be slow to do this test every time; I wonder if there is a better way
sPartName = startTag.getAttributeValue("PartName");
sContentType = startTag.getAttributeValue("ContentType");
if (htXMLFileType!=null)
htXMLFileType.put(sPartName, sContentType);
}
if (canStartNewTextUnit()) // DWH 1-14-09 then not currently in text unit; added else
addToDocumentPart(sTagString); // 1-5-09
else if (bInTextRun) // DWH 4-10-09
addToTextRun(startTag);
else
addToNonTextRun(startTag); // DWH 5-5-09
}
}
/**
* Handles end tags. These either add to current text runs
* or end text runs or text units as appropriate.
* @param endTag the end tag to process
*/
@Override
protected void handleEndTag(EndTag endTag) {
// if in excluded state everything is skeleton including text
String sTagName; // DWH 2-26-09
String sTagString; // DWH 4-14-09
String tempTagType; // DWH 5-5-09
String sTagElementType; // DWH 6-13-09
String s; // temporary string
DocumentPart dippy; // DWH 7-28-09 textbox
GenericSkeleton skel; // DWH 7-28-09 textbox
TextUnit tu; // DWH 7-28-09 textbox
int dpid; // DWH 7-28-09 textbox
WordTextBox wtb = null; // DWH 7-23-09 textbox
ArrayList<Event> textBoxEventList=null; // DWH 7-23-09 textbox
Event event; // DWH 7-23-09 textbox
OpenXMLContentFilter tboxcf; // DWH 7-23-09
if (endTag==null) // DWH 4-14-09
return;
sTagName = endTag.getName(); // DWH 2-26-09
sTagElementType = getConfig().getElementType(sTagName); // DWH 6-13-09
if (bInDeletion)
{
addToNonTextRun(endTag);
if (sTagElementType.equals("delete")) // DWH 6-13-09
{
bInDeletion = false;
}
return;
}
sTagString = endTag.toString(); // DWH 2-26-09
if (getRuleState().isExludedState()) {
addToDocumentPart(sTagString); // DWH 7-16-09
// process these tag types to update parser state
switch (getConfig().getMainRuleType(sTagName)) {
// DWH 1-23-09
case EXCLUDED_ELEMENT:
getRuleState().popExcludedIncludedRule();
break;
case INCLUDED_ELEMENT:
getRuleState().popExcludedIncludedRule();
break;
case PRESERVE_WHITESPACE:
getRuleState().popPreserverWhitespaceRule();
break;
}
return;
}
if (bInTextBox && getConfig().getMainRuleType(sTagName)!=RULE_TYPE.GROUP_ELEMENT)
{
sInsideTextBox += sTagString;
return;
}
switch (getConfig().getMainRuleType(sTagName)) {
// DWH 1-23-09
case INLINE_ELEMENT:
if (canStartNewTextUnit())
{
addToDocumentPart(sTagString); // DWH 5-29-09
if (sTagElementType.equals("sharedstring")) // DWH 6-13-09 shared string in Excel
{
if (nCurrentSharedString==nOriginalSharedStringCount-1) // this is the last original shared string
{
bExcludeTextInUnit = false; // DWH 5-29-09 only exclude text if specific circumstances occur
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09 trNonTextRun should be null at this point
bBeforeFirstTextRun = true; // DWH 5-5-09 addNonTextRunToCurrentTextUnit sets it false
bInTextRun = false;
bBetweenTextMarkers = false;
for(int i=nCurrentSharedString+1;i<nNextSharedStringCount;i++)
{
ExcelSharedString ess = tmSharedStrings.get(new Integer(i));
String txt = ess.getS();
if (ess.getBTranslatable())
{
startTextUnit(new GenericSkeleton("<si><t>"));
addToTextUnit(txt);
endTextUnit(new GenericSkeleton("</t></si>"));
}
else
addToDocumentPart("<si><t>"+txt+"</t></si>");
}
nCurrentSharedString = -1; // reset so other text will translate; see handleText
}
}
}
else if (bInTextRun) // DWH 5-29-09
addToTextRun(endTag);
else if (sTagElementType.equals("delete")) // DWH 5-7-09 6-13-09
{
if (trNonTextRun!=null)
addNonTextRunToCurrentTextUnit();
addToTextUnitCode(TextFragment.TagType.CLOSING, sTagString, "delete"); // DWH 5-7-09 adds as opening d
}
else if (sTagElementType.equals("excell")) // DWH 6-13-09 cell in Excel sheet
{
bInExcelSharedStringCell = false;
addToDocumentPart(sTagString);
}
else
addToNonTextRun(endTag); // DWH 5-5-09
break;
case GROUP_ELEMENT:
if (sInsideTextBox.length()>0)
{
wtb = new WordTextBox();
tboxcf = wtb.getTextBoxOpenXMLContentFilter();
wtb.open(sInsideTextBox, getSrcLang());
tboxcf.setUpConfig(MSWORD);
tboxcf.setTextUnitId(getTextUnitId()); // set min textUnitId so no overlap
tboxcf.setDocumentPartId(getDocumentPartId()); // set min documentPartId so no overlap
textBoxEventList = wtb.doEvents();
for(Iterator<Event> it=textBoxEventList.iterator() ; it.hasNext();)
{
event = it.next();
addFilterEvent(event); // add events from WordTextBox before EndGroup event
}
setTextUnitId(tboxcf.getTextUnitId());
// set current TextUnitId to next one not used inside textbox
setDocumentPartId(tboxcf.getDocumentPartId());
// set current DocumentPartId to next one not used inside textbox
// Note: if this class ever uses startGroupId, endGroupId, subDocumentId or documentId
// they will need to be set as textUnitId and documentPartId above and here
}
bInTextBox = false;
sInsideTextBox = "";
getRuleState().popGroupRule();
endGroup(new GenericSkeleton(sTagString));
break;
case EXCLUDED_ELEMENT:
getRuleState().popExcludedIncludedRule();
addToDocumentPart(sTagString);
break;
case INCLUDED_ELEMENT:
getRuleState().popExcludedIncludedRule();
addToDocumentPart(sTagString);
break;
case TEXT_UNIT_ELEMENT:
bExcludeTextInUnit = false; // DWH 5-29-09 only exclude text if specific circumstances occur
if (bInTextRun)
{
addTextRunToCurrentTextUnit(true);
bInTextRun = false;
} // otherwise this is an illegal element, so just ignore it
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
bBetweenTextMarkers = true; // DWH 4-16-09 ???
getRuleState().popTextUnitRule();
endTextUnit(new GenericSkeleton(sTagString));
break;
case TEXT_RUN_ELEMENT: // DWH 4-10-09 smoosh text runs into single <x>text</x>
bExcludeTextInRun = false; // DWH 5-29-09 only exclude text if specific circumstances occur
if (canStartNewTextUnit()) // DWH 5-5-09
addToDocumentPart(sTagString);
else
{
addToTextRun(endTag);
if (sTagElementType.equals("insert")) // DWH 6-13-09 end of insertion </w:ins>
{
bInInsertion = false;
addTextRunToCurrentTextUnit(true);
bInTextRun = false;
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
}
else if (bInSubTextRun)
bInSubTextRun = false;
else if (bInTextRun)
{
if (!bInInsertion) // DWH 5-5-09 if inserting, don't end TextRun till end of insertion
{
addTextRunToCurrentTextUnit(true);
addNonTextRunToCurrentTextUnit(); // DWH 5-5-09
}
bInTextRun = false;
} // otherwise this is an illegal element, so just ignore it
}
break;
case TEXT_MARKER_ELEMENT: // DWH 4-14-09 whole case
if (canStartNewTextUnit()) // DWH 5-5-09
addToDocumentPart(sTagString);
else if (bInTextRun) // DWH 5-5-09 lacked else
{
bBetweenTextMarkers = false;
addToTextRun(endTag);
}
else
addToNonTextRun(sTagString); // DWH 5-5-09
break;
case PRESERVE_WHITESPACE:
getRuleState().popPreserverWhitespaceRule();
addToDocumentPart(sTagString);
break;
default:
if (canStartNewTextUnit()) // DWH 1-14-09 then not currently in text unit; added else
addToDocumentPart(sTagString); // not in text unit, so add to skeleton
else if (bInTextRun) // DWH 4-9-09
addToTextRun(endTag);
else
addToNonTextRun(endTag); // DWH 5-5-09
break;
}
}
/**
* Treats XML comments as DocumentParts.
* @param tag comment tag
*/
@Override
protected void handleComment(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML doc type declaratons as DocumentParts.
* @param tag doc type declaration tag
*/
@Override
protected void handleDocTypeDeclaration(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML markup declaratons as DocumentParts.
* @param tag markup declaration tag
*/
@Override
protected void handleMarkupDeclaration(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML processing instructions as DocumentParts.
* @param tag processing instruction tag
*/
@Override
protected void handleProcessingInstruction(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML server common tags as DocumentParts.
* @param tag server common tag
*/
@Override
protected void handleServerCommon(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats server common escaped tags as DocumentParts.
* @param tag server common escaped tag
*/
@Override
protected void handleServerCommonEscaped(Tag tag) {
handleDocumentPart(tag);
}
/**
* Treats XML declaratons as DocumentParts.
* @param tag XML declaration tag
*/
@Override
protected void handleXmlDeclaration(Tag tag) {
handleDocumentPart(tag);
}
/**
* Returns name of the filter.
* @return name of the filter
*/
public String getName() {
return "OpenXMLContentFilter";
}
/**
* Normalizes naming of attributes whose values are the
* encoding or a language name, so that they can be
* automatically changed to the output encoding and output.
* Unfortunately, this hard codes the tags to look for.
* @param attrName name of the attribute
* @param attrValue, value of the attribute
* @param tag tag that contains the attribute
* @return a normalized name for the attribute
*/
@Override
protected String normalizeAttributeName(String attrName, String attrValue, Tag tag) {
// normalize values for HTML
String normalizedName = attrName;
String tagName; // DWH 2-19-09 */
// Any attribute that encodes language should be renamed here to "language"
// Any attribute that encodes locale or charset should be normalized too
/*
// <meta http-equiv="Content-Type"
// content="text/html; charset=ISO-2022-JP">
if (isMetaCharset(attrName, attrValue, tag)) {
normalizedName = HtmlEncoder.NORMALIZED_ENCODING;
return normalizedName;
}
// <meta http-equiv="Content-Language" content="en"
if (tag.getName().equals("meta") && attrName.equals(HtmlEncoder.CONTENT)) {
StartTag st = (StartTag) tag;
if (st.getAttributeValue("http-equiv") != null) {
if (st.getAttributeValue("http-equiv").equals("Content-Language")) {
normalizedName = HtmlEncoder.NORMALIZED_LANGUAGE;
return normalizedName;
}
}
}
*/
// <w:lang w:val="en-US" ...>
tagName = tag.getName();
if (tagName.equals("w:lang") || tagName.equals("w:themefontlang")) // DWH 4-3-09 themeFontLang
{
StartTag st = (StartTag) tag;
if (st.getAttributeValue("w:val") != null)
{
normalizedName = Property.LANGUAGE;
return normalizedName;
}
}
else if (tagName.equals("c:lang")) // DWH 4-3-09
{
StartTag st = (StartTag) tag;
if (st.getAttributeValue("val") != null)
{
normalizedName = Property.LANGUAGE;
return normalizedName;
}
}
else if (tagName.equals("a:endpararpr") || tagName.equals("a:rpr"))
{
StartTag st = (StartTag) tag;
if (st.getAttributeValue("lang") != null)
{
normalizedName = Property.LANGUAGE;
return normalizedName;
}
}
return normalizedName;
}
protected void initFileTypes() // DWH $$$ needed?
{
htXMLFileType = new Hashtable();
}
protected String getContentType(String sPartName) // DWH $$$ needed?
{
String rslt="",tmp;
if (sPartName!=null)
{
tmp = (String)htXMLFileType.get(sPartName);
if (tmp!=null)
rslt = tmp;
}
return(rslt);
}
/**
* Adds a text string to a sequence of tags that are
* not in a text run, that will become a single code.
* @param s the text string to add
*/
private void addToNonTextRun(String s) // DWH 5-5-09
{
if (trNonTextRun==null)
trNonTextRun = new TextRun();
trNonTextRun.append(s);
}
/**
* Adds a tag to a sequence of tags that are
* not in a text run, that will become a single code.
* @param s the text string to add
*/
private void addToNonTextRun(Tag tag) // DWH 5-5-09
{
if (trNonTextRun==null)
trNonTextRun = new TextRun();
trNonTextRun.append(tag.toString());
}
/**
* Adds a tag and codes to a sequence of tags that are
* not in a text run, that will become a single code.
* @param tag the tag to add
* @param propertyTextUnitPlaceholders a list of codes of embedded text
*/
private void addToNonTextRun(Tag tag, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders)
{
String txt;
int offset;
if (trNonTextRun==null)
trNonTextRun = new TextRun();
txt=trNonTextRun.getText();
offset=txt.length();
trNonTextRun.appendWithPropertyTextUnitPlaceholders(tag.toString(),offset,propertyTextUnitPlaceholders);
}
/**
* Adds a text string to a text run that will become a single code.
* @param s the text string to add
*/
private void addToTextRun(String s)
{
if (trTextRun==null)
trTextRun = new TextRun();
trTextRun.append(s);
}
/**
* Adds a tag to a text run that will become a single code.
* @param tag the tag to add
*/
private void addToTextRun(Tag tag) // DWH 4-10-09 adds tag text to string that will be part of larger code later
{
// add something here to check if it was bold, italics, etc. to set a property
if (trTextRun==null)
trTextRun = new TextRun();
trTextRun.append(tag.toString());
}
/**
* Adds a tag and codes to a text run that will become a single code.
* @param tag the tag to add
* @param propertyTextUnitPlaceholders a list of codes of embedded text
*/
private void addToTextRun(Tag tag, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders)
{
String txt;
int offset;
if (trTextRun==null)
trTextRun = new TextRun();
txt=trTextRun.getText();
offset=txt.length();
trTextRun.appendWithPropertyTextUnitPlaceholders(tag.toString(),offset,propertyTextUnitPlaceholders);
}
/**
* Adds the text and codes in a text run as a single code in a text unit.
* If it is after text, it is added as a MARKER_CLOSING. If no text
* was encountered and this is being called by an ending TEXT_RUN_ELEMENT
* or ending TEXT_UNIT_ELEMENT, it is added as a MARKER_PLACEHOLDER.
* Otherwise, it is added as a MARKER_OPENING.
* compatible contiguous text runs if desired, and creates a
* START_SUBDOCUMENT event
* @param bEndRun true if called while processing an end TEXT_RUN_ELEMENT
* or end TEXT_UNIT_ELEMENT
*/
private void addTextRunToCurrentTextUnit(boolean bEndRun) {
List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders;
TextFragment.TagType codeType;
String text,tempTagType;
int len;
if (trTextRun!=null && !(text=trTextRun.getText()).equals("")) // DWH 5-14-09 "" can occur with Character entities
{
if (bAfterText)
codeType = TextFragment.TagType.CLOSING;
else if (bEndRun) // if no text was encountered and this is the </w:r> or </w:p>, this is a standalone code
codeType = TextFragment.TagType.PLACEHOLDER;
else
codeType = TextFragment.TagType.OPENING;
// text = trTextRun.getText();
if (codeType==TextFragment.TagType.OPENING &&
!bBeforeFirstTextRun && // DWH 4-15-09 only do this if there wasn't stuff before <w:r>
bInMainFile && // DWH 4-15-08 only do this in MSWORD document and MSPOWERPOINT slides
((text.equals("<w:r><w:t>") || text.equals("<w:r><w:t xml:space=\"preserve\">")) ||
(text.equals("<a:r><a:t>") || text.equals("<a:r><a:t xml:space=\"preserve\">"))))
{
bIgnoredPreRun = true; // don't put codes around text that has no attributes
trTextRun = null;
return;
}
else if (codeType==TextFragment.TagType.CLOSING && bIgnoredPreRun)
{
bIgnoredPreRun = false;
if (text.endsWith("</w:t></w:r>") || text.endsWith("</a:t></a:r>"))
{
len = text.length();
if (len>12) // take off the end codes and leave the rest as a placeholder code, if any
{
text = text.substring(0,len-12);
codeType = TextFragment.TagType.CLOSING;
}
else
{
trTextRun = null;
return;
}
}
}
propertyTextUnitPlaceholders = trTextRun.getPropertyTextUnitPlaceholders();
if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) {
// add code and process actionable attributes
addToTextUnitCode(codeType, text, "x", propertyTextUnitPlaceholders);
} else {
// no actionable attributes, just add the code as-is
addToTextUnitCode(codeType, text, "x");
}
trTextRun = null;
bBeforeFirstTextRun = false; // since the text run has now been added to the text unit
}
}
private void addNonTextRunToCurrentTextUnit() { // DWW 5-5-09
List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders;
TextFragment.TagType codeType;
String text,tempTagType;
if (trNonTextRun!=null)
{
text = trNonTextRun.getText();
if (canStartNewTextUnit()) // DWH shouldn't happen
{
addToDocumentPart(text);
}
propertyTextUnitPlaceholders = trNonTextRun.getPropertyTextUnitPlaceholders();
if (bBeforeFirstTextRun &&
(propertyTextUnitPlaceholders==null || propertyTextUnitPlaceholders.size()==0))
// if a nonTextRun occurs before the first text run, and it doesn't have any
// embedded text, just add the tags to the skeleton after <w:r> or <a:r>.
// Since skeleton is not a TextFragment, it can't have embedded text, so if
// there is embedded text, do the else and make a PLACEHOLDER code
{
appendToFirstSkeletonPart(text);
}
else
{
codeType = TextFragment.TagType.PLACEHOLDER;
if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) {
// add code and process actionable attributes
addToTextUnitCode(codeType, text, "x", propertyTextUnitPlaceholders);
} else {
// no actionable attributes, just add the code as-is
addToTextUnitCode(codeType, text, "x");
}
}
trNonTextRun = null;
}
}
public void excludeStyle(String sTyle) // DWH 5-27-09 to exclude selected styles or hidden text
{
if (sTyle!=null && !sTyle.equals(""))
tsExcludeWordStyles.add(sTyle);
}
private boolean evaluateSharedString(Tag tag) // DWH 6-13-09 Excel options
{
boolean bExcludeCell=false;
String sCell;
String sStyle;
for (Attribute attribute : tag.parseAttributes())
{
if (attribute.getName().equals("r"))
{
sCell = attribute.getValue();
Excell eggshell = new Excell(sCell);
if (bPreferenceTranslateExcelExcludeColumns &&
((tsExcelExcludedColumns.contains(sCurrentExcelSheet+eggshell.getColumn())) || // matches excluded sheet and column
((new Integer(sCurrentExcelSheet).intValue())>3 && tsExcelExcludedColumns.contains("3"+eggshell.getColumn()))))
// matches column on a sheet>3
bExcludeCell = true; // this cell has been specifically excluded
}
else if (attribute.getName().equals("s"))
{
sStyle = attribute.getValue();
if (bPreferenceTranslateExcelExcludeColors && tsExcelExcludedStyles.contains(sStyle))
bExcludeCell = true; // this style includes an excluded color
}
else if (attribute.getName().equals("t"))
{
bInExcelSharedStringCell = attribute.getValue().equals("s"); // global for handleText
// true if this string is in sharedStrings.xml
}
}
if (!bInExcelSharedStringCell)
bExcludeCell = false; // only exclude the cell if the string is in sharedStrings.xml
return bExcludeCell;
}
public int getConfigurationType()
{
return configurationType;
}
protected void setBInMainFile(boolean bInMainFile) // DWH 4-15-09
{
this.bInMainFile = bInMainFile;
}
protected boolean getBInMainFile() // DWH 4-15-09
{
return bInMainFile;
}
public void setLogger(Logger lgr)
{
LOGGER = lgr;
}
public void setTsExcludeWordStyles(TreeSet tsExcludeWordStyles)
{
this.tsExcludeWordStyles = tsExcludeWordStyles;
}
public TreeSet getTsExcludeWordStyles()
{
return tsExcludeWordStyles;
}
public void setBPreferenceTranslateWordHidden(boolean bPreferenceTranslateWordHidden)
{
this.bPreferenceTranslateWordHidden = bPreferenceTranslateWordHidden;
}
public boolean getBPreferenceTranslateWordHidden()
{
return bPreferenceTranslateWordHidden;
}
public void setBPreferenceTranslateExcelExcludeColors(boolean bPreferenceTranslateExcelExcludeColors) // DWH 6-13-09 Excel options
{
this.bPreferenceTranslateExcelExcludeColors = bPreferenceTranslateExcelExcludeColors;
}
public boolean getBPreferenceTranslateExcelExcludeColors() // DWH 6-13-09 Excel options
{
return bPreferenceTranslateExcelExcludeColors;
}
public void setBPreferenceTranslateExcelExcludeColumns(boolean bPreferenceTranslateExcelExcludeColumns) // DWH 6-13-09 Excel options
{
this.bPreferenceTranslateExcelExcludeColumns = bPreferenceTranslateExcelExcludeColumns;
}
public boolean getBPreferenceTranslateExcelExcludeColumns() // DWH 6-13-09 Excel options
{
return bPreferenceTranslateExcelExcludeColumns;
}
public void setSCurrentExcelSheet(String sCurrentExcelSheet) // DWH 6-13-09 Excel options
{
this.sCurrentExcelSheet = sCurrentExcelSheet;
}
public String getSCurrentExcelSheet() // DWH 6-13-09 Excel options
{
return sCurrentExcelSheet;
}
public void setTsExcelExcludedStyles(TreeSet<String> tsExcelExcludedStyles) // DWH 6-13-09 Excel options
{
this.tsExcelExcludedStyles = tsExcelExcludedStyles;
}
public TreeSet<String> getTsExcelExcludedStyles() // DWH 6-13-09 Excel options
{
return tsExcelExcludedStyles;
}
public void setTsExcelExcludedColumns(TreeSet<String> tsExcelExcludedColumns) // DWH 6-13-09 Excel options
{
this.tsExcelExcludedColumns = tsExcelExcludedColumns;
}
public TreeSet<String> gettsExcelExcludedColumns() // DWH 6-13-09 Excel options
{
return tsExcelExcludedColumns;
}
protected void initTmSharedStrings(int nExcelOriginalSharedStringCount) // DWH 6-13-09 Excel options
{
this.nOriginalSharedStringCount = nExcelOriginalSharedStringCount; // DWH 6-13-09
this.nNextSharedStringCount = nExcelOriginalSharedStringCount; // next count to modify
tmSharedStrings = new TreeMap<Integer,ExcelSharedString>();
for(int i=0;i<nExcelOriginalSharedStringCount;i++)
tmSharedStrings.put(new Integer(i), new ExcelSharedString(false,true,-1,""));
// DWH 6-25-09 leave nIndex -1 unless a copy of a shared string is needed
nCurrentSharedString = -1;
}
private String newSharedStringCount(String sTagString)
// DWH 6-13-09 replaces count of sharedStrings in sst element in sharedStrings.xml in Excel
// if some shared Strings are to be translated in some contexts but not others
{
String sNewTagString=sTagString,sOrigNum;
int nDx,nDx2;
nDx = sTagString.indexOf("uniqueCount");
if (nDx==-1)
nDx = sTagString.indexOf("count=");
if (nDx>-1)
{
nDx2 = sTagString.substring(nDx+7).indexOf('"');
if (nDx2>nDx)
{
sOrigNum = sTagString.substring(nDx+7,nDx2);
if (sOrigNum.equals(new Integer(nOriginalSharedStringCount).toString()))
sNewTagString = sTagString.substring(0,nDx+7) +
(new Integer(nNextSharedStringCount)).toString() +
sTagString.substring(nDx2); // replace old count with new one
}
}
return sNewTagString;
}
private boolean containsAString(TreeSet ts, String s)
{
boolean rslt = false;
String ss;
for(Iterator it=ts.iterator(); it.hasNext();)
{
ss = (String)it.next();
if (s.equals(ss))
{
rslt = true;
break;
}
}
return rslt;
}
@Override
protected TaggedFilterConfiguration getConfig() {
return config; // this may be bad if AbstractMarkup calls it too soon !!!!
}
public IParameters getParameters() { // DWH 7-16-09
// TODO Auto-generated method stub
return params;
}
public void setParameters(IParameters params) { // DWH 7-16-09
this.params = (YamlParameters)params;
}
private void addToTextUnitCode(TagType codeType, String data, String type)
{
addToTextUnit(new Code(codeType, type, data));
}
private void addToTextUnitCode(TagType codeType, String data, String type, List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders)
{
addToTextUnit(new Code(codeType, type, data), propertyTextUnitPlaceholders);
}
private String getCommonTagType(Tag tag)
{
return getConfig().getElementType(tag); // DWH
}
/*
Textbox code
private void handleTextBox(List<PropertyTextUnitPlaceholder> propertyTextUnitPlaceholders,
StartTag tag)
{
if (propertyTextUnitPlaceholders != null && !propertyTextUnitPlaceholders.isEmpty()) {
startDocumentPart(tag.toString(), tag.getName(), propertyTextUnitPlaceholders);
endDocumentPart()
} else {
// no attributes that needs processing - just treat as skeleton
addToDocumentPart(tag.toString());
}
if (propOrText.getType() == PlaceholderType.TRANSLATABLE) {
TextUnit tu = embeddedTextUnit(propOrText, tag);
currentSkeleton.addReference(tu);
referencableFilterEvents.add(new Event(EventType.TEXT_UNIT, tu));
}
private TextUnit embeddedTextUnit(PropertyTextUnitPlaceholder propOrText, String tag) {
TextUnit tu = new TextUnit(createId(TEXT_UNIT, ++textUnitId), propOrText.getValue());
tu.setPreserveWhitespaces(isPreserveWhitespace());
tu.setMimeType(propOrText.getMimeType());
tu.setIsReferent(true);
GenericSkeleton skel = new GenericSkeleton();
skel.add(tag.substring(propOrText.getMainStartPos(), propOrText.getValueStartPos()));
skel.addContentPlaceholder(tu);
skel.add(tag.substring(propOrText.getValueEndPos(), propOrText.getMainEndPos()));
tu.setSkeleton(skel);
return tu;
}
*/
}
| false | true | public InputStream combineRepeatedFormat(final InputStream in, final PipedOutputStream pios)
{
PipedInputStream piis=null;
// final PipedOutputStream pios = new PipedOutputStream();
try
{
piis = new PipedInputStream(pios);
}
catch (IOException e)
{
LOGGER.log(Level.SEVERE,"Can't read piped input stream.");
throw new OkapiIOException("Can't read piped input stream.");
}
final OutputStreamWriter osw = new OutputStreamWriter(pios);
final BufferedWriter bw = new BufferedWriter(osw);
final InputStreamReader isr = new InputStreamReader(in);
final BufferedReader br = new BufferedReader(isr);
Thread readThread = new Thread(new Runnable()
{
char cbuf[] = new char[512];
String curtag="",curtext="",curtagname="",onp="",offp="";
String r1b4text="",r1aftext="",t1="";
String r2b4text="",r2aftext="",t2="";
int i,n;
boolean bIntag=false,bGotname=false,bInap=false,bHavr1=false;
boolean bInsideTextMarkers=false,bInr=false,bB4text=true,bInInnerR=false;
boolean bInsideNastyTextBox=false; // DWH 7-16-09
public void run()
{
try
{
while((n=br.read(cbuf,0,512))!=-1)
{
for(i=0;i<n;i++)
{
handleOneChar(cbuf[i]);
}
}
if (curtext.length()>0)
havtext(curtext);
}
catch(IOException e)
{
LOGGER.log(Level.SEVERE,"Can't read input pipe.");
throw new OkapiIOException("Can't read input pipe.");
}
try {
br.close();
isr.close();
bw.flush();
bw.close();
// osw.flush();
osw.close();
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Can't read piped input.");
throw new OkapiIOException("Can't read piped input.");
}
}
private void handleOneChar(char c)
{
if (c=='>')
{
curtag = curtag + ">";
havatag(curtag,curtagname);
curtag = "";
curtagname = "";
bIntag = false;
}
else if (c=='<')
{
if (!bIntag)
{
if (curtext.length()>0)
{
havtext(curtext);
curtext = "";
}
curtag = curtag + "<";
bIntag = true;
bGotname = false;
}
else
{
curtag = curtag + "<";
}
}
else
{
if (bIntag)
{
curtag = curtag + c;
if (!bGotname)
if (c==' ')
bGotname = true;
else
curtagname = curtagname + c;
}
else
curtext = curtext + c;
}
}
private void havatag(String snug,String tugname) // DWH 5-16-09 snug was tug
{
String tug=snug; // DWH 5-16-09
String b4text; // DWH 5-20-09
boolean bCollapsing=false; // DWH 5-22-09
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes but still remove rsids
{
if (tugname.equals("/v:textbox")) // DWH 7-16-09 ignore textboxes
bInsideNastyTextBox = false;
else
tug = killRevisionIDsAndErrs(snug);
innanar(tug);
}
else if (tugname.equals("v:textbox")) // DWH 7-16-09 ignore textboxes
{
bInsideNastyTextBox = true;
innanar(tug);
}
else if (tugname.equals("w:p") || tugname.equals("a:p"))
{
tug = killRevisionIDsAndErrs(snug);
onp = tug;
if (tug.equals("<w:p/>"))
{
bInap = false; // DWH 5-30-09
offp += tug; // DWH 5-30-09
streamTheCurrentStuff();
}
else
{
bInap = true;
bInr = false;
bInInnerR = false; // DWH 3-9-09
bHavr1 = false;
bB4text = false;
}
}
else if (tugname.equals("/w:p") || tugname.equals("/a:p"))
{
offp = tug;
bInap = false;
streamTheCurrentStuff();
}
else if (tugname.equals("w:t") || tugname.equals("a:t")) // DWH 5-18-09
{
bInsideTextMarkers = true;
innanar(tug);
}
else if (tugname.equals("/w:t") || tugname.equals("/a:t")) // DWH 5-18-09
{
bInsideTextMarkers = false;
innanar(tug);
}
else if (bInap)
{
if (tugname.equals("w:r") ||
tugname.equals("a:r") || tugname.equals("a:fld")) // DWH 5-27-09 a:fld
{
tug = killRevisionIDsAndErrs(snug);
if (bInr)
{
bInInnerR = true; // DWH 3-2-09 ruby text has embedded <w:r> codes
innanar(tug);
}
else
{
if (bHavr1)
r2b4text = tug;
else
r1b4text = tug;
bInr = true;
bB4text = true;
}
}
else if (tugname.equals("/w:r") ||
tugname.equals("/a:r") || tugname.equals("/a:fld")) // DWH 5-27-09 a:fld
{
if (bInInnerR)
{
bInInnerR = false; // DWH 3-2-09
innanar(tug);
}
else
{
bInr = false;
if (bHavr1)
{
r2aftext = r2aftext + tug;
// if (r1b4text.equals(r2b4text) && r1aftext.equals(r2aftext))
if (r1aftext.equals(r2aftext))
{
bCollapsing = false;
b4text = r1b4text;
if (r1b4text.equals(r2b4text))
bCollapsing = true;
else
{
int ndx = r1b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r2b4text.equals(
r1b4text.substring(0,ndx)+":t"+r1b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r1b4text; // choose one with preserve
}
}
ndx = r2b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r1b4text.equals(
r2b4text.substring(0,ndx)+":t"+r2b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r2b4text; // choose one with preserve
}
}
}
if (bCollapsing)
{
r1b4text = b4text; // DWH 5-22-09
t1 = t1 + t2;
r2b4text = "";
r2aftext = "";
t2 = "";
}
else
streamTheCurrentStuff(); // DWH 5-22-09
}
else
streamTheCurrentStuff();
// tug is added by "r1aftext=r1aftext+tug" below or "r2aftext=r2aftext+tug" above
}
else
{
r1aftext = r1aftext + tug;
bHavr1 = true;
}
}
}
else if (bInr)
innanar(tug);
else
{
streamTheCurrentStuff();
onp = tug; // this puts out <w:p> and any previous unoutput <w:r> blocks,
// then puts current tag in onp to be output next
}
}
else if (tugname.equalsIgnoreCase("w:sectPr") ||
tugname.equalsIgnoreCase("a:sectPr"))
{
tug = killRevisionIDsAndErrs(tug);
rat(tug);
}
else
rat(tug);
}
private void innanar(String tug)
{
if (bHavr1)
{
if (bB4text)
r2b4text = r2b4text + tug;
else
r2aftext = r2aftext + tug;
}
else
{
if (bB4text)
r1b4text = r1b4text + tug;
else
r1aftext = r1aftext + tug;
}
}
private String killRevisionIDsAndErrs(String tug) // DWH 5-16-09
{
String tigger;
if (configurationType==MSWORD)
tigger = killRevisionIDs(tug);
else // this will be MSPOWERPOINT
tigger=killErrs(tug);
return tigger;
}
private String killRevisionIDs(String tug) // DWH 5-16-09 remove rsid attributes
{
String snug=tug;
String shrug="";
String slug;
int ndx;
while ((ndx=snug.indexOf(" w:rsid"))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the rsid up to first space
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
break;
}
}
shrug += snug; // add whatever is left
return shrug;
}
private String killErrs(String tug) // DWH 5-16-09 remove err= attribute
{
String snug=tug;
String shrug="";
String slug;
int ndx;
if ((ndx=snug.indexOf(" err="))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the err=
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
}
}
shrug += snug;
return shrug; // add whatever is left
}
private void havtext(String curtext)
{
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes and the text inside them
innanar(curtext);
else if (bInap)
{
if (bInInnerR || !bInsideTextMarkers)
{
// DWH 3-2-09 (just the condition) ruby text has embedded <w:r> codes
// DWH 5-18-09 has to be inside text markers to be counted as text
if (bInr) // DWH 5-21-09
innanar(curtext);
else
{
streamTheCurrentStuff(); // DWH 5-21-09 if not in a text run
streamTheCurrentStuff(); // DWH 5-21-09 put out previous text runs
onp = curtext; // DWH 5-21-09 treat this as new material in p
}
}
else
{
bB4text = false;
if (bHavr1)
{
t2 = curtext;
}
else
t1 = curtext;
}
}
else
rat(curtext);
}
private void streamTheCurrentStuff()
{
if (bInap)
{
rat(onp+r1b4text+t1+r1aftext);
onp = "";
r1b4text = r2b4text;
t1 = t2;
r1aftext = r2aftext;
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
}
else
{
rat(onp+r1b4text+t1+r1aftext+r2b4text+t2+r2aftext+offp);
onp = "";
r1b4text = "";
t1 = "";
r1aftext = "";
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
bHavr1 = false;
}
}
private void rat(String s) // the Texan form of "write"
{
try
{
bw.write(s);
LOGGER.log(Level.FINEST,s); //
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Problem writing piped stream.");
// throw new OkapiIOException("Can't read piped input.");
s = s + " ";
}
}
});
readThread.start();
return piis;
}
| public InputStream combineRepeatedFormat(final InputStream in, final PipedOutputStream pios)
{
final OutputStreamWriter osw;
final BufferedWriter bw;
final InputStreamReader isr;
final BufferedReader br;
PipedInputStream piis=null;
// final PipedOutputStream pios = new PipedOutputStream();
try
{
piis = new PipedInputStream(pios);
osw = new OutputStreamWriter(pios,"UTF-8");
bw = new BufferedWriter(osw);
isr = new InputStreamReader(in,"UTF-8");
br = new BufferedReader(isr);
}
catch (IOException e)
{
LOGGER.log(Level.SEVERE,"Can't read piped input stream.");
throw new OkapiIOException("Can't read piped input stream.");
}
Thread readThread = new Thread(new Runnable()
{
char cbuf[] = new char[512];
String curtag="",curtext="",curtagname="",onp="",offp="";
String r1b4text="",r1aftext="",t1="";
String r2b4text="",r2aftext="",t2="";
int i,n;
boolean bIntag=false,bGotname=false,bInap=false,bHavr1=false;
boolean bInsideTextMarkers=false,bInr=false,bB4text=true,bInInnerR=false;
boolean bInsideNastyTextBox=false; // DWH 7-16-09
public void run()
{
try
{
while((n=br.read(cbuf,0,512))!=-1)
{
for(i=0;i<n;i++)
{
handleOneChar(cbuf[i]);
}
}
if (curtext.length()>0)
havtext(curtext);
}
catch(IOException e)
{
LOGGER.log(Level.SEVERE,"Can't read input pipe.");
throw new OkapiIOException("Can't read input pipe.");
}
try {
br.close();
isr.close();
bw.flush();
bw.close();
// osw.flush();
osw.close();
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Can't read piped input.");
throw new OkapiIOException("Can't read piped input.");
}
}
private void handleOneChar(char c)
{
if (c=='>')
{
curtag = curtag + ">";
havatag(curtag,curtagname);
curtag = "";
curtagname = "";
bIntag = false;
}
else if (c=='<')
{
if (!bIntag)
{
if (curtext.length()>0)
{
havtext(curtext);
curtext = "";
}
curtag = curtag + "<";
bIntag = true;
bGotname = false;
}
else
{
curtag = curtag + "<";
}
}
else
{
if (bIntag)
{
curtag = curtag + c;
if (!bGotname)
if (c==' ')
bGotname = true;
else
curtagname = curtagname + c;
}
else
curtext = curtext + c;
}
}
private void havatag(String snug,String tugname) // DWH 5-16-09 snug was tug
{
String tug=snug; // DWH 5-16-09
String b4text; // DWH 5-20-09
boolean bCollapsing=false; // DWH 5-22-09
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes but still remove rsids
{
if (tugname.equals("/v:textbox")) // DWH 7-16-09 ignore textboxes
bInsideNastyTextBox = false;
else
tug = killRevisionIDsAndErrs(snug);
innanar(tug);
}
else if (tugname.equals("v:textbox")) // DWH 7-16-09 ignore textboxes
{
bInsideNastyTextBox = true;
innanar(tug);
}
else if (tugname.equals("w:p") || tugname.equals("a:p"))
{
tug = killRevisionIDsAndErrs(snug);
onp = tug;
if (tug.equals("<w:p/>"))
{
bInap = false; // DWH 5-30-09
offp += tug; // DWH 5-30-09
streamTheCurrentStuff();
}
else
{
bInap = true;
bInr = false;
bInInnerR = false; // DWH 3-9-09
bHavr1 = false;
bB4text = false;
}
}
else if (tugname.equals("/w:p") || tugname.equals("/a:p"))
{
offp = tug;
bInap = false;
streamTheCurrentStuff();
}
else if (tugname.equals("w:t") || tugname.equals("a:t")) // DWH 5-18-09
{
bInsideTextMarkers = true;
innanar(tug);
}
else if (tugname.equals("/w:t") || tugname.equals("/a:t")) // DWH 5-18-09
{
bInsideTextMarkers = false;
innanar(tug);
}
else if (bInap)
{
if (tugname.equals("w:r") ||
tugname.equals("a:r") || tugname.equals("a:fld")) // DWH 5-27-09 a:fld
{
tug = killRevisionIDsAndErrs(snug);
if (bInr)
{
bInInnerR = true; // DWH 3-2-09 ruby text has embedded <w:r> codes
innanar(tug);
}
else
{
if (bHavr1)
r2b4text = tug;
else
r1b4text = tug;
bInr = true;
bB4text = true;
}
}
else if (tugname.equals("/w:r") ||
tugname.equals("/a:r") || tugname.equals("/a:fld")) // DWH 5-27-09 a:fld
{
if (bInInnerR)
{
bInInnerR = false; // DWH 3-2-09
innanar(tug);
}
else
{
bInr = false;
if (bHavr1)
{
r2aftext = r2aftext + tug;
// if (r1b4text.equals(r2b4text) && r1aftext.equals(r2aftext))
if (r1aftext.equals(r2aftext))
{
bCollapsing = false;
b4text = r1b4text;
if (r1b4text.equals(r2b4text))
bCollapsing = true;
else
{
int ndx = r1b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r2b4text.equals(
r1b4text.substring(0,ndx)+":t"+r1b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r1b4text; // choose one with preserve
}
}
ndx = r2b4text.indexOf(":t xml:space=\"preserve\"");
if (ndx>-1)
{
if (r1b4text.equals(
r2b4text.substring(0,ndx)+":t"+r2b4text.substring(ndx+23)))
{
bCollapsing = true;
b4text = r2b4text; // choose one with preserve
}
}
}
if (bCollapsing)
{
r1b4text = b4text; // DWH 5-22-09
t1 = t1 + t2;
r2b4text = "";
r2aftext = "";
t2 = "";
}
else
streamTheCurrentStuff(); // DWH 5-22-09
}
else
streamTheCurrentStuff();
// tug is added by "r1aftext=r1aftext+tug" below or "r2aftext=r2aftext+tug" above
}
else
{
r1aftext = r1aftext + tug;
bHavr1 = true;
}
}
}
else if (bInr)
innanar(tug);
else
{
streamTheCurrentStuff();
onp = tug; // this puts out <w:p> and any previous unoutput <w:r> blocks,
// then puts current tag in onp to be output next
}
}
else if (tugname.equalsIgnoreCase("w:sectPr") ||
tugname.equalsIgnoreCase("a:sectPr"))
{
tug = killRevisionIDsAndErrs(tug);
rat(tug);
}
else
rat(tug);
}
private void innanar(String tug)
{
if (bHavr1)
{
if (bB4text)
r2b4text = r2b4text + tug;
else
r2aftext = r2aftext + tug;
}
else
{
if (bB4text)
r1b4text = r1b4text + tug;
else
r1aftext = r1aftext + tug;
}
}
private String killRevisionIDsAndErrs(String tug) // DWH 5-16-09
{
String tigger;
if (configurationType==MSWORD)
tigger = killRevisionIDs(tug);
else // this will be MSPOWERPOINT
tigger=killErrs(tug);
return tigger;
}
private String killRevisionIDs(String tug) // DWH 5-16-09 remove rsid attributes
{
String snug=tug;
String shrug="";
String slug;
int ndx;
while ((ndx=snug.indexOf(" w:rsid"))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the rsid up to first space
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
break;
}
}
shrug += snug; // add whatever is left
return shrug;
}
private String killErrs(String tug) // DWH 5-16-09 remove err= attribute
{
String snug=tug;
String shrug="";
String slug;
int ndx;
if ((ndx=snug.indexOf(" err="))>-1)
{
shrug += snug.substring(0,ndx); // include all before the w:rsid
snug = snug.substring(ndx); // look only at string starting with w:rsid
slug = snug.substring(1);
ndx = slug.indexOf(' ');
if (ndx>-1)
snug = slug.substring(ndx); // remove the err=
else
{
ndx = slug.indexOf("/>");
if (ndx>-1)
snug = snug.substring(ndx+1);
else
{
ndx = slug.indexOf('>');
if (ndx>-1)
snug = snug.substring(ndx+1);
}
}
}
shrug += snug;
return shrug; // add whatever is left
}
private void havtext(String curtext)
{
if (bInsideNastyTextBox) // DWH 7-16-09 ignore textboxes and the text inside them
innanar(curtext);
else if (bInap)
{
if (bInInnerR || !bInsideTextMarkers)
{
// DWH 3-2-09 (just the condition) ruby text has embedded <w:r> codes
// DWH 5-18-09 has to be inside text markers to be counted as text
if (bInr) // DWH 5-21-09
innanar(curtext);
else
{
streamTheCurrentStuff(); // DWH 5-21-09 if not in a text run
streamTheCurrentStuff(); // DWH 5-21-09 put out previous text runs
onp = curtext; // DWH 5-21-09 treat this as new material in p
}
}
else
{
bB4text = false;
if (bHavr1)
{
t2 = curtext;
}
else
t1 = curtext;
}
}
else
rat(curtext);
}
private void streamTheCurrentStuff()
{
if (bInap)
{
rat(onp+r1b4text+t1+r1aftext);
onp = "";
r1b4text = r2b4text;
t1 = t2;
r1aftext = r2aftext;
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
}
else
{
rat(onp+r1b4text+t1+r1aftext+r2b4text+t2+r2aftext+offp);
onp = "";
r1b4text = "";
t1 = "";
r1aftext = "";
r2b4text = "";
t2 = "";
r2aftext = "";
offp = "";
bHavr1 = false;
}
}
private void rat(String s) // the Texan form of "write"
{
try
{
bw.write(s);
LOGGER.log(Level.FINEST,s); //
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Problem writing piped stream.");
// throw new OkapiIOException("Can't read piped input.");
s = s + " ";
}
}
});
readThread.start();
return piis;
}
|
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
index 37eced5d6..236c198ad 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
@@ -1,302 +1,312 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* Group class for static methods to help with creation and getting of the binary dictionary
* file from the dictionary provider
*/
public class BinaryDictionaryFileDumper {
private static final String TAG = BinaryDictionaryFileDumper.class.getSimpleName();
private static final boolean DEBUG = false;
/**
* The size of the temporary buffer to copy files.
*/
private static final int FILE_READ_BUFFER_SIZE = 1024;
// TODO: make the following data common with the native code
private static final byte[] MAGIC_NUMBER_VERSION_1 =
new byte[] { (byte)0x78, (byte)0xB1, (byte)0x00, (byte)0x00 };
private static final byte[] MAGIC_NUMBER_VERSION_2 =
new byte[] { (byte)0x9B, (byte)0xC1, (byte)0x3A, (byte)0xFE };
private static final String DICTIONARY_PROJECTION[] = { "id" };
public static final String QUERY_PARAMETER_MAY_PROMPT_USER = "mayPrompt";
public static final String QUERY_PARAMETER_TRUE = "true";
public static final String QUERY_PARAMETER_DELETE_RESULT = "result";
public static final String QUERY_PARAMETER_SUCCESS = "success";
public static final String QUERY_PARAMETER_FAILURE = "failure";
// Prevents this class to be accidentally instantiated.
private BinaryDictionaryFileDumper() {
}
/**
* Returns a URI builder pointing to the dictionary pack.
*
* This creates a URI builder able to build a URI pointing to the dictionary
* pack content provider for a specific dictionary id.
*/
private static Uri.Builder getProviderUriBuilder(final String path) {
return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
.authority(BinaryDictionary.DICTIONARY_PACK_AUTHORITY).appendPath(
path);
}
/**
* Queries a content provider for the list of word lists for a specific locale
* available to copy into Latin IME.
*/
private static List<WordListInfo> getWordListWordListInfos(final Locale locale,
final Context context, final boolean hasDefaultWordList) {
final ContentResolver resolver = context.getContentResolver();
final Uri.Builder builder = getProviderUriBuilder(locale.toString());
if (!hasDefaultWordList) {
builder.appendQueryParameter(QUERY_PARAMETER_MAY_PROMPT_USER, QUERY_PARAMETER_TRUE);
}
final Uri dictionaryPackUri = builder.build();
final Cursor c = resolver.query(dictionaryPackUri, DICTIONARY_PROJECTION, null, null, null);
if (null == c) return Collections.<WordListInfo>emptyList();
if (c.getCount() <= 0 || !c.moveToFirst()) {
c.close();
return Collections.<WordListInfo>emptyList();
}
try {
final List<WordListInfo> list = new ArrayList<WordListInfo>();
do {
final String wordListId = c.getString(0);
final String wordListLocale = c.getString(1);
if (TextUtils.isEmpty(wordListId)) continue;
list.add(new WordListInfo(wordListId, wordListLocale));
} while (c.moveToNext());
c.close();
return list;
} catch (Exception e) {
// Just in case we hit a problem in communication with the dictionary pack.
// We don't want to die.
Log.e(TAG, "Exception communicating with the dictionary pack : " + e);
return Collections.<WordListInfo>emptyList();
}
}
/**
* Helper method to encapsulate exception handling.
*/
private static AssetFileDescriptor openAssetFileDescriptor(final ContentResolver resolver,
final Uri uri) {
try {
return resolver.openAssetFileDescriptor(uri, "r");
} catch (FileNotFoundException e) {
// I don't want to log the word list URI here for security concerns
Log.e(TAG, "Could not find a word list from the dictionary provider.");
return null;
}
}
/**
* Caches a word list the id of which is passed as an argument. This will write the file
* to the cache file name designated by its id and locale, overwriting it if already present
* and creating it (and its containing directory) if necessary.
*/
private static AssetFileAddress cacheWordList(final String id, final String locale,
final ContentResolver resolver, final Context context) {
final int COMPRESSED_CRYPTED_COMPRESSED = 0;
final int CRYPTED_COMPRESSED = 1;
final int COMPRESSED_CRYPTED = 2;
final int COMPRESSED_ONLY = 3;
final int CRYPTED_ONLY = 4;
final int NONE = 5;
final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED;
final int MODE_MAX = NONE;
final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id);
- final String outputFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context);
+ final String finalFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context);
+ final String tempFileName = finalFileName + ".tmp";
for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) {
InputStream originalSourceStream = null;
InputStream inputStream = null;
File outputFile = null;
FileOutputStream outputStream = null;
AssetFileDescriptor afd = null;
final Uri wordListUri = wordListUriBuilder.build();
try {
// Open input.
afd = openAssetFileDescriptor(resolver, wordListUri);
// If we can't open it at all, don't even try a number of times.
if (null == afd) return null;
originalSourceStream = afd.createInputStream();
// Open output.
- outputFile = new File(outputFileName);
+ outputFile = new File(tempFileName);
+ // Just to be sure, delete the file. This may fail silently, and return false: this
+ // is the right thing to do, as we just want to continue anyway.
+ outputFile.delete();
outputStream = new FileOutputStream(outputFile);
// Get the appropriate decryption method for this try
switch (mode) {
case COMPRESSED_CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(
originalSourceStream)));
break;
case CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(originalSourceStream));
break;
case COMPRESSED_CRYPTED:
inputStream = FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(originalSourceStream));
break;
case COMPRESSED_ONLY:
inputStream = FileTransforms.getUncompressedStream(originalSourceStream);
break;
case CRYPTED_ONLY:
inputStream = FileTransforms.getDecryptedStream(originalSourceStream);
break;
case NONE:
inputStream = originalSourceStream;
break;
}
checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream);
+ outputStream.flush();
+ outputStream.close();
+ final File finalFile = new File(finalFileName);
+ if (!outputFile.renameTo(finalFile)) {
+ throw new IOException("Can't move the file to its final name");
+ }
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_SUCCESS);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "Could not have the dictionary pack delete a word list");
}
- BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, outputFile);
+ BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, finalFile);
// Success! Close files (through the finally{} clause) and return.
- return AssetFileAddress.makeFromFileName(outputFileName);
+ return AssetFileAddress.makeFromFileName(finalFileName);
} catch (Exception e) {
if (DEBUG) {
Log.i(TAG, "Can't open word list in mode " + mode + " : " + e);
}
if (null != outputFile) {
// This may or may not fail. The file may not have been created if the
// exception was thrown before it could be. Hence, both failure and
// success are expected outcomes, so we don't check the return value.
outputFile.delete();
}
// Try the next method.
} finally {
// Ignore exceptions while closing files.
try {
// inputStream.close() will close afd, we should not call afd.close().
if (null != inputStream) inputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e);
}
try {
if (null != outputStream) outputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a file : " + e);
}
}
}
// We could not copy the file at all. This is very unexpected.
// I'd rather not print the word list ID to the log out of security concerns
Log.e(TAG, "Could not copy a word list. Will not be able to use it.");
// If we can't copy it we should warn the dictionary provider so that it can mark it
// as invalid.
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_FAILURE);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "In addition, we were unable to delete it.");
}
return null;
}
/**
* Queries a content provider for word list data for some locale and cache the returned files
*
* This will query a content provider for word list data for a given locale, and copy the
* files locally so that they can be mmap'ed. This may overwrite previously cached word lists
* with newer versions if a newer version is made available by the content provider.
* @returns the addresses of the word list files, or null if no data could be obtained.
* @throw FileNotFoundException if the provider returns non-existent data.
* @throw IOException if the provider-returned data could not be read.
*/
public static List<AssetFileAddress> cacheWordListsFromContentProvider(final Locale locale,
final Context context, final boolean hasDefaultWordList) {
final ContentResolver resolver = context.getContentResolver();
final List<WordListInfo> idList = getWordListWordListInfos(locale, context,
hasDefaultWordList);
final List<AssetFileAddress> fileAddressList = new ArrayList<AssetFileAddress>();
for (WordListInfo id : idList) {
final AssetFileAddress afd = cacheWordList(id.mId, id.mLocale, resolver, context);
if (null != afd) {
fileAddressList.add(afd);
}
}
return fileAddressList;
}
/**
* Copies the data in an input stream to a target file if the magic number matches.
*
* If the magic number does not match the expected value, this method throws an
* IOException. Other usual conditions for IOException or FileNotFoundException
* also apply.
*
* @param input the stream to be copied.
* @param output an output stream to copy the data to.
*/
private static void checkMagicAndCopyFileTo(final BufferedInputStream input,
final FileOutputStream output) throws FileNotFoundException, IOException {
// Check the magic number
final int length = MAGIC_NUMBER_VERSION_2.length;
final byte[] magicNumberBuffer = new byte[length];
final int readMagicNumberSize = input.read(magicNumberBuffer, 0, length);
if (readMagicNumberSize < length) {
throw new IOException("Less bytes to read than the magic number length");
}
if (!Arrays.equals(MAGIC_NUMBER_VERSION_2, magicNumberBuffer)) {
if (!Arrays.equals(MAGIC_NUMBER_VERSION_1, magicNumberBuffer)) {
throw new IOException("Wrong magic number for downloaded file");
}
}
output.write(magicNumberBuffer);
// Actually copy the file
final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE];
for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer))
output.write(buffer, 0, readBytes);
input.close();
}
}
| false | true | private static AssetFileAddress cacheWordList(final String id, final String locale,
final ContentResolver resolver, final Context context) {
final int COMPRESSED_CRYPTED_COMPRESSED = 0;
final int CRYPTED_COMPRESSED = 1;
final int COMPRESSED_CRYPTED = 2;
final int COMPRESSED_ONLY = 3;
final int CRYPTED_ONLY = 4;
final int NONE = 5;
final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED;
final int MODE_MAX = NONE;
final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id);
final String outputFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context);
for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) {
InputStream originalSourceStream = null;
InputStream inputStream = null;
File outputFile = null;
FileOutputStream outputStream = null;
AssetFileDescriptor afd = null;
final Uri wordListUri = wordListUriBuilder.build();
try {
// Open input.
afd = openAssetFileDescriptor(resolver, wordListUri);
// If we can't open it at all, don't even try a number of times.
if (null == afd) return null;
originalSourceStream = afd.createInputStream();
// Open output.
outputFile = new File(outputFileName);
outputStream = new FileOutputStream(outputFile);
// Get the appropriate decryption method for this try
switch (mode) {
case COMPRESSED_CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(
originalSourceStream)));
break;
case CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(originalSourceStream));
break;
case COMPRESSED_CRYPTED:
inputStream = FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(originalSourceStream));
break;
case COMPRESSED_ONLY:
inputStream = FileTransforms.getUncompressedStream(originalSourceStream);
break;
case CRYPTED_ONLY:
inputStream = FileTransforms.getDecryptedStream(originalSourceStream);
break;
case NONE:
inputStream = originalSourceStream;
break;
}
checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream);
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_SUCCESS);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "Could not have the dictionary pack delete a word list");
}
BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, outputFile);
// Success! Close files (through the finally{} clause) and return.
return AssetFileAddress.makeFromFileName(outputFileName);
} catch (Exception e) {
if (DEBUG) {
Log.i(TAG, "Can't open word list in mode " + mode + " : " + e);
}
if (null != outputFile) {
// This may or may not fail. The file may not have been created if the
// exception was thrown before it could be. Hence, both failure and
// success are expected outcomes, so we don't check the return value.
outputFile.delete();
}
// Try the next method.
} finally {
// Ignore exceptions while closing files.
try {
// inputStream.close() will close afd, we should not call afd.close().
if (null != inputStream) inputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e);
}
try {
if (null != outputStream) outputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a file : " + e);
}
}
}
// We could not copy the file at all. This is very unexpected.
// I'd rather not print the word list ID to the log out of security concerns
Log.e(TAG, "Could not copy a word list. Will not be able to use it.");
// If we can't copy it we should warn the dictionary provider so that it can mark it
// as invalid.
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_FAILURE);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "In addition, we were unable to delete it.");
}
return null;
}
| private static AssetFileAddress cacheWordList(final String id, final String locale,
final ContentResolver resolver, final Context context) {
final int COMPRESSED_CRYPTED_COMPRESSED = 0;
final int CRYPTED_COMPRESSED = 1;
final int COMPRESSED_CRYPTED = 2;
final int COMPRESSED_ONLY = 3;
final int CRYPTED_ONLY = 4;
final int NONE = 5;
final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED;
final int MODE_MAX = NONE;
final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id);
final String finalFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context);
final String tempFileName = finalFileName + ".tmp";
for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) {
InputStream originalSourceStream = null;
InputStream inputStream = null;
File outputFile = null;
FileOutputStream outputStream = null;
AssetFileDescriptor afd = null;
final Uri wordListUri = wordListUriBuilder.build();
try {
// Open input.
afd = openAssetFileDescriptor(resolver, wordListUri);
// If we can't open it at all, don't even try a number of times.
if (null == afd) return null;
originalSourceStream = afd.createInputStream();
// Open output.
outputFile = new File(tempFileName);
// Just to be sure, delete the file. This may fail silently, and return false: this
// is the right thing to do, as we just want to continue anyway.
outputFile.delete();
outputStream = new FileOutputStream(outputFile);
// Get the appropriate decryption method for this try
switch (mode) {
case COMPRESSED_CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(
originalSourceStream)));
break;
case CRYPTED_COMPRESSED:
inputStream = FileTransforms.getUncompressedStream(
FileTransforms.getDecryptedStream(originalSourceStream));
break;
case COMPRESSED_CRYPTED:
inputStream = FileTransforms.getDecryptedStream(
FileTransforms.getUncompressedStream(originalSourceStream));
break;
case COMPRESSED_ONLY:
inputStream = FileTransforms.getUncompressedStream(originalSourceStream);
break;
case CRYPTED_ONLY:
inputStream = FileTransforms.getDecryptedStream(originalSourceStream);
break;
case NONE:
inputStream = originalSourceStream;
break;
}
checkMagicAndCopyFileTo(new BufferedInputStream(inputStream), outputStream);
outputStream.flush();
outputStream.close();
final File finalFile = new File(finalFileName);
if (!outputFile.renameTo(finalFile)) {
throw new IOException("Can't move the file to its final name");
}
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_SUCCESS);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "Could not have the dictionary pack delete a word list");
}
BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, finalFile);
// Success! Close files (through the finally{} clause) and return.
return AssetFileAddress.makeFromFileName(finalFileName);
} catch (Exception e) {
if (DEBUG) {
Log.i(TAG, "Can't open word list in mode " + mode + " : " + e);
}
if (null != outputFile) {
// This may or may not fail. The file may not have been created if the
// exception was thrown before it could be. Hence, both failure and
// success are expected outcomes, so we don't check the return value.
outputFile.delete();
}
// Try the next method.
} finally {
// Ignore exceptions while closing files.
try {
// inputStream.close() will close afd, we should not call afd.close().
if (null != inputStream) inputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e);
}
try {
if (null != outputStream) outputStream.close();
} catch (Exception e) {
Log.e(TAG, "Exception while closing a file : " + e);
}
}
}
// We could not copy the file at all. This is very unexpected.
// I'd rather not print the word list ID to the log out of security concerns
Log.e(TAG, "Could not copy a word list. Will not be able to use it.");
// If we can't copy it we should warn the dictionary provider so that it can mark it
// as invalid.
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_FAILURE);
if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "In addition, we were unable to delete it.");
}
return null;
}
|
diff --git a/src/com/mavu/appcode/DataAccess.java b/src/com/mavu/appcode/DataAccess.java
index 65b6afc..c5897ec 100644
--- a/src/com/mavu/appcode/DataAccess.java
+++ b/src/com/mavu/appcode/DataAccess.java
@@ -1,499 +1,502 @@
package com.mavu.appcode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class DataAccess extends AsyncTask<String, Integer, Boolean> {
private android.app.ProgressDialog progressDialog;
private OnResponseListener responder;
private SelectionParameters parameters;
private Post postVals;
private Account account;
private Vector<Post> posts;
private String accountID;
private int currentAction;
public DataAccess(android.app.ProgressDialog progressDialog,OnResponseListener responder){
this.responder = responder;
this.progressDialog = progressDialog;
}
public DataAccess(Context context, OnResponseListener responder, SelectionParameters parameters){
this.responder = responder;
this.parameters = parameters;
this.progressDialog = new ProgressDialog(context, "Loading...");
}
public DataAccess(Context context, OnResponseListener responder){
this.responder = responder;
this.progressDialog = new ProgressDialog(context, "Loading...");
}
public DataAccess(Context context, OnResponseListener responder, Post postVals){
this.responder = responder;
this.postVals = postVals;
this.progressDialog = new ProgressDialog(context, "Loading...");
}
public DataAccess(Context context, OnResponseListener responder, Account account){
this.responder = responder;
this.account = account;
this.progressDialog = new ProgressDialog(context, "Loading...");
}
//Used for getting the account based on the account id
public DataAccess(Context context, OnResponseListener responder, String accountId){
this.responder = responder;
this.accountID = accountId;
this.progressDialog = new ProgressDialog(context, "Loading...");
}
@Override
protected void onPreExecute(){
progressDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
/*
* case 1: Login
* case 2: Create Account
* case 3: Update Account
* case 4: Get Account (By account Id)
* case 5: Create Post
* case 6: Get Posts
* case 7: See if account username is taken
* case 8: Get Account (By email)
*/
List<NameValuePair> nameValuePair;
InputStream is = null;
String json = "";
HttpClient httpClient;
HttpPost httpPost;
JSONObject jObj;
currentAction = Integer.parseInt(params[0]);
switch (Integer.parseInt(params[0])) {
case 1:
//TODO Login
//email sent as 2nd parameter value and password sent as 3rd
nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("action", "Login"));
nameValuePair.add(new BasicNameValuePair("email", params[1]));
nameValuePair.add(new BasicNameValuePair("password", params[2]));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
account = new Account();
try {
JSONArray jArray = new JSONArray(json);
jObj = jArray.getJSONObject(0);
Log.i("account vals", jObj.getString("first_name") + " " + jObj.getString("last_name"));
//Set account fields
account.setAccountId(jObj.getString("account_id"));
account.setDob(jObj.getString("dob"));
account.setEmail(jObj.getString("email"));
account.setfName(jObj.getString("first_name"));
account.setlName(jObj.getString("last_name"));
//account.setPassword(jObj.getString("password"));
//TODO - implement likes and dislikes
//account.setLikes(jObj.getInt("likes"));
//account.setDislikes(jObj.getInt("dislikes"));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return false;
}
return true;
case 2:
nameValuePair = new ArrayList<NameValuePair>(6);
nameValuePair.add(new BasicNameValuePair("action", "Create Account"));
nameValuePair.add(new BasicNameValuePair("fname", account.getfName()));
nameValuePair.add(new BasicNameValuePair("lname", account.getlName()));
nameValuePair.add(new BasicNameValuePair("email", account.getEmail()));
nameValuePair.add(new BasicNameValuePair("password", account.getPassword()));
nameValuePair.add(new BasicNameValuePair("dob", account.getDob()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Log.i("create return val", jObj.getString("insert"));
if(jObj.getString("insert").equals("success")){
Log.i("create userID val", jObj.getString("accountID"));
accountID = jObj.getString("accountID");
}
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 3:
nameValuePair = new ArrayList<NameValuePair>(7);
nameValuePair.add(new BasicNameValuePair("action", "Update Account"));
nameValuePair.add(new BasicNameValuePair("account_id", String.valueOf(account.getAccountId())));
nameValuePair.add(new BasicNameValuePair("fname", account.getfName()));
nameValuePair.add(new BasicNameValuePair("lname", account.getlName()));
nameValuePair.add(new BasicNameValuePair("email", account.getEmail()));
nameValuePair.add(new BasicNameValuePair("password", account.getPassword()));
nameValuePair.add(new BasicNameValuePair("dob", account.getDob()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Log.i("create return val", jObj.getString("update"));
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 4:
//TODO get account
nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("action", "Get Account"));
nameValuePair.add(new BasicNameValuePair("account_id", this.accountID));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
account = new Account();
try {
JSONArray jArray = new JSONArray(json);
jObj = jArray.getJSONObject(0);
Log.i("account vals", jObj.getString("first_name") + " " + jObj.getString("last_name"));
//Set account fields
//account.setAccountId(jObj.getString("account_id"));
account.setDob(jObj.getString("dob"));
account.setEmail(jObj.getString("email"));
account.setfName(jObj.getString("first_name"));
account.setlName(jObj.getString("last_name"));
//account.setPassword(jObj.getString("password"));
//TODO - implement likes and dislikes
//account.setLikes(jObj.getInt("likes"));
//account.setDislikes(jObj.getInt("dislikes"));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return false;
}
return true;
case 5:
//TODO create post
nameValuePair = new ArrayList<NameValuePair>(10);
nameValuePair.add(new BasicNameValuePair("action", "Create Post"));
nameValuePair.add(new BasicNameValuePair("title", postVals.getTitle()));
nameValuePair.add(new BasicNameValuePair("account_id", postVals.getAccountID()));
nameValuePair.add(new BasicNameValuePair("description", postVals.getDesc()));
nameValuePair.add(new BasicNameValuePair("category", postVals.getCategory()));
nameValuePair.add(new BasicNameValuePair("city", postVals.getCity()));
nameValuePair.add(new BasicNameValuePair("time", postVals.getTime()));
nameValuePair.add(new BasicNameValuePair("date", postVals.getDate().toString()));
nameValuePair.add(new BasicNameValuePair("address", postVals.getAddress()));
//TODO do we need zipcode?
//nameValuePair.add(new BasicNameValuePair("zipcode", postVals.getZip()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
case 6:
//Get Posts
nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("action", "Get Posts"));
nameValuePair.add(new BasicNameValuePair("lowDate", parameters.getLowDate().toString()));
nameValuePair.add(new BasicNameValuePair("highDate", parameters.getHighDate().toString()));
if (!parameters.getCity().equals("") && !parameters.getCity().equals("n/a"))
{
nameValuePair.add(new BasicNameValuePair("city", parameters.getCity().toString()));
}
- if (parameters.getMusic_category())
+ /*if (parameters.getMusic_category())
{
nameValuePair.add(new BasicNameValuePair("music", parameters.getMusic_category().toString()));
- }
- if (parameters.getFood_category())
+ }*/
+ /*if (parameters.getFood_category())
{
nameValuePair.add(new BasicNameValuePair("food", parameters.getFood_category().toString()));
- }
- if (parameters.getBusiness_category())
+ }*/
+ nameValuePair.add(new BasicNameValuePair("music", parameters.getMusic_category().toString()));
+ nameValuePair.add(new BasicNameValuePair("food", parameters.getFood_category().toString()));
+ nameValuePair.add(new BasicNameValuePair("business", parameters.getBusiness_category().toString()));
+ /*if (parameters.getBusiness_category())
{
nameValuePair.add(new BasicNameValuePair("business", parameters.getBusiness_category().toString()));
- }
+ }*/
if (!parameters.getTitle().equals(""))
{
nameValuePair.add(new BasicNameValuePair("title", parameters.getTitle().toString()));
}
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
//Log.i("json data", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
Log.i("array leng", String.valueOf(jArray.length()));
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Post post = new Post(jObj.get("post_id").toString(), jObj.getString("title"), jObj.getString("description"), jObj.getString("category"),jObj.getString("address"), jObj.getString("city"), jObj.getString("time"), jObj.get("date").toString());
- //post.setAccountID(jObj.getString("account_id"));
+ post.setAccountID(jObj.getString("accountID"));
posts.add(post);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 7:
//TODO see if username is taken
break;
default:
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean result){
if(this.progressDialog.isShowing()) {
this.progressDialog.dismiss();
}
if(result)
{
switch (currentAction)
{
case 1: //Get Account by email
responder.onSuccess(account);
break;
case 2: //Create Account - we want to return the account so that we can get the newly assigned account Id
responder.onSuccess(accountID);
break;
case 3: //Update Account
responder.onSuccess(result);
break;
case 4: //Get Account (By Id)
responder.onSuccess(account);
break;
case 5: //Create Post
responder.onSuccess(result);
break;
case 6:
responder.onSuccess(posts);
break;
case 8: //Get Account (By Email)
responder.onSuccess(account);
break;
}
}
else {
responder.onFailure("Fail");
}
}
public interface OnResponseListener {
public void onSuccess(Vector<Post> posts);
public void onSuccess(Account account);
public void onSuccess(String accountID);
public void onSuccess(Boolean passed);
public void onFailure(String message);
}
public class ProgressDialog extends android.app.ProgressDialog {
public ProgressDialog(Context context, String progressMessage){
super(context);
setCancelable(false);
setMessage(progressMessage);
}
}
}
| false | true | protected Boolean doInBackground(String... params) {
/*
* case 1: Login
* case 2: Create Account
* case 3: Update Account
* case 4: Get Account (By account Id)
* case 5: Create Post
* case 6: Get Posts
* case 7: See if account username is taken
* case 8: Get Account (By email)
*/
List<NameValuePair> nameValuePair;
InputStream is = null;
String json = "";
HttpClient httpClient;
HttpPost httpPost;
JSONObject jObj;
currentAction = Integer.parseInt(params[0]);
switch (Integer.parseInt(params[0])) {
case 1:
//TODO Login
//email sent as 2nd parameter value and password sent as 3rd
nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("action", "Login"));
nameValuePair.add(new BasicNameValuePair("email", params[1]));
nameValuePair.add(new BasicNameValuePair("password", params[2]));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
account = new Account();
try {
JSONArray jArray = new JSONArray(json);
jObj = jArray.getJSONObject(0);
Log.i("account vals", jObj.getString("first_name") + " " + jObj.getString("last_name"));
//Set account fields
account.setAccountId(jObj.getString("account_id"));
account.setDob(jObj.getString("dob"));
account.setEmail(jObj.getString("email"));
account.setfName(jObj.getString("first_name"));
account.setlName(jObj.getString("last_name"));
//account.setPassword(jObj.getString("password"));
//TODO - implement likes and dislikes
//account.setLikes(jObj.getInt("likes"));
//account.setDislikes(jObj.getInt("dislikes"));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return false;
}
return true;
case 2:
nameValuePair = new ArrayList<NameValuePair>(6);
nameValuePair.add(new BasicNameValuePair("action", "Create Account"));
nameValuePair.add(new BasicNameValuePair("fname", account.getfName()));
nameValuePair.add(new BasicNameValuePair("lname", account.getlName()));
nameValuePair.add(new BasicNameValuePair("email", account.getEmail()));
nameValuePair.add(new BasicNameValuePair("password", account.getPassword()));
nameValuePair.add(new BasicNameValuePair("dob", account.getDob()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Log.i("create return val", jObj.getString("insert"));
if(jObj.getString("insert").equals("success")){
Log.i("create userID val", jObj.getString("accountID"));
accountID = jObj.getString("accountID");
}
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 3:
nameValuePair = new ArrayList<NameValuePair>(7);
nameValuePair.add(new BasicNameValuePair("action", "Update Account"));
nameValuePair.add(new BasicNameValuePair("account_id", String.valueOf(account.getAccountId())));
nameValuePair.add(new BasicNameValuePair("fname", account.getfName()));
nameValuePair.add(new BasicNameValuePair("lname", account.getlName()));
nameValuePair.add(new BasicNameValuePair("email", account.getEmail()));
nameValuePair.add(new BasicNameValuePair("password", account.getPassword()));
nameValuePair.add(new BasicNameValuePair("dob", account.getDob()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Log.i("create return val", jObj.getString("update"));
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 4:
//TODO get account
nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("action", "Get Account"));
nameValuePair.add(new BasicNameValuePair("account_id", this.accountID));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
account = new Account();
try {
JSONArray jArray = new JSONArray(json);
jObj = jArray.getJSONObject(0);
Log.i("account vals", jObj.getString("first_name") + " " + jObj.getString("last_name"));
//Set account fields
//account.setAccountId(jObj.getString("account_id"));
account.setDob(jObj.getString("dob"));
account.setEmail(jObj.getString("email"));
account.setfName(jObj.getString("first_name"));
account.setlName(jObj.getString("last_name"));
//account.setPassword(jObj.getString("password"));
//TODO - implement likes and dislikes
//account.setLikes(jObj.getInt("likes"));
//account.setDislikes(jObj.getInt("dislikes"));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return false;
}
return true;
case 5:
//TODO create post
nameValuePair = new ArrayList<NameValuePair>(10);
nameValuePair.add(new BasicNameValuePair("action", "Create Post"));
nameValuePair.add(new BasicNameValuePair("title", postVals.getTitle()));
nameValuePair.add(new BasicNameValuePair("account_id", postVals.getAccountID()));
nameValuePair.add(new BasicNameValuePair("description", postVals.getDesc()));
nameValuePair.add(new BasicNameValuePair("category", postVals.getCategory()));
nameValuePair.add(new BasicNameValuePair("city", postVals.getCity()));
nameValuePair.add(new BasicNameValuePair("time", postVals.getTime()));
nameValuePair.add(new BasicNameValuePair("date", postVals.getDate().toString()));
nameValuePair.add(new BasicNameValuePair("address", postVals.getAddress()));
//TODO do we need zipcode?
//nameValuePair.add(new BasicNameValuePair("zipcode", postVals.getZip()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
case 6:
//Get Posts
nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("action", "Get Posts"));
nameValuePair.add(new BasicNameValuePair("lowDate", parameters.getLowDate().toString()));
nameValuePair.add(new BasicNameValuePair("highDate", parameters.getHighDate().toString()));
if (!parameters.getCity().equals("") && !parameters.getCity().equals("n/a"))
{
nameValuePair.add(new BasicNameValuePair("city", parameters.getCity().toString()));
}
if (parameters.getMusic_category())
{
nameValuePair.add(new BasicNameValuePair("music", parameters.getMusic_category().toString()));
}
if (parameters.getFood_category())
{
nameValuePair.add(new BasicNameValuePair("food", parameters.getFood_category().toString()));
}
if (parameters.getBusiness_category())
{
nameValuePair.add(new BasicNameValuePair("business", parameters.getBusiness_category().toString()));
}
if (!parameters.getTitle().equals(""))
{
nameValuePair.add(new BasicNameValuePair("title", parameters.getTitle().toString()));
}
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
//Log.i("json data", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
Log.i("array leng", String.valueOf(jArray.length()));
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Post post = new Post(jObj.get("post_id").toString(), jObj.getString("title"), jObj.getString("description"), jObj.getString("category"),jObj.getString("address"), jObj.getString("city"), jObj.getString("time"), jObj.get("date").toString());
//post.setAccountID(jObj.getString("account_id"));
posts.add(post);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 7:
//TODO see if username is taken
break;
default:
return false;
}
return true;
}
| protected Boolean doInBackground(String... params) {
/*
* case 1: Login
* case 2: Create Account
* case 3: Update Account
* case 4: Get Account (By account Id)
* case 5: Create Post
* case 6: Get Posts
* case 7: See if account username is taken
* case 8: Get Account (By email)
*/
List<NameValuePair> nameValuePair;
InputStream is = null;
String json = "";
HttpClient httpClient;
HttpPost httpPost;
JSONObject jObj;
currentAction = Integer.parseInt(params[0]);
switch (Integer.parseInt(params[0])) {
case 1:
//TODO Login
//email sent as 2nd parameter value and password sent as 3rd
nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("action", "Login"));
nameValuePair.add(new BasicNameValuePair("email", params[1]));
nameValuePair.add(new BasicNameValuePair("password", params[2]));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
account = new Account();
try {
JSONArray jArray = new JSONArray(json);
jObj = jArray.getJSONObject(0);
Log.i("account vals", jObj.getString("first_name") + " " + jObj.getString("last_name"));
//Set account fields
account.setAccountId(jObj.getString("account_id"));
account.setDob(jObj.getString("dob"));
account.setEmail(jObj.getString("email"));
account.setfName(jObj.getString("first_name"));
account.setlName(jObj.getString("last_name"));
//account.setPassword(jObj.getString("password"));
//TODO - implement likes and dislikes
//account.setLikes(jObj.getInt("likes"));
//account.setDislikes(jObj.getInt("dislikes"));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return false;
}
return true;
case 2:
nameValuePair = new ArrayList<NameValuePair>(6);
nameValuePair.add(new BasicNameValuePair("action", "Create Account"));
nameValuePair.add(new BasicNameValuePair("fname", account.getfName()));
nameValuePair.add(new BasicNameValuePair("lname", account.getlName()));
nameValuePair.add(new BasicNameValuePair("email", account.getEmail()));
nameValuePair.add(new BasicNameValuePair("password", account.getPassword()));
nameValuePair.add(new BasicNameValuePair("dob", account.getDob()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Log.i("create return val", jObj.getString("insert"));
if(jObj.getString("insert").equals("success")){
Log.i("create userID val", jObj.getString("accountID"));
accountID = jObj.getString("accountID");
}
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 3:
nameValuePair = new ArrayList<NameValuePair>(7);
nameValuePair.add(new BasicNameValuePair("action", "Update Account"));
nameValuePair.add(new BasicNameValuePair("account_id", String.valueOf(account.getAccountId())));
nameValuePair.add(new BasicNameValuePair("fname", account.getfName()));
nameValuePair.add(new BasicNameValuePair("lname", account.getlName()));
nameValuePair.add(new BasicNameValuePair("email", account.getEmail()));
nameValuePair.add(new BasicNameValuePair("password", account.getPassword()));
nameValuePair.add(new BasicNameValuePair("dob", account.getDob()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Log.i("create return val", jObj.getString("update"));
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 4:
//TODO get account
nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("action", "Get Account"));
nameValuePair.add(new BasicNameValuePair("account_id", this.accountID));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
account = new Account();
try {
JSONArray jArray = new JSONArray(json);
jObj = jArray.getJSONObject(0);
Log.i("account vals", jObj.getString("first_name") + " " + jObj.getString("last_name"));
//Set account fields
//account.setAccountId(jObj.getString("account_id"));
account.setDob(jObj.getString("dob"));
account.setEmail(jObj.getString("email"));
account.setfName(jObj.getString("first_name"));
account.setlName(jObj.getString("last_name"));
//account.setPassword(jObj.getString("password"));
//TODO - implement likes and dislikes
//account.setLikes(jObj.getInt("likes"));
//account.setDislikes(jObj.getInt("dislikes"));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
return false;
}
return true;
case 5:
//TODO create post
nameValuePair = new ArrayList<NameValuePair>(10);
nameValuePair.add(new BasicNameValuePair("action", "Create Post"));
nameValuePair.add(new BasicNameValuePair("title", postVals.getTitle()));
nameValuePair.add(new BasicNameValuePair("account_id", postVals.getAccountID()));
nameValuePair.add(new BasicNameValuePair("description", postVals.getDesc()));
nameValuePair.add(new BasicNameValuePair("category", postVals.getCategory()));
nameValuePair.add(new BasicNameValuePair("city", postVals.getCity()));
nameValuePair.add(new BasicNameValuePair("time", postVals.getTime()));
nameValuePair.add(new BasicNameValuePair("date", postVals.getDate().toString()));
nameValuePair.add(new BasicNameValuePair("address", postVals.getAddress()));
//TODO do we need zipcode?
//nameValuePair.add(new BasicNameValuePair("zipcode", postVals.getZip()));
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
case 6:
//Get Posts
nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("action", "Get Posts"));
nameValuePair.add(new BasicNameValuePair("lowDate", parameters.getLowDate().toString()));
nameValuePair.add(new BasicNameValuePair("highDate", parameters.getHighDate().toString()));
if (!parameters.getCity().equals("") && !parameters.getCity().equals("n/a"))
{
nameValuePair.add(new BasicNameValuePair("city", parameters.getCity().toString()));
}
/*if (parameters.getMusic_category())
{
nameValuePair.add(new BasicNameValuePair("music", parameters.getMusic_category().toString()));
}*/
/*if (parameters.getFood_category())
{
nameValuePair.add(new BasicNameValuePair("food", parameters.getFood_category().toString()));
}*/
nameValuePair.add(new BasicNameValuePair("music", parameters.getMusic_category().toString()));
nameValuePair.add(new BasicNameValuePair("food", parameters.getFood_category().toString()));
nameValuePair.add(new BasicNameValuePair("business", parameters.getBusiness_category().toString()));
/*if (parameters.getBusiness_category())
{
nameValuePair.add(new BasicNameValuePair("business", parameters.getBusiness_category().toString()));
}*/
if (!parameters.getTitle().equals(""))
{
nameValuePair.add(new BasicNameValuePair("title", parameters.getTitle().toString()));
}
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://mavu.jordanrhode.com/user_actions.php");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
//Log.i("json data", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
posts = new Vector<Post>();
try {
JSONArray jArray = new JSONArray(json);
Log.i("array leng", String.valueOf(jArray.length()));
for(int i=0; i<jArray.length(); i++)
{
jObj = jArray.getJSONObject(i);
Post post = new Post(jObj.get("post_id").toString(), jObj.getString("title"), jObj.getString("description"), jObj.getString("category"),jObj.getString("address"), jObj.getString("city"), jObj.getString("time"), jObj.get("date").toString());
post.setAccountID(jObj.getString("accountID"));
posts.add(post);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return true;
case 7:
//TODO see if username is taken
break;
default:
return false;
}
return true;
}
|
diff --git a/opal-reporting/src/main/java/org/obiba/opal/web/reporting/Dtos.java b/opal-reporting/src/main/java/org/obiba/opal/web/reporting/Dtos.java
index de136adf4..0dd9cc4f5 100644
--- a/opal-reporting/src/main/java/org/obiba/opal/web/reporting/Dtos.java
+++ b/opal-reporting/src/main/java/org/obiba/opal/web/reporting/Dtos.java
@@ -1,72 +1,73 @@
/*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* 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.obiba.opal.web.reporting;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.obiba.opal.core.cfg.ReportTemplate;
import org.obiba.opal.web.model.Opal;
import org.obiba.opal.web.model.Opal.ParameterDto;
import org.obiba.opal.web.model.Opal.ReportTemplateDto;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class Dtos {
public static ReportTemplate fromDto(ReportTemplateDto reportTemplateDto) {
ReportTemplate reportTemplate = new ReportTemplate();
reportTemplate.setName(reportTemplateDto.getName());
reportTemplate.setDesign(reportTemplateDto.getDesign());
reportTemplate.setFormat(reportTemplateDto.getFormat());
Map<String, String> params = Maps.newLinkedHashMap();
for(ParameterDto param : reportTemplateDto.getParametersList()) {
params.put(param.getKey(), param.getValue());
}
+ reportTemplate.setParameters(params);
String schedule = reportTemplateDto.getCron();
if(schedule != null) {
reportTemplate.setSchedule(reportTemplateDto.getCron());
}
reportTemplate.setEmailNotificationAddresses(Sets.newHashSet(reportTemplateDto.getEmailNotificationList()));
return reportTemplate;
}
public static ReportTemplateDto asDto(ReportTemplate reportTemplate) {
ReportTemplateDto.Builder dtoBuilder = ReportTemplateDto.newBuilder().setName(reportTemplate.getName()).setDesign(reportTemplate.getDesign()).setFormat(reportTemplate.getFormat());
for(Map.Entry<String, String> param : reportTemplate.getParameters().entrySet()) {
dtoBuilder.addParameters(ParameterDto.newBuilder().setKey(param.getKey()).setValue(param.getValue()));
}
String schedule = reportTemplate.getSchedule();
if(schedule != null) {
dtoBuilder.setCron(schedule);
}
dtoBuilder.addAllEmailNotification(reportTemplate.getEmailNotificationAddresses());
return dtoBuilder.build();
}
public static Set<ReportTemplateDto> asDto(Set<ReportTemplate> reportTemplates) {
Set<Opal.ReportTemplateDto> reportTemplateDtos = new LinkedHashSet<ReportTemplateDto>();
for(ReportTemplate reportTemplate : reportTemplates) {
reportTemplateDtos.add(asDto(reportTemplate));
}
return reportTemplateDtos;
}
}
| true | true | public static ReportTemplate fromDto(ReportTemplateDto reportTemplateDto) {
ReportTemplate reportTemplate = new ReportTemplate();
reportTemplate.setName(reportTemplateDto.getName());
reportTemplate.setDesign(reportTemplateDto.getDesign());
reportTemplate.setFormat(reportTemplateDto.getFormat());
Map<String, String> params = Maps.newLinkedHashMap();
for(ParameterDto param : reportTemplateDto.getParametersList()) {
params.put(param.getKey(), param.getValue());
}
String schedule = reportTemplateDto.getCron();
if(schedule != null) {
reportTemplate.setSchedule(reportTemplateDto.getCron());
}
reportTemplate.setEmailNotificationAddresses(Sets.newHashSet(reportTemplateDto.getEmailNotificationList()));
return reportTemplate;
}
| public static ReportTemplate fromDto(ReportTemplateDto reportTemplateDto) {
ReportTemplate reportTemplate = new ReportTemplate();
reportTemplate.setName(reportTemplateDto.getName());
reportTemplate.setDesign(reportTemplateDto.getDesign());
reportTemplate.setFormat(reportTemplateDto.getFormat());
Map<String, String> params = Maps.newLinkedHashMap();
for(ParameterDto param : reportTemplateDto.getParametersList()) {
params.put(param.getKey(), param.getValue());
}
reportTemplate.setParameters(params);
String schedule = reportTemplateDto.getCron();
if(schedule != null) {
reportTemplate.setSchedule(reportTemplateDto.getCron());
}
reportTemplate.setEmailNotificationAddresses(Sets.newHashSet(reportTemplateDto.getEmailNotificationList()));
return reportTemplate;
}
|
diff --git a/src/org/geworkbench/engine/skin/Skin.java b/src/org/geworkbench/engine/skin/Skin.java
index ab1303b6..fe72435e 100755
--- a/src/org/geworkbench/engine/skin/Skin.java
+++ b/src/org/geworkbench/engine/skin/Skin.java
@@ -1,809 +1,805 @@
package org.geworkbench.engine.skin;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.eleritec.docking.DockableAdapter;
import net.eleritec.docking.DockingManager;
import net.eleritec.docking.DockingPort;
import net.eleritec.docking.defaults.ComponentProviderAdapter;
import net.eleritec.docking.defaults.DefaultDockingPort;
import org.apache.commons.collections15.map.ReferenceMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.biocollections.DSDataSet;
import org.geworkbench.bison.datastructure.bioobjects.DSBioObject;
import org.geworkbench.builtin.projects.Icons;
import org.geworkbench.engine.ccm.ComponentConfigurationManagerWindow2;
import org.geworkbench.engine.config.Closable;
import org.geworkbench.engine.config.GUIFramework;
import org.geworkbench.engine.config.PluginDescriptor;
import org.geworkbench.engine.config.VisualPlugin;
import org.geworkbench.engine.config.rules.GeawConfigObject;
import org.geworkbench.engine.management.ComponentRegistry;
import org.geworkbench.engine.properties.PropertiesManager;
import org.geworkbench.util.FilePathnameUtils;
import org.geworkbench.util.JAutoList;
/**
* <p>Title: Bioworks</p>
* <p>Description: Modular Application Framework for Gene Expession, Sequence and Genotype Analysis</p>
* <p>Copyright: Copyright (c) 2003 -2004</p>
* <p>Company: Columbia University</p>
*
* @author manjunath at genomecenter dot columbia dot edu
* @version $Id$
*/
public class Skin extends GUIFramework {
private static final String YES = "yes";
private static final String NO = "no";
private static final long serialVersionUID = 3617137568252369693L;
static Log log = LogFactory.getLog(Skin.class);
private static Map<Component, String> visualRegistry = new HashMap<Component, String>();
private JPanel contentPane;
private JLabel statusBar = new JLabel();
private BorderLayout borderLayout1 = new BorderLayout();
private JSplitPane jSplitPane1 = new JSplitPane();
private DefaultDockingPort visualPanel = new DefaultDockingPort();
private DefaultDockingPort commandPanel = new DefaultDockingPort();
private JSplitPane jSplitPane2 = new JSplitPane();
private JSplitPane jSplitPane3 = new JSplitPane();
private DefaultDockingPort selectionPanel = new DefaultDockingPort();
private JToolBar jToolBar = new JToolBar();
private DefaultDockingPort projectPanel = new DefaultDockingPort();
private Map<String, DefaultDockingPort> areas = new Hashtable<String, DefaultDockingPort>();
private Set<Class<?>> acceptors;
private HashMap<Component, Class<?>> mainComponentClass = new HashMap<Component, Class<?>>();
private ReferenceMap<DSDataSet<? extends DSBioObject>, String> visualLastSelected = new ReferenceMap<DSDataSet<? extends DSBioObject>, String>();
private ReferenceMap<DSDataSet<? extends DSBioObject>, String> commandLastSelected = new ReferenceMap<DSDataSet<? extends DSBioObject>, String>();
private ReferenceMap<DSDataSet<? extends DSBioObject>, String> selectionLastSelected = new ReferenceMap<DSDataSet<? extends DSBioObject>, String>();
private ArrayList<DockableImpl> visualDockables = new ArrayList<DockableImpl>();
private ArrayList<DockableImpl> commandDockables = new ArrayList<DockableImpl>();
private ArrayList<DockableImpl> selectorDockables = new ArrayList<DockableImpl>();
private DSDataSet<? extends DSBioObject> currentDataSet;
private boolean tabSwappingMode = false;
public static final String APP_SIZE_FILE = "appCoords.txt";
public String getVisualLastSelected(DSDataSet<? extends DSBioObject> dataSet) {
return visualLastSelected.get(dataSet);
}
public String getCommandLastSelected(DSDataSet<? extends DSBioObject> dataSet) {
return commandLastSelected.get(dataSet);
}
public String getSelectionLastSelected(DSDataSet<? extends DSBioObject> dataSet) {
return selectionLastSelected.get(dataSet);
}
public void setVisualLastSelected(DSDataSet<? extends DSBioObject> dataSet, String component) {
if (component != null) {
visualLastSelected.put(dataSet, component);
}
}
public void setCommandLastSelected(DSDataSet<? extends DSBioObject> dataSet, String component) {
if (component != null) {
commandLastSelected.put(dataSet, component);
}
}
public void setSelectionLastSelected(DSDataSet<? extends DSBioObject> dataSet, String component) {
if (component != null) {
selectionLastSelected.put(dataSet, component);
}
}
public Skin() {
registerAreas();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Dimension finalSize = getSize();
Point finalLocation = getLocation();
File f = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
try {
PrintWriter out = new PrintWriter(new FileWriter(f));
out.println("" + finalSize.width);
out.println("" + finalSize.height);
out.println("" + finalLocation.x);
out.println("" + finalLocation.y);
out.close();
List<Object> list = ComponentRegistry.getRegistry().getComponentsList();
for(Object obj: list)
{
if ( obj instanceof Closable)
((Closable)obj).closing();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
private void setApplicationTitle() {
MessageFormat format = new MessageFormat(System.getProperty("application.title"));
Object[] version = { VERSION };
appTitle = format.format(version);
setTitle(appTitle);
}
private String appTitle = "";
public String getApplicationTitle() {
return appTitle;
}
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
setApplicationTitle();
statusBar.setBorder(BorderFactory.createEmptyBorder(3, 10, 3, 10));
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
JPanel statusBarPanel = new JPanel();
statusBarPanel.setLayout(new BorderLayout() );
statusBarPanel.add(statusBar, BorderLayout.EAST);
contentPane.add(statusBarPanel, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 6732252343409902879L;
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
final String RCM_DIALOG = "rcm-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG);
contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 3053589598512384113L;
public void actionPerformed(ActionEvent event) {
loadRCM();
}
});
ActionListener timerAction = new ActionListener() {
final private static long MEGABYTE = 1024*1024;
public void actionPerformed(ActionEvent evt) {
Runtime runtime = Runtime.getRuntime();
long total = runtime.totalMemory();
long free = runtime.freeMemory();
long used = total-free;
setStatusBarText("Memory: "+used/MEGABYTE+"M Used, "+free/MEGABYTE+"M Free, "+total/MEGABYTE+"M Total.");
}
};
if(showMemoryUsage)
new Timer(10000, timerAction).start();
}
private boolean showMemoryUsage = true;
private static class DialogResult {
public boolean cancelled = false;
}
void loadRCM(){
ComponentConfigurationManagerWindow2.load();
}
void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class<?>>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Class<?> type: acceptors) {
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
private static final long serialVersionUID = -5117126504179347748L;
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
if (getHighlightedIndex() == -1 ){
return;
}
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
boolean found = false;
for (String key : areas.keySet()) {
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
// areas.put(TOOL_AREA, jToolBar); // this is not used any more
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
@SuppressWarnings("rawtypes")
@Override
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
private boolean docked = true;
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
// no-op
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
if(index>=0) {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
}
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
public void setStatusBarText(String text) {
statusBar.setText(text);
}
private void addAppropriateComponents(Set<Class<?>> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Component component : visualRegistry.keySet()) {
if (visualRegistry.get(component).equals(screenRegion)) {
Class<?> mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
public void resetSelectorTabOrder() {
selectLastComponent(GUIFramework.SELECTION_AREA, "Markers");
}
public void initWelcomeScreen() {
PropertiesManager pm = PropertiesManager.getInstance();
try {
String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES);
if(showWelcomeScreen.equalsIgnoreCase(YES)) {
showWelcomeScreen();
} else {
hideWelcomeScreen();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
static private final String welcomeScreenClassName = "org.geworkbench.engine.WelcomeScreen";
public void showWelcomeScreen() {
- Class<?> welcomeScreenClass;
- try {
- welcomeScreenClass = Class.forName(welcomeScreenClassName);
- } catch (ClassNotFoundException e1) {
- e1.printStackTrace();
- return;
- }
- ComponentRegistry.getRegistry().addAcceptor(null, welcomeScreenClass);
+ Class<?> welcomeScreenClass = org.geworkbench.engine.WelcomeScreen.class;
+ ComponentRegistry.getRegistry().addAcceptor(null, org.geworkbench.engine.WelcomeScreen.class);
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
acceptors.add(welcomeScreenClass);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
+ PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(welcomeScreenClass);
+ selectLastComponent(GUIFramework.VISUAL_AREA, desc.getLabel());
contentPane.revalidate();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
YES);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(false);
}
public void hideWelcomeScreen() {
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
for (Class<?> componentClass : ComponentRegistry.getRegistry().getAcceptors(null)) {
if ( componentClass.getName().equals(welcomeScreenClassName) ) {
acceptors.remove(componentClass);
break;
}
}
ComponentRegistry.getRegistry().removeAcceptor(null, welcomeScreenClassName);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
contentPane.repaint();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
NO);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(true);
}
private static final String WELCOME_SCREEN_KEY = "Welcome Screen ";
public static final String VERSION = System.getProperty("application.version");
}
| false | true | private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
setApplicationTitle();
statusBar.setBorder(BorderFactory.createEmptyBorder(3, 10, 3, 10));
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
JPanel statusBarPanel = new JPanel();
statusBarPanel.setLayout(new BorderLayout() );
statusBarPanel.add(statusBar, BorderLayout.EAST);
contentPane.add(statusBarPanel, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 6732252343409902879L;
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
final String RCM_DIALOG = "rcm-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG);
contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 3053589598512384113L;
public void actionPerformed(ActionEvent event) {
loadRCM();
}
});
ActionListener timerAction = new ActionListener() {
final private static long MEGABYTE = 1024*1024;
public void actionPerformed(ActionEvent evt) {
Runtime runtime = Runtime.getRuntime();
long total = runtime.totalMemory();
long free = runtime.freeMemory();
long used = total-free;
setStatusBarText("Memory: "+used/MEGABYTE+"M Used, "+free/MEGABYTE+"M Free, "+total/MEGABYTE+"M Total.");
}
};
if(showMemoryUsage)
new Timer(10000, timerAction).start();
}
private boolean showMemoryUsage = true;
private static class DialogResult {
public boolean cancelled = false;
}
void loadRCM(){
ComponentConfigurationManagerWindow2.load();
}
void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class<?>>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Class<?> type: acceptors) {
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
private static final long serialVersionUID = -5117126504179347748L;
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
if (getHighlightedIndex() == -1 ){
return;
}
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
boolean found = false;
for (String key : areas.keySet()) {
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
// areas.put(TOOL_AREA, jToolBar); // this is not used any more
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
@SuppressWarnings("rawtypes")
@Override
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
private boolean docked = true;
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
// no-op
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
if(index>=0) {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
}
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
public void setStatusBarText(String text) {
statusBar.setText(text);
}
private void addAppropriateComponents(Set<Class<?>> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Component component : visualRegistry.keySet()) {
if (visualRegistry.get(component).equals(screenRegion)) {
Class<?> mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
public void resetSelectorTabOrder() {
selectLastComponent(GUIFramework.SELECTION_AREA, "Markers");
}
public void initWelcomeScreen() {
PropertiesManager pm = PropertiesManager.getInstance();
try {
String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES);
if(showWelcomeScreen.equalsIgnoreCase(YES)) {
showWelcomeScreen();
} else {
hideWelcomeScreen();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
static private final String welcomeScreenClassName = "org.geworkbench.engine.WelcomeScreen";
public void showWelcomeScreen() {
Class<?> welcomeScreenClass;
try {
welcomeScreenClass = Class.forName(welcomeScreenClassName);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
return;
}
ComponentRegistry.getRegistry().addAcceptor(null, welcomeScreenClass);
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
acceptors.add(welcomeScreenClass);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
YES);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(false);
}
public void hideWelcomeScreen() {
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
for (Class<?> componentClass : ComponentRegistry.getRegistry().getAcceptors(null)) {
if ( componentClass.getName().equals(welcomeScreenClassName) ) {
acceptors.remove(componentClass);
break;
}
}
ComponentRegistry.getRegistry().removeAcceptor(null, welcomeScreenClassName);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
contentPane.repaint();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
NO);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(true);
}
private static final String WELCOME_SCREEN_KEY = "Welcome Screen ";
public static final String VERSION = System.getProperty("application.version");
}
| private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
setApplicationTitle();
statusBar.setBorder(BorderFactory.createEmptyBorder(3, 10, 3, 10));
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
JPanel statusBarPanel = new JPanel();
statusBarPanel.setLayout(new BorderLayout() );
statusBarPanel.add(statusBar, BorderLayout.EAST);
contentPane.add(statusBarPanel, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 6732252343409902879L;
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
final String RCM_DIALOG = "rcm-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG);
contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 3053589598512384113L;
public void actionPerformed(ActionEvent event) {
loadRCM();
}
});
ActionListener timerAction = new ActionListener() {
final private static long MEGABYTE = 1024*1024;
public void actionPerformed(ActionEvent evt) {
Runtime runtime = Runtime.getRuntime();
long total = runtime.totalMemory();
long free = runtime.freeMemory();
long used = total-free;
setStatusBarText("Memory: "+used/MEGABYTE+"M Used, "+free/MEGABYTE+"M Free, "+total/MEGABYTE+"M Total.");
}
};
if(showMemoryUsage)
new Timer(10000, timerAction).start();
}
private boolean showMemoryUsage = true;
private static class DialogResult {
public boolean cancelled = false;
}
void loadRCM(){
ComponentConfigurationManagerWindow2.load();
}
void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class<?>>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Class<?> type: acceptors) {
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
private static final long serialVersionUID = -5117126504179347748L;
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
if (getHighlightedIndex() == -1 ){
return;
}
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
boolean found = false;
for (String key : areas.keySet()) {
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
// areas.put(TOOL_AREA, jToolBar); // this is not used any more
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
@SuppressWarnings("rawtypes")
@Override
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
private boolean docked = true;
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
// no-op
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
if(index>=0) {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
}
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
public void setStatusBarText(String text) {
statusBar.setText(text);
}
private void addAppropriateComponents(Set<Class<?>> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Component component : visualRegistry.keySet()) {
if (visualRegistry.get(component).equals(screenRegion)) {
Class<?> mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
public void resetSelectorTabOrder() {
selectLastComponent(GUIFramework.SELECTION_AREA, "Markers");
}
public void initWelcomeScreen() {
PropertiesManager pm = PropertiesManager.getInstance();
try {
String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES);
if(showWelcomeScreen.equalsIgnoreCase(YES)) {
showWelcomeScreen();
} else {
hideWelcomeScreen();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
static private final String welcomeScreenClassName = "org.geworkbench.engine.WelcomeScreen";
public void showWelcomeScreen() {
Class<?> welcomeScreenClass = org.geworkbench.engine.WelcomeScreen.class;
ComponentRegistry.getRegistry().addAcceptor(null, org.geworkbench.engine.WelcomeScreen.class);
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
acceptors.add(welcomeScreenClass);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(welcomeScreenClass);
selectLastComponent(GUIFramework.VISUAL_AREA, desc.getLabel());
contentPane.revalidate();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
YES);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(false);
}
public void hideWelcomeScreen() {
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
for (Class<?> componentClass : ComponentRegistry.getRegistry().getAcceptors(null)) {
if ( componentClass.getName().equals(welcomeScreenClassName) ) {
acceptors.remove(componentClass);
break;
}
}
ComponentRegistry.getRegistry().removeAcceptor(null, welcomeScreenClassName);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
contentPane.repaint();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
NO);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(true);
}
private static final String WELCOME_SCREEN_KEY = "Welcome Screen ";
public static final String VERSION = System.getProperty("application.version");
}
|
diff --git a/main/src/cgeo/geocaching/files/GPXParser.java b/main/src/cgeo/geocaching/files/GPXParser.java
index 7870a168c..7cc8fbca2 100644
--- a/main/src/cgeo/geocaching/files/GPXParser.java
+++ b/main/src/cgeo/geocaching/files/GPXParser.java
@@ -1,834 +1,834 @@
package cgeo.geocaching.files;
import cgeo.geocaching.LogEntry;
import cgeo.geocaching.R;
import cgeo.geocaching.StoredList;
import cgeo.geocaching.cgCache;
import cgeo.geocaching.cgTrackable;
import cgeo.geocaching.cgWaypoint;
import cgeo.geocaching.cgeoapplication;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.Log;
import org.apache.commons.lang3.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.sax.StartElementListener;
import android.util.Xml;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class GPXParser extends FileParser {
private static final SimpleDateFormat formatSimple = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // 2010-04-20T07:00:00
private static final SimpleDateFormat formatSimpleZ = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // 2010-04-20T07:00:00Z
private static final SimpleDateFormat formatTimezone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); // 2010-04-20T01:01:03-04:00
/**
* Attention: case sensitive geocode pattern to avoid matching normal words in the name or description of the cache.
*/
private static final Pattern patternGeocode = Pattern.compile("([A-Z][0-9A-Z]+)");
private static final Pattern patternGuid = Pattern.compile(".*" + Pattern.quote("guid=") + "([0-9a-z\\-]+)", Pattern.CASE_INSENSITIVE);
/**
* supported groundspeak extensions of the GPX format
*/
private static final String[] nsGCList = new String[] {
"http://www.groundspeak.com/cache/1/1", // PQ 1.1
"http://www.groundspeak.com/cache/1/0/1", // PQ 1.0.1
"http://www.groundspeak.com/cache/1/0", // PQ 1.0
};
/**
* supported GSAK extension of the GPX format
*/
private static final String[] GSAK_NS = new String[] {
"http://www.gsak.net/xmlv1/5",
"http://www.gsak.net/xmlv1/6"
};
private static final Pattern PATTERN_MILLISECONDS = Pattern.compile("\\.\\d{3,7}");
private int listId = StoredList.STANDARD_LIST_ID;
final protected String namespace;
final private String version;
private cgCache cache;
private cgTrackable trackable = new cgTrackable();
private LogEntry log = null;
private String type = null;
private String sym = null;
private String name = null;
private String cmt = null;
private String desc = null;
protected final String[] userData = new String[5]; // take 5 cells, that makes indexing 1..4 easier
/**
* Parser result. Maps geocode to cache.
*/
private final Map<String, cgCache> result = new HashMap<String, cgCache>(500);
private ProgressInputStream progressStream;
private final class UserDataListener implements EndTextElementListener {
private final int index;
public UserDataListener(int index) {
this.index = index;
}
@Override
public void end(String user) {
userData[index] = validate(user);
}
}
private static final class CacheAttributeTranslator {
// List of cache attributes matching IDs used in GPX files.
// The ID is represented by the position of the String in the array.
// Strings are not used as text but as resource IDs of strings, just to be aware of changes
// made in strings.xml which then will lead to compile errors here and not to runtime errors.
private static final int[] CACHE_ATTRIBUTES = {
-1, // 0
R.string.attribute_dogs_yes, // 1
R.string.attribute_fee_yes, // 2
R.string.attribute_rappelling_yes, // 3
R.string.attribute_boat_yes, // 4
R.string.attribute_scuba_yes, // 5
R.string.attribute_kids_yes, // 6
R.string.attribute_onehour_yes, // 7
R.string.attribute_scenic_yes, // 8
R.string.attribute_hiking_yes, // 9
R.string.attribute_climbing_yes, // 10
R.string.attribute_wading_yes, // 11
R.string.attribute_swimming_yes, // 12
R.string.attribute_available_yes, // 13
R.string.attribute_night_yes, // 14
R.string.attribute_winter_yes, // 15
-1, // 16
R.string.attribute_poisonoak_yes, // 17
R.string.attribute_dangerousanimals_yes, // 18
R.string.attribute_ticks_yes, // 19
R.string.attribute_mine_yes, // 20
R.string.attribute_cliff_yes, // 21
R.string.attribute_hunting_yes, // 22
R.string.attribute_danger_yes, // 23
R.string.attribute_wheelchair_yes, // 24
R.string.attribute_parking_yes, // 25
R.string.attribute_public_yes, // 26
R.string.attribute_water_yes, // 27
R.string.attribute_restrooms_yes, // 28
R.string.attribute_phone_yes, // 29
R.string.attribute_picnic_yes, // 30
R.string.attribute_camping_yes, // 31
R.string.attribute_bicycles_yes, // 32
R.string.attribute_motorcycles_yes, // 33
R.string.attribute_quads_yes, // 34
R.string.attribute_jeeps_yes, // 35
R.string.attribute_snowmobiles_yes, // 36
R.string.attribute_horses_yes, // 37
R.string.attribute_campfires_yes, // 38
R.string.attribute_thorn_yes, // 39
R.string.attribute_stealth_yes, // 40
R.string.attribute_stroller_yes, // 41
R.string.attribute_firstaid_yes, // 42
R.string.attribute_cow_yes, // 43
R.string.attribute_flashlight_yes, // 44
R.string.attribute_landf_yes, // 45
R.string.attribute_rv_yes, // 46
R.string.attribute_field_puzzle_yes, // 47
R.string.attribute_uv_yes, // 48
R.string.attribute_snowshoes_yes, // 49
R.string.attribute_skiis_yes, // 50
R.string.attribute_s_tool_yes, // 51
R.string.attribute_nightcache_yes, // 52
R.string.attribute_parkngrab_yes, // 53
R.string.attribute_abandonedbuilding_yes, // 54
R.string.attribute_hike_short_yes, // 55
R.string.attribute_hike_med_yes, // 56
R.string.attribute_hike_long_yes, // 57
R.string.attribute_fuel_yes, // 58
R.string.attribute_food_yes, // 59
R.string.attribute_wirelessbeacon_yes, // 60
R.string.attribute_partnership_yes, // 61
R.string.attribute_seasonal_yes, // 62
R.string.attribute_touristok_yes, // 63
R.string.attribute_treeclimbing_yes, // 64
R.string.attribute_frontyard_yes, // 65
R.string.attribute_teamwork_yes, // 66
};
private static final String YES = "_yes";
private static final String NO = "_no";
private static final Pattern BASENAME_PATTERN = Pattern.compile("^.*attribute_(.*)(_yes|_no)");
// map GPX-Attribute-Id to baseName
public static String getBaseName(final int id) {
// get String out of array
if (CACHE_ATTRIBUTES.length <= id) {
return null;
}
final int stringId = CACHE_ATTRIBUTES[id];
if (stringId == -1) {
return null; // id not found
}
// get text for string
String stringName;
try {
stringName = cgeoapplication.getInstance().getResources().getResourceName(stringId);
} catch (NullPointerException e) {
return null;
}
if (stringName == null) {
return null;
}
// cut out baseName
final Matcher m = BASENAME_PATTERN.matcher(stringName);
if (!m.matches()) {
return null;
}
return m.group(1);
}
// @return baseName + "_yes" or "_no" e.g. "food_no" or "uv_yes"
public static String getInternalId(final int attributeId, final boolean active) {
final String baseName = CacheAttributeTranslator.getBaseName(attributeId);
if (baseName == null) {
return null;
}
return baseName + (active ? YES : NO);
}
}
protected GPXParser(int listIdIn, String namespaceIn, String versionIn) {
listId = listIdIn;
namespace = namespaceIn;
version = versionIn;
}
static Date parseDate(String inputUntrimmed) throws ParseException {
String input = inputUntrimmed.trim();
// remove milli seconds to reduce number of needed patterns
final Matcher matcher = PATTERN_MILLISECONDS.matcher(input);
input = matcher.replaceFirst("");
if (input.contains("Z")) {
return formatSimpleZ.parse(input);
}
if (StringUtils.countMatches(input, ":") == 3) {
final String removeColon = input.substring(0, input.length() - 3) + input.substring(input.length() - 2);
return formatTimezone.parse(removeColon);
}
return formatSimple.parse(input);
}
@Override
public Collection<cgCache> parse(final InputStream stream, final CancellableHandler progressHandler) throws IOException, ParserException {
resetCache();
final RootElement root = new RootElement(namespace, "gpx");
final Element waypoint = root.getChild(namespace, "wpt");
// waypoint - attributes
waypoint.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) {
cache.setCoords(new Geopoint(Double.valueOf(attrs.getValue("lat")),
Double.valueOf(attrs.getValue("lon"))));
}
} catch (Exception e) {
Log.w("Failed to parse waypoint's latitude and/or longitude.");
}
}
});
// waypoint
waypoint.setEndElementListener(new EndElementListener() {
@Override
public void end() {
// try to find geocode somewhere else
if (StringUtils.isBlank(cache.getGeocode())) {
findGeoCode(name);
findGeoCode(desc);
findGeoCode(cmt);
}
// take the name as code, if nothing else is available
if (StringUtils.isBlank(cache.getGeocode())) {
if (StringUtils.isNotBlank(name)) {
cache.setGeocode(name.trim().toUpperCase());
}
}
if (StringUtils.isNotBlank(cache.getGeocode())
&& cache.getCoords() != null
&& ((type == null && sym == null)
|| StringUtils.contains(type, "geocache")
|| StringUtils.contains(sym, "geocache"))) {
fixCache(cache);
cache.setListId(listId);
cache.setDetailed(true);
createNoteFromGSAKUserdata();
final String key = cache.getGeocode();
if (result.containsKey(key)) {
Log.w("Duplicate geocode during GPX import: " + key);
}
result.put(key, cache);
showProgressMessage(progressHandler, progressStream.getProgress());
} else if (StringUtils.isNotBlank(cache.getName())
&& cache.getCoords() != null
&& StringUtils.contains(type, "waypoint")) {
addWaypointToCache();
}
resetCache();
}
private void addWaypointToCache() {
fixCache(cache);
if (cache.getName().length() > 2) {
final String cacheGeocodeForWaypoint = "GC" + cache.getName().substring(2).toUpperCase();
// lookup cache for waypoint in already parsed caches
final cgCache cacheForWaypoint = result.get(cacheGeocodeForWaypoint);
if (cacheForWaypoint != null) {
final cgWaypoint waypoint = new cgWaypoint(cache.getShortdesc(), convertWaypointSym2Type(sym), false);
waypoint.setId(-1);
waypoint.setGeocode(cacheGeocodeForWaypoint);
waypoint.setPrefix(cache.getName().substring(0, 2));
waypoint.setLookup("---");
// there is no lookup code in gpx file
waypoint.setCoords(cache.getCoords());
waypoint.setNote(cache.getDescription());
ArrayList<cgWaypoint> mergedWayPoints = new ArrayList<cgWaypoint>();
mergedWayPoints.addAll(cacheForWaypoint.getWaypoints());
cgWaypoint.mergeWayPoints(mergedWayPoints, Collections.singletonList(waypoint), true);
cacheForWaypoint.setWaypoints(mergedWayPoints, false);
result.put(cacheGeocodeForWaypoint, cacheForWaypoint);
showProgressMessage(progressHandler, progressStream.getProgress());
}
}
}
});
// waypoint.time
waypoint.getChild(namespace, "time").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setHidden(parseDate(body));
} catch (Exception e) {
Log.w("Failed to parse cache date: " + e.toString());
}
}
});
// waypoint.getName()
waypoint.getChild(namespace, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
name = body;
final String content = body.trim();
cache.setName(content);
findGeoCode(cache.getName());
}
});
// waypoint.desc
waypoint.getChild(namespace, "desc").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
desc = body;
cache.setShortdesc(validate(body));
}
});
// waypoint.cmt
waypoint.getChild(namespace, "cmt").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cmt = body;
cache.setDescription(validate(body));
}
});
// waypoint.getType()
waypoint.getChild(namespace, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String[] content = body.split("\\|");
if (content.length > 0) {
type = content[0].toLowerCase().trim();
}
}
});
// waypoint.sym
waypoint.getChild(namespace, "sym").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(final String body) {
sym = body.toLowerCase();
if (sym.contains("geocache") && sym.contains("found")) {
cache.setFound(true);
}
}
});
// waypoint.url
waypoint.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String url) {
final Matcher matcher = patternGuid.matcher(url);
if (matcher.matches()) {
final String guid = matcher.group(1);
if (StringUtils.isNotBlank(guid)) {
cache.setGuid(guid);
}
}
}
});
// for GPX 1.0, cache info comes from waypoint node (so called private children,
// for GPX 1.1 from extensions node
final Element cacheParent = getCacheParent(waypoint);
// GSAK extensions
for (String gsakNamespace : GSAK_NS) {
final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension");
gsak.getChild(gsakNamespace, "Watch").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String watchList) {
cache.setOnWatchlist(Boolean.valueOf(watchList.trim()));
}
});
gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1));
for (int i = 2; i <= 4; i++) {
gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i));
}
}
// 3 different versions of the GC schema
for (String nsGC : nsGCList) {
// waypoints.cache
final Element gcCache = cacheParent.getChild(nsGC, "cache");
gcCache.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1) {
cache.setCacheId(attrs.getValue("id"));
}
if (attrs.getIndex("archived") > -1) {
cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true"));
}
if (attrs.getIndex("available") > -1) {
cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true"));
}
} catch (Exception e) {
Log.w("Failed to parse cache attributes.");
}
}
});
// waypoint.cache.getName()
gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheName) {
cache.setName(validate(cacheName));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheOwner) {
cache.setOwner(validate(cacheOwner));
}
});
// waypoint.cache.getType()
gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setType(CacheType.getByPattern(validate(body.toLowerCase())));
}
});
// waypoint.cache.container
gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setSize(CacheSize.getById(validate(body.toLowerCase())));
}
});
// waypoint.cache.getAttributes()
// @see issue #299
// <groundspeak:attributes>
// <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
// <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
// where inc = 0 => _no, inc = 1 => _yes
// IDs see array CACHE_ATTRIBUTES
final Element gcAttributes = gcCache.getChild(nsGC, "attributes");
// waypoint.cache.attribute
final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");
gcAttribute.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
int attributeId = Integer.parseInt(attrs.getValue("id"));
boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
if (internalId != null) {
cache.addAttribute(internalId);
}
}
} catch (NumberFormatException e) {
// nothing
}
}
});
// waypoint.cache.getDifficulty()
gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setDifficulty(Float.parseFloat(body));
} catch (NumberFormatException e) {
Log.w("Failed to parse difficulty: " + e.toString());
}
}
});
// waypoint.cache.getTerrain()
gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setTerrain(Float.parseFloat(body));
} catch (NumberFormatException e) {
Log.w("Failed to parse terrain: " + e.toString());
}
}
});
// waypoint.cache.country
gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String country) {
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(country));
} else {
cache.setLocation(cache.getLocation() + ", " + country.trim());
}
}
});
// waypoint.cache.state
gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String state) {
String trimmedState = state.trim();
if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(state));
} else {
cache.setLocation(trimmedState + ", " + cache.getLocation());
}
}
}
});
// waypoint.cache.encoded_hints
gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String encoded) {
cache.setHint(validate(encoded));
}
});
gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String shortDesc) {
cache.setShortdesc(validate(shortDesc));
}
});
gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String desc) {
cache.setDescription(validate(desc));
}
});
// waypoint.cache.travelbugs
final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");
// waypoint.cache.travelbug
final Element gcTB = gcTBs.getChild(nsGC, "travelbug");
// waypoint.cache.travelbugs.travelbug
gcTB.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
trackable = new cgTrackable();
try {
if (attrs.getIndex("ref") > -1) {
trackable.setGeocode(attrs.getValue("ref").toUpperCase());
}
} catch (Exception e) {
// nothing
}
}
});
gcTB.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) {
if (cache.getInventory() == null) {
cache.setInventory(new ArrayList<cgTrackable>());
}
cache.getInventory().add(trackable);
}
}
});
// waypoint.cache.travelbugs.travelbug.getName()
gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String tbName) {
trackable.setName(validate(tbName));
}
});
// waypoint.cache.logs
final Element gcLogs = gcCache.getChild(nsGC, "logs");
// waypoint.cache.log
final Element gcLog = gcLogs.getChild(nsGC, "log");
gcLog.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
log = new LogEntry("", 0, LogType.LOG_UNKNOWN, "");
try {
if (attrs.getIndex("id") > -1) {
log.id = Integer.parseInt(attrs.getValue("id"));
}
} catch (Exception e) {
// nothing
}
}
});
gcLog.setEndElementListener(new EndElementListener() {
@Override
public void end() {
- if (StringUtils.isNotBlank(log.log)) {
+ if (log.type != LogType.LOG_UNKNOWN) {
cache.appendLog(log);
}
}
});
// waypoint.cache.logs.log.date
gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
log.date = parseDate(body).getTime();
} catch (Exception e) {
Log.w("Failed to parse log date: " + e.toString());
}
}
});
// waypoint.cache.logs.log.getType()
gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String logType = validate(body).toLowerCase();
log.type = LogType.getByType(logType);
}
});
// waypoint.cache.logs.log.finder
gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String finderName) {
log.author = validate(finderName);
}
});
// waypoint.cache.logs.log.text
gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String logText) {
log.log = validate(logText);
}
});
}
try {
progressStream = new ProgressInputStream(stream);
Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
return result.values();
} catch (SAXException e) {
Log.e("Cannot parse .gpx file as GPX " + version + ": could not parse XML - " + e.toString());
throw new ParserException("Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
}
}
/**
* GPX 1.0 and 1.1 use different XML elements to put the cache into, therefore needs to be overwritten in the
* version specific subclasses
*
* @param waypoint
* @return
*/
protected abstract Element getCacheParent(Element waypoint);
protected static String validate(String input) {
if ("nil".equalsIgnoreCase(input)) {
return "";
}
return input.trim();
}
static WaypointType convertWaypointSym2Type(final String sym) {
if ("parking area".equalsIgnoreCase(sym)) {
return WaypointType.PARKING;
} else if ("stages of a multicache".equalsIgnoreCase(sym)) {
return WaypointType.STAGE;
} else if ("question to answer".equalsIgnoreCase(sym)) {
return WaypointType.PUZZLE;
} else if ("trailhead".equalsIgnoreCase(sym)) {
return WaypointType.TRAILHEAD;
} else if ("final location".equalsIgnoreCase(sym)) {
return WaypointType.FINAL;
} else {
return WaypointType.WAYPOINT;
}
}
private void findGeoCode(final String input) {
if (input == null || StringUtils.isNotBlank(cache.getGeocode())) {
return;
}
final String trimmed = input.trim();
final Matcher matcherGeocode = patternGeocode.matcher(trimmed);
if (matcherGeocode.find()) {
final String geocode = matcherGeocode.group(1);
// a geocode should not be part of a word
if (geocode.length() == trimmed.length() || Character.isWhitespace(trimmed.charAt(geocode.length()))) {
if (ConnectorFactory.canHandle(geocode)) {
cache.setGeocode(geocode);
}
}
}
}
/**
* reset all fields that are used to store cache fields over the duration of parsing a single cache
*/
private void resetCache() {
type = null;
sym = null;
name = null;
desc = null;
cmt = null;
cache = new cgCache();
cache.setReliableLatLon(true);
for (int i = 0; i < userData.length; i++) {
userData[i] = null;
}
}
/**
* create a cache note from the UserData1 to UserData4 fields supported by GSAK
*/
private void createNoteFromGSAKUserdata() {
if (StringUtils.isBlank(cache.getPersonalNote())) {
final StringBuilder buffer = new StringBuilder();
for (final String anUserData : userData) {
if (StringUtils.isNotBlank(anUserData)) {
buffer.append(' ').append(anUserData);
}
}
final String note = buffer.toString().trim();
if (StringUtils.isNotBlank(note)) {
cache.setPersonalNote(note);
}
}
}
}
| true | true | public Collection<cgCache> parse(final InputStream stream, final CancellableHandler progressHandler) throws IOException, ParserException {
resetCache();
final RootElement root = new RootElement(namespace, "gpx");
final Element waypoint = root.getChild(namespace, "wpt");
// waypoint - attributes
waypoint.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) {
cache.setCoords(new Geopoint(Double.valueOf(attrs.getValue("lat")),
Double.valueOf(attrs.getValue("lon"))));
}
} catch (Exception e) {
Log.w("Failed to parse waypoint's latitude and/or longitude.");
}
}
});
// waypoint
waypoint.setEndElementListener(new EndElementListener() {
@Override
public void end() {
// try to find geocode somewhere else
if (StringUtils.isBlank(cache.getGeocode())) {
findGeoCode(name);
findGeoCode(desc);
findGeoCode(cmt);
}
// take the name as code, if nothing else is available
if (StringUtils.isBlank(cache.getGeocode())) {
if (StringUtils.isNotBlank(name)) {
cache.setGeocode(name.trim().toUpperCase());
}
}
if (StringUtils.isNotBlank(cache.getGeocode())
&& cache.getCoords() != null
&& ((type == null && sym == null)
|| StringUtils.contains(type, "geocache")
|| StringUtils.contains(sym, "geocache"))) {
fixCache(cache);
cache.setListId(listId);
cache.setDetailed(true);
createNoteFromGSAKUserdata();
final String key = cache.getGeocode();
if (result.containsKey(key)) {
Log.w("Duplicate geocode during GPX import: " + key);
}
result.put(key, cache);
showProgressMessage(progressHandler, progressStream.getProgress());
} else if (StringUtils.isNotBlank(cache.getName())
&& cache.getCoords() != null
&& StringUtils.contains(type, "waypoint")) {
addWaypointToCache();
}
resetCache();
}
private void addWaypointToCache() {
fixCache(cache);
if (cache.getName().length() > 2) {
final String cacheGeocodeForWaypoint = "GC" + cache.getName().substring(2).toUpperCase();
// lookup cache for waypoint in already parsed caches
final cgCache cacheForWaypoint = result.get(cacheGeocodeForWaypoint);
if (cacheForWaypoint != null) {
final cgWaypoint waypoint = new cgWaypoint(cache.getShortdesc(), convertWaypointSym2Type(sym), false);
waypoint.setId(-1);
waypoint.setGeocode(cacheGeocodeForWaypoint);
waypoint.setPrefix(cache.getName().substring(0, 2));
waypoint.setLookup("---");
// there is no lookup code in gpx file
waypoint.setCoords(cache.getCoords());
waypoint.setNote(cache.getDescription());
ArrayList<cgWaypoint> mergedWayPoints = new ArrayList<cgWaypoint>();
mergedWayPoints.addAll(cacheForWaypoint.getWaypoints());
cgWaypoint.mergeWayPoints(mergedWayPoints, Collections.singletonList(waypoint), true);
cacheForWaypoint.setWaypoints(mergedWayPoints, false);
result.put(cacheGeocodeForWaypoint, cacheForWaypoint);
showProgressMessage(progressHandler, progressStream.getProgress());
}
}
}
});
// waypoint.time
waypoint.getChild(namespace, "time").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setHidden(parseDate(body));
} catch (Exception e) {
Log.w("Failed to parse cache date: " + e.toString());
}
}
});
// waypoint.getName()
waypoint.getChild(namespace, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
name = body;
final String content = body.trim();
cache.setName(content);
findGeoCode(cache.getName());
}
});
// waypoint.desc
waypoint.getChild(namespace, "desc").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
desc = body;
cache.setShortdesc(validate(body));
}
});
// waypoint.cmt
waypoint.getChild(namespace, "cmt").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cmt = body;
cache.setDescription(validate(body));
}
});
// waypoint.getType()
waypoint.getChild(namespace, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String[] content = body.split("\\|");
if (content.length > 0) {
type = content[0].toLowerCase().trim();
}
}
});
// waypoint.sym
waypoint.getChild(namespace, "sym").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(final String body) {
sym = body.toLowerCase();
if (sym.contains("geocache") && sym.contains("found")) {
cache.setFound(true);
}
}
});
// waypoint.url
waypoint.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String url) {
final Matcher matcher = patternGuid.matcher(url);
if (matcher.matches()) {
final String guid = matcher.group(1);
if (StringUtils.isNotBlank(guid)) {
cache.setGuid(guid);
}
}
}
});
// for GPX 1.0, cache info comes from waypoint node (so called private children,
// for GPX 1.1 from extensions node
final Element cacheParent = getCacheParent(waypoint);
// GSAK extensions
for (String gsakNamespace : GSAK_NS) {
final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension");
gsak.getChild(gsakNamespace, "Watch").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String watchList) {
cache.setOnWatchlist(Boolean.valueOf(watchList.trim()));
}
});
gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1));
for (int i = 2; i <= 4; i++) {
gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i));
}
}
// 3 different versions of the GC schema
for (String nsGC : nsGCList) {
// waypoints.cache
final Element gcCache = cacheParent.getChild(nsGC, "cache");
gcCache.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1) {
cache.setCacheId(attrs.getValue("id"));
}
if (attrs.getIndex("archived") > -1) {
cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true"));
}
if (attrs.getIndex("available") > -1) {
cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true"));
}
} catch (Exception e) {
Log.w("Failed to parse cache attributes.");
}
}
});
// waypoint.cache.getName()
gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheName) {
cache.setName(validate(cacheName));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheOwner) {
cache.setOwner(validate(cacheOwner));
}
});
// waypoint.cache.getType()
gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setType(CacheType.getByPattern(validate(body.toLowerCase())));
}
});
// waypoint.cache.container
gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setSize(CacheSize.getById(validate(body.toLowerCase())));
}
});
// waypoint.cache.getAttributes()
// @see issue #299
// <groundspeak:attributes>
// <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
// <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
// where inc = 0 => _no, inc = 1 => _yes
// IDs see array CACHE_ATTRIBUTES
final Element gcAttributes = gcCache.getChild(nsGC, "attributes");
// waypoint.cache.attribute
final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");
gcAttribute.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
int attributeId = Integer.parseInt(attrs.getValue("id"));
boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
if (internalId != null) {
cache.addAttribute(internalId);
}
}
} catch (NumberFormatException e) {
// nothing
}
}
});
// waypoint.cache.getDifficulty()
gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setDifficulty(Float.parseFloat(body));
} catch (NumberFormatException e) {
Log.w("Failed to parse difficulty: " + e.toString());
}
}
});
// waypoint.cache.getTerrain()
gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setTerrain(Float.parseFloat(body));
} catch (NumberFormatException e) {
Log.w("Failed to parse terrain: " + e.toString());
}
}
});
// waypoint.cache.country
gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String country) {
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(country));
} else {
cache.setLocation(cache.getLocation() + ", " + country.trim());
}
}
});
// waypoint.cache.state
gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String state) {
String trimmedState = state.trim();
if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(state));
} else {
cache.setLocation(trimmedState + ", " + cache.getLocation());
}
}
}
});
// waypoint.cache.encoded_hints
gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String encoded) {
cache.setHint(validate(encoded));
}
});
gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String shortDesc) {
cache.setShortdesc(validate(shortDesc));
}
});
gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String desc) {
cache.setDescription(validate(desc));
}
});
// waypoint.cache.travelbugs
final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");
// waypoint.cache.travelbug
final Element gcTB = gcTBs.getChild(nsGC, "travelbug");
// waypoint.cache.travelbugs.travelbug
gcTB.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
trackable = new cgTrackable();
try {
if (attrs.getIndex("ref") > -1) {
trackable.setGeocode(attrs.getValue("ref").toUpperCase());
}
} catch (Exception e) {
// nothing
}
}
});
gcTB.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) {
if (cache.getInventory() == null) {
cache.setInventory(new ArrayList<cgTrackable>());
}
cache.getInventory().add(trackable);
}
}
});
// waypoint.cache.travelbugs.travelbug.getName()
gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String tbName) {
trackable.setName(validate(tbName));
}
});
// waypoint.cache.logs
final Element gcLogs = gcCache.getChild(nsGC, "logs");
// waypoint.cache.log
final Element gcLog = gcLogs.getChild(nsGC, "log");
gcLog.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
log = new LogEntry("", 0, LogType.LOG_UNKNOWN, "");
try {
if (attrs.getIndex("id") > -1) {
log.id = Integer.parseInt(attrs.getValue("id"));
}
} catch (Exception e) {
// nothing
}
}
});
gcLog.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (StringUtils.isNotBlank(log.log)) {
cache.appendLog(log);
}
}
});
// waypoint.cache.logs.log.date
gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
log.date = parseDate(body).getTime();
} catch (Exception e) {
Log.w("Failed to parse log date: " + e.toString());
}
}
});
// waypoint.cache.logs.log.getType()
gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String logType = validate(body).toLowerCase();
log.type = LogType.getByType(logType);
}
});
// waypoint.cache.logs.log.finder
gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String finderName) {
log.author = validate(finderName);
}
});
// waypoint.cache.logs.log.text
gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String logText) {
log.log = validate(logText);
}
});
}
try {
progressStream = new ProgressInputStream(stream);
Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
return result.values();
} catch (SAXException e) {
Log.e("Cannot parse .gpx file as GPX " + version + ": could not parse XML - " + e.toString());
throw new ParserException("Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
}
}
| public Collection<cgCache> parse(final InputStream stream, final CancellableHandler progressHandler) throws IOException, ParserException {
resetCache();
final RootElement root = new RootElement(namespace, "gpx");
final Element waypoint = root.getChild(namespace, "wpt");
// waypoint - attributes
waypoint.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) {
cache.setCoords(new Geopoint(Double.valueOf(attrs.getValue("lat")),
Double.valueOf(attrs.getValue("lon"))));
}
} catch (Exception e) {
Log.w("Failed to parse waypoint's latitude and/or longitude.");
}
}
});
// waypoint
waypoint.setEndElementListener(new EndElementListener() {
@Override
public void end() {
// try to find geocode somewhere else
if (StringUtils.isBlank(cache.getGeocode())) {
findGeoCode(name);
findGeoCode(desc);
findGeoCode(cmt);
}
// take the name as code, if nothing else is available
if (StringUtils.isBlank(cache.getGeocode())) {
if (StringUtils.isNotBlank(name)) {
cache.setGeocode(name.trim().toUpperCase());
}
}
if (StringUtils.isNotBlank(cache.getGeocode())
&& cache.getCoords() != null
&& ((type == null && sym == null)
|| StringUtils.contains(type, "geocache")
|| StringUtils.contains(sym, "geocache"))) {
fixCache(cache);
cache.setListId(listId);
cache.setDetailed(true);
createNoteFromGSAKUserdata();
final String key = cache.getGeocode();
if (result.containsKey(key)) {
Log.w("Duplicate geocode during GPX import: " + key);
}
result.put(key, cache);
showProgressMessage(progressHandler, progressStream.getProgress());
} else if (StringUtils.isNotBlank(cache.getName())
&& cache.getCoords() != null
&& StringUtils.contains(type, "waypoint")) {
addWaypointToCache();
}
resetCache();
}
private void addWaypointToCache() {
fixCache(cache);
if (cache.getName().length() > 2) {
final String cacheGeocodeForWaypoint = "GC" + cache.getName().substring(2).toUpperCase();
// lookup cache for waypoint in already parsed caches
final cgCache cacheForWaypoint = result.get(cacheGeocodeForWaypoint);
if (cacheForWaypoint != null) {
final cgWaypoint waypoint = new cgWaypoint(cache.getShortdesc(), convertWaypointSym2Type(sym), false);
waypoint.setId(-1);
waypoint.setGeocode(cacheGeocodeForWaypoint);
waypoint.setPrefix(cache.getName().substring(0, 2));
waypoint.setLookup("---");
// there is no lookup code in gpx file
waypoint.setCoords(cache.getCoords());
waypoint.setNote(cache.getDescription());
ArrayList<cgWaypoint> mergedWayPoints = new ArrayList<cgWaypoint>();
mergedWayPoints.addAll(cacheForWaypoint.getWaypoints());
cgWaypoint.mergeWayPoints(mergedWayPoints, Collections.singletonList(waypoint), true);
cacheForWaypoint.setWaypoints(mergedWayPoints, false);
result.put(cacheGeocodeForWaypoint, cacheForWaypoint);
showProgressMessage(progressHandler, progressStream.getProgress());
}
}
}
});
// waypoint.time
waypoint.getChild(namespace, "time").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setHidden(parseDate(body));
} catch (Exception e) {
Log.w("Failed to parse cache date: " + e.toString());
}
}
});
// waypoint.getName()
waypoint.getChild(namespace, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
name = body;
final String content = body.trim();
cache.setName(content);
findGeoCode(cache.getName());
}
});
// waypoint.desc
waypoint.getChild(namespace, "desc").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
desc = body;
cache.setShortdesc(validate(body));
}
});
// waypoint.cmt
waypoint.getChild(namespace, "cmt").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cmt = body;
cache.setDescription(validate(body));
}
});
// waypoint.getType()
waypoint.getChild(namespace, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String[] content = body.split("\\|");
if (content.length > 0) {
type = content[0].toLowerCase().trim();
}
}
});
// waypoint.sym
waypoint.getChild(namespace, "sym").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(final String body) {
sym = body.toLowerCase();
if (sym.contains("geocache") && sym.contains("found")) {
cache.setFound(true);
}
}
});
// waypoint.url
waypoint.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String url) {
final Matcher matcher = patternGuid.matcher(url);
if (matcher.matches()) {
final String guid = matcher.group(1);
if (StringUtils.isNotBlank(guid)) {
cache.setGuid(guid);
}
}
}
});
// for GPX 1.0, cache info comes from waypoint node (so called private children,
// for GPX 1.1 from extensions node
final Element cacheParent = getCacheParent(waypoint);
// GSAK extensions
for (String gsakNamespace : GSAK_NS) {
final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension");
gsak.getChild(gsakNamespace, "Watch").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String watchList) {
cache.setOnWatchlist(Boolean.valueOf(watchList.trim()));
}
});
gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1));
for (int i = 2; i <= 4; i++) {
gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i));
}
}
// 3 different versions of the GC schema
for (String nsGC : nsGCList) {
// waypoints.cache
final Element gcCache = cacheParent.getChild(nsGC, "cache");
gcCache.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1) {
cache.setCacheId(attrs.getValue("id"));
}
if (attrs.getIndex("archived") > -1) {
cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true"));
}
if (attrs.getIndex("available") > -1) {
cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true"));
}
} catch (Exception e) {
Log.w("Failed to parse cache attributes.");
}
}
});
// waypoint.cache.getName()
gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheName) {
cache.setName(validate(cacheName));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheOwner) {
cache.setOwner(validate(cacheOwner));
}
});
// waypoint.cache.getType()
gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setType(CacheType.getByPattern(validate(body.toLowerCase())));
}
});
// waypoint.cache.container
gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setSize(CacheSize.getById(validate(body.toLowerCase())));
}
});
// waypoint.cache.getAttributes()
// @see issue #299
// <groundspeak:attributes>
// <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
// <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
// where inc = 0 => _no, inc = 1 => _yes
// IDs see array CACHE_ATTRIBUTES
final Element gcAttributes = gcCache.getChild(nsGC, "attributes");
// waypoint.cache.attribute
final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");
gcAttribute.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
int attributeId = Integer.parseInt(attrs.getValue("id"));
boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
if (internalId != null) {
cache.addAttribute(internalId);
}
}
} catch (NumberFormatException e) {
// nothing
}
}
});
// waypoint.cache.getDifficulty()
gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setDifficulty(Float.parseFloat(body));
} catch (NumberFormatException e) {
Log.w("Failed to parse difficulty: " + e.toString());
}
}
});
// waypoint.cache.getTerrain()
gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setTerrain(Float.parseFloat(body));
} catch (NumberFormatException e) {
Log.w("Failed to parse terrain: " + e.toString());
}
}
});
// waypoint.cache.country
gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String country) {
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(country));
} else {
cache.setLocation(cache.getLocation() + ", " + country.trim());
}
}
});
// waypoint.cache.state
gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String state) {
String trimmedState = state.trim();
if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(state));
} else {
cache.setLocation(trimmedState + ", " + cache.getLocation());
}
}
}
});
// waypoint.cache.encoded_hints
gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String encoded) {
cache.setHint(validate(encoded));
}
});
gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String shortDesc) {
cache.setShortdesc(validate(shortDesc));
}
});
gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String desc) {
cache.setDescription(validate(desc));
}
});
// waypoint.cache.travelbugs
final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");
// waypoint.cache.travelbug
final Element gcTB = gcTBs.getChild(nsGC, "travelbug");
// waypoint.cache.travelbugs.travelbug
gcTB.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
trackable = new cgTrackable();
try {
if (attrs.getIndex("ref") > -1) {
trackable.setGeocode(attrs.getValue("ref").toUpperCase());
}
} catch (Exception e) {
// nothing
}
}
});
gcTB.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) {
if (cache.getInventory() == null) {
cache.setInventory(new ArrayList<cgTrackable>());
}
cache.getInventory().add(trackable);
}
}
});
// waypoint.cache.travelbugs.travelbug.getName()
gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String tbName) {
trackable.setName(validate(tbName));
}
});
// waypoint.cache.logs
final Element gcLogs = gcCache.getChild(nsGC, "logs");
// waypoint.cache.log
final Element gcLog = gcLogs.getChild(nsGC, "log");
gcLog.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
log = new LogEntry("", 0, LogType.LOG_UNKNOWN, "");
try {
if (attrs.getIndex("id") > -1) {
log.id = Integer.parseInt(attrs.getValue("id"));
}
} catch (Exception e) {
// nothing
}
}
});
gcLog.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (log.type != LogType.LOG_UNKNOWN) {
cache.appendLog(log);
}
}
});
// waypoint.cache.logs.log.date
gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
log.date = parseDate(body).getTime();
} catch (Exception e) {
Log.w("Failed to parse log date: " + e.toString());
}
}
});
// waypoint.cache.logs.log.getType()
gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String logType = validate(body).toLowerCase();
log.type = LogType.getByType(logType);
}
});
// waypoint.cache.logs.log.finder
gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String finderName) {
log.author = validate(finderName);
}
});
// waypoint.cache.logs.log.text
gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String logText) {
log.log = validate(logText);
}
});
}
try {
progressStream = new ProgressInputStream(stream);
Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
return result.values();
} catch (SAXException e) {
Log.e("Cannot parse .gpx file as GPX " + version + ": could not parse XML - " + e.toString());
throw new ParserException("Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
}
}
|
diff --git a/src/main/java/org/dynmap/ClientUpdateComponent.java b/src/main/java/org/dynmap/ClientUpdateComponent.java
index 46aa628e..4d2f5284 100644
--- a/src/main/java/org/dynmap/ClientUpdateComponent.java
+++ b/src/main/java/org/dynmap/ClientUpdateComponent.java
@@ -1,60 +1,75 @@
package org.dynmap;
import static org.dynmap.JSONUtils.a;
import static org.dynmap.JSONUtils.s;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class ClientUpdateComponent extends Component {
public ClientUpdateComponent(final DynmapPlugin plugin, ConfigurationNode configuration) {
super(plugin, configuration);
plugin.events.addListener("buildclientupdate", new Event.Listener<ClientUpdateEvent>() {
@Override
public void triggered(ClientUpdateEvent e) {
buildClientUpdate(e);
}
});
}
protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
- s(jp, "world", p.getWorld().getName());
- s(jp, "x", pl.getX());
- s(jp, "y", pl.getY());
- s(jp, "z", pl.getZ());
- if (configuration.getBoolean("sendhealth", false)) {
+ /* Don't leak player location for world not visible on maps, or if sendposition disbaled */
+ boolean player_visible = MapManager.mapman.worldsLookup.containsKey(p.getWorld().getName());
+ if(configuration.getBoolean("sendpositon", true) && player_visible) {
+ s(jp, "world", p.getWorld().getName());
+ s(jp, "x", pl.getX());
+ s(jp, "y", pl.getY());
+ s(jp, "z", pl.getZ());
+ }
+ else {
+ s(jp, "world", "-some-other-bogus-world-");
+ s(jp, "x", 0.0);
+ s(jp, "y", 64.0);
+ s(jp, "z", 0.0);
+ }
+ /* Only send health if enabled AND we're on visible world */
+ if (configuration.getBoolean("sendhealth", false) && player_visible) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
+ else {
+ s(jp, "health", 0);
+ s(jp, "armor", 0);
+ }
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
}
| false | true | protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
s(jp, "world", p.getWorld().getName());
s(jp, "x", pl.getX());
s(jp, "y", pl.getY());
s(jp, "z", pl.getZ());
if (configuration.getBoolean("sendhealth", false)) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
| protected void buildClientUpdate(ClientUpdateEvent e) {
World world = e.world.world;
JSONObject u = e.update;
long since = e.timestamp;
String worldName = world.getName();
s(u, "servertime", world.getTime() % 24000);
s(u, "hasStorm", world.hasStorm());
s(u, "isThundering", world.isThundering());
s(u, "players", new JSONArray());
Player[] players = plugin.playerList.getVisiblePlayers();
for(int i=0;i<players.length;i++) {
Player p = players[i];
Location pl = p.getLocation();
JSONObject jp = new JSONObject();
s(jp, "type", "player");
s(jp, "name", ChatColor.stripColor(p.getDisplayName()));
s(jp, "account", p.getName());
/* Don't leak player location for world not visible on maps, or if sendposition disbaled */
boolean player_visible = MapManager.mapman.worldsLookup.containsKey(p.getWorld().getName());
if(configuration.getBoolean("sendpositon", true) && player_visible) {
s(jp, "world", p.getWorld().getName());
s(jp, "x", pl.getX());
s(jp, "y", pl.getY());
s(jp, "z", pl.getZ());
}
else {
s(jp, "world", "-some-other-bogus-world-");
s(jp, "x", 0.0);
s(jp, "y", 64.0);
s(jp, "z", 0.0);
}
/* Only send health if enabled AND we're on visible world */
if (configuration.getBoolean("sendhealth", false) && player_visible) {
s(jp, "health", p.getHealth());
s(jp, "armor", Armor.getArmorPoints(p));
}
else {
s(jp, "health", 0);
s(jp, "armor", 0);
}
a(u, "players", jp);
}
s(u, "updates", new JSONArray());
for(Object update : plugin.mapManager.getWorldUpdates(worldName, since)) {
a(u, "updates", (Client.Update)update);
}
}
|
diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java
index 78fda2919..de27bea87 100755
--- a/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java
+++ b/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java
@@ -1,206 +1,207 @@
/**
* 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.activemq.transport.discovery;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.ManagementContext;
import org.apache.activemq.transport.discovery.multicast.MulticastDiscoveryAgentFactory;
import org.apache.activemq.util.SocketProxy;
import org.apache.activemq.util.Wait;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.Invocation;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.action.CustomAction;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(JMock.class)
public class DiscoveryNetworkReconnectTest {
private static final Log LOG = LogFactory.getLog(DiscoveryNetworkReconnectTest.class);
final int maxReconnects = 5;
final String groupName = "GroupID-" + "DiscoveryNetworkReconnectTest";
final String discoveryAddress = "multicast://default?group=" + groupName + "&initialReconnectDelay=1000";
final Semaphore mbeanRegistered = new Semaphore(0);
final Semaphore mbeanUnregistered = new Semaphore(0);
BrokerService brokerA, brokerB;
Mockery context;
ManagementContext managementContext;
DiscoveryAgent agent;
SocketProxy proxy;
// ignore the hostname resolution component as this is machine dependent
class NetworkBridgeObjectNameMatcher<T> extends BaseMatcher<T> {
T name;
NetworkBridgeObjectNameMatcher(T o) {
name = o;
}
public boolean matches(Object arg0) {
ObjectName other = (ObjectName) arg0;
ObjectName mine = (ObjectName) name;
return other.getKeyProperty("Type").equals(mine.getKeyProperty("Type")) &&
other.getKeyProperty("NetworkConnectorName").equals(mine.getKeyProperty("NetworkConnectorName"));
}
public void describeTo(Description arg0) {
arg0.appendText(this.getClass().getName());
}
}
@Before
public void setUp() throws Exception {
context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
brokerA = new BrokerService();
brokerA.setBrokerName("BrokerA");
configure(brokerA);
brokerA.addConnector("tcp://localhost:0");
brokerA.start();
proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri());
managementContext = context.mock(ManagementContext.class);
context.checking(new Expectations(){{
allowing (managementContext).getJmxDomainName(); will (returnValue("Test"));
allowing (managementContext).start();
+ allowing (managementContext).isCreateConnector();
allowing (managementContext).stop();
allowing (managementContext).isConnectorStarted();
// expected MBeans
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Registered: " + invocation.getParameter(0));
mbeanRegistered.release();
return new ObjectInstance((ObjectName)invocation.getParameter(0), "dscription");
}
});
atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Unregistered: " + invocation.getParameter(0));
mbeanUnregistered.release();
return null;
}
});
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
}});
brokerB = new BrokerService();
brokerB.setManagementContext(managementContext);
brokerB.setBrokerName("BrokerNC");
configure(brokerB);
}
@After
public void tearDown() throws Exception {
brokerA.stop();
brokerB.stop();
proxy.close();
}
private void configure(BrokerService broker) {
broker.setPersistent(false);
broker.setUseJmx(true);
}
@Test
public void testMulicastReconnect() throws Exception {
// control multicast advertise agent to inject proxy
agent = MulticastDiscoveryAgentFactory.createDiscoveryAgent(new URI(discoveryAddress));
agent.registerService(proxy.getUrl().toString());
agent.start();
brokerB.addNetworkConnector(discoveryAddress + "&wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000");
brokerB.start();
doReconnect();
}
@Test
public void testSimpleReconnect() throws Exception {
brokerB.addNetworkConnector("simple://(" + proxy.getUrl()
+ ")?useExponentialBackOff=false&initialReconnectDelay=500&wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000");
brokerB.start();
doReconnect();
}
private void doReconnect() throws Exception {
for (int i=0; i<maxReconnects; i++) {
// Wait for connection
assertTrue("we got a network connection in a timely manner", Wait.waitFor(new Wait.Condition() {
public boolean isSatisified() throws Exception {
return proxy.connections.size() >= 1;
}
}));
// wait for network connector
assertTrue("network connector mbean registered within 1 minute", mbeanRegistered.tryAcquire(60, TimeUnit.SECONDS));
// force an inactivity timeout via the proxy
proxy.pause();
// wait for the inactivity timeout and network shutdown
assertTrue("network connector mbean unregistered within 1 minute", mbeanUnregistered.tryAcquire(60, TimeUnit.SECONDS));
// whack all connections
proxy.close();
// let a reconnect succeed
proxy.reopen();
}
}
}
| true | true | public void setUp() throws Exception {
context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
brokerA = new BrokerService();
brokerA.setBrokerName("BrokerA");
configure(brokerA);
brokerA.addConnector("tcp://localhost:0");
brokerA.start();
proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri());
managementContext = context.mock(ManagementContext.class);
context.checking(new Expectations(){{
allowing (managementContext).getJmxDomainName(); will (returnValue("Test"));
allowing (managementContext).start();
allowing (managementContext).stop();
allowing (managementContext).isConnectorStarted();
// expected MBeans
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Registered: " + invocation.getParameter(0));
mbeanRegistered.release();
return new ObjectInstance((ObjectName)invocation.getParameter(0), "dscription");
}
});
atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Unregistered: " + invocation.getParameter(0));
mbeanUnregistered.release();
return null;
}
});
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
}});
brokerB = new BrokerService();
brokerB.setManagementContext(managementContext);
brokerB.setBrokerName("BrokerNC");
configure(brokerB);
}
| public void setUp() throws Exception {
context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
brokerA = new BrokerService();
brokerA.setBrokerName("BrokerA");
configure(brokerA);
brokerA.addConnector("tcp://localhost:0");
brokerA.start();
proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri());
managementContext = context.mock(ManagementContext.class);
context.checking(new Expectations(){{
allowing (managementContext).getJmxDomainName(); will (returnValue("Test"));
allowing (managementContext).start();
allowing (managementContext).isCreateConnector();
allowing (managementContext).stop();
allowing (managementContext).isConnectorStarted();
// expected MBeans
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost"))));
allowing (managementContext).registerMBean(with(any(Object.class)), with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Registered: " + invocation.getParameter(0));
mbeanRegistered.release();
return new ObjectInstance((ObjectName)invocation.getParameter(0), "dscription");
}
});
atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_"
+ proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") {
public Object invoke(Invocation invocation) throws Throwable {
LOG.info("Mbean Unregistered: " + invocation.getParameter(0));
mbeanUnregistered.release();
return null;
}
});
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Broker"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost"))));
allowing (managementContext).unregisterMBean(with(equal(
new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection"))));
}});
brokerB = new BrokerService();
brokerB.setManagementContext(managementContext);
brokerB.setBrokerName("BrokerNC");
configure(brokerB);
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/console/JavaConsoleTracker.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/console/JavaConsoleTracker.java
index ed72c918b..4c3fce720 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/console/JavaConsoleTracker.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/console/JavaConsoleTracker.java
@@ -1,112 +1,114 @@
/*******************************************************************************
* 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.jdt.internal.debug.ui.console;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.debug.ui.console.IConsole;
import org.eclipse.debug.ui.console.IConsoleHyperlink;
import org.eclipse.debug.ui.console.IConsoleLineTracker;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IRegion;
/**
* Provides links for stack traces
*/
public class JavaConsoleTracker implements IConsoleLineTracker {
/**
* The console associated with this line tracker
*/
private IConsole fConsole;
private StringMatcher fJavaMatcher;
private StringMatcher fNativeMatcher;
private Pattern fJavaQualifiedNamePattern;
private boolean fInTrace = false;
String fPrevText = null;
private IRegion fPrevLine = null;
/**
* @see org.eclipse.debug.ui.console.IConsoleLineTracker#init(org.eclipse.debug.ui.console.IConsole)
*/
public void init(IConsole console) {
fConsole = console;
fJavaMatcher = new StringMatcher("*(*.java:*)", false, false); //$NON-NLS-1$
fNativeMatcher = new StringMatcher("*(Native Method)", false, false); //$NON-NLS-1$
fJavaQualifiedNamePattern = Pattern.compile("([$_A-Za-z][$_A-Za-z0-9]*[.])*[$_A-Za-z][$_A-Za-z0-9]*Exception"); //$NON-NLS-1$
}
/**
* @see org.eclipse.debug.ui.console.IConsoleLineTracker#lineAppended(org.eclipse.jface.text.IRegion)
*/
public void lineAppended(IRegion line) {
try {
int offset = line.getOffset();
int length = line.getLength();
String text = fConsole.getDocument().get(offset, length);
boolean standardMatch = false;
int index = -1;
if (fJavaMatcher.match(text)) {
standardMatch = true;
// find the last space in the line
index = text.lastIndexOf(' ');
} else if (fNativeMatcher.match(text)) {
// find the second last space in the line
index = text.lastIndexOf(' ', text.length() - 15);
}
if (index >= 0) {
if (!fInTrace) {
fInTrace = true;
// look for exception name
- Matcher m = fJavaQualifiedNamePattern.matcher(fPrevText);
- if (m.find()) {
- int start = m.start();
- int end = m.end();
- int size = end - start;
- IConsoleHyperlink link = new JavaExceptionHyperLink(fConsole, fPrevText.substring(start, end));
- start += fPrevLine.getOffset();
- fConsole.addLink(link, start, size);
+ if (fPrevText != null) {
+ Matcher m = fJavaQualifiedNamePattern.matcher(fPrevText);
+ if (m.find()) {
+ int start = m.start();
+ int end = m.end();
+ int size = end - start;
+ IConsoleHyperlink link = new JavaExceptionHyperLink(fConsole, fPrevText.substring(start, end));
+ start += fPrevLine.getOffset();
+ fConsole.addLink(link, start, size);
+ }
}
}
int linkOffset = offset + index + 1;
int linkLength = length - index - 1;
IConsoleHyperlink link = null;
if (standardMatch) {
link = new JavaStackTraceHyperlink(fConsole);
} else {
link = new JavaNativeStackTraceHyperlink(fConsole);
}
fConsole.addLink(link, linkOffset, linkLength);
} else {
if (fInTrace) {
fInTrace = false;
}
}
fPrevText = text;
fPrevLine = line;
} catch (BadLocationException e) {
}
}
/**
* @see org.eclipse.debug.ui.console.IConsoleLineTracker#dispose()
*/
public void dispose() {
fConsole = null;
fJavaMatcher = null;
fNativeMatcher = null;
}
}
| true | true | public void lineAppended(IRegion line) {
try {
int offset = line.getOffset();
int length = line.getLength();
String text = fConsole.getDocument().get(offset, length);
boolean standardMatch = false;
int index = -1;
if (fJavaMatcher.match(text)) {
standardMatch = true;
// find the last space in the line
index = text.lastIndexOf(' ');
} else if (fNativeMatcher.match(text)) {
// find the second last space in the line
index = text.lastIndexOf(' ', text.length() - 15);
}
if (index >= 0) {
if (!fInTrace) {
fInTrace = true;
// look for exception name
Matcher m = fJavaQualifiedNamePattern.matcher(fPrevText);
if (m.find()) {
int start = m.start();
int end = m.end();
int size = end - start;
IConsoleHyperlink link = new JavaExceptionHyperLink(fConsole, fPrevText.substring(start, end));
start += fPrevLine.getOffset();
fConsole.addLink(link, start, size);
}
}
int linkOffset = offset + index + 1;
int linkLength = length - index - 1;
IConsoleHyperlink link = null;
if (standardMatch) {
link = new JavaStackTraceHyperlink(fConsole);
} else {
link = new JavaNativeStackTraceHyperlink(fConsole);
}
fConsole.addLink(link, linkOffset, linkLength);
} else {
if (fInTrace) {
fInTrace = false;
}
}
fPrevText = text;
fPrevLine = line;
} catch (BadLocationException e) {
}
}
| public void lineAppended(IRegion line) {
try {
int offset = line.getOffset();
int length = line.getLength();
String text = fConsole.getDocument().get(offset, length);
boolean standardMatch = false;
int index = -1;
if (fJavaMatcher.match(text)) {
standardMatch = true;
// find the last space in the line
index = text.lastIndexOf(' ');
} else if (fNativeMatcher.match(text)) {
// find the second last space in the line
index = text.lastIndexOf(' ', text.length() - 15);
}
if (index >= 0) {
if (!fInTrace) {
fInTrace = true;
// look for exception name
if (fPrevText != null) {
Matcher m = fJavaQualifiedNamePattern.matcher(fPrevText);
if (m.find()) {
int start = m.start();
int end = m.end();
int size = end - start;
IConsoleHyperlink link = new JavaExceptionHyperLink(fConsole, fPrevText.substring(start, end));
start += fPrevLine.getOffset();
fConsole.addLink(link, start, size);
}
}
}
int linkOffset = offset + index + 1;
int linkLength = length - index - 1;
IConsoleHyperlink link = null;
if (standardMatch) {
link = new JavaStackTraceHyperlink(fConsole);
} else {
link = new JavaNativeStackTraceHyperlink(fConsole);
}
fConsole.addLink(link, linkOffset, linkLength);
} else {
if (fInTrace) {
fInTrace = false;
}
}
fPrevText = text;
fPrevLine = line;
} catch (BadLocationException e) {
}
}
|
diff --git a/modules/activiti-upgrade/src/test/java/org/activiti/upgrade/DatabaseFormatterPostgres.java b/modules/activiti-upgrade/src/test/java/org/activiti/upgrade/DatabaseFormatterPostgres.java
index 62e7d9c60..57fd66c04 100644
--- a/modules/activiti-upgrade/src/test/java/org/activiti/upgrade/DatabaseFormatterPostgres.java
+++ b/modules/activiti-upgrade/src/test/java/org/activiti/upgrade/DatabaseFormatterPostgres.java
@@ -1,27 +1,27 @@
/* 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.activiti.upgrade;
public class DatabaseFormatterPostgres extends DatabaseFormatter {
@Override
public String formatBinary(byte[] bytes) {
StringBuffer sb = new StringBuffer();
- sb.append("E'\\\\x");
+ sb.append("decode('");
appendBytesInHex(sb, bytes);
- sb.append("'");
+ sb.append("', 'hex')");
return sb.toString();
}
}
| false | true | public String formatBinary(byte[] bytes) {
StringBuffer sb = new StringBuffer();
sb.append("E'\\\\x");
appendBytesInHex(sb, bytes);
sb.append("'");
return sb.toString();
}
| public String formatBinary(byte[] bytes) {
StringBuffer sb = new StringBuffer();
sb.append("decode('");
appendBytesInHex(sb, bytes);
sb.append("', 'hex')");
return sb.toString();
}
|
diff --git a/podsalinan/src/com/mimpidev/podsalinan/cli/options/downloads/ShowSelectedMenu.java b/podsalinan/src/com/mimpidev/podsalinan/cli/options/downloads/ShowSelectedMenu.java
index 6b86bb3..c12aeb5 100644
--- a/podsalinan/src/com/mimpidev/podsalinan/cli/options/downloads/ShowSelectedMenu.java
+++ b/podsalinan/src/com/mimpidev/podsalinan/cli/options/downloads/ShowSelectedMenu.java
@@ -1,103 +1,103 @@
/**
*
*/
package com.mimpidev.podsalinan.cli.options.downloads;
import java.io.File;
import com.mimpidev.podsalinan.DataStorage;
import com.mimpidev.podsalinan.Podsalinan;
import com.mimpidev.podsalinan.cli.CLIOption;
import com.mimpidev.podsalinan.cli.ReturnCall;
import com.mimpidev.podsalinan.data.Episode;
import com.mimpidev.podsalinan.data.URLDownload;
/**
* @author sbell
*
*/
public class ShowSelectedMenu extends CLIOption {
/**
* @param newData
*/
public ShowSelectedMenu(DataStorage newData) {
super(newData);
debug=true;
}
public void printDetails(URLDownload selectedDownload, boolean showDirectory){
- if (selectedDownload==null){
+ if (selectedDownload!=null){
System.out.println("URL: "+selectedDownload.getURL().toString());
switch (selectedDownload.getStatus()){
case Episode.DOWNLOAD_QUEUED:
System.out.println ("Status: Download Queued");
break;
case Episode.CURRENTLY_DOWNLOADING:
System.out.println ("Status: Currently Downloading");
break;
case Episode.INCOMPLETE_DOWNLOAD:
System.out.println ("Status: Download Incomplete");
break;
case Episode.FINISHED:
System.out.println ("Status: Completed Download");
break;
case Episode.DOWNLOAD_CANCELLED:
System.out.println ("Status: Download Cancelled");
default:
System.out.println ("Status: "+selectedDownload.getStatus());
}
if ((showDirectory)&&(selectedDownload.getDestination()!=null))
System.out.println("Destination: "+selectedDownload.getDestination());
long fileSize;
//String filePath=selectedDownload.getDestination()+fileSystemSlash+getFilenameDownload();
if (!selectedDownload.getDestinationFile().isDirectory()){
File destination = selectedDownload.getDestinationFile();
if (destination.exists())
fileSize = destination.length();
else
fileSize = 0;
} else {
fileSize=0;
}
// Need to make these sizes human readable
System.out.println ("Downloaded: "+humanReadableSize(fileSize)+" / "+humanReadableSize(new Long(selectedDownload.getSize()).longValue()));
}
}
/* (non-Javadoc)
* @see com.mimpidev.podsalinan.cli.CLIOption#execute(java.lang.String)
*/
@Override
public ReturnCall execute(String command) {
if (debug) Podsalinan.debugLog.logInfo("["+getClass().getName()+"] command: "+command);
int downloadId = Integer.parseInt(command.split(" ")[0]);
int count=0;
for (URLDownload currentDownload: data.getUrlDownloads().getDownloads()){
if (!currentDownload.isRemoved()){
if (count==downloadId){
System.out.println();
printDetails(currentDownload,false);
System.out.println();
System.out.println("1. Delete Download");
System.out.println("2. Restart Download");
System.out.println("3. Stop Download");
System.out.println("4. Start Download (Add to active Queue)");
System.out.println("5. Increase Priority");
System.out.println("6. Decrease Priority");
System.out.println("7. Change Destination");
System.out.println();
System.out.println("9. Return to Download List");
}
count++;
}
}
return returnObject;
}
}
| true | true | public void printDetails(URLDownload selectedDownload, boolean showDirectory){
if (selectedDownload==null){
System.out.println("URL: "+selectedDownload.getURL().toString());
switch (selectedDownload.getStatus()){
case Episode.DOWNLOAD_QUEUED:
System.out.println ("Status: Download Queued");
break;
case Episode.CURRENTLY_DOWNLOADING:
System.out.println ("Status: Currently Downloading");
break;
case Episode.INCOMPLETE_DOWNLOAD:
System.out.println ("Status: Download Incomplete");
break;
case Episode.FINISHED:
System.out.println ("Status: Completed Download");
break;
case Episode.DOWNLOAD_CANCELLED:
System.out.println ("Status: Download Cancelled");
default:
System.out.println ("Status: "+selectedDownload.getStatus());
}
if ((showDirectory)&&(selectedDownload.getDestination()!=null))
System.out.println("Destination: "+selectedDownload.getDestination());
long fileSize;
//String filePath=selectedDownload.getDestination()+fileSystemSlash+getFilenameDownload();
if (!selectedDownload.getDestinationFile().isDirectory()){
File destination = selectedDownload.getDestinationFile();
if (destination.exists())
fileSize = destination.length();
else
fileSize = 0;
} else {
fileSize=0;
}
// Need to make these sizes human readable
System.out.println ("Downloaded: "+humanReadableSize(fileSize)+" / "+humanReadableSize(new Long(selectedDownload.getSize()).longValue()));
}
}
| public void printDetails(URLDownload selectedDownload, boolean showDirectory){
if (selectedDownload!=null){
System.out.println("URL: "+selectedDownload.getURL().toString());
switch (selectedDownload.getStatus()){
case Episode.DOWNLOAD_QUEUED:
System.out.println ("Status: Download Queued");
break;
case Episode.CURRENTLY_DOWNLOADING:
System.out.println ("Status: Currently Downloading");
break;
case Episode.INCOMPLETE_DOWNLOAD:
System.out.println ("Status: Download Incomplete");
break;
case Episode.FINISHED:
System.out.println ("Status: Completed Download");
break;
case Episode.DOWNLOAD_CANCELLED:
System.out.println ("Status: Download Cancelled");
default:
System.out.println ("Status: "+selectedDownload.getStatus());
}
if ((showDirectory)&&(selectedDownload.getDestination()!=null))
System.out.println("Destination: "+selectedDownload.getDestination());
long fileSize;
//String filePath=selectedDownload.getDestination()+fileSystemSlash+getFilenameDownload();
if (!selectedDownload.getDestinationFile().isDirectory()){
File destination = selectedDownload.getDestinationFile();
if (destination.exists())
fileSize = destination.length();
else
fileSize = 0;
} else {
fileSize=0;
}
// Need to make these sizes human readable
System.out.println ("Downloaded: "+humanReadableSize(fileSize)+" / "+humanReadableSize(new Long(selectedDownload.getSize()).longValue()));
}
}
|
diff --git a/plugin/src/main/java/hudson/plugins/findbugs/FindBugsPlugin.java b/plugin/src/main/java/hudson/plugins/findbugs/FindBugsPlugin.java
index 4b48b8e..f4ab25c 100644
--- a/plugin/src/main/java/hudson/plugins/findbugs/FindBugsPlugin.java
+++ b/plugin/src/main/java/hudson/plugins/findbugs/FindBugsPlugin.java
@@ -1,22 +1,24 @@
package hudson.plugins.findbugs;
import hudson.Plugin;
import hudson.plugins.analysis.views.DetailFactory;
import java.io.IOException;
import org.xml.sax.SAXException;
/**
* Initializes the FindBugs messages, descriptions and detail view factory.
*
* @author Ulli Hafner
*/
public class FindBugsPlugin extends Plugin {
/** {@inheritDoc} */
@Override
public void start() throws IOException, SAXException {
FindBugsMessages.getInstance().initialize();
- DetailFactory.addDetailBuilder(FindBugsResultAction.class, new FindBugsDetailFactory());
+ FindBugsDetailFactory detailBuilder = new FindBugsDetailFactory();
+ DetailFactory.addDetailBuilder(FindBugsResultAction.class, detailBuilder);
+ DetailFactory.addDetailBuilder(FindBugsMavenResultAction.class, detailBuilder);
}
}
| true | true | public void start() throws IOException, SAXException {
FindBugsMessages.getInstance().initialize();
DetailFactory.addDetailBuilder(FindBugsResultAction.class, new FindBugsDetailFactory());
}
| public void start() throws IOException, SAXException {
FindBugsMessages.getInstance().initialize();
FindBugsDetailFactory detailBuilder = new FindBugsDetailFactory();
DetailFactory.addDetailBuilder(FindBugsResultAction.class, detailBuilder);
DetailFactory.addDetailBuilder(FindBugsMavenResultAction.class, detailBuilder);
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.